xref: /titanic_41/usr/src/uts/common/inet/ipf/fil.c (revision 4a6ec905b96eb96a398c346f59e034a90ce8ad37)
1 /*
2  * Copyright (C) 1993-2003 by Darren Reed.
3  *
4  * See the IPFILTER.LICENCE file for details on licencing.
5  *
6  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
7  * Use is subject to license terms.
8  */
9 
10 #pragma ident	"%Z%%M%	%I%	%E% SMI"
11 
12 #if defined(KERNEL) || defined(_KERNEL)
13 # undef KERNEL
14 # undef _KERNEL
15 # define        KERNEL	1
16 # define        _KERNEL	1
17 #endif
18 #include <sys/errno.h>
19 #include <sys/types.h>
20 #include <sys/param.h>
21 #include <sys/time.h>
22 #if defined(__NetBSD__)
23 # if (NetBSD >= 199905) && !defined(IPFILTER_LKM) && defined(_KERNEL)
24 #  include "opt_ipfilter_log.h"
25 # endif
26 #endif
27 #if defined(_KERNEL) && defined(__FreeBSD_version) && \
28     (__FreeBSD_version >= 220000)
29 # if (__FreeBSD_version >= 400000)
30 #  if !defined(IPFILTER_LKM)
31 #   include "opt_inet6.h"
32 #  endif
33 #  if (__FreeBSD_version == 400019)
34 #   define CSUM_DELAY_DATA
35 #  endif
36 # endif
37 # include <sys/filio.h>
38 #else
39 # include <sys/ioctl.h>
40 #endif
41 #if !defined(_AIX51)
42 # include <sys/fcntl.h>
43 #endif
44 #if defined(_KERNEL)
45 # include <sys/systm.h>
46 # include <sys/file.h>
47 #else
48 # include <stdio.h>
49 # include <string.h>
50 # include <stdlib.h>
51 # include <stddef.h>
52 # include <sys/file.h>
53 # define _KERNEL
54 # ifdef __OpenBSD__
55 struct file;
56 # endif
57 # include <sys/uio.h>
58 # undef _KERNEL
59 #endif
60 #if !defined(__SVR4) && !defined(__svr4__) && !defined(__hpux) && \
61     !defined(linux)
62 # include <sys/mbuf.h>
63 #else
64 # if !defined(linux)
65 #  include <sys/byteorder.h>
66 # endif
67 # if (SOLARIS2 < 5) && defined(sun)
68 #  include <sys/dditypes.h>
69 # endif
70 #endif
71 #ifdef __hpux
72 # define _NET_ROUTE_INCLUDED
73 #endif
74 #if !defined(linux)
75 # include <sys/protosw.h>
76 #endif
77 #include <sys/socket.h>
78 #include <net/if.h>
79 #ifdef sun
80 # include <net/af.h>
81 #endif
82 #if !defined(_KERNEL) && defined(__FreeBSD__)
83 # include "radix_ipf.h"
84 #endif
85 #include <net/route.h>
86 #include <netinet/in.h>
87 #include <netinet/in_systm.h>
88 #include <netinet/ip.h>
89 #if !defined(linux)
90 # include <netinet/ip_var.h>
91 #endif
92 #if defined(__sgi) && defined(IFF_DRVRLOCK) /* IRIX 6 */
93 # include <sys/hashing.h>
94 # include <netinet/in_var.h>
95 #endif
96 #include <netinet/tcp.h>
97 #if (!defined(__sgi) && !defined(AIX)) || defined(_KERNEL)
98 # include <netinet/udp.h>
99 # include <netinet/ip_icmp.h>
100 #endif
101 #ifdef __hpux
102 # undef _NET_ROUTE_INCLUDED
103 #endif
104 #include "netinet/ip_compat.h"
105 #ifdef	USE_INET6
106 # include <netinet/icmp6.h>
107 # if !SOLARIS && defined(_KERNEL) && !defined(__osf__) && !defined(__hpux)
108 #  include <netinet6/in6_var.h>
109 # endif
110 #endif
111 #include <netinet/tcpip.h>
112 #include "netinet/ip_fil.h"
113 #include "netinet/ip_nat.h"
114 #include "netinet/ip_frag.h"
115 #include "netinet/ip_state.h"
116 #include "netinet/ip_proxy.h"
117 #include "netinet/ip_auth.h"
118 #include "netinet/ipf_stack.h"
119 #ifdef IPFILTER_SCAN
120 # include "netinet/ip_scan.h"
121 #endif
122 #ifdef IPFILTER_SYNC
123 # include "netinet/ip_sync.h"
124 #endif
125 #include "netinet/ip_pool.h"
126 #include "netinet/ip_htable.h"
127 #ifdef IPFILTER_COMPILED
128 # include "netinet/ip_rules.h"
129 #endif
130 #if defined(IPFILTER_BPF) && defined(_KERNEL)
131 # include <net/bpf.h>
132 #endif
133 #if defined(__FreeBSD_version) && (__FreeBSD_version >= 300000)
134 # include <sys/malloc.h>
135 # if defined(_KERNEL) && !defined(IPFILTER_LKM)
136 #  include "opt_ipfilter.h"
137 # endif
138 #endif
139 #include "netinet/ipl.h"
140 /* END OF INCLUDES */
141 
142 #if !defined(lint)
143 static const char sccsid[] = "@(#)fil.c	1.36 6/5/96 (C) 1993-2000 Darren Reed";
144 static const char rcsid[] = "@(#)$Id: fil.c,v 2.243.2.64 2005/08/13 05:19:59 darrenr Exp $";
145 #endif
146 
147 #ifndef	_KERNEL
148 # include "ipf.h"
149 # include "ipt.h"
150 # include "bpf-ipf.h"
151 extern	int	opts;
152 
153 # define	FR_VERBOSE(verb_pr)			verbose verb_pr
154 # define	FR_DEBUG(verb_pr)			debug verb_pr
155 #else /* #ifndef _KERNEL */
156 # define	FR_VERBOSE(verb_pr)
157 # define	FR_DEBUG(verb_pr)
158 #endif /* _KERNEL */
159 
160 
161 char	ipfilter_version[] = IPL_VERSION;
162 int	fr_features = 0
163 #ifdef	IPFILTER_LKM
164 		| IPF_FEAT_LKM
165 #endif
166 #ifdef	IPFILTER_LOG
167 		| IPF_FEAT_LOG
168 #endif
169 #ifdef	IPFILTER_LOOKUP
170 		| IPF_FEAT_LOOKUP
171 #endif
172 #ifdef	IPFILTER_BPF
173 		| IPF_FEAT_BPF
174 #endif
175 #ifdef	IPFILTER_COMPILED
176 		| IPF_FEAT_COMPILED
177 #endif
178 #ifdef	IPFILTER_CKSUM
179 		| IPF_FEAT_CKSUM
180 #endif
181 #ifdef	IPFILTER_SYNC
182 		| IPF_FEAT_SYNC
183 #endif
184 #ifdef	IPFILTER_SCAN
185 		| IPF_FEAT_SCAN
186 #endif
187 #ifdef	USE_INET6
188 		| IPF_FEAT_IPV6
189 #endif
190 	;
191 
192 static	INLINE int	fr_ipfcheck __P((fr_info_t *, frentry_t *, int));
193 static	int		fr_portcheck __P((frpcmp_t *, u_short *));
194 static	int		frflushlist __P((int, minor_t, int *, frentry_t **,
195 					 ipf_stack_t *));
196 static	ipfunc_t	fr_findfunc __P((ipfunc_t));
197 static	frentry_t	*fr_firewall __P((fr_info_t *, u_32_t *));
198 static	int		fr_funcinit __P((frentry_t *fr, ipf_stack_t *));
199 static	INLINE void	frpr_ah __P((fr_info_t *));
200 static	INLINE void	frpr_esp __P((fr_info_t *));
201 static	INLINE void	frpr_gre __P((fr_info_t *));
202 static	INLINE void	frpr_udp __P((fr_info_t *));
203 static	INLINE void	frpr_tcp __P((fr_info_t *));
204 static	INLINE void	frpr_icmp __P((fr_info_t *));
205 static	INLINE void	frpr_ipv4hdr __P((fr_info_t *));
206 static	INLINE int	frpr_pullup __P((fr_info_t *, int));
207 static	INLINE void	frpr_short __P((fr_info_t *, int));
208 static	INLINE void	frpr_tcpcommon __P((fr_info_t *));
209 static	INLINE void	frpr_udpcommon __P((fr_info_t *));
210 static	INLINE int	fr_updateipid __P((fr_info_t *));
211 #ifdef	IPFILTER_LOOKUP
212 static	int		fr_grpmapinit __P((frentry_t *fr, ipf_stack_t *));
213 static	INLINE void	*fr_resolvelookup __P((u_int, u_int, lookupfunc_t *,
214 					       ipf_stack_t *));
215 #endif
216 static	void		frsynclist __P((int, int, void *, char *, frentry_t *,
217     ipf_stack_t *));
218 static	void		*fr_ifsync __P((int, int, char *, char *,
219 					void *, void *, ipf_stack_t *));
220 static	ipftuneable_t	*fr_findtunebyname __P((const char *, ipf_stack_t *));
221 static	ipftuneable_t	*fr_findtunebycookie __P((void *, void **, ipf_stack_t *));
222 static	void		ipf_unlinktoken __P((ipftoken_t *, ipf_stack_t *));
223 
224 
225 /*
226  * bit values for identifying presence of individual IP options
227  * All of these tables should be ordered by increasing key value on the left
228  * hand side to allow for binary searching of the array and include a trailer
229  * with a 0 for the bitmask for linear searches to easily find the end with.
230  */
231 const	struct	optlist	ipopts[20] = {
232 	{ IPOPT_NOP,	0x000001 },
233 	{ IPOPT_RR,	0x000002 },
234 	{ IPOPT_ZSU,	0x000004 },
235 	{ IPOPT_MTUP,	0x000008 },
236 	{ IPOPT_MTUR,	0x000010 },
237 	{ IPOPT_ENCODE,	0x000020 },
238 	{ IPOPT_TS,	0x000040 },
239 	{ IPOPT_TR,	0x000080 },
240 	{ IPOPT_SECURITY, 0x000100 },
241 	{ IPOPT_LSRR,	0x000200 },
242 	{ IPOPT_E_SEC,	0x000400 },
243 	{ IPOPT_CIPSO,	0x000800 },
244 	{ IPOPT_SATID,	0x001000 },
245 	{ IPOPT_SSRR,	0x002000 },
246 	{ IPOPT_ADDEXT,	0x004000 },
247 	{ IPOPT_VISA,	0x008000 },
248 	{ IPOPT_IMITD,	0x010000 },
249 	{ IPOPT_EIP,	0x020000 },
250 	{ IPOPT_FINN,	0x040000 },
251 	{ 0,		0x000000 }
252 };
253 
254 #ifdef USE_INET6
255 struct optlist ip6exthdr[] = {
256 	{ IPPROTO_HOPOPTS,		0x000001 },
257 	{ IPPROTO_IPV6,			0x000002 },
258 	{ IPPROTO_ROUTING,		0x000004 },
259 	{ IPPROTO_FRAGMENT,		0x000008 },
260 	{ IPPROTO_ESP,			0x000010 },
261 	{ IPPROTO_AH,			0x000020 },
262 	{ IPPROTO_NONE,			0x000040 },
263 	{ IPPROTO_DSTOPTS,		0x000080 },
264 	{ 0,				0 }
265 };
266 #endif
267 
268 struct optlist tcpopts[] = {
269 	{ TCPOPT_NOP,			0x000001 },
270 	{ TCPOPT_MAXSEG,		0x000002 },
271 	{ TCPOPT_WINDOW,		0x000004 },
272 	{ TCPOPT_SACK_PERMITTED,	0x000008 },
273 	{ TCPOPT_SACK,			0x000010 },
274 	{ TCPOPT_TIMESTAMP,		0x000020 },
275 	{ 0,				0x000000 }
276 };
277 
278 /*
279  * bit values for identifying presence of individual IP security options
280  */
281 const	struct	optlist	secopt[8] = {
282 	{ IPSO_CLASS_RES4,	0x01 },
283 	{ IPSO_CLASS_TOPS,	0x02 },
284 	{ IPSO_CLASS_SECR,	0x04 },
285 	{ IPSO_CLASS_RES3,	0x08 },
286 	{ IPSO_CLASS_CONF,	0x10 },
287 	{ IPSO_CLASS_UNCL,	0x20 },
288 	{ IPSO_CLASS_RES2,	0x40 },
289 	{ IPSO_CLASS_RES1,	0x80 }
290 };
291 
292 
293 /*
294  * Table of functions available for use with call rules.
295  */
296 static ipfunc_resolve_t fr_availfuncs[] = {
297 #ifdef	IPFILTER_LOOKUP
298 	{ "fr_srcgrpmap", fr_srcgrpmap, fr_grpmapinit },
299 	{ "fr_dstgrpmap", fr_dstgrpmap, fr_grpmapinit },
300 #endif
301 	{ "", NULL }
302 };
303 
304 
305 /*
306  * The next section of code is a a collection of small routines that set
307  * fields in the fr_info_t structure passed based on properties of the
308  * current packet.  There are different routines for the same protocol
309  * for each of IPv4 and IPv6.  Adding a new protocol, for which there
310  * will "special" inspection for setup, is now more easily done by adding
311  * a new routine and expanding the frpr_ipinit*() function rather than by
312  * adding more code to a growing switch statement.
313  */
314 #ifdef USE_INET6
315 static	INLINE int	frpr_ah6 __P((fr_info_t *));
316 static	INLINE void	frpr_esp6 __P((fr_info_t *));
317 static	INLINE void	frpr_gre6 __P((fr_info_t *));
318 static	INLINE void	frpr_udp6 __P((fr_info_t *));
319 static	INLINE void	frpr_tcp6 __P((fr_info_t *));
320 static	INLINE void	frpr_icmp6 __P((fr_info_t *));
321 static	INLINE int	frpr_ipv6hdr __P((fr_info_t *));
322 static	INLINE void	frpr_short6 __P((fr_info_t *, int));
323 static	INLINE int	frpr_hopopts6 __P((fr_info_t *));
324 static	INLINE int	frpr_routing6 __P((fr_info_t *));
325 static	INLINE int	frpr_dstopts6 __P((fr_info_t *));
326 static	INLINE int	frpr_fragment6 __P((fr_info_t *));
327 static	INLINE int	frpr_ipv6exthdr __P((fr_info_t *, int, int));
328 
329 
330 /* ------------------------------------------------------------------------ */
331 /* Function:    frpr_short6                                                 */
332 /* Returns:     void                                                        */
333 /* Parameters:  fin(I) - pointer to packet information                      */
334 /*                                                                          */
335 /* IPv6 Only                                                                */
336 /* This is function enforces the 'is a packet too short to be legit' rule   */
337 /* for IPv6 and marks the packet with FI_SHORT if so.  See function comment */
338 /* for frpr_short() for more details.                                       */
339 /* ------------------------------------------------------------------------ */
340 static INLINE void frpr_short6(fin, xmin)
341 fr_info_t *fin;
342 int xmin;
343 {
344 
345 	if (fin->fin_dlen < xmin)
346 		fin->fin_flx |= FI_SHORT;
347 }
348 
349 
350 /* ------------------------------------------------------------------------ */
351 /* Function:    frpr_ipv6hdr                                                */
352 /* Returns:     int                                                         */
353 /* Parameters:  fin(I) - pointer to packet information                      */
354 /*                                                                          */
355 /* IPv6 Only                                                                */
356 /* Copy values from the IPv6 header into the fr_info_t struct and call the  */
357 /* per-protocol analyzer if it exists.                                      */
358 /* ------------------------------------------------------------------------ */
359 static INLINE int frpr_ipv6hdr(fin)
360 fr_info_t *fin;
361 {
362 	ip6_t *ip6 = (ip6_t *)fin->fin_ip;
363 	int p, go = 1, i, hdrcount;
364 	fr_ip_t *fi = &fin->fin_fi;
365 
366 	fin->fin_off = 0;
367 
368 	fi->fi_tos = 0;
369 	fi->fi_optmsk = 0;
370 	fi->fi_secmsk = 0;
371 	fi->fi_auth = 0;
372 
373 	p = ip6->ip6_nxt;
374 	fi->fi_ttl = ip6->ip6_hlim;
375 	fi->fi_src.in6 = ip6->ip6_src;
376 	fi->fi_dst.in6 = ip6->ip6_dst;
377 	fin->fin_id = 0;
378 
379 	hdrcount = 0;
380 	while (go && !(fin->fin_flx & (FI_BAD|FI_SHORT))) {
381 		switch (p)
382 		{
383 		case IPPROTO_UDP :
384 			frpr_udp6(fin);
385 			go = 0;
386 			break;
387 
388 		case IPPROTO_TCP :
389 			frpr_tcp6(fin);
390 			go = 0;
391 			break;
392 
393 		case IPPROTO_ICMPV6 :
394 			frpr_icmp6(fin);
395 			go = 0;
396 			break;
397 
398 		case IPPROTO_GRE :
399 			frpr_gre6(fin);
400 			go = 0;
401 			break;
402 
403 		case IPPROTO_HOPOPTS :
404 			/*
405 			 * hop by hop ext header is only allowed
406 			 * right after IPv6 header.
407 			 */
408 			if (hdrcount != 0) {
409 				fin->fin_flx |= FI_BAD;
410 				p = IPPROTO_NONE;
411 			} else {
412 				p = frpr_hopopts6(fin);
413 			}
414 			break;
415 
416 		case IPPROTO_DSTOPTS :
417 			p = frpr_dstopts6(fin);
418 			break;
419 
420 		case IPPROTO_ROUTING :
421 			p = frpr_routing6(fin);
422 			break;
423 
424 		case IPPROTO_AH :
425 			p = frpr_ah6(fin);
426 			break;
427 
428 		case IPPROTO_ESP :
429 			frpr_esp6(fin);
430 			go = 0;
431 			break;
432 
433 		case IPPROTO_IPV6 :
434 			for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
435 				if (ip6exthdr[i].ol_val == p) {
436 					fin->fin_flx |= ip6exthdr[i].ol_bit;
437 					break;
438 				}
439 			go = 0;
440 			break;
441 
442 		case IPPROTO_NONE :
443 			go = 0;
444 			break;
445 
446 		case IPPROTO_FRAGMENT :
447 			p = frpr_fragment6(fin);
448 			if (fin->fin_off != 0)  /* Not the first frag */
449 				go = 0;
450 			break;
451 
452 		default :
453 			go = 0;
454 			break;
455 		}
456 		hdrcount++;
457 
458 		/*
459 		 * It is important to note that at this point, for the
460 		 * extension headers (go != 0), the entire header may not have
461 		 * been pulled up when the code gets to this point.  This is
462 		 * only done for "go != 0" because the other header handlers
463 		 * will all pullup their complete header.  The other indicator
464 		 * of an incomplete packet is that this was just an extension
465 		 * header.
466 		 */
467 		if ((go != 0) && (p != IPPROTO_NONE) &&
468 		    (frpr_pullup(fin, 0) == -1)) {
469 			p = IPPROTO_NONE;
470 			go = 0;
471 		}
472 	}
473 	fi->fi_p = p;
474 
475 	if (fin->fin_flx & FI_BAD)
476 		return -1;
477 
478 	return 0;
479 }
480 
481 
482 /* ------------------------------------------------------------------------ */
483 /* Function:    frpr_ipv6exthdr                                             */
484 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
485 /* Parameters:  fin(I)      - pointer to packet information                 */
486 /*              multiple(I) - flag indicating yes/no if multiple occurances */
487 /*                            of this extension header are allowed.         */
488 /*              proto(I)    - protocol number for this extension header     */
489 /*                                                                          */
490 /* IPv6 Only                                                                */
491 /* ------------------------------------------------------------------------ */
492 static INLINE int frpr_ipv6exthdr(fin, multiple, proto)
493 fr_info_t *fin;
494 int multiple, proto;
495 {
496 	struct ip6_ext *hdr;
497 	u_short shift;
498 	int i;
499 
500 	fin->fin_flx |= FI_V6EXTHDR;
501 
502 				/* 8 is default length of extension hdr */
503 	if ((fin->fin_dlen - 8) < 0) {
504 		fin->fin_flx |= FI_SHORT;
505 		return IPPROTO_NONE;
506 	}
507 
508 	if (frpr_pullup(fin, 8) == -1)
509 		return IPPROTO_NONE;
510 
511 	hdr = fin->fin_dp;
512 	shift = 8 + (hdr->ip6e_len << 3);
513 	if (shift > fin->fin_dlen) {	/* Nasty extension header length? */
514 		fin->fin_flx |= FI_BAD;
515 		return IPPROTO_NONE;
516 	}
517 
518 	for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
519 		if (ip6exthdr[i].ol_val == proto) {
520 			/*
521 			 * Most IPv6 extension headers are only allowed once.
522 			 */
523 			if ((multiple == 0) &&
524 			    ((fin->fin_optmsk & ip6exthdr[i].ol_bit) != 0))
525 				fin->fin_flx |= FI_BAD;
526 			else
527 				fin->fin_optmsk |= ip6exthdr[i].ol_bit;
528 			break;
529 		}
530 
531 	fin->fin_dp = (char *)fin->fin_dp + shift;
532 	fin->fin_dlen -= shift;
533 
534 	return hdr->ip6e_nxt;
535 }
536 
537 
538 /* ------------------------------------------------------------------------ */
539 /* Function:    frpr_hopopts6                                               */
540 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
541 /* Parameters:  fin(I) - pointer to packet information                      */
542 /*                                                                          */
543 /* IPv6 Only                                                                */
544 /* This is function checks pending hop by hop options extension header      */
545 /* ------------------------------------------------------------------------ */
546 static INLINE int frpr_hopopts6(fin)
547 fr_info_t *fin;
548 {
549 	return frpr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
550 }
551 
552 
553 /* ------------------------------------------------------------------------ */
554 /* Function:    frpr_routing6                                               */
555 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
556 /* Parameters:  fin(I) - pointer to packet information                      */
557 /*                                                                          */
558 /* IPv6 Only                                                                */
559 /* This is function checks pending routing extension header                 */
560 /* ------------------------------------------------------------------------ */
561 static INLINE int frpr_routing6(fin)
562 fr_info_t *fin;
563 {
564 	struct ip6_ext *hdr;
565 	int shift;
566 
567 	hdr = fin->fin_dp;
568 	if (frpr_ipv6exthdr(fin, 0, IPPROTO_ROUTING) == IPPROTO_NONE)
569 		return IPPROTO_NONE;
570 
571 	shift = 8 + (hdr->ip6e_len << 3);
572 	/*
573 	 * Nasty extension header length?
574 	 */
575 	if ((hdr->ip6e_len << 3) & 15) {
576 		fin->fin_flx |= FI_BAD;
577 		/*
578 		 * Compensate for the changes made in frpr_ipv6exthdr()
579 		 */
580 		fin->fin_dlen += shift;
581 		fin->fin_dp = (char *)fin->fin_dp - shift;
582 		return IPPROTO_NONE;
583 	}
584 
585 	return hdr->ip6e_nxt;
586 }
587 
588 
589 /* ------------------------------------------------------------------------ */
590 /* Function:    frpr_fragment6                                              */
591 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
592 /* Parameters:  fin(I) - pointer to packet information                      */
593 /*                                                                          */
594 /* IPv6 Only                                                                */
595 /* Examine the IPv6 fragment header and extract fragment offset information.*/
596 /*                                                                          */
597 /* We don't know where the transport layer header (or whatever is next is), */
598 /* as it could be behind destination options (amongst others).  Because     */
599 /* there is no fragment cache, there is no knowledge about whether or not an*/
600 /* upper layer header has been seen (or where it ends) and thus we are not  */
601 /* able to continue processing beyond this header with any confidence.      */
602 /* ------------------------------------------------------------------------ */
603 static INLINE int frpr_fragment6(fin)
604 fr_info_t *fin;
605 {
606 	struct ip6_frag *frag;
607 	int dlen;
608 
609 	fin->fin_flx |= FI_FRAG;
610 
611 	dlen = fin->fin_dlen;
612 	if (frpr_ipv6exthdr(fin, 0, IPPROTO_FRAGMENT) == IPPROTO_NONE)
613 		return IPPROTO_NONE;
614 
615 	if (frpr_pullup(fin, sizeof(*frag)) == -1)
616 		return IPPROTO_NONE;
617 
618 	frpr_short6(fin, sizeof(*frag));
619 
620 	if ((fin->fin_flx & FI_SHORT) != 0)
621 		return IPPROTO_NONE;
622 
623 	frag = (struct ip6_frag *)((char *)fin->fin_dp - sizeof(*frag));
624 	/*
625 	 * Fragment but no fragmentation info set?  Bad packet...
626 	 */
627 	if (frag->ip6f_offlg == 0) {
628 		fin->fin_flx |= FI_BAD;
629 		return IPPROTO_NONE;
630 	}
631 
632 	fin->fin_id = frag->ip6f_ident;
633 	fin->fin_off = frag->ip6f_offlg & IP6F_OFF_MASK;
634 	fin->fin_off = ntohs(fin->fin_off);
635 	if (fin->fin_off != 0)
636 		fin->fin_flx |= FI_FRAGBODY;
637 
638 	fin->fin_dp = (char *)frag + sizeof(*frag);
639 	fin->fin_dlen = dlen - sizeof(*frag);
640 
641 	/* length of hdrs(after frag hdr) + data */
642 	fin->fin_flen = fin->fin_dlen;
643 
644 	/*
645 	 * If the frag is not the last one and the payload length
646 	 * is not multiple of 8, it must be dropped.
647 	 */
648 	if ((frag->ip6f_offlg & IP6F_MORE_FRAG) && (dlen % 8)) {
649 		fin->fin_flx |= FI_BAD;
650 		return IPPROTO_NONE;
651 	}
652 
653 	return frag->ip6f_nxt;
654 }
655 
656 
657 /* ------------------------------------------------------------------------ */
658 /* Function:    frpr_dstopts6                                               */
659 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
660 /* Parameters:  fin(I) - pointer to packet information                      */
661 /*              nextheader(I) - stores next header value                    */
662 /*                                                                          */
663 /* IPv6 Only                                                                */
664 /* This is function checks pending destination options extension header     */
665 /* ------------------------------------------------------------------------ */
666 static INLINE int frpr_dstopts6(fin)
667 fr_info_t *fin;
668 {
669 	return frpr_ipv6exthdr(fin, 1, IPPROTO_DSTOPTS);
670 }
671 
672 
673 /* ------------------------------------------------------------------------ */
674 /* Function:    frpr_icmp6                                                  */
675 /* Returns:     void                                                        */
676 /* Parameters:  fin(I) - pointer to packet information                      */
677 /*                                                                          */
678 /* IPv6 Only                                                                */
679 /* This routine is mainly concerned with determining the minimum valid size */
680 /* for an ICMPv6 packet.                                                    */
681 /* ------------------------------------------------------------------------ */
682 static INLINE void frpr_icmp6(fin)
683 fr_info_t *fin;
684 {
685 	int minicmpsz = sizeof(struct icmp6_hdr);
686 	struct icmp6_hdr *icmp6;
687 
688 	if (frpr_pullup(fin, ICMP6ERR_MINPKTLEN - sizeof(ip6_t)) == -1)
689 		return;
690 
691 	if (fin->fin_dlen > 1) {
692 		icmp6 = fin->fin_dp;
693 
694 		fin->fin_data[0] = *(u_short *)icmp6;
695 
696 		switch (icmp6->icmp6_type)
697 		{
698 		case ICMP6_ECHO_REPLY :
699 		case ICMP6_ECHO_REQUEST :
700 			minicmpsz = ICMP6ERR_MINPKTLEN - sizeof(ip6_t);
701 			break;
702 		case ICMP6_DST_UNREACH :
703 		case ICMP6_PACKET_TOO_BIG :
704 		case ICMP6_TIME_EXCEEDED :
705 		case ICMP6_PARAM_PROB :
706 			if ((fin->fin_m != NULL) &&
707 			    (M_LEN(fin->fin_m) < fin->fin_plen)) {
708 				if (fr_coalesce(fin) != 1)
709 					return;
710 			}
711 			fin->fin_flx |= FI_ICMPERR;
712 			minicmpsz = ICMP6ERR_IPICMPHLEN - sizeof(ip6_t);
713 			break;
714 		default :
715 			break;
716 		}
717 	}
718 
719 	frpr_short6(fin, minicmpsz);
720 	fin->fin_flen -= fin->fin_dlen - minicmpsz;
721 }
722 
723 
724 /* ------------------------------------------------------------------------ */
725 /* Function:    frpr_udp6                                                   */
726 /* Returns:     void                                                        */
727 /* Parameters:  fin(I) - pointer to packet information                      */
728 /*                                                                          */
729 /* IPv6 Only                                                                */
730 /* Analyse the packet for IPv6/UDP properties.                              */
731 /* Is not expected to be called for fragmented packets.                     */
732 /* ------------------------------------------------------------------------ */
733 static INLINE void frpr_udp6(fin)
734 fr_info_t *fin;
735 {
736 
737 	fr_checkv6sum(fin);
738 
739 	frpr_short6(fin, sizeof(struct udphdr));
740 	if (frpr_pullup(fin, sizeof(struct udphdr)) == -1)
741 		return;
742 
743 	fin->fin_flen -= fin->fin_dlen - sizeof(struct udphdr);
744 
745 	frpr_udpcommon(fin);
746 }
747 
748 
749 /* ------------------------------------------------------------------------ */
750 /* Function:    frpr_tcp6                                                   */
751 /* Returns:     void                                                        */
752 /* Parameters:  fin(I) - pointer to packet information                      */
753 /*                                                                          */
754 /* IPv6 Only                                                                */
755 /* Analyse the packet for IPv6/TCP properties.                              */
756 /* Is not expected to be called for fragmented packets.                     */
757 /* ------------------------------------------------------------------------ */
758 static INLINE void frpr_tcp6(fin)
759 fr_info_t *fin;
760 {
761 
762 	fr_checkv6sum(fin);
763 
764 	frpr_short6(fin, sizeof(struct tcphdr));
765 	if (frpr_pullup(fin, sizeof(struct tcphdr)) == -1)
766 		return;
767 
768 	fin->fin_flen -= fin->fin_dlen - sizeof(struct tcphdr);
769 
770 	frpr_tcpcommon(fin);
771 }
772 
773 
774 /* ------------------------------------------------------------------------ */
775 /* Function:    frpr_esp6                                                   */
776 /* Returns:     void                                                        */
777 /* Parameters:  fin(I) - pointer to packet information                      */
778 /*                                                                          */
779 /* IPv6 Only                                                                */
780 /* Analyse the packet for ESP properties.                                   */
781 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits)  */
782 /* even though the newer ESP packets must also have a sequence number that  */
783 /* is 32bits as well, it is not possible(?) to determine the version from a */
784 /* simple packet header.                                                    */
785 /* ------------------------------------------------------------------------ */
786 static INLINE void frpr_esp6(fin)
787 fr_info_t *fin;
788 {
789 	int i;
790 	frpr_short6(fin, sizeof(grehdr_t));
791 
792 	(void) frpr_pullup(fin, 8);
793 
794 	for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
795 		if (ip6exthdr[i].ol_val == IPPROTO_ESP) {
796 			fin->fin_optmsk |= ip6exthdr[i].ol_bit;
797 			break;
798 		}
799 }
800 
801 
802 /* ------------------------------------------------------------------------ */
803 /* Function:    frpr_ah6                                                    */
804 /* Returns:     void                                                        */
805 /* Parameters:  fin(I) - pointer to packet information                      */
806 /*                                                                          */
807 /* IPv6 Only                                                                */
808 /* Analyse the packet for AH properties.                                    */
809 /* The minimum length is taken to be the combination of all fields in the   */
810 /* header being present and no authentication data (null algorithm used.)   */
811 /* ------------------------------------------------------------------------ */
812 static INLINE int frpr_ah6(fin)
813 fr_info_t *fin;
814 {
815 	authhdr_t *ah;
816 	int i, shift;
817 
818 	frpr_short6(fin, 12);
819 
820 	if (frpr_pullup(fin, sizeof(*ah)) == -1)
821 		return IPPROTO_NONE;
822 
823 	for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
824 		if (ip6exthdr[i].ol_val == IPPROTO_AH) {
825 			fin->fin_optmsk |= ip6exthdr[i].ol_bit;
826 			break;
827 		}
828 
829 	ah = (authhdr_t *)fin->fin_dp;
830 
831 	shift = (ah->ah_plen + 2) * 4;
832 	fin->fin_dlen -= shift;
833 	fin->fin_dp = (char*)fin->fin_dp + shift;
834 
835 	return ah->ah_next;
836 }
837 
838 
839 /* ------------------------------------------------------------------------ */
840 /* Function:    frpr_gre6                                                   */
841 /* Returns:     void                                                        */
842 /* Parameters:  fin(I) - pointer to packet information                      */
843 /*                                                                          */
844 /* Analyse the packet for GRE properties.                                   */
845 /* ------------------------------------------------------------------------ */
846 static INLINE void frpr_gre6(fin)
847 fr_info_t *fin;
848 {
849 	grehdr_t *gre;
850 
851 	frpr_short6(fin, sizeof(grehdr_t));
852 
853 	if (frpr_pullup(fin, sizeof(grehdr_t)) == -1)
854 		return;
855 
856 	gre = fin->fin_dp;
857 	if (GRE_REV(gre->gr_flags) == 1)
858 		fin->fin_data[0] = gre->gr_call;
859 }
860 #endif	/* USE_INET6 */
861 
862 
863 /* ------------------------------------------------------------------------ */
864 /* Function:    frpr_pullup                                                 */
865 /* Returns:     int     - 0 == pullup succeeded, -1 == failure              */
866 /* Parameters:  fin(I)  - pointer to packet information                     */
867 /*              plen(I) - length (excluding L3 header) to pullup            */
868 /*                                                                          */
869 /* Short inline function to cut down on code duplication to perform a call  */
870 /* to fr_pullup to ensure there is the required amount of data,             */
871 /* consecutively in the packet buffer.                                      */
872 /* ------------------------------------------------------------------------ */
873 static INLINE int frpr_pullup(fin, plen)
874 fr_info_t *fin;
875 int plen;
876 {
877 #if defined(_KERNEL)
878 	if (fin->fin_m != NULL) {
879 		if (fin->fin_dp != NULL)
880 			plen += (char *)fin->fin_dp -
881 				((char *)fin->fin_ip + fin->fin_hlen);
882 		plen += ((char *)fin->fin_ip - MTOD(fin->fin_m, char *)) +
883 		    fin->fin_hlen;
884 		if (M_LEN(fin->fin_m) < plen) {
885 			if (fr_pullup(fin->fin_m, fin, plen) == NULL)
886 				return -1;
887 		}
888 	}
889 #endif
890 	return 0;
891 }
892 
893 
894 /* ------------------------------------------------------------------------ */
895 /* Function:    frpr_short                                                  */
896 /* Returns:     void                                                        */
897 /* Parameters:  fin(I)  - pointer to packet information                     */
898 /*              xmin(I) - minimum header size                               */
899 /*                                                                          */
900 /* Check if a packet is "short" as defined by xmin.  The rule we are        */
901 /* applying here is that the packet must not be fragmented within the layer */
902 /* 4 header.  That is, it must not be a fragment that has its offset set to */
903 /* start within the layer 4 header (hdrmin) or if it is at offset 0, the    */
904 /* entire layer 4 header must be present (min).                             */
905 /* ------------------------------------------------------------------------ */
906 static INLINE void frpr_short(fin, xmin)
907 fr_info_t *fin;
908 int xmin;
909 {
910 
911 	if (fin->fin_off == 0) {
912 		if (fin->fin_dlen < xmin)
913 			fin->fin_flx |= FI_SHORT;
914 	} else if (fin->fin_off < xmin) {
915 		fin->fin_flx |= FI_SHORT;
916 	}
917 }
918 
919 
920 /* ------------------------------------------------------------------------ */
921 /* Function:    frpr_icmp                                                   */
922 /* Returns:     void                                                        */
923 /* Parameters:  fin(I) - pointer to packet information                      */
924 /*                                                                          */
925 /* IPv4 Only                                                                */
926 /* Do a sanity check on the packet for ICMP (v4).  In nearly all cases,     */
927 /* except extrememly bad packets, both type and code will be present.       */
928 /* The expected minimum size of an ICMP packet is very much dependent on    */
929 /* the type of it.                                                          */
930 /*                                                                          */
931 /* XXX - other ICMP sanity checks?                                          */
932 /* ------------------------------------------------------------------------ */
933 static INLINE void frpr_icmp(fin)
934 fr_info_t *fin;
935 {
936 	int minicmpsz = sizeof(struct icmp);
937 	icmphdr_t *icmp;
938 	ip_t *oip;
939 	ipf_stack_t *ifs = fin->fin_ifs;
940 
941 	if (fin->fin_off != 0) {
942 		frpr_short(fin, ICMPERR_ICMPHLEN);
943 		return;
944 	}
945 
946 	if (frpr_pullup(fin, ICMPERR_ICMPHLEN) == -1)
947 		return;
948 
949 	fr_checkv4sum(fin);
950 
951 	if (fin->fin_dlen > 1) {
952 		icmp = fin->fin_dp;
953 
954 		fin->fin_data[0] = *(u_short *)icmp;
955 
956 		switch (icmp->icmp_type)
957 		{
958 		case ICMP_ECHOREPLY :
959 		case ICMP_ECHO :
960 		/* Router discovery messaes - RFC 1256 */
961 		case ICMP_ROUTERADVERT :
962 		case ICMP_ROUTERSOLICIT :
963 			minicmpsz = ICMP_MINLEN;
964 			break;
965 		/*
966 		 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
967 		 * 3 * timestamp(3 * 4)
968 		 */
969 		case ICMP_TSTAMP :
970 		case ICMP_TSTAMPREPLY :
971 			minicmpsz = 20;
972 			break;
973 		/*
974 		 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
975 		 * mask(4)
976 		 */
977 		case ICMP_MASKREQ :
978 		case ICMP_MASKREPLY :
979 			minicmpsz = 12;
980 			break;
981 		/*
982 		 * type(1) + code(1) + cksum(2) + id(2) seq(2) + ip(20+)
983 		 */
984 		case ICMP_UNREACH :
985 			if (icmp->icmp_code == ICMP_UNREACH_NEEDFRAG) {
986 				if (icmp->icmp_nextmtu < ifs->ifs_fr_icmpminfragmtu)
987 					fin->fin_flx |= FI_BAD;
988 			}
989 			/* FALLTHRU */
990 		case ICMP_SOURCEQUENCH :
991 		case ICMP_REDIRECT :
992 		case ICMP_TIMXCEED :
993 		case ICMP_PARAMPROB :
994 			fin->fin_flx |= FI_ICMPERR;
995 			if (fr_coalesce(fin) != 1)
996 				return;
997 			/*
998 			 * ICMP error packets should not be generated for IP
999 			 * packets that are a fragment that isn't the first
1000 			 * fragment.
1001 			 */
1002 			oip = (ip_t *)((char *)fin->fin_dp + ICMPERR_ICMPHLEN);
1003 			if ((ntohs(oip->ip_off) & IP_OFFMASK) != 0)
1004 				fin->fin_flx |= FI_BAD;
1005 			break;
1006 		default :
1007 			break;
1008 		}
1009 
1010 		if (fin->fin_dlen >= 6)				/* ID field */
1011 			fin->fin_data[1] = icmp->icmp_id;
1012 	}
1013 
1014 	frpr_short(fin, minicmpsz);
1015 }
1016 
1017 
1018 /* ------------------------------------------------------------------------ */
1019 /* Function:    frpr_tcpcommon                                              */
1020 /* Returns:     void                                                        */
1021 /* Parameters:  fin(I) - pointer to packet information                      */
1022 /*                                                                          */
1023 /* TCP header sanity checking.  Look for bad combinations of TCP flags,     */
1024 /* and make some checks with how they interact with other fields.           */
1025 /* If compiled with IPFILTER_CKSUM, check to see if the TCP checksum is     */
1026 /* valid and mark the packet as bad if not.                                 */
1027 /* ------------------------------------------------------------------------ */
1028 static INLINE void frpr_tcpcommon(fin)
1029 fr_info_t *fin;
1030 {
1031 	int flags, tlen;
1032 	tcphdr_t *tcp;
1033 
1034 	fin->fin_flx |= FI_TCPUDP;
1035 	if (fin->fin_off != 0)
1036 		return;
1037 
1038 	if (frpr_pullup(fin, sizeof(*tcp)) == -1)
1039 		return;
1040 	tcp = fin->fin_dp;
1041 
1042 	if (fin->fin_dlen > 3) {
1043 		fin->fin_sport = ntohs(tcp->th_sport);
1044 		fin->fin_dport = ntohs(tcp->th_dport);
1045 	}
1046 
1047 	if ((fin->fin_flx & FI_SHORT) != 0)
1048 		return;
1049 
1050 	/*
1051 	 * Use of the TCP data offset *must* result in a value that is at
1052 	 * least the same size as the TCP header.
1053 	 */
1054 	tlen = TCP_OFF(tcp) << 2;
1055 	if (tlen < sizeof(tcphdr_t)) {
1056 		fin->fin_flx |= FI_BAD;
1057 		return;
1058 	}
1059 
1060 	flags = tcp->th_flags;
1061 	fin->fin_tcpf = tcp->th_flags;
1062 
1063 	/*
1064 	 * If the urgent flag is set, then the urgent pointer must
1065 	 * also be set and vice versa.  Good TCP packets do not have
1066 	 * just one of these set.
1067 	 */
1068 	if ((flags & TH_URG) != 0 && (tcp->th_urp == 0)) {
1069 		fin->fin_flx |= FI_BAD;
1070 	} else if ((flags & TH_URG) == 0 && (tcp->th_urp != 0)) {
1071 		/* Ignore this case, it shows up in "real" traffic with */
1072 		/* bogus values in the urgent pointer field. */
1073 		flags = flags; /* LINT */
1074 	} else if (((flags & (TH_SYN|TH_FIN)) != 0) &&
1075 		   ((flags & (TH_RST|TH_ACK)) == TH_RST)) {
1076 		/* TH_FIN|TH_RST|TH_ACK seems to appear "naturally" */
1077 		fin->fin_flx |= FI_BAD;
1078 	} else if (!(flags & TH_ACK)) {
1079 		/*
1080 		 * If the ack bit isn't set, then either the SYN or
1081 		 * RST bit must be set.  If the SYN bit is set, then
1082 		 * we expect the ACK field to be 0.  If the ACK is
1083 		 * not set and if URG, PSH or FIN are set, consdier
1084 		 * that to indicate a bad TCP packet.
1085 		 */
1086 		if ((flags == TH_SYN) && (tcp->th_ack != 0)) {
1087 			/*
1088 			 * Cisco PIX sets the ACK field to a random value.
1089 			 * In light of this, do not set FI_BAD until a patch
1090 			 * is available from Cisco to ensure that
1091 			 * interoperability between existing systems is
1092 			 * achieved.
1093 			 */
1094 			/*fin->fin_flx |= FI_BAD*/;
1095 			flags = flags; /* LINT */
1096 		} else if (!(flags & (TH_RST|TH_SYN))) {
1097 			fin->fin_flx |= FI_BAD;
1098 		} else if ((flags & (TH_URG|TH_PUSH|TH_FIN)) != 0) {
1099 			fin->fin_flx |= FI_BAD;
1100 		}
1101 	}
1102 
1103 	/*
1104 	 * At this point, it's not exactly clear what is to be gained by
1105 	 * marking up which TCP options are and are not present.  The one we
1106 	 * are most interested in is the TCP window scale.  This is only in
1107 	 * a SYN packet [RFC1323] so we don't need this here...?
1108 	 * Now if we were to analyse the header for passive fingerprinting,
1109 	 * then that might add some weight to adding this...
1110 	 */
1111 	if (tlen == sizeof(tcphdr_t))
1112 		return;
1113 
1114 	if (frpr_pullup(fin, tlen) == -1)
1115 		return;
1116 
1117 #if 0
1118 	ip = fin->fin_ip;
1119 	s = (u_char *)(tcp + 1);
1120 	off = IP_HL(ip) << 2;
1121 # ifdef _KERNEL
1122 	if (fin->fin_mp != NULL) {
1123 		mb_t *m = *fin->fin_mp;
1124 
1125 		if (off + tlen > M_LEN(m))
1126 			return;
1127 	}
1128 # endif
1129 	for (tlen -= (int)sizeof(*tcp); tlen > 0; ) {
1130 		opt = *s;
1131 		if (opt == '\0')
1132 			break;
1133 		else if (opt == TCPOPT_NOP)
1134 			ol = 1;
1135 		else {
1136 			if (tlen < 2)
1137 				break;
1138 			ol = (int)*(s + 1);
1139 			if (ol < 2 || ol > tlen)
1140 				break;
1141 		}
1142 
1143 		for (i = 9, mv = 4; mv >= 0; ) {
1144 			op = ipopts + i;
1145 			if (opt == (u_char)op->ol_val) {
1146 				optmsk |= op->ol_bit;
1147 				break;
1148 			}
1149 		}
1150 		tlen -= ol;
1151 		s += ol;
1152 	}
1153 #endif /* 0 */
1154 }
1155 
1156 
1157 
1158 /* ------------------------------------------------------------------------ */
1159 /* Function:    frpr_udpcommon                                              */
1160 /* Returns:     void                                                        */
1161 /* Parameters:  fin(I) - pointer to packet information                      */
1162 /*                                                                          */
1163 /* Extract the UDP source and destination ports, if present.  If compiled   */
1164 /* with IPFILTER_CKSUM, check to see if the UDP checksum is valid.          */
1165 /* ------------------------------------------------------------------------ */
1166 static INLINE void frpr_udpcommon(fin)
1167 fr_info_t *fin;
1168 {
1169 	udphdr_t *udp;
1170 
1171 	fin->fin_flx |= FI_TCPUDP;
1172 
1173 	if (!fin->fin_off && (fin->fin_dlen > 3)) {
1174 		if (frpr_pullup(fin, sizeof(*udp)) == -1) {
1175 			fin->fin_flx |= FI_SHORT;
1176 			return;
1177 		}
1178 
1179 		udp = fin->fin_dp;
1180 
1181 		fin->fin_sport = ntohs(udp->uh_sport);
1182 		fin->fin_dport = ntohs(udp->uh_dport);
1183 	}
1184 }
1185 
1186 
1187 /* ------------------------------------------------------------------------ */
1188 /* Function:    frpr_tcp                                                    */
1189 /* Returns:     void                                                        */
1190 /* Parameters:  fin(I) - pointer to packet information                      */
1191 /*                                                                          */
1192 /* IPv4 Only                                                                */
1193 /* Analyse the packet for IPv4/TCP properties.                              */
1194 /* ------------------------------------------------------------------------ */
1195 static INLINE void frpr_tcp(fin)
1196 fr_info_t *fin;
1197 {
1198 
1199 	fr_checkv4sum(fin);
1200 
1201 	frpr_short(fin, sizeof(tcphdr_t));
1202 
1203 	frpr_tcpcommon(fin);
1204 }
1205 
1206 
1207 /* ------------------------------------------------------------------------ */
1208 /* Function:    frpr_udp                                                    */
1209 /* Returns:     void                                                        */
1210 /* Parameters:  fin(I) - pointer to packet information                      */
1211 /*                                                                          */
1212 /* IPv4 Only                                                                */
1213 /* Analyse the packet for IPv4/UDP properties.                              */
1214 /* ------------------------------------------------------------------------ */
1215 static INLINE void frpr_udp(fin)
1216 fr_info_t *fin;
1217 {
1218 
1219 	fr_checkv4sum(fin);
1220 
1221 	frpr_short(fin, sizeof(udphdr_t));
1222 
1223 	frpr_udpcommon(fin);
1224 }
1225 
1226 
1227 /* ------------------------------------------------------------------------ */
1228 /* Function:    frpr_esp                                                    */
1229 /* Returns:     void                                                        */
1230 /* Parameters:  fin(I) - pointer to packet information                      */
1231 /*                                                                          */
1232 /* Analyse the packet for ESP properties.                                   */
1233 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits)  */
1234 /* even though the newer ESP packets must also have a sequence number that  */
1235 /* is 32bits as well, it is not possible(?) to determine the version from a */
1236 /* simple packet header.                                                    */
1237 /* ------------------------------------------------------------------------ */
1238 static INLINE void frpr_esp(fin)
1239 fr_info_t *fin;
1240 {
1241 	if ((fin->fin_off == 0) && (frpr_pullup(fin, 8) == -1))
1242 		return;
1243 
1244 	frpr_short(fin, 8);
1245 }
1246 
1247 
1248 /* ------------------------------------------------------------------------ */
1249 /* Function:    frpr_ah                                                     */
1250 /* Returns:     void                                                        */
1251 /* Parameters:  fin(I) - pointer to packet information                      */
1252 /*                                                                          */
1253 /* Analyse the packet for AH properties.                                    */
1254 /* The minimum length is taken to be the combination of all fields in the   */
1255 /* header being present and no authentication data (null algorithm used.)   */
1256 /* ------------------------------------------------------------------------ */
1257 static INLINE void frpr_ah(fin)
1258 fr_info_t *fin;
1259 {
1260 	authhdr_t *ah;
1261 	int len;
1262 
1263 	if ((fin->fin_off == 0) && (frpr_pullup(fin, sizeof(*ah)) == -1))
1264 		return;
1265 
1266 	ah = (authhdr_t *)fin->fin_dp;
1267 
1268 	len = (ah->ah_plen + 2) << 2;
1269 	frpr_short(fin, len);
1270 }
1271 
1272 
1273 /* ------------------------------------------------------------------------ */
1274 /* Function:    frpr_gre                                                    */
1275 /* Returns:     void                                                        */
1276 /* Parameters:  fin(I) - pointer to packet information                      */
1277 /*                                                                          */
1278 /* Analyse the packet for GRE properties.                                   */
1279 /* ------------------------------------------------------------------------ */
1280 static INLINE void frpr_gre(fin)
1281 fr_info_t *fin;
1282 {
1283 	grehdr_t *gre;
1284 
1285 	if ((fin->fin_off == 0) && (frpr_pullup(fin, sizeof(grehdr_t)) == -1))
1286 		return;
1287 
1288 	frpr_short(fin, sizeof(grehdr_t));
1289 
1290 	if (fin->fin_off == 0) {
1291 		gre = fin->fin_dp;
1292 		if (GRE_REV(gre->gr_flags) == 1)
1293 			fin->fin_data[0] = gre->gr_call;
1294 	}
1295 }
1296 
1297 
1298 /* ------------------------------------------------------------------------ */
1299 /* Function:    frpr_ipv4hdr                                                */
1300 /* Returns:     void                                                        */
1301 /* Parameters:  fin(I) - pointer to packet information                      */
1302 /*                                                                          */
1303 /* IPv4 Only                                                                */
1304 /* Analyze the IPv4 header and set fields in the fr_info_t structure.       */
1305 /* Check all options present and flag their presence if any exist.          */
1306 /* ------------------------------------------------------------------------ */
1307 static INLINE void frpr_ipv4hdr(fin)
1308 fr_info_t *fin;
1309 {
1310 	u_short optmsk = 0, secmsk = 0, auth = 0;
1311 	int hlen, ol, mv, p, i;
1312 	const struct optlist *op;
1313 	u_char *s, opt;
1314 	u_short off;
1315 	fr_ip_t *fi;
1316 	ip_t *ip;
1317 
1318 	fi = &fin->fin_fi;
1319 	hlen = fin->fin_hlen;
1320 
1321 	ip = fin->fin_ip;
1322 	p = ip->ip_p;
1323 	fi->fi_p = p;
1324 	fi->fi_tos = ip->ip_tos;
1325 	fin->fin_id = ip->ip_id;
1326 	off = ip->ip_off;
1327 
1328 	/* Get both TTL and protocol */
1329 	fi->fi_p = ip->ip_p;
1330 	fi->fi_ttl = ip->ip_ttl;
1331 #if 0
1332 	(*(((u_short *)fi) + 1)) = (*(((u_short *)ip) + 4));
1333 #endif
1334 
1335 	/* Zero out bits not used in IPv6 address */
1336 	fi->fi_src.i6[1] = 0;
1337 	fi->fi_src.i6[2] = 0;
1338 	fi->fi_src.i6[3] = 0;
1339 	fi->fi_dst.i6[1] = 0;
1340 	fi->fi_dst.i6[2] = 0;
1341 	fi->fi_dst.i6[3] = 0;
1342 
1343 	fi->fi_saddr = ip->ip_src.s_addr;
1344 	fi->fi_daddr = ip->ip_dst.s_addr;
1345 
1346 	/*
1347 	 * set packet attribute flags based on the offset and
1348 	 * calculate the byte offset that it represents.
1349 	 */
1350 	off &= IP_MF|IP_OFFMASK;
1351 	if (off != 0) {
1352 		fi->fi_flx |= FI_FRAG;
1353 		off &= IP_OFFMASK;
1354 		if (off != 0) {
1355 			fin->fin_flx |= FI_FRAGBODY;
1356 			off <<= 3;
1357 			if ((off + fin->fin_dlen > 65535) ||
1358 			    (fin->fin_dlen == 0) ||
1359 			    ((ip->ip_off & IP_MF) && (fin->fin_dlen & 7))) {
1360 				/*
1361 				 * The length of the packet, starting at its
1362 				 * offset cannot exceed 65535 (0xffff) as the
1363 				 * length of an IP packet is only 16 bits.
1364 				 *
1365 				 * Any fragment that isn't the last fragment
1366 				 * must have a length greater than 0 and it
1367 				 * must be an even multiple of 8.
1368 				 */
1369 				fi->fi_flx |= FI_BAD;
1370 			}
1371 		}
1372 	}
1373 	fin->fin_off = off;
1374 
1375 	/*
1376 	 * Call per-protocol setup and checking
1377 	 */
1378 	switch (p)
1379 	{
1380 	case IPPROTO_UDP :
1381 		frpr_udp(fin);
1382 		break;
1383 	case IPPROTO_TCP :
1384 		frpr_tcp(fin);
1385 		break;
1386 	case IPPROTO_ICMP :
1387 		frpr_icmp(fin);
1388 		break;
1389 	case IPPROTO_AH :
1390 		frpr_ah(fin);
1391 		break;
1392 	case IPPROTO_ESP :
1393 		frpr_esp(fin);
1394 		break;
1395 	case IPPROTO_GRE :
1396 		frpr_gre(fin);
1397 		break;
1398 	}
1399 
1400 	ip = fin->fin_ip;
1401 	if (ip == NULL)
1402 		return;
1403 
1404 	/*
1405 	 * If it is a standard IP header (no options), set the flag fields
1406 	 * which relate to options to 0.
1407 	 */
1408 	if (hlen == sizeof(*ip)) {
1409 		fi->fi_optmsk = 0;
1410 		fi->fi_secmsk = 0;
1411 		fi->fi_auth = 0;
1412 		return;
1413 	}
1414 
1415 	/*
1416 	 * So the IP header has some IP options attached.  Walk the entire
1417 	 * list of options present with this packet and set flags to indicate
1418 	 * which ones are here and which ones are not.  For the somewhat out
1419 	 * of date and obscure security classification options, set a flag to
1420 	 * represent which classification is present.
1421 	 */
1422 	fi->fi_flx |= FI_OPTIONS;
1423 
1424 	for (s = (u_char *)(ip + 1), hlen -= (int)sizeof(*ip); hlen > 0; ) {
1425 		opt = *s;
1426 		if (opt == '\0')
1427 			break;
1428 		else if (opt == IPOPT_NOP)
1429 			ol = 1;
1430 		else {
1431 			if (hlen < 2)
1432 				break;
1433 			ol = (int)*(s + 1);
1434 			if (ol < 2 || ol > hlen)
1435 				break;
1436 		}
1437 		for (i = 9, mv = 4; mv >= 0; ) {
1438 			op = ipopts + i;
1439 			if ((opt == (u_char)op->ol_val) && (ol > 4)) {
1440 				optmsk |= op->ol_bit;
1441 				if (opt == IPOPT_SECURITY) {
1442 					const struct optlist *sp;
1443 					u_char	sec;
1444 					int j, m;
1445 
1446 					sec = *(s + 2);	/* classification */
1447 					for (j = 3, m = 2; m >= 0; ) {
1448 						sp = secopt + j;
1449 						if (sec == sp->ol_val) {
1450 							secmsk |= sp->ol_bit;
1451 							auth = *(s + 3);
1452 							auth *= 256;
1453 							auth += *(s + 4);
1454 							break;
1455 						}
1456 						if (sec < sp->ol_val)
1457 							j -= m;
1458 						else
1459 							j += m;
1460 						m--;
1461 					}
1462 				}
1463 				break;
1464 			}
1465 			if (opt < op->ol_val)
1466 				i -= mv;
1467 			else
1468 				i += mv;
1469 			mv--;
1470 		}
1471 		hlen -= ol;
1472 		s += ol;
1473 	}
1474 
1475 	/*
1476 	 *
1477 	 */
1478 	if (auth && !(auth & 0x0100))
1479 		auth &= 0xff00;
1480 	fi->fi_optmsk = optmsk;
1481 	fi->fi_secmsk = secmsk;
1482 	fi->fi_auth = auth;
1483 }
1484 
1485 
1486 /* ------------------------------------------------------------------------ */
1487 /* Function:    fr_makefrip                                                 */
1488 /* Returns:     int - 1 == hdr checking error, 0 == OK                      */
1489 /* Parameters:  hlen(I) - length of IP packet header                        */
1490 /*              ip(I)   - pointer to the IP header                          */
1491 /*              fin(IO) - pointer to packet information                     */
1492 /*                                                                          */
1493 /* Compact the IP header into a structure which contains just the info.     */
1494 /* which is useful for comparing IP headers with and store this information */
1495 /* in the fr_info_t structure pointer to by fin.  At present, it is assumed */
1496 /* this function will be called with either an IPv4 or IPv6 packet.         */
1497 /* ------------------------------------------------------------------------ */
1498 int	fr_makefrip(hlen, ip, fin)
1499 int hlen;
1500 ip_t *ip;
1501 fr_info_t *fin;
1502 {
1503 	int v;
1504 
1505 	fin->fin_nat = NULL;
1506 	fin->fin_state = NULL;
1507 	fin->fin_depth = 0;
1508 	fin->fin_hlen = (u_short)hlen;
1509 	fin->fin_ip = ip;
1510 	fin->fin_rule = 0xffffffff;
1511 	fin->fin_group[0] = -1;
1512 	fin->fin_group[1] = '\0';
1513 	fin->fin_dlen = fin->fin_plen - hlen;
1514 	fin->fin_dp = (char *)ip + hlen;
1515 
1516 	v = fin->fin_v;
1517 	if (v == 4)
1518 		frpr_ipv4hdr(fin);
1519 #ifdef	USE_INET6
1520 	else if (v == 6) {
1521 		if (frpr_ipv6hdr(fin) == -1)
1522 			return -1;
1523 	}
1524 #endif
1525 	if (fin->fin_ip == NULL)
1526 		return -1;
1527 	return 0;
1528 }
1529 
1530 
1531 /* ------------------------------------------------------------------------ */
1532 /* Function:    fr_portcheck                                                */
1533 /* Returns:     int - 1 == port matched, 0 == port match failed             */
1534 /* Parameters:  frp(I) - pointer to port check `expression'                 */
1535 /*              pop(I) - pointer to port number to evaluate                 */
1536 /*                                                                          */
1537 /* Perform a comparison of a port number against some other(s), using a     */
1538 /* structure with compare information stored in it.                         */
1539 /* ------------------------------------------------------------------------ */
1540 static INLINE int fr_portcheck(frp, pop)
1541 frpcmp_t *frp;
1542 u_short *pop;
1543 {
1544 	u_short tup, po;
1545 	int err = 1;
1546 
1547 	tup = *pop;
1548 	po = frp->frp_port;
1549 
1550 	/*
1551 	 * Do opposite test to that required and continue if that succeeds.
1552 	 */
1553 	switch (frp->frp_cmp)
1554 	{
1555 	case FR_EQUAL :
1556 		if (tup != po) /* EQUAL */
1557 			err = 0;
1558 		break;
1559 	case FR_NEQUAL :
1560 		if (tup == po) /* NOTEQUAL */
1561 			err = 0;
1562 		break;
1563 	case FR_LESST :
1564 		if (tup >= po) /* LESSTHAN */
1565 			err = 0;
1566 		break;
1567 	case FR_GREATERT :
1568 		if (tup <= po) /* GREATERTHAN */
1569 			err = 0;
1570 		break;
1571 	case FR_LESSTE :
1572 		if (tup > po) /* LT or EQ */
1573 			err = 0;
1574 		break;
1575 	case FR_GREATERTE :
1576 		if (tup < po) /* GT or EQ */
1577 			err = 0;
1578 		break;
1579 	case FR_OUTRANGE :
1580 		if (tup >= po && tup <= frp->frp_top) /* Out of range */
1581 			err = 0;
1582 		break;
1583 	case FR_INRANGE :
1584 		if (tup <= po || tup >= frp->frp_top) /* In range */
1585 			err = 0;
1586 		break;
1587 	case FR_INCRANGE :
1588 		if (tup < po || tup > frp->frp_top) /* Inclusive range */
1589 			err = 0;
1590 		break;
1591 	default :
1592 		break;
1593 	}
1594 	return err;
1595 }
1596 
1597 
1598 /* ------------------------------------------------------------------------ */
1599 /* Function:    fr_tcpudpchk                                                */
1600 /* Returns:     int - 1 == protocol matched, 0 == check failed              */
1601 /* Parameters:  fin(I) - pointer to packet information                      */
1602 /*              ft(I)  - pointer to structure with comparison data          */
1603 /*                                                                          */
1604 /* Compares the current pcket (assuming it is TCP/UDP) information with a   */
1605 /* structure containing information that we want to match against.          */
1606 /* ------------------------------------------------------------------------ */
1607 int fr_tcpudpchk(fin, ft)
1608 fr_info_t *fin;
1609 frtuc_t *ft;
1610 {
1611 	int err = 1;
1612 
1613 	/*
1614 	 * Both ports should *always* be in the first fragment.
1615 	 * So far, I cannot find any cases where they can not be.
1616 	 *
1617 	 * compare destination ports
1618 	 */
1619 	if (ft->ftu_dcmp)
1620 		err = fr_portcheck(&ft->ftu_dst, &fin->fin_dport);
1621 
1622 	/*
1623 	 * compare source ports
1624 	 */
1625 	if (err && ft->ftu_scmp)
1626 		err = fr_portcheck(&ft->ftu_src, &fin->fin_sport);
1627 
1628 	/*
1629 	 * If we don't have all the TCP/UDP header, then how can we
1630 	 * expect to do any sort of match on it ?  If we were looking for
1631 	 * TCP flags, then NO match.  If not, then match (which should
1632 	 * satisfy the "short" class too).
1633 	 */
1634 	if (err && (fin->fin_p == IPPROTO_TCP)) {
1635 		if (fin->fin_flx & FI_SHORT)
1636 			return !(ft->ftu_tcpf | ft->ftu_tcpfm);
1637 		/*
1638 		 * Match the flags ?  If not, abort this match.
1639 		 */
1640 		if (ft->ftu_tcpfm &&
1641 		    ft->ftu_tcpf != (fin->fin_tcpf & ft->ftu_tcpfm)) {
1642 			FR_DEBUG(("f. %#x & %#x != %#x\n", fin->fin_tcpf,
1643 				 ft->ftu_tcpfm, ft->ftu_tcpf));
1644 			err = 0;
1645 		}
1646 	}
1647 	return err;
1648 }
1649 
1650 
1651 /* ------------------------------------------------------------------------ */
1652 /* Function:    fr_ipfcheck                                                 */
1653 /* Returns:     int - 0 == match, 1 == no match                             */
1654 /* Parameters:  fin(I)     - pointer to packet information                  */
1655 /*              fr(I)      - pointer to filter rule                         */
1656 /*              portcmp(I) - flag indicating whether to attempt matching on */
1657 /*                           TCP/UDP port data.                             */
1658 /*                                                                          */
1659 /* Check to see if a packet matches an IPFilter rule.  Checks of addresses, */
1660 /* port numbers, etc, for "standard" IPFilter rules are all orchestrated in */
1661 /* this function.                                                           */
1662 /* ------------------------------------------------------------------------ */
1663 static INLINE int fr_ipfcheck(fin, fr, portcmp)
1664 fr_info_t *fin;
1665 frentry_t *fr;
1666 int portcmp;
1667 {
1668 	u_32_t	*ld, *lm, *lip;
1669 	fripf_t *fri;
1670 	fr_ip_t *fi;
1671 	int i;
1672 	ipf_stack_t *ifs = fin->fin_ifs;
1673 
1674 	fi = &fin->fin_fi;
1675 	fri = fr->fr_ipf;
1676 	lip = (u_32_t *)fi;
1677 	lm = (u_32_t *)&fri->fri_mip;
1678 	ld = (u_32_t *)&fri->fri_ip;
1679 
1680 	/*
1681 	 * first 32 bits to check coversion:
1682 	 * IP version, TOS, TTL, protocol
1683 	 */
1684 	i = ((*lip & *lm) != *ld);
1685 	FR_DEBUG(("0. %#08x & %#08x != %#08x\n",
1686 		   *lip, *lm, *ld));
1687 	if (i)
1688 		return 1;
1689 
1690 	/*
1691 	 * Next 32 bits is a constructed bitmask indicating which IP options
1692 	 * are present (if any) in this packet.
1693 	 */
1694 	lip++, lm++, ld++;
1695 	i |= ((*lip & *lm) != *ld);
1696 	FR_DEBUG(("1. %#08x & %#08x != %#08x\n",
1697 		   *lip, *lm, *ld));
1698 	if (i)
1699 		return 1;
1700 
1701 	lip++, lm++, ld++;
1702 	/*
1703 	 * Unrolled loops (4 each, for 32 bits) for address checks.
1704 	 */
1705 	/*
1706 	 * Check the source address.
1707 	 */
1708 #ifdef	IPFILTER_LOOKUP
1709 	if (fr->fr_satype == FRI_LOOKUP) {
1710 		i = (*fr->fr_srcfunc)(fr->fr_srcptr, fi->fi_v, lip, ifs);
1711 		if (i == -1)
1712 			return 1;
1713 		lip += 3;
1714 		lm += 3;
1715 		ld += 3;
1716 	} else {
1717 #endif
1718 		i = ((*lip & *lm) != *ld);
1719 		FR_DEBUG(("2a. %#08x & %#08x != %#08x\n",
1720 			   *lip, *lm, *ld));
1721 		if (fi->fi_v == 6) {
1722 			lip++, lm++, ld++;
1723 			i |= ((*lip & *lm) != *ld);
1724 			FR_DEBUG(("2b. %#08x & %#08x != %#08x\n",
1725 				   *lip, *lm, *ld));
1726 			lip++, lm++, ld++;
1727 			i |= ((*lip & *lm) != *ld);
1728 			FR_DEBUG(("2c. %#08x & %#08x != %#08x\n",
1729 				   *lip, *lm, *ld));
1730 			lip++, lm++, ld++;
1731 			i |= ((*lip & *lm) != *ld);
1732 			FR_DEBUG(("2d. %#08x & %#08x != %#08x\n",
1733 				   *lip, *lm, *ld));
1734 		} else {
1735 			lip += 3;
1736 			lm += 3;
1737 			ld += 3;
1738 		}
1739 #ifdef	IPFILTER_LOOKUP
1740 	}
1741 #endif
1742 	i ^= (fr->fr_flags & FR_NOTSRCIP) >> 6;
1743 	if (i)
1744 		return 1;
1745 
1746 	/*
1747 	 * Check the destination address.
1748 	 */
1749 	lip++, lm++, ld++;
1750 #ifdef	IPFILTER_LOOKUP
1751 	if (fr->fr_datype == FRI_LOOKUP) {
1752 		i = (*fr->fr_dstfunc)(fr->fr_dstptr, fi->fi_v, lip, ifs);
1753 		if (i == -1)
1754 			return 1;
1755 		lip += 3;
1756 		lm += 3;
1757 		ld += 3;
1758 	} else {
1759 #endif
1760 		i = ((*lip & *lm) != *ld);
1761 		FR_DEBUG(("3a. %#08x & %#08x != %#08x\n",
1762 			   *lip, *lm, *ld));
1763 		if (fi->fi_v == 6) {
1764 			lip++, lm++, ld++;
1765 			i |= ((*lip & *lm) != *ld);
1766 			FR_DEBUG(("3b. %#08x & %#08x != %#08x\n",
1767 				   *lip, *lm, *ld));
1768 			lip++, lm++, ld++;
1769 			i |= ((*lip & *lm) != *ld);
1770 			FR_DEBUG(("3c. %#08x & %#08x != %#08x\n",
1771 				   *lip, *lm, *ld));
1772 			lip++, lm++, ld++;
1773 			i |= ((*lip & *lm) != *ld);
1774 			FR_DEBUG(("3d. %#08x & %#08x != %#08x\n",
1775 				   *lip, *lm, *ld));
1776 		} else {
1777 			lip += 3;
1778 			lm += 3;
1779 			ld += 3;
1780 		}
1781 #ifdef	IPFILTER_LOOKUP
1782 	}
1783 #endif
1784 	i ^= (fr->fr_flags & FR_NOTDSTIP) >> 7;
1785 	if (i)
1786 		return 1;
1787 	/*
1788 	 * IP addresses matched.  The next 32bits contains:
1789 	 * mast of old IP header security & authentication bits.
1790 	 */
1791 	lip++, lm++, ld++;
1792 	i |= ((*lip & *lm) != *ld);
1793 	FR_DEBUG(("4. %#08x & %#08x != %#08x\n",
1794 		   *lip, *lm, *ld));
1795 
1796 	/*
1797 	 * Next we have 32 bits of packet flags.
1798 	 */
1799 	lip++, lm++, ld++;
1800 	i |= ((*lip & *lm) != *ld);
1801 	FR_DEBUG(("5. %#08x & %#08x != %#08x\n",
1802 		   *lip, *lm, *ld));
1803 
1804 	if (i == 0) {
1805 		/*
1806 		 * If a fragment, then only the first has what we're
1807 		 * looking for here...
1808 		 */
1809 		if (portcmp) {
1810 			if (!fr_tcpudpchk(fin, &fr->fr_tuc))
1811 				i = 1;
1812 		} else {
1813 			if (fr->fr_dcmp || fr->fr_scmp ||
1814 			    fr->fr_tcpf || fr->fr_tcpfm)
1815 				i = 1;
1816 			if (fr->fr_icmpm || fr->fr_icmp) {
1817 				if (((fi->fi_p != IPPROTO_ICMP) &&
1818 				     (fi->fi_p != IPPROTO_ICMPV6)) ||
1819 				    fin->fin_off || (fin->fin_dlen < 2))
1820 					i = 1;
1821 				else if ((fin->fin_data[0] & fr->fr_icmpm) !=
1822 					 fr->fr_icmp) {
1823 					FR_DEBUG(("i. %#x & %#x != %#x\n",
1824 						 fin->fin_data[0],
1825 						 fr->fr_icmpm, fr->fr_icmp));
1826 					i = 1;
1827 				}
1828 			}
1829 		}
1830 	}
1831 	return i;
1832 }
1833 
1834 
1835 /* ------------------------------------------------------------------------ */
1836 /* Function:    fr_scanlist                                                 */
1837 /* Returns:     int - result flags of scanning filter list                  */
1838 /* Parameters:  fin(I) - pointer to packet information                      */
1839 /*              pass(I) - default result to return for filtering            */
1840 /*                                                                          */
1841 /* Check the input/output list of rules for a match to the current packet.  */
1842 /* If a match is found, the value of fr_flags from the rule becomes the     */
1843 /* return value and fin->fin_fr points to the matched rule.                 */
1844 /*                                                                          */
1845 /* This function may be called recusively upto 16 times (limit inbuilt.)    */
1846 /* When unwinding, it should finish up with fin_depth as 0.                 */
1847 /*                                                                          */
1848 /* Could be per interface, but this gets real nasty when you don't have,    */
1849 /* or can't easily change, the kernel source code to .                      */
1850 /* ------------------------------------------------------------------------ */
1851 int fr_scanlist(fin, pass)
1852 fr_info_t *fin;
1853 u_32_t pass;
1854 {
1855 	int rulen, portcmp, off, logged, skip;
1856 	struct frentry *fr, *fnext;
1857 	u_32_t passt, passo;
1858 	ipf_stack_t *ifs = fin->fin_ifs;
1859 
1860 	/*
1861 	 * Do not allow nesting deeper than 16 levels.
1862 	 */
1863 	if (fin->fin_depth >= 16)
1864 		return pass;
1865 
1866 	fr = fin->fin_fr;
1867 
1868 	/*
1869 	 * If there are no rules in this list, return now.
1870 	 */
1871 	if (fr == NULL)
1872 		return pass;
1873 
1874 	skip = 0;
1875 	logged = 0;
1876 	portcmp = 0;
1877 	fin->fin_depth++;
1878 	fin->fin_fr = NULL;
1879 	off = fin->fin_off;
1880 
1881 	if ((fin->fin_flx & FI_TCPUDP) && (fin->fin_dlen > 3) && !off)
1882 		portcmp = 1;
1883 
1884 	for (rulen = 0; fr; fr = fnext, rulen++) {
1885 		fnext = fr->fr_next;
1886 		if (skip != 0) {
1887 			FR_VERBOSE(("%d (%#x)\n", skip, fr->fr_flags));
1888 			skip--;
1889 			continue;
1890 		}
1891 
1892 		/*
1893 		 * In all checks below, a null (zero) value in the
1894 		 * filter struture is taken to mean a wildcard.
1895 		 *
1896 		 * check that we are working for the right interface
1897 		 */
1898 #ifdef	_KERNEL
1899 		if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
1900 			continue;
1901 #else
1902 		if (opts & (OPT_VERBOSE|OPT_DEBUG))
1903 			printf("\n");
1904 		FR_VERBOSE(("%c", FR_ISSKIP(pass) ? 's' :
1905 				  FR_ISPASS(pass) ? 'p' :
1906 				  FR_ISACCOUNT(pass) ? 'A' :
1907 				  FR_ISAUTH(pass) ? 'a' :
1908 				  (pass & FR_NOMATCH) ? 'n' :'b'));
1909 		if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
1910 			continue;
1911 		FR_VERBOSE((":i"));
1912 #endif
1913 
1914 		switch (fr->fr_type)
1915 		{
1916 		case FR_T_IPF :
1917 		case FR_T_IPF|FR_T_BUILTIN :
1918 			if (fr_ipfcheck(fin, fr, portcmp))
1919 				continue;
1920 			break;
1921 #if defined(IPFILTER_BPF)
1922 		case FR_T_BPFOPC :
1923 		case FR_T_BPFOPC|FR_T_BUILTIN :
1924 		    {
1925 			u_char *mc;
1926 
1927 			if (*fin->fin_mp == NULL)
1928 				continue;
1929 			if (fin->fin_v != fr->fr_v)
1930 				continue;
1931 			mc = (u_char *)fin->fin_m;
1932 			if (!bpf_filter(fr->fr_data, mc, fin->fin_plen, 0))
1933 				continue;
1934 			break;
1935 		    }
1936 #endif
1937 		case FR_T_CALLFUNC|FR_T_BUILTIN :
1938 		    {
1939 			frentry_t *f;
1940 
1941 			f = (*fr->fr_func)(fin, &pass);
1942 			if (f != NULL)
1943 				fr = f;
1944 			else
1945 				continue;
1946 			break;
1947 		    }
1948 		default :
1949 			break;
1950 		}
1951 
1952 		if ((fin->fin_out == 0) && (fr->fr_nattag.ipt_num[0] != 0)) {
1953 			if (fin->fin_nattag == NULL)
1954 				continue;
1955 			if (fr_matchtag(&fr->fr_nattag, fin->fin_nattag) == 0)
1956 				continue;
1957 		}
1958 		FR_VERBOSE(("=%s.%d *", fr->fr_group, rulen));
1959 
1960 		passt = fr->fr_flags;
1961 
1962 		/*
1963 		 * Allowing a rule with the "keep state" flag set to match
1964 		 * packets that have been tagged "out of window" by the TCP
1965 		 * state tracking is foolish as the attempt to add a new
1966 		 * state entry to the table will fail.
1967 		 */
1968 		if ((passt & FR_KEEPSTATE) && (fin->fin_flx & FI_OOW))
1969 			continue;
1970 
1971 		/*
1972 		 * If the rule is a "call now" rule, then call the function
1973 		 * in the rule, if it exists and use the results from that.
1974 		 * If the function pointer is bad, just make like we ignore
1975 		 * it, except for increasing the hit counter.
1976 		 */
1977 		if ((passt & FR_CALLNOW) != 0) {
1978 			ATOMIC_INC64(fr->fr_hits);
1979 			if ((fr->fr_func != NULL) &&
1980 			    (fr->fr_func != (ipfunc_t)-1)) {
1981 				frentry_t *frs;
1982 
1983 				frs = fin->fin_fr;
1984 				fin->fin_fr = fr;
1985 				fr = (*fr->fr_func)(fin, &passt);
1986 				if (fr == NULL) {
1987 					fin->fin_fr = frs;
1988 					continue;
1989 				}
1990 				passt = fr->fr_flags;
1991 				fin->fin_fr = fr;
1992 			}
1993 		} else {
1994 			fin->fin_fr = fr;
1995 		}
1996 
1997 #ifdef  IPFILTER_LOG
1998 		/*
1999 		 * Just log this packet...
2000 		 */
2001 		if ((passt & FR_LOGMASK) == FR_LOG) {
2002 			if (ipflog(fin, passt) == -1) {
2003 				if (passt & FR_LOGORBLOCK) {
2004 					passt &= ~FR_CMDMASK;
2005 					passt |= FR_BLOCK|FR_QUICK;
2006 				}
2007 				ATOMIC_INCL(ifs->ifs_frstats[fin->fin_out].fr_skip);
2008 			}
2009 			ATOMIC_INCL(ifs->ifs_frstats[fin->fin_out].fr_pkl);
2010 			logged = 1;
2011 		}
2012 #endif /* IPFILTER_LOG */
2013 		fr->fr_bytes += (U_QUAD_T)fin->fin_plen;
2014 		passo = pass;
2015 		if (FR_ISSKIP(passt))
2016 			skip = fr->fr_arg;
2017 		else if ((passt & FR_LOGMASK) != FR_LOG)
2018 			pass = passt;
2019 		if (passt & (FR_RETICMP|FR_FAKEICMP))
2020 			fin->fin_icode = fr->fr_icode;
2021 		FR_DEBUG(("pass %#x\n", pass));
2022 		ATOMIC_INC64(fr->fr_hits);
2023 		fin->fin_rule = rulen;
2024 		(void) strncpy(fin->fin_group, fr->fr_group, FR_GROUPLEN);
2025 		if (fr->fr_grp != NULL) {
2026 			fin->fin_fr = *fr->fr_grp;
2027 			pass = fr_scanlist(fin, pass);
2028 			if (fin->fin_fr == NULL) {
2029 				fin->fin_rule = rulen;
2030 				(void) strncpy(fin->fin_group, fr->fr_group,
2031 					       FR_GROUPLEN);
2032 				fin->fin_fr = fr;
2033 			}
2034 			if (fin->fin_flx & FI_DONTCACHE)
2035 				logged = 1;
2036 		}
2037 
2038 		if (pass & FR_QUICK) {
2039 			/*
2040 			 * Finally, if we've asked to track state for this
2041 			 * packet, set it up.  Add state for "quick" rules
2042 			 * here so that if the action fails we can consider
2043 			 * the rule to "not match" and keep on processing
2044 			 * filter rules.
2045 			 */
2046 			if ((pass & FR_KEEPSTATE) &&
2047 			    !(fin->fin_flx & FI_STATE)) {
2048 				int out = fin->fin_out;
2049 
2050 				if (fr_addstate(fin, NULL, 0) != NULL) {
2051 					ATOMIC_INCL(ifs->ifs_frstats[out].fr_ads);
2052 				} else {
2053 					ATOMIC_INCL(ifs->ifs_frstats[out].fr_bads);
2054 					pass = passo;
2055 					continue;
2056 				}
2057 			}
2058 			break;
2059 		}
2060 	}
2061 	if (logged)
2062 		fin->fin_flx |= FI_DONTCACHE;
2063 	fin->fin_depth--;
2064 	return pass;
2065 }
2066 
2067 
2068 /* ------------------------------------------------------------------------ */
2069 /* Function:    fr_acctpkt                                                  */
2070 /* Returns:     frentry_t* - always returns NULL                            */
2071 /* Parameters:  fin(I) - pointer to packet information                      */
2072 /*              passp(IO) - pointer to current/new filter decision (unused) */
2073 /*                                                                          */
2074 /* Checks a packet against accounting rules, if there are any for the given */
2075 /* IP protocol version.                                                     */
2076 /*                                                                          */
2077 /* N.B.: this function returns NULL to match the prototype used by other    */
2078 /* functions called from the IPFilter "mainline" in fr_check().             */
2079 /* ------------------------------------------------------------------------ */
2080 frentry_t *fr_acctpkt(fin, passp)
2081 fr_info_t *fin;
2082 u_32_t *passp;
2083 {
2084 	char group[FR_GROUPLEN];
2085 	frentry_t *fr, *frsave;
2086 	u_32_t pass, rulen;
2087 	ipf_stack_t *ifs = fin->fin_ifs;
2088 
2089 	passp = passp;
2090 #ifdef	USE_INET6
2091 	if (fin->fin_v == 6)
2092 		fr = ifs->ifs_ipacct6[fin->fin_out][ifs->ifs_fr_active];
2093 	else
2094 #endif
2095 		fr = ifs->ifs_ipacct[fin->fin_out][ifs->ifs_fr_active];
2096 
2097 	if (fr != NULL) {
2098 		frsave = fin->fin_fr;
2099 		bcopy(fin->fin_group, group, FR_GROUPLEN);
2100 		rulen = fin->fin_rule;
2101 		fin->fin_fr = fr;
2102 		pass = fr_scanlist(fin, FR_NOMATCH);
2103 		if (FR_ISACCOUNT(pass)) {
2104 			ATOMIC_INCL(ifs->ifs_frstats[0].fr_acct);
2105 		}
2106 		fin->fin_fr = frsave;
2107 		bcopy(group, fin->fin_group, FR_GROUPLEN);
2108 		fin->fin_rule = rulen;
2109 	}
2110 	return NULL;
2111 }
2112 
2113 
2114 /* ------------------------------------------------------------------------ */
2115 /* Function:    fr_firewall                                                 */
2116 /* Returns:     frentry_t* - returns pointer to matched rule, if no matches */
2117 /*                           were found, returns NULL.                      */
2118 /* Parameters:  fin(I) - pointer to packet information                      */
2119 /*              passp(IO) - pointer to current/new filter decision (unused) */
2120 /*                                                                          */
2121 /* Applies an appropriate set of firewall rules to the packet, to see if    */
2122 /* there are any matches.  The first check is to see if a match can be seen */
2123 /* in the cache.  If not, then search an appropriate list of rules.  Once a */
2124 /* matching rule is found, take any appropriate actions as defined by the   */
2125 /* rule - except logging.                                                   */
2126 /* ------------------------------------------------------------------------ */
2127 static frentry_t *fr_firewall(fin, passp)
2128 fr_info_t *fin;
2129 u_32_t *passp;
2130 {
2131 	frentry_t *fr;
2132 	fr_info_t *fc;
2133 	u_32_t pass;
2134 	int out;
2135 	ipf_stack_t *ifs = fin->fin_ifs;
2136 
2137 	out = fin->fin_out;
2138 	pass = *passp;
2139 
2140 	/*
2141 	 * If a packet is found in the auth table, then skip checking
2142 	 * the access lists for permission but we do need to consider
2143 	 * the result as if it were from the ACL's.
2144 	 */
2145 	fc = &ifs->ifs_frcache[out][CACHE_HASH(fin)];
2146 	READ_ENTER(&ifs->ifs_ipf_frcache);
2147 	if (!bcmp((char *)fin, (char *)fc, FI_CSIZE)) {
2148 		/*
2149 		 * copy cached data so we can unlock the mutexes earlier.
2150 		 */
2151 		bcopy((char *)fc, (char *)fin, FI_COPYSIZE);
2152 		RWLOCK_EXIT(&ifs->ifs_ipf_frcache);
2153 		ATOMIC_INCL(ifs->ifs_frstats[out].fr_chit);
2154 
2155 		if ((fr = fin->fin_fr) != NULL) {
2156 			ATOMIC_INC64(fr->fr_hits);
2157 			pass = fr->fr_flags;
2158 		}
2159 	} else {
2160 		RWLOCK_EXIT(&ifs->ifs_ipf_frcache);
2161 
2162 #ifdef	USE_INET6
2163 		if (fin->fin_v == 6)
2164 			fin->fin_fr = ifs->ifs_ipfilter6[out][ifs->ifs_fr_active];
2165 		else
2166 #endif
2167 			fin->fin_fr = ifs->ifs_ipfilter[out][ifs->ifs_fr_active];
2168 		if (fin->fin_fr != NULL)
2169 			pass = fr_scanlist(fin, ifs->ifs_fr_pass);
2170 
2171 		if (((pass & FR_KEEPSTATE) == 0) &&
2172 		    ((fin->fin_flx & FI_DONTCACHE) == 0)) {
2173 			WRITE_ENTER(&ifs->ifs_ipf_frcache);
2174 			bcopy((char *)fin, (char *)fc, FI_COPYSIZE);
2175 			RWLOCK_EXIT(&ifs->ifs_ipf_frcache);
2176 		}
2177 		if ((pass & FR_NOMATCH)) {
2178 			ATOMIC_INCL(ifs->ifs_frstats[out].fr_nom);
2179 		}
2180 		fr = fin->fin_fr;
2181 	}
2182 
2183 	/*
2184 	 * Apply packets per second rate-limiting to a rule as required.
2185 	 */
2186 	if ((fr != NULL) && (fr->fr_pps != 0) &&
2187 	    !ppsratecheck(&fr->fr_lastpkt, &fr->fr_curpps, fr->fr_pps)) {
2188 		pass &= ~(FR_CMDMASK|FR_DUP|FR_RETICMP|FR_RETRST);
2189 		pass |= FR_BLOCK;
2190 		ATOMIC_INCL(ifs->ifs_frstats[out].fr_ppshit);
2191 	}
2192 
2193 	/*
2194 	 * If we fail to add a packet to the authorization queue, then we
2195 	 * drop the packet later.  However, if it was added then pretend
2196 	 * we've dropped it already.
2197 	 */
2198 	if (FR_ISAUTH(pass)) {
2199 		if (fr_newauth(fin->fin_m, fin) != 0) {
2200 #ifdef	_KERNEL
2201 			fin->fin_m = *fin->fin_mp = NULL;
2202 #else
2203 			;
2204 #endif
2205 			fin->fin_error = 0;
2206 		} else
2207 			fin->fin_error = ENOSPC;
2208 	}
2209 
2210 	if ((fr != NULL) && (fr->fr_func != NULL) &&
2211 	    (fr->fr_func != (ipfunc_t)-1) && !(pass & FR_CALLNOW))
2212 		(void) (*fr->fr_func)(fin, &pass);
2213 
2214 	/*
2215 	 * If a rule is a pre-auth rule, check again in the list of rules
2216 	 * loaded for authenticated use.  It does not particulary matter
2217 	 * if this search fails because a "preauth" result, from a rule,
2218 	 * is treated as "not a pass", hence the packet is blocked.
2219 	 */
2220 	if (FR_ISPREAUTH(pass)) {
2221 		if ((fin->fin_fr = ifs->ifs_ipauth) != NULL)
2222 			pass = fr_scanlist(fin, ifs->ifs_fr_pass);
2223 	}
2224 
2225 	/*
2226 	 * If the rule has "keep frag" and the packet is actually a fragment,
2227 	 * then create a fragment state entry.
2228 	 */
2229 	if ((pass & (FR_KEEPFRAG|FR_KEEPSTATE)) == FR_KEEPFRAG) {
2230 		if (fin->fin_flx & FI_FRAG) {
2231 			if (fr_newfrag(fin, pass) == -1) {
2232 				ATOMIC_INCL(ifs->ifs_frstats[out].fr_bnfr);
2233 			} else {
2234 				ATOMIC_INCL(ifs->ifs_frstats[out].fr_nfr);
2235 			}
2236 		} else {
2237 			ATOMIC_INCL(ifs->ifs_frstats[out].fr_cfr);
2238 		}
2239 	}
2240 
2241 	/*
2242 	 * Finally, if we've asked to track state for this packet, set it up.
2243 	 */
2244 	if ((pass & FR_KEEPSTATE) && !(fin->fin_flx & FI_STATE)) {
2245 		if (fr_addstate(fin, NULL, 0) != NULL) {
2246 			ATOMIC_INCL(ifs->ifs_frstats[out].fr_ads);
2247 		} else {
2248 			ATOMIC_INCL(ifs->ifs_frstats[out].fr_bads);
2249 			if (FR_ISPASS(pass)) {
2250 				pass &= ~FR_CMDMASK;
2251 				pass |= FR_BLOCK;
2252 			}
2253 		}
2254 	}
2255 
2256 	fr = fin->fin_fr;
2257 
2258 	if (passp != NULL)
2259 		*passp = pass;
2260 
2261 	return fr;
2262 }
2263 
2264 
2265 /* ------------------------------------------------------------------------ */
2266 /* Function:    fr_check                                                    */
2267 /* Returns:     int -  0 == packet allowed through,                         */
2268 /*              User space:                                                 */
2269 /*                    -1 == packet blocked                                  */
2270 /*                     1 == packet not matched                              */
2271 /*                    -2 == requires authentication                         */
2272 /*              Kernel:                                                     */
2273 /*                   > 0 == filter error # for packet                       */
2274 /* Parameters: ip(I)   - pointer to start of IPv4/6 packet                  */
2275 /*             hlen(I) - length of header                                   */
2276 /*             ifp(I)  - pointer to interface this packet is on             */
2277 /*             out(I)  - 0 == packet going in, 1 == packet going out        */
2278 /*             mp(IO)  - pointer to caller's buffer pointer that holds this */
2279 /*                       IP packet.                                         */
2280 /* Solaris & HP-UX ONLY :                                                   */
2281 /*             qpi(I)  - pointer to STREAMS queue information for this      */
2282 /*                       interface & direction.                             */
2283 /*                                                                          */
2284 /* fr_check() is the master function for all IPFilter packet processing.    */
2285 /* It orchestrates: Network Address Translation (NAT), checking for packet  */
2286 /* authorisation (or pre-authorisation), presence of related state info.,   */
2287 /* generating log entries, IP packet accounting, routing of packets as      */
2288 /* directed by firewall rules and of course whether or not to allow the     */
2289 /* packet to be further processed by the kernel.                            */
2290 /*                                                                          */
2291 /* For packets blocked, the contents of "mp" will be NULL'd and the buffer  */
2292 /* freed.  Packets passed may be returned with the pointer pointed to by    */
2293 /* by "mp" changed to a new buffer.                                         */
2294 /* ------------------------------------------------------------------------ */
2295 int fr_check(ip, hlen, ifp, out
2296 #if defined(_KERNEL) && defined(MENTAT)
2297 , qif, mp, ifs)
2298 void *qif;
2299 #else
2300 , mp, ifs)
2301 #endif
2302 mb_t **mp;
2303 ip_t *ip;
2304 int hlen;
2305 void *ifp;
2306 int out;
2307 ipf_stack_t *ifs;
2308 {
2309 	/*
2310 	 * The above really sucks, but short of writing a diff
2311 	 */
2312 	fr_info_t frinfo;
2313 	fr_info_t *fin = &frinfo;
2314 	u_32_t pass;
2315 	frentry_t *fr = NULL;
2316 	int v = IP_V(ip);
2317 	mb_t *mc = NULL;
2318 	mb_t *m;
2319 #ifdef USE_INET6
2320 	ip6_t *ip6;
2321 #endif
2322 #ifdef	_KERNEL
2323 # ifdef MENTAT
2324 	qpktinfo_t *qpi = qif;
2325 #endif
2326 #endif
2327 
2328 	SPL_INT(s);
2329 	pass = ifs->ifs_fr_pass;
2330 
2331 	/*
2332 	 * The first part of fr_check() deals with making sure that what goes
2333 	 * into the filtering engine makes some sense.  Information about the
2334 	 * the packet is distilled, collected into a fr_info_t structure and
2335 	 * the an attempt to ensure the buffer the packet is in is big enough
2336 	 * to hold all the required packet headers.
2337 	 */
2338 #ifdef	_KERNEL
2339 # ifdef MENTAT
2340 	if (!OK_32PTR(ip))
2341 		return 2;
2342 # endif
2343 
2344 	READ_ENTER(&ifs->ifs_ipf_global);
2345 
2346 	if (ifs->ifs_fr_running <= 0) {
2347 		RWLOCK_EXIT(&ifs->ifs_ipf_global);
2348 		return 0;
2349 	}
2350 
2351 	bzero((char *)fin, sizeof(*fin));
2352 
2353 # ifdef MENTAT
2354 	fin->fin_flx = qpi->qpi_flags & (FI_NOCKSUM|FI_MBCAST|FI_MULTICAST|
2355 					 FI_BROADCAST);
2356 	m = qpi->qpi_m;
2357 	fin->fin_qfm = m;
2358 	fin->fin_qpi = qpi;
2359 # else /* MENTAT */
2360 
2361 	m = *mp;
2362 
2363 #  if defined(M_MCAST)
2364 	if ((m->m_flags & M_MCAST) != 0)
2365 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2366 #  endif
2367 #  if defined(M_MLOOP)
2368 	if ((m->m_flags & M_MLOOP) != 0)
2369 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2370 #  endif
2371 #  if defined(M_BCAST)
2372 	if ((m->m_flags & M_BCAST) != 0)
2373 		fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2374 #  endif
2375 #  ifdef M_CANFASTFWD
2376 	/*
2377 	 * XXX For now, IP Filter and fast-forwarding of cached flows
2378 	 * XXX are mutually exclusive.  Eventually, IP Filter should
2379 	 * XXX get a "can-fast-forward" filter rule.
2380 	 */
2381 	m->m_flags &= ~M_CANFASTFWD;
2382 #  endif /* M_CANFASTFWD */
2383 #  ifdef CSUM_DELAY_DATA
2384 	/*
2385 	 * disable delayed checksums.
2386 	 */
2387 	if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2388 		in_delayed_cksum(m);
2389 		m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2390 	}
2391 #  endif /* CSUM_DELAY_DATA */
2392 # endif /* MENTAT */
2393 #else
2394 	READ_ENTER(&ifs->ifs_ipf_global);
2395 
2396 	bzero((char *)fin, sizeof(*fin));
2397 	m = *mp;
2398 #endif /* _KERNEL */
2399 
2400 	fin->fin_v = v;
2401 	fin->fin_m = m;
2402 	fin->fin_ip = ip;
2403 	fin->fin_mp = mp;
2404 	fin->fin_out = out;
2405 	fin->fin_ifp = ifp;
2406 	fin->fin_error = ENETUNREACH;
2407 	fin->fin_hlen = (u_short)hlen;
2408 	fin->fin_dp = (char *)ip + hlen;
2409 	fin->fin_ipoff = (char *)ip - MTOD(m, char *);
2410 	fin->fin_ifs = ifs;
2411 
2412 	SPL_NET(s);
2413 
2414 #ifdef	USE_INET6
2415 	if (v == 6) {
2416 		ATOMIC_INCL(ifs->ifs_frstats[out].fr_ipv6);
2417 		/*
2418 		 * Jumbo grams are quite likely too big for internal buffer
2419 		 * structures to handle comfortably, for now, so just drop
2420 		 * them.
2421 		 */
2422 		ip6 = (ip6_t *)ip;
2423 		fin->fin_plen = ntohs(ip6->ip6_plen);
2424 		if (fin->fin_plen == 0) {
2425 			READ_ENTER(&ifs->ifs_ipf_mutex);
2426 			pass = FR_BLOCK|FR_NOMATCH;
2427 			goto filtered;
2428 		}
2429 		fin->fin_plen += sizeof(ip6_t);
2430 	} else
2431 #endif
2432 	{
2433 #if (OpenBSD >= 200311) && defined(_KERNEL)
2434 		ip->ip_len = ntohs(ip->ip_len);
2435 		ip->ip_off = ntohs(ip->ip_off);
2436 #endif
2437 		fin->fin_plen = ip->ip_len;
2438 	}
2439 
2440 	if (fr_makefrip(hlen, ip, fin) == -1) {
2441 		READ_ENTER(&ifs->ifs_ipf_mutex);
2442 		pass = FR_BLOCK;
2443 		goto filtered;
2444 	}
2445 
2446 	/*
2447 	 * For at least IPv6 packets, if a m_pullup() fails then this pointer
2448 	 * becomes NULL and so we have no packet to free.
2449 	 */
2450 	if (*fin->fin_mp == NULL)
2451 		goto finished;
2452 
2453 	if (!out) {
2454 		if (v == 4) {
2455 #ifdef _KERNEL
2456 			if (ifs->ifs_fr_chksrc && !fr_verifysrc(fin)) {
2457 				ATOMIC_INCL(ifs->ifs_frstats[0].fr_badsrc);
2458 				fin->fin_flx |= FI_BADSRC;
2459 			}
2460 #endif
2461 			if (fin->fin_ip->ip_ttl < ifs->ifs_fr_minttl) {
2462 				ATOMIC_INCL(ifs->ifs_frstats[0].fr_badttl);
2463 				fin->fin_flx |= FI_LOWTTL;
2464 			}
2465 		}
2466 #ifdef USE_INET6
2467 		else  if (v == 6) {
2468 			ip6 = (ip6_t *)ip;
2469 #ifdef _KERNEL
2470 			if (ifs->ifs_fr_chksrc && !fr_verifysrc(fin)) {
2471 				ATOMIC_INCL(ifs->ifs_frstats[0].fr_badsrc);
2472 				fin->fin_flx |= FI_BADSRC;
2473 			}
2474 #endif
2475 			if (ip6->ip6_hlim < ifs->ifs_fr_minttl) {
2476 				ATOMIC_INCL(ifs->ifs_frstats[0].fr_badttl);
2477 				fin->fin_flx |= FI_LOWTTL;
2478 			}
2479 		}
2480 #endif
2481 	}
2482 
2483 	if (fin->fin_flx & FI_SHORT) {
2484 		ATOMIC_INCL(ifs->ifs_frstats[out].fr_short);
2485 	}
2486 
2487 	READ_ENTER(&ifs->ifs_ipf_mutex);
2488 
2489 	/*
2490 	 * Check auth now.  This, combined with the check below to see if apass
2491 	 * is 0 is to ensure that we don't count the packet twice, which can
2492 	 * otherwise occur when we reprocess it.  As it is, we only count it
2493 	 * after it has no auth. table matchup.  This also stops NAT from
2494 	 * occuring until after the packet has been auth'd.
2495 	 */
2496 	fr = fr_checkauth(fin, &pass);
2497 	if (!out) {
2498 		if (fr_checknatin(fin, &pass) == -1) {
2499 			RWLOCK_EXIT(&ifs->ifs_ipf_mutex);
2500 			goto finished;
2501 		}
2502 	}
2503 	if (!out)
2504 		(void) fr_acctpkt(fin, NULL);
2505 
2506 	if (fr == NULL)
2507 		if ((fin->fin_flx & (FI_FRAG|FI_BAD)) == FI_FRAG)
2508 			fr = fr_knownfrag(fin, &pass);
2509 	if (fr == NULL)
2510 		fr = fr_checkstate(fin, &pass);
2511 
2512 	if ((pass & FR_NOMATCH) || (fr == NULL))
2513 		fr = fr_firewall(fin, &pass);
2514 
2515 	fin->fin_fr = fr;
2516 
2517 	/*
2518 	 * Only count/translate packets which will be passed on, out the
2519 	 * interface.
2520 	 */
2521 	if (out && FR_ISPASS(pass)) {
2522 		(void) fr_acctpkt(fin, NULL);
2523 
2524 		if (fr_checknatout(fin, &pass) == -1) {
2525 			RWLOCK_EXIT(&ifs->ifs_ipf_mutex);
2526 			goto finished;
2527 		} else if ((ifs->ifs_fr_update_ipid != 0) && (v == 4)) {
2528 			if (fr_updateipid(fin) == -1) {
2529 				ATOMIC_INCL(ifs->ifs_frstats[1].fr_ipud);
2530 				pass &= ~FR_CMDMASK;
2531 				pass |= FR_BLOCK;
2532 			} else {
2533 				ATOMIC_INCL(ifs->ifs_frstats[0].fr_ipud);
2534 			}
2535 		}
2536 	}
2537 
2538 #ifdef	IPFILTER_LOG
2539 	if ((ifs->ifs_fr_flags & FF_LOGGING) || (pass & FR_LOGMASK)) {
2540 		(void) fr_dolog(fin, &pass);
2541 	}
2542 #endif
2543 
2544 	if (fin->fin_state != NULL)
2545 		fr_statederef((ipstate_t **)&fin->fin_state, ifs);
2546 
2547 	if (fin->fin_nat != NULL)
2548 		fr_natderef((nat_t **)&fin->fin_nat, ifs);
2549 
2550 	/*
2551 	 * Only allow FR_DUP to work if a rule matched - it makes no sense to
2552 	 * set FR_DUP as a "default" as there are no instructions about where
2553 	 * to send the packet.  Use fin_m here because it may have changed
2554 	 * (without an update of 'm') in prior processing.
2555 	 */
2556 	if ((fr != NULL) && (pass & FR_DUP)) {
2557 		mc = M_DUPLICATE(fin->fin_m);
2558 	}
2559 
2560 	if (pass & (FR_RETRST|FR_RETICMP)) {
2561 		/*
2562 		 * Should we return an ICMP packet to indicate error
2563 		 * status passing through the packet filter ?
2564 		 * WARNING: ICMP error packets AND TCP RST packets should
2565 		 * ONLY be sent in repsonse to incoming packets.  Sending them
2566 		 * in response to outbound packets can result in a panic on
2567 		 * some operating systems.
2568 		 */
2569 		if (!out) {
2570 			if (pass & FR_RETICMP) {
2571 				int dst;
2572 
2573 				if ((pass & FR_RETMASK) == FR_FAKEICMP)
2574 					dst = 1;
2575 				else
2576 					dst = 0;
2577 				(void) fr_send_icmp_err(ICMP_UNREACH, fin, dst);
2578 				ATOMIC_INCL(ifs->ifs_frstats[0].fr_ret);
2579 			} else if (((pass & FR_RETMASK) == FR_RETRST) &&
2580 				   !(fin->fin_flx & FI_SHORT)) {
2581 				if (fr_send_reset(fin) == 0) {
2582 					ATOMIC_INCL(ifs->ifs_frstats[1].fr_ret);
2583 				}
2584 			}
2585 		} else {
2586 			if (pass & FR_RETRST)
2587 				fin->fin_error = ECONNRESET;
2588 		}
2589 	}
2590 
2591 	/*
2592 	 * If we didn't drop off the bottom of the list of rules (and thus
2593 	 * the 'current' rule fr is not NULL), then we may have some extra
2594 	 * instructions about what to do with a packet.
2595 	 * Once we're finished return to our caller, freeing the packet if
2596 	 * we are dropping it (* BSD ONLY *).
2597 	 * Reassign m from fin_m as we may have a new buffer, now.
2598 	 */
2599 filtered:
2600 	m = fin->fin_m;
2601 
2602 	if (fr != NULL) {
2603 		frdest_t *fdp;
2604 
2605 		fdp = &fr->fr_tifs[fin->fin_rev];
2606 
2607 		if (!out && (pass & FR_FASTROUTE)) {
2608 			/*
2609 			 * For fastroute rule, no destioation interface defined
2610 			 * so pass NULL as the frdest_t parameter
2611 			 */
2612 			(void) fr_fastroute(m, mp, fin, NULL);
2613 			m = *mp = NULL;
2614 		} else if ((fdp->fd_ifp != NULL) &&
2615 			   (fdp->fd_ifp != (struct ifnet *)-1)) {
2616 			/* this is for to rules: */
2617 			(void) fr_fastroute(m, mp, fin, fdp);
2618 			m = *mp = NULL;
2619 		}
2620 
2621 		/*
2622 		 * Generate a duplicated packet.
2623 		 */
2624 		if (mc != NULL)
2625 			(void) fr_fastroute(mc, &mc, fin, &fr->fr_dif);
2626 	}
2627 
2628 	/*
2629 	 * This late because the likes of fr_fastroute() use fin_fr.
2630 	 */
2631 	RWLOCK_EXIT(&ifs->ifs_ipf_mutex);
2632 
2633 finished:
2634 	if (!FR_ISPASS(pass)) {
2635 		ATOMIC_INCL(ifs->ifs_frstats[out].fr_block);
2636 		if (*mp != NULL) {
2637 			FREE_MB_T(*mp);
2638 			m = *mp = NULL;
2639 		}
2640 	} else {
2641 		ATOMIC_INCL(ifs->ifs_frstats[out].fr_pass);
2642 #if defined(_KERNEL) && defined(__sgi)
2643 		if ((fin->fin_hbuf != NULL) &&
2644 		    (mtod(fin->fin_m, struct ip *) != fin->fin_ip)) {
2645 			COPYBACK(m, 0, fin->fin_plen, fin->fin_hbuf);
2646 		}
2647 #endif
2648 	}
2649 
2650 	SPL_X(s);
2651 	RWLOCK_EXIT(&ifs->ifs_ipf_global);
2652 
2653 #ifdef _KERNEL
2654 # if OpenBSD >= 200311
2655 	if (FR_ISPASS(pass) && (v == 4)) {
2656 		ip = fin->fin_ip;
2657 		ip->ip_len = ntohs(ip->ip_len);
2658 		ip->ip_off = ntohs(ip->ip_off);
2659 	}
2660 # endif
2661 	return (FR_ISPASS(pass)) ? 0 : fin->fin_error;
2662 #else /* _KERNEL */
2663 	FR_VERBOSE(("fin_flx %#x pass %#x ", fin->fin_flx, pass));
2664 	if ((pass & FR_NOMATCH) != 0)
2665 		return 1;
2666 
2667 	if ((pass & FR_RETMASK) != 0)
2668 		switch (pass & FR_RETMASK)
2669 		{
2670 		case FR_RETRST :
2671 			return 3;
2672 		case FR_RETICMP :
2673 			return 4;
2674 		case FR_FAKEICMP :
2675 			return 5;
2676 		}
2677 
2678 	switch (pass & FR_CMDMASK)
2679 	{
2680 	case FR_PASS :
2681 		return 0;
2682 	case FR_BLOCK :
2683 		return -1;
2684 	case FR_AUTH :
2685 		return -2;
2686 	case FR_ACCOUNT :
2687 		return -3;
2688 	case FR_PREAUTH :
2689 		return -4;
2690 	}
2691 	return 2;
2692 #endif /* _KERNEL */
2693 }
2694 
2695 
2696 #ifdef	IPFILTER_LOG
2697 /* ------------------------------------------------------------------------ */
2698 /* Function:    fr_dolog                                                    */
2699 /* Returns:     frentry_t* - returns contents of fin_fr (no change made)    */
2700 /* Parameters:  fin(I) - pointer to packet information                      */
2701 /*              passp(IO) - pointer to current/new filter decision (unused) */
2702 /*                                                                          */
2703 /* Checks flags set to see how a packet should be logged, if it is to be    */
2704 /* logged.  Adjust statistics based on its success or not.                  */
2705 /* ------------------------------------------------------------------------ */
2706 frentry_t *fr_dolog(fin, passp)
2707 fr_info_t *fin;
2708 u_32_t *passp;
2709 {
2710 	u_32_t pass;
2711 	int out;
2712 	ipf_stack_t *ifs = fin->fin_ifs;
2713 
2714 	out = fin->fin_out;
2715 	pass = *passp;
2716 
2717 	if ((ifs->ifs_fr_flags & FF_LOGNOMATCH) && (pass & FR_NOMATCH)) {
2718 		pass |= FF_LOGNOMATCH;
2719 		ATOMIC_INCL(ifs->ifs_frstats[out].fr_npkl);
2720 		goto logit;
2721 	} else if (((pass & FR_LOGMASK) == FR_LOGP) ||
2722 	    (FR_ISPASS(pass) && (ifs->ifs_fr_flags & FF_LOGPASS))) {
2723 		if ((pass & FR_LOGMASK) != FR_LOGP)
2724 			pass |= FF_LOGPASS;
2725 		ATOMIC_INCL(ifs->ifs_frstats[out].fr_ppkl);
2726 		goto logit;
2727 	} else if (((pass & FR_LOGMASK) == FR_LOGB) ||
2728 		   (FR_ISBLOCK(pass) && (ifs->ifs_fr_flags & FF_LOGBLOCK))) {
2729 		if ((pass & FR_LOGMASK) != FR_LOGB)
2730 			pass |= FF_LOGBLOCK;
2731 		ATOMIC_INCL(ifs->ifs_frstats[out].fr_bpkl);
2732 logit:
2733 		if (ipflog(fin, pass) == -1) {
2734 			ATOMIC_INCL(ifs->ifs_frstats[out].fr_skip);
2735 
2736 			/*
2737 			 * If the "or-block" option has been used then
2738 			 * block the packet if we failed to log it.
2739 			 */
2740 			if ((pass & FR_LOGORBLOCK) &&
2741 			    FR_ISPASS(pass)) {
2742 				pass &= ~FR_CMDMASK;
2743 				pass |= FR_BLOCK;
2744 			}
2745 		}
2746 		*passp = pass;
2747 	}
2748 
2749 	return fin->fin_fr;
2750 }
2751 #endif /* IPFILTER_LOG */
2752 
2753 
2754 /* ------------------------------------------------------------------------ */
2755 /* Function:    ipf_cksum                                                   */
2756 /* Returns:     u_short - IP header checksum                                */
2757 /* Parameters:  addr(I) - pointer to start of buffer to checksum            */
2758 /*              len(I)  - length of buffer in bytes                         */
2759 /*                                                                          */
2760 /* Calculate the two's complement 16 bit checksum of the buffer passed.     */
2761 /*                                                                          */
2762 /* N.B.: addr should be 16bit aligned.                                      */
2763 /* ------------------------------------------------------------------------ */
2764 u_short ipf_cksum(addr, len)
2765 u_short *addr;
2766 int len;
2767 {
2768 	u_32_t sum = 0;
2769 
2770 	for (sum = 0; len > 1; len -= 2)
2771 		sum += *addr++;
2772 
2773 	/* mop up an odd byte, if necessary */
2774 	if (len == 1)
2775 		sum += *(u_char *)addr;
2776 
2777 	/*
2778 	 * add back carry outs from top 16 bits to low 16 bits
2779 	 */
2780 	sum = (sum >> 16) + (sum & 0xffff);	/* add hi 16 to low 16 */
2781 	sum += (sum >> 16);			/* add carry */
2782 	return (u_short)(~sum);
2783 }
2784 
2785 
2786 /* ------------------------------------------------------------------------ */
2787 /* Function:    fr_cksum                                                    */
2788 /* Returns:     u_short - layer 4 checksum                                  */
2789 /* Parameters:  m(I  )     - pointer to buffer holding packet               */
2790 /*              ip(I)      - pointer to IP header                           */
2791 /*              l4proto(I) - protocol to caclulate checksum for             */
2792 /*              l4hdr(I)   - pointer to layer 4 header                      */
2793 /*                                                                          */
2794 /* Calculates the TCP checksum for the packet held in "m", using the data   */
2795 /* in the IP header "ip" to seed it.                                        */
2796 /*                                                                          */
2797 /* NB: This function assumes we've pullup'd enough for all of the IP header */
2798 /* and the TCP header.  We also assume that data blocks aren't allocated in */
2799 /* odd sizes.                                                               */
2800 /*                                                                          */
2801 /* Expects ip_len to be in host byte order when called.                     */
2802 /* ------------------------------------------------------------------------ */
2803 u_short fr_cksum(m, ip, l4proto, l4hdr)
2804 mb_t *m;
2805 ip_t *ip;
2806 int l4proto;
2807 void *l4hdr;
2808 {
2809 	u_short *sp, slen, sumsave, l4hlen, *csump;
2810 	u_int sum, sum2;
2811 	int hlen;
2812 #ifdef	USE_INET6
2813 	ip6_t *ip6;
2814 #endif
2815 
2816 	csump = NULL;
2817 	sumsave = 0;
2818 	l4hlen = 0;
2819 	sp = NULL;
2820 	slen = 0;
2821 	hlen = 0;
2822 	sum = 0;
2823 
2824 	/*
2825 	 * Add up IP Header portion
2826 	 */
2827 #ifdef	USE_INET6
2828 	if (IP_V(ip) == 4) {
2829 #endif
2830 		hlen = IP_HL(ip) << 2;
2831 		slen = ip->ip_len - hlen;
2832 		sum = htons((u_short)l4proto);
2833 		sum += htons(slen);
2834 		sp = (u_short *)&ip->ip_src;
2835 		sum += *sp++;	/* ip_src */
2836 		sum += *sp++;
2837 		sum += *sp++;	/* ip_dst */
2838 		sum += *sp++;
2839 #ifdef	USE_INET6
2840 	} else if (IP_V(ip) == 6) {
2841 		ip6 = (ip6_t *)ip;
2842 		hlen = sizeof(*ip6);
2843 		slen = ntohs(ip6->ip6_plen);
2844 		sum = htons((u_short)l4proto);
2845 		sum += htons(slen);
2846 		sp = (u_short *)&ip6->ip6_src;
2847 		sum += *sp++;	/* ip6_src */
2848 		sum += *sp++;
2849 		sum += *sp++;
2850 		sum += *sp++;
2851 		sum += *sp++;
2852 		sum += *sp++;
2853 		sum += *sp++;
2854 		sum += *sp++;
2855 		sum += *sp++;	/* ip6_dst */
2856 		sum += *sp++;
2857 		sum += *sp++;
2858 		sum += *sp++;
2859 		sum += *sp++;
2860 		sum += *sp++;
2861 		sum += *sp++;
2862 		sum += *sp++;
2863 	}
2864 #endif
2865 
2866 	switch (l4proto)
2867 	{
2868 	case IPPROTO_UDP :
2869 		csump = &((udphdr_t *)l4hdr)->uh_sum;
2870 		l4hlen = sizeof(udphdr_t);
2871 		break;
2872 
2873 	case IPPROTO_TCP :
2874 		csump = &((tcphdr_t *)l4hdr)->th_sum;
2875 		l4hlen = sizeof(tcphdr_t);
2876 		break;
2877 	case IPPROTO_ICMP :
2878 		csump = &((icmphdr_t *)l4hdr)->icmp_cksum;
2879 		l4hlen = 4;
2880 		sum = 0;
2881 		break;
2882 	default :
2883 		break;
2884 	}
2885 
2886 	if (csump != NULL) {
2887 		sumsave = *csump;
2888 		*csump = 0;
2889 	}
2890 
2891 	l4hlen = l4hlen;	/* LINT */
2892 
2893 #ifdef	_KERNEL
2894 # ifdef MENTAT
2895 	{
2896 	void *rp = m->b_rptr;
2897 
2898 	if ((unsigned char *)ip > m->b_rptr && (unsigned char *)ip < m->b_wptr)
2899 		m->b_rptr = (u_char *)ip;
2900 	sum2 = ip_cksum(m, hlen, sum);	/* hlen == offset */
2901 	m->b_rptr = rp;
2902 	sum2 = (sum2 & 0xffff) + (sum2 >> 16);
2903 	sum2 = ~sum2 & 0xffff;
2904 	}
2905 # else /* MENTAT */
2906 #  if defined(BSD) || defined(sun)
2907 #   if BSD >= 199103
2908 	m->m_data += hlen;
2909 #   else
2910 	m->m_off += hlen;
2911 #   endif
2912 	m->m_len -= hlen;
2913 	sum2 = in_cksum(m, slen);
2914 	m->m_len += hlen;
2915 #   if BSD >= 199103
2916 	m->m_data -= hlen;
2917 #   else
2918 	m->m_off -= hlen;
2919 #   endif
2920 	/*
2921 	 * Both sum and sum2 are partial sums, so combine them together.
2922 	 */
2923 	sum += ~sum2 & 0xffff;
2924 	while (sum > 0xffff)
2925 		sum = (sum & 0xffff) + (sum >> 16);
2926 	sum2 = ~sum & 0xffff;
2927 #  else /* defined(BSD) || defined(sun) */
2928 {
2929 	union {
2930 		u_char	c[2];
2931 		u_short	s;
2932 	} bytes;
2933 	u_short len = ip->ip_len;
2934 #   if defined(__sgi)
2935 	int add;
2936 #   endif
2937 
2938 	/*
2939 	 * Add up IP Header portion
2940 	 */
2941 	if (sp != (u_short *)l4hdr)
2942 		sp = (u_short *)l4hdr;
2943 
2944 	switch (l4proto)
2945 	{
2946 	case IPPROTO_UDP :
2947 		sum += *sp++;	/* sport */
2948 		sum += *sp++;	/* dport */
2949 		sum += *sp++;	/* udp length */
2950 		sum += *sp++;	/* checksum */
2951 		break;
2952 
2953 	case IPPROTO_TCP :
2954 		sum += *sp++;	/* sport */
2955 		sum += *sp++;	/* dport */
2956 		sum += *sp++;	/* seq */
2957 		sum += *sp++;
2958 		sum += *sp++;	/* ack */
2959 		sum += *sp++;
2960 		sum += *sp++;	/* off */
2961 		sum += *sp++;	/* win */
2962 		sum += *sp++;	/* checksum */
2963 		sum += *sp++;	/* urp */
2964 		break;
2965 	case IPPROTO_ICMP :
2966 		sum = *sp++;	/* type/code */
2967 		sum += *sp++;	/* checksum */
2968 		break;
2969 	}
2970 
2971 #   ifdef	__sgi
2972 	/*
2973 	 * In case we had to copy the IP & TCP header out of mbufs,
2974 	 * skip over the mbuf bits which are the header
2975 	 */
2976 	if ((caddr_t)ip != mtod(m, caddr_t)) {
2977 		hlen = (caddr_t)sp - (caddr_t)ip;
2978 		while (hlen) {
2979 			add = MIN(hlen, m->m_len);
2980 			sp = (u_short *)(mtod(m, caddr_t) + add);
2981 			hlen -= add;
2982 			if (add == m->m_len) {
2983 				m = m->m_next;
2984 				if (!hlen) {
2985 					if (!m)
2986 						break;
2987 					sp = mtod(m, u_short *);
2988 				}
2989 				PANIC((!m),("fr_cksum(1): not enough data"));
2990 			}
2991 		}
2992 	}
2993 #   endif
2994 
2995 	len -= (l4hlen + hlen);
2996 	if (len <= 0)
2997 		goto nodata;
2998 
2999 	while (len > 1) {
3000 		if (((caddr_t)sp - mtod(m, caddr_t)) >= m->m_len) {
3001 			m = m->m_next;
3002 			PANIC((!m),("fr_cksum(2): not enough data"));
3003 			sp = mtod(m, u_short *);
3004 		}
3005 		if (((caddr_t)(sp + 1) - mtod(m, caddr_t)) > m->m_len) {
3006 			bytes.c[0] = *(u_char *)sp;
3007 			m = m->m_next;
3008 			PANIC((!m),("fr_cksum(3): not enough data"));
3009 			sp = mtod(m, u_short *);
3010 			bytes.c[1] = *(u_char *)sp;
3011 			sum += bytes.s;
3012 			sp = (u_short *)((u_char *)sp + 1);
3013 		}
3014 		if ((u_long)sp & 1) {
3015 			bcopy((char *)sp++, (char *)&bytes.s, sizeof(bytes.s));
3016 			sum += bytes.s;
3017 		} else
3018 			sum += *sp++;
3019 		len -= 2;
3020 	}
3021 
3022 	if (len != 0)
3023 		sum += ntohs(*(u_char *)sp << 8);
3024 nodata:
3025 	while (sum > 0xffff)
3026 		sum = (sum & 0xffff) + (sum >> 16);
3027 	sum2 = (u_short)(~sum & 0xffff);
3028 }
3029 #  endif /*  defined(BSD) || defined(sun) */
3030 # endif /* MENTAT */
3031 #else /* _KERNEL */
3032 	for (; slen > 1; slen -= 2)
3033 	        sum += *sp++;
3034 	if (slen)
3035 		sum += ntohs(*(u_char *)sp << 8);
3036 	while (sum > 0xffff)
3037 		sum = (sum & 0xffff) + (sum >> 16);
3038 	sum2 = (u_short)(~sum & 0xffff);
3039 #endif /* _KERNEL */
3040 	if (csump != NULL)
3041 		*csump = sumsave;
3042 	return sum2;
3043 }
3044 
3045 
3046 #if defined(_KERNEL) && ( ((BSD < 199103) && !defined(MENTAT)) || \
3047     defined(__sgi) ) && !defined(linux) && !defined(_AIX51)
3048 /*
3049  * Copyright (c) 1982, 1986, 1988, 1991, 1993
3050  *	The Regents of the University of California.  All rights reserved.
3051  *
3052  * Redistribution and use in source and binary forms, with or without
3053  * modification, are permitted provided that the following conditions
3054  * are met:
3055  * 1. Redistributions of source code must retain the above copyright
3056  *    notice, this list of conditions and the following disclaimer.
3057  * 2. Redistributions in binary form must reproduce the above copyright
3058  *    notice, this list of conditions and the following disclaimer in the
3059  *    documentation and/or other materials provided with the distribution.
3060  * 3. Neither the name of the University nor the names of its contributors
3061  *    may be used to endorse or promote products derived from this software
3062  *    without specific prior written permission.
3063  *
3064  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3065  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3066  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3067  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3068  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3069  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3070  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3071  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3072  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3073  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3074  * SUCH DAMAGE.
3075  *
3076  *	@(#)uipc_mbuf.c	8.2 (Berkeley) 1/4/94
3077  * $Id: fil.c,v 2.243.2.64 2005/08/13 05:19:59 darrenr Exp $
3078  */
3079 /*
3080  * Copy data from an mbuf chain starting "off" bytes from the beginning,
3081  * continuing for "len" bytes, into the indicated buffer.
3082  */
3083 void
3084 m_copydata(m, off, len, cp)
3085 	mb_t *m;
3086 	int off;
3087 	int len;
3088 	caddr_t cp;
3089 {
3090 	unsigned count;
3091 
3092 	if (off < 0 || len < 0)
3093 		panic("m_copydata");
3094 	while (off > 0) {
3095 		if (m == 0)
3096 			panic("m_copydata");
3097 		if (off < m->m_len)
3098 			break;
3099 		off -= m->m_len;
3100 		m = m->m_next;
3101 	}
3102 	while (len > 0) {
3103 		if (m == 0)
3104 			panic("m_copydata");
3105 		count = MIN(m->m_len - off, len);
3106 		bcopy(mtod(m, caddr_t) + off, cp, count);
3107 		len -= count;
3108 		cp += count;
3109 		off = 0;
3110 		m = m->m_next;
3111 	}
3112 }
3113 
3114 
3115 /*
3116  * Copy data from a buffer back into the indicated mbuf chain,
3117  * starting "off" bytes from the beginning, extending the mbuf
3118  * chain if necessary.
3119  */
3120 void
3121 m_copyback(m0, off, len, cp)
3122 	struct	mbuf *m0;
3123 	int off;
3124 	int len;
3125 	caddr_t cp;
3126 {
3127 	int mlen;
3128 	struct mbuf *m = m0, *n;
3129 	int totlen = 0;
3130 
3131 	if (m0 == 0)
3132 		return;
3133 	while (off > (mlen = m->m_len)) {
3134 		off -= mlen;
3135 		totlen += mlen;
3136 		if (m->m_next == 0) {
3137 			n = m_getclr(M_DONTWAIT, m->m_type);
3138 			if (n == 0)
3139 				goto out;
3140 			n->m_len = min(MLEN, len + off);
3141 			m->m_next = n;
3142 		}
3143 		m = m->m_next;
3144 	}
3145 	while (len > 0) {
3146 		mlen = min(m->m_len - off, len);
3147 		bcopy(cp, off + mtod(m, caddr_t), (unsigned)mlen);
3148 		cp += mlen;
3149 		len -= mlen;
3150 		mlen += off;
3151 		off = 0;
3152 		totlen += mlen;
3153 		if (len == 0)
3154 			break;
3155 		if (m->m_next == 0) {
3156 			n = m_get(M_DONTWAIT, m->m_type);
3157 			if (n == 0)
3158 				break;
3159 			n->m_len = min(MLEN, len);
3160 			m->m_next = n;
3161 		}
3162 		m = m->m_next;
3163 	}
3164 out:
3165 #if 0
3166 	if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
3167 		m->m_pkthdr.len = totlen;
3168 #endif
3169 	return;
3170 }
3171 #endif /* (_KERNEL) && ( ((BSD < 199103) && !MENTAT) || __sgi) */
3172 
3173 
3174 /* ------------------------------------------------------------------------ */
3175 /* Function:    fr_findgroup                                                */
3176 /* Returns:     frgroup_t * - NULL = group not found, else pointer to group */
3177 /* Parameters:  group(I) - group name to search for                         */
3178 /*              unit(I)  - device to which this group belongs               */
3179 /*              set(I)   - which set of rules (inactive/inactive) this is   */
3180 /*              fgpp(O)  - pointer to place to store pointer to the pointer */
3181 /*                         to where to add the next (last) group or where   */
3182 /*                         to delete group from.                            */
3183 /*                                                                          */
3184 /* Search amongst the defined groups for a particular group number.         */
3185 /* ------------------------------------------------------------------------ */
3186 frgroup_t *fr_findgroup(group, unit, set, fgpp, ifs)
3187 char *group;
3188 minor_t unit;
3189 int set;
3190 frgroup_t ***fgpp;
3191 ipf_stack_t *ifs;
3192 {
3193 	frgroup_t *fg, **fgp;
3194 
3195 	/*
3196 	 * Which list of groups to search in is dependent on which list of
3197 	 * rules are being operated on.
3198 	 */
3199 	fgp = &ifs->ifs_ipfgroups[unit][set];
3200 
3201 	while ((fg = *fgp) != NULL) {
3202 		if (strncmp(group, fg->fg_name, FR_GROUPLEN) == 0)
3203 			break;
3204 		else
3205 			fgp = &fg->fg_next;
3206 	}
3207 	if (fgpp != NULL)
3208 		*fgpp = fgp;
3209 	return fg;
3210 }
3211 
3212 
3213 /* ------------------------------------------------------------------------ */
3214 /* Function:    fr_addgroup                                                 */
3215 /* Returns:     frgroup_t * - NULL == did not create group,                 */
3216 /*                            != NULL == pointer to the group               */
3217 /* Parameters:  num(I)   - group number to add                              */
3218 /*              head(I)  - rule pointer that is using this as the head      */
3219 /*              flags(I) - rule flags which describe the type of rule it is */
3220 /*              unit(I)  - device to which this group will belong to        */
3221 /*              set(I)   - which set of rules (inactive/inactive) this is   */
3222 /* Write Locks: ipf_mutex                                                   */
3223 /*                                                                          */
3224 /* Add a new group head, or if it already exists, increase the reference    */
3225 /* count to it.                                                             */
3226 /* ------------------------------------------------------------------------ */
3227 frgroup_t *fr_addgroup(group, head, flags, unit, set, ifs)
3228 char *group;
3229 void *head;
3230 u_32_t flags;
3231 minor_t unit;
3232 int set;
3233 ipf_stack_t *ifs;
3234 {
3235 	frgroup_t *fg, **fgp;
3236 	u_32_t gflags;
3237 
3238 	if (group == NULL)
3239 		return NULL;
3240 
3241 	if (unit == IPL_LOGIPF && *group == '\0')
3242 		return NULL;
3243 
3244 	fgp = NULL;
3245 	gflags = flags & FR_INOUT;
3246 
3247 	fg = fr_findgroup(group, unit, set, &fgp, ifs);
3248 	if (fg != NULL) {
3249 		if (fg->fg_flags == 0)
3250 			fg->fg_flags = gflags;
3251 		else if (gflags != fg->fg_flags)
3252 			return NULL;
3253 		fg->fg_ref++;
3254 		return fg;
3255 	}
3256 	KMALLOC(fg, frgroup_t *);
3257 	if (fg != NULL) {
3258 		fg->fg_head = head;
3259 		fg->fg_start = NULL;
3260 		fg->fg_next = *fgp;
3261 		bcopy(group, fg->fg_name, FR_GROUPLEN);
3262 		fg->fg_flags = gflags;
3263 		fg->fg_ref = 1;
3264 		*fgp = fg;
3265 	}
3266 	return fg;
3267 }
3268 
3269 
3270 /* ------------------------------------------------------------------------ */
3271 /* Function:    fr_delgroup                                                 */
3272 /* Returns:     Nil                                                         */
3273 /* Parameters:  group(I) - group name to delete                             */
3274 /*              unit(I)  - device to which this group belongs               */
3275 /*              set(I)   - which set of rules (inactive/inactive) this is   */
3276 /* Write Locks: ipf_mutex                                                   */
3277 /*                                                                          */
3278 /* Attempt to delete a group head.                                          */
3279 /* Only do this when its reference count reaches 0.                         */
3280 /* ------------------------------------------------------------------------ */
3281 void fr_delgroup(group, unit, set, ifs)
3282 char *group;
3283 minor_t unit;
3284 int set;
3285 ipf_stack_t *ifs;
3286 {
3287 	frgroup_t *fg, **fgp;
3288 
3289 	fg = fr_findgroup(group, unit, set, &fgp, ifs);
3290 	if (fg == NULL)
3291 		return;
3292 
3293 	fg->fg_ref--;
3294 	if (fg->fg_ref == 0) {
3295 		*fgp = fg->fg_next;
3296 		KFREE(fg);
3297 	}
3298 }
3299 
3300 
3301 /* ------------------------------------------------------------------------ */
3302 /* Function:    fr_getrulen                                                 */
3303 /* Returns:     frentry_t * - NULL == not found, else pointer to rule n     */
3304 /* Parameters:  unit(I)  - device for which to count the rule's number      */
3305 /*              flags(I) - which set of rules to find the rule in           */
3306 /*              group(I) - group name                                       */
3307 /*              n(I)     - rule number to find                              */
3308 /*                                                                          */
3309 /* Find rule # n in group # g and return a pointer to it.  Return NULl if   */
3310 /* group # g doesn't exist or there are less than n rules in the group.     */
3311 /* ------------------------------------------------------------------------ */
3312 frentry_t *fr_getrulen(unit, group, n, ifs)
3313 int unit;
3314 char *group;
3315 u_32_t n;
3316 ipf_stack_t *ifs;
3317 {
3318 	frentry_t *fr;
3319 	frgroup_t *fg;
3320 
3321 	fg = fr_findgroup(group, unit, ifs->ifs_fr_active, NULL, ifs);
3322 	if (fg == NULL)
3323 		return NULL;
3324 	for (fr = fg->fg_head; fr && n; fr = fr->fr_next, n--)
3325 		;
3326 	if (n != 0)
3327 		return NULL;
3328 	return fr;
3329 }
3330 
3331 
3332 /* ------------------------------------------------------------------------ */
3333 /* Function:    fr_rulen                                                    */
3334 /* Returns:     int - >= 0 - rule number, -1 == search failed               */
3335 /* Parameters:  unit(I) - device for which to count the rule's number       */
3336 /*              fr(I)   - pointer to rule to match                          */
3337 /*                                                                          */
3338 /* Return the number for a rule on a specific filtering device.             */
3339 /* ------------------------------------------------------------------------ */
3340 int fr_rulen(unit, fr, ifs)
3341 int unit;
3342 frentry_t *fr;
3343 ipf_stack_t *ifs;
3344 {
3345 	frentry_t *fh;
3346 	frgroup_t *fg;
3347 	u_32_t n = 0;
3348 
3349 	if (fr == NULL)
3350 		return -1;
3351 	fg = fr_findgroup(fr->fr_group, unit, ifs->ifs_fr_active, NULL, ifs);
3352 	if (fg == NULL)
3353 		return -1;
3354 	for (fh = fg->fg_head; fh; n++, fh = fh->fr_next)
3355 		if (fh == fr)
3356 			break;
3357 	if (fh == NULL)
3358 		return -1;
3359 	return n;
3360 }
3361 
3362 
3363 /* ------------------------------------------------------------------------ */
3364 /* Function:    frflushlist                                                 */
3365 /* Returns:     int - >= 0 - number of flushed rules                        */
3366 /* Parameters:  set(I)   - which set of rules (inactive/inactive) this is   */
3367 /*              unit(I)  - device for which to flush rules                  */
3368 /*              flags(I) - which set of rules to flush                      */
3369 /*              nfreedp(O) - pointer to int where flush count is stored     */
3370 /*              listp(I)   - pointer to list to flush pointer               */
3371 /* Write Locks: ipf_mutex                                                   */
3372 /*                                                                          */
3373 /* Recursively flush rules from the list, descending groups as they are     */
3374 /* encountered.  if a rule is the head of a group and it has lost all its   */
3375 /* group members, then also delete the group reference.  nfreedp is needed  */
3376 /* to store the accumulating count of rules removed, whereas the returned   */
3377 /* value is just the number removed from the current list.  The latter is   */
3378 /* needed to correctly adjust reference counts on rules that define groups. */
3379 /*                                                                          */
3380 /* NOTE: Rules not loaded from user space cannot be flushed.                */
3381 /* ------------------------------------------------------------------------ */
3382 static int frflushlist(set, unit, nfreedp, listp, ifs)
3383 int set;
3384 minor_t unit;
3385 int *nfreedp;
3386 frentry_t **listp;
3387 ipf_stack_t *ifs;
3388 {
3389 	int freed = 0;
3390 	frentry_t *fp;
3391 
3392 	while ((fp = *listp) != NULL) {
3393 		if ((fp->fr_type & FR_T_BUILTIN) ||
3394 		    !(fp->fr_flags & FR_COPIED)) {
3395 			listp = &fp->fr_next;
3396 			continue;
3397 		}
3398 		*listp = fp->fr_next;
3399 		if (fp->fr_grp != NULL) {
3400 			(void) frflushlist(set, unit, nfreedp, fp->fr_grp, ifs);
3401 		}
3402 
3403 		if (fp->fr_grhead != NULL) {
3404 			fr_delgroup(fp->fr_grhead, unit, set, ifs);
3405 			*fp->fr_grhead = '\0';
3406 		}
3407 
3408 		ASSERT(fp->fr_ref > 0);
3409 		fp->fr_next = NULL;
3410 		if (fr_derefrule(&fp, ifs) == 0)
3411 			freed++;
3412 	}
3413 	*nfreedp += freed;
3414 	return freed;
3415 }
3416 
3417 
3418 /* ------------------------------------------------------------------------ */
3419 /* Function:    frflush                                                     */
3420 /* Returns:     int - >= 0 - number of flushed rules                        */
3421 /* Parameters:  unit(I)  - device for which to flush rules                  */
3422 /*              flags(I) - which set of rules to flush                      */
3423 /*                                                                          */
3424 /* Calls flushlist() for all filter rules (accounting, firewall - both IPv4 */
3425 /* and IPv6) as defined by the value of flags.                              */
3426 /* ------------------------------------------------------------------------ */
3427 int frflush(unit, proto, flags, ifs)
3428 minor_t unit;
3429 int proto, flags;
3430 ipf_stack_t *ifs;
3431 {
3432 	int flushed = 0, set;
3433 
3434 	WRITE_ENTER(&ifs->ifs_ipf_mutex);
3435 	bzero((char *)&ifs->ifs_frcache, sizeof (ifs->ifs_frcache));
3436 
3437 	set = ifs->ifs_fr_active;
3438 	if ((flags & FR_INACTIVE) == FR_INACTIVE)
3439 		set = 1 - set;
3440 
3441 	if (flags & FR_OUTQUE) {
3442 		if (proto == 0 || proto == 6) {
3443 			(void) frflushlist(set, unit,
3444 			    &flushed, &ifs->ifs_ipfilter6[1][set], ifs);
3445 			(void) frflushlist(set, unit,
3446 			    &flushed, &ifs->ifs_ipacct6[1][set], ifs);
3447 		}
3448 		if (proto == 0 || proto == 4) {
3449 			(void) frflushlist(set, unit,
3450 			    &flushed, &ifs->ifs_ipfilter[1][set], ifs);
3451 			(void) frflushlist(set, unit,
3452 			    &flushed, &ifs->ifs_ipacct[1][set], ifs);
3453 		}
3454 	}
3455 	if (flags & FR_INQUE) {
3456 		if (proto == 0 || proto == 6) {
3457 			(void) frflushlist(set, unit,
3458 			    &flushed, &ifs->ifs_ipfilter6[0][set], ifs);
3459 			(void) frflushlist(set, unit,
3460 			    &flushed, &ifs->ifs_ipacct6[0][set], ifs);
3461 		}
3462 		if (proto == 0 || proto == 4) {
3463 			(void) frflushlist(set, unit,
3464 			    &flushed, &ifs->ifs_ipfilter[0][set], ifs);
3465 			(void) frflushlist(set, unit,
3466 			    &flushed, &ifs->ifs_ipacct[0][set], ifs);
3467 		}
3468 	}
3469 	RWLOCK_EXIT(&ifs->ifs_ipf_mutex);
3470 
3471 	if (unit == IPL_LOGIPF) {
3472 		int tmp;
3473 
3474 		tmp = frflush(IPL_LOGCOUNT, proto, flags, ifs);
3475 		if (tmp >= 0)
3476 			flushed += tmp;
3477 	}
3478 	return flushed;
3479 }
3480 
3481 
3482 /* ------------------------------------------------------------------------ */
3483 /* Function:    memstr                                                      */
3484 /* Returns:     char *  - NULL if failed, != NULL pointer to matching bytes */
3485 /* Parameters:  src(I)  - pointer to byte sequence to match                 */
3486 /*              dst(I)  - pointer to byte sequence to search                */
3487 /*              slen(I) - match length                                      */
3488 /*              dlen(I) - length available to search in                     */
3489 /*                                                                          */
3490 /* Search dst for a sequence of bytes matching those at src and extend for  */
3491 /* slen bytes.                                                              */
3492 /* ------------------------------------------------------------------------ */
3493 char *memstr(src, dst, slen, dlen)
3494 char *src, *dst;
3495 int slen, dlen;
3496 {
3497 	char *s = NULL;
3498 
3499 	while (dlen >= slen) {
3500 		if (bcmp(src, dst, slen) == 0) {
3501 			s = dst;
3502 			break;
3503 		}
3504 		dst++;
3505 		dlen--;
3506 	}
3507 	return s;
3508 }
3509 /* ------------------------------------------------------------------------ */
3510 /* Function:    fr_fixskip                                                  */
3511 /* Returns:     Nil                                                         */
3512 /* Parameters:  listp(IO)    - pointer to start of list with skip rule      */
3513 /*              rp(I)        - rule added/removed with skip in it.          */
3514 /*              addremove(I) - adjustment (-1/+1) to make to skip count,    */
3515 /*                             depending on whether a rule was just added   */
3516 /*                             or removed.                                  */
3517 /*                                                                          */
3518 /* Adjust all the rules in a list which would have skip'd past the position */
3519 /* where we are inserting to skip to the right place given the change.      */
3520 /* ------------------------------------------------------------------------ */
3521 void fr_fixskip(listp, rp, addremove)
3522 frentry_t **listp, *rp;
3523 int addremove;
3524 {
3525 	int rules, rn;
3526 	frentry_t *fp;
3527 
3528 	rules = 0;
3529 	for (fp = *listp; (fp != NULL) && (fp != rp); fp = fp->fr_next)
3530 		rules++;
3531 
3532 	if (!fp)
3533 		return;
3534 
3535 	for (rn = 0, fp = *listp; fp && (fp != rp); fp = fp->fr_next, rn++)
3536 		if (FR_ISSKIP(fp->fr_flags) && (rn + fp->fr_arg >= rules))
3537 			fp->fr_arg += addremove;
3538 }
3539 
3540 
3541 #ifdef	_KERNEL
3542 /* ------------------------------------------------------------------------ */
3543 /* Function:    count4bits                                                  */
3544 /* Returns:     int - >= 0 - number of consecutive bits in input            */
3545 /* Parameters:  ip(I) - 32bit IP address                                    */
3546 /*                                                                          */
3547 /* IPv4 ONLY                                                                */
3548 /* count consecutive 1's in bit mask.  If the mask generated by counting    */
3549 /* consecutive 1's is different to that passed, return -1, else return #    */
3550 /* of bits.                                                                 */
3551 /* ------------------------------------------------------------------------ */
3552 int	count4bits(ip)
3553 u_32_t	ip;
3554 {
3555 	u_32_t	ipn;
3556 	int	cnt = 0, i, j;
3557 
3558 	ip = ipn = ntohl(ip);
3559 	for (i = 32; i; i--, ipn *= 2)
3560 		if (ipn & 0x80000000)
3561 			cnt++;
3562 		else
3563 			break;
3564 	ipn = 0;
3565 	for (i = 32, j = cnt; i; i--, j--) {
3566 		ipn *= 2;
3567 		if (j > 0)
3568 			ipn++;
3569 	}
3570 	if (ipn == ip)
3571 		return cnt;
3572 	return -1;
3573 }
3574 
3575 
3576 #ifdef USE_INET6
3577 /* ------------------------------------------------------------------------ */
3578 /* Function:    count6bits                                                  */
3579 /* Returns:     int - >= 0 - number of consecutive bits in input            */
3580 /* Parameters:  msk(I) - pointer to start of IPv6 bitmask                   */
3581 /*                                                                          */
3582 /* IPv6 ONLY                                                                */
3583 /* count consecutive 1's in bit mask.                                       */
3584 /* ------------------------------------------------------------------------ */
3585 int count6bits(msk)
3586 u_32_t *msk;
3587 {
3588 	int i = 0, k;
3589 	u_32_t j;
3590 
3591 	for (k = 3; k >= 0; k--)
3592 		if (msk[k] == 0xffffffff)
3593 			i += 32;
3594 		else {
3595 			for (j = msk[k]; j; j <<= 1)
3596 				if (j & 0x80000000)
3597 					i++;
3598 		}
3599 	return i;
3600 }
3601 # endif
3602 #endif /* _KERNEL */
3603 
3604 
3605 /* ------------------------------------------------------------------------ */
3606 /* Function:    fr_ifsync                                                   */
3607 /* Returns:     void *    - new interface identifier                        */
3608 /* Parameters:  action(I)  - type of synchronisation to do                  */
3609 /*              v(I)       - IP version being sync'd (v4 or v6)             */
3610 /*              newifp(I)  - interface identifier being introduced/removed  */
3611 /*              oldifp(I)  - interface identifier in a filter rule          */
3612 /*              newname(I) - name associated with oldifp interface          */
3613 /*              oldname(I) - name associated with newifp interface          */
3614 /*                                                                          */
3615 /* This function returns what the new value for "oldifp" should be for its  */
3616 /* caller.  In some cases it will not change, in some it will.              */
3617 /* action == IPFSYNC_RESYNC                                                 */
3618 /*   a new value for oldifp will always be looked up, according to oldname, */
3619 /*   the values of newname and newifp are ignored.                          */
3620 /* action == IPFSYNC_NEWIFP                                                 */
3621 /*   if oldname matches newname then we are doing a sync for the matching   */
3622 /*   interface, so we return newifp to be used in place of oldifp.  If the  */
3623 /*   the names don't match, just return oldifp.                             */
3624 /* action == IPFSYNC_OLDIFP                                                 */
3625 /*   if oldifp matches newifp then we are are doing a sync to remove any    */
3626 /*   references to oldifp, so we return "-1".                               */
3627 /* ------------------------------------------------------------------------ */
3628 static void *fr_ifsync(action, v, newname, oldname, newifp, oldifp, ifs)
3629 int action, v;
3630 char *newname, *oldname;
3631 void *newifp, *oldifp;
3632 ipf_stack_t *ifs;
3633 {
3634 	void *rval = oldifp;
3635 
3636 	switch (action)
3637 	{
3638 	case IPFSYNC_RESYNC :
3639 		if (oldname[0] != '\0') {
3640 			rval = fr_resolvenic(oldname, v, ifs);
3641 		}
3642 		break;
3643 	case IPFSYNC_NEWIFP :
3644 		if (!strncmp(newname, oldname, LIFNAMSIZ))
3645 			rval = newifp;
3646 		break;
3647 	case IPFSYNC_OLDIFP :
3648 		if (newifp == oldifp)
3649 			rval = (oldifp) ? (void *)-1 : NULL;
3650 		break;
3651 	}
3652 
3653 	return rval;
3654 }
3655 
3656 
3657 /* ------------------------------------------------------------------------ */
3658 /* Function:    frsynclist                                                  */
3659 /* Returns:     void                                                        */
3660 /* Parameters:  action(I) - type of synchronisation to do                   */
3661 /*              v(I)      - IP version being sync'd (v4 or v6)              */
3662 /*              ifp(I)    - interface identifier associated with action     */
3663 /*              name(I)   - name associated with ifp parameter              */
3664 /* Write Locks: ipf_mutex                                                   */
3665 /*                                                                          */
3666 /* Walk through a list of filter rules and resolve any interface names into */
3667 /* pointers.  Where dynamic addresses are used, also update the IP address  */
3668 /* used in the rule.  The interface pointer is used to limit the lookups to */
3669 /* a specific set of matching names if it is non-NULL.                      */
3670 /* ------------------------------------------------------------------------ */
3671 static void frsynclist(action, v, ifp, ifname, fr, ifs)
3672 int action, v;
3673 void *ifp;
3674 char *ifname;
3675 frentry_t *fr;
3676 ipf_stack_t *ifs;
3677 {
3678 	frdest_t *fdp;
3679 	int rv, i;
3680 
3681 	for (; fr; fr = fr->fr_next) {
3682 		rv = fr->fr_v;
3683 		if (v != 0 && v != rv)
3684 			continue;
3685 
3686 		/*
3687 		 * Lookup all the interface names that are part of the rule.
3688 		 */
3689 		for (i = 0; i < 4; i++) {
3690 			fr->fr_ifas[i] = fr_ifsync(action, rv, ifname,
3691 						   fr->fr_ifnames[i],
3692 						   ifp, fr->fr_ifas[i],
3693 						   ifs);
3694 		}
3695 
3696 		fdp = &fr->fr_tifs[0];
3697 		fdp->fd_ifp = fr_ifsync(action, rv, ifname, fdp->fd_ifname,
3698 					   ifp, fdp->fd_ifp, ifs);
3699 
3700 		fdp = &fr->fr_tifs[1];
3701 		fdp->fd_ifp = fr_ifsync(action, rv, ifname, fdp->fd_ifname,
3702 					   ifp, fdp->fd_ifp, ifs);
3703 
3704 		fdp = &fr->fr_dif;
3705 		fdp->fd_ifp = fr_ifsync(action, rv, ifname, fdp->fd_ifname,
3706 					   ifp, fdp->fd_ifp, ifs);
3707 
3708 		if (action != IPFSYNC_RESYNC)
3709 			continue;
3710 
3711 		if (fr->fr_type == FR_T_IPF) {
3712 			if (fr->fr_satype != FRI_NORMAL &&
3713 			    fr->fr_satype != FRI_LOOKUP) {
3714 				(void)fr_ifpaddr(rv, fr->fr_satype,
3715 						 fr->fr_ifas[fr->fr_sifpidx],
3716 						 &fr->fr_src, &fr->fr_smsk,
3717 						 ifs);
3718 			}
3719 			if (fr->fr_datype != FRI_NORMAL &&
3720 			    fr->fr_datype != FRI_LOOKUP) {
3721 				(void)fr_ifpaddr(rv, fr->fr_datype,
3722 						 fr->fr_ifas[fr->fr_difpidx],
3723 						 &fr->fr_dst, &fr->fr_dmsk,
3724 						 ifs);
3725 			}
3726 		}
3727 
3728 #ifdef	IPFILTER_LOOKUP
3729 		if (fr->fr_type == FR_T_IPF && fr->fr_satype == FRI_LOOKUP &&
3730 		    fr->fr_srcptr == NULL) {
3731 			fr->fr_srcptr = fr_resolvelookup(fr->fr_srctype,
3732 							 fr->fr_srcnum,
3733 							 &fr->fr_srcfunc, ifs);
3734 		}
3735 		if (fr->fr_type == FR_T_IPF && fr->fr_datype == FRI_LOOKUP &&
3736 		    fr->fr_dstptr == NULL) {
3737 			fr->fr_dstptr = fr_resolvelookup(fr->fr_dsttype,
3738 							 fr->fr_dstnum,
3739 							 &fr->fr_dstfunc, ifs);
3740 		}
3741 #endif
3742 	}
3743 }
3744 
3745 
3746 #ifdef	_KERNEL
3747 /* ------------------------------------------------------------------------ */
3748 /* Function:    frsync                                                      */
3749 /* Returns:     void                                                        */
3750 /* Parameters:  action(I) - type of synchronisation to do                   */
3751 /*              v(I)      - IP version being sync'd (v4 or v6)              */
3752 /*              ifp(I)    - interface identifier associated with action     */
3753 /*              name(I)   - name associated with ifp parameter              */
3754 /*                                                                          */
3755 /* frsync() is called when we suspect that the interface list or            */
3756 /* information about interfaces (like IP#) has changed.  Go through all     */
3757 /* filter rules, NAT entries and the state table and check if anything      */
3758 /* needs to be changed/updated.                                             */
3759 /* With the filtering hooks added to Solaris, we needed to change the manner*/
3760 /* in which this was done to support three different types of sync:         */
3761 /* - complete resync of all interface name/identifiers                      */
3762 /* - new interface being announced with its name and identifier             */
3763 /* - interface removal being announced by only its identifier               */
3764 /* ------------------------------------------------------------------------ */
3765 void frsync(action, v, ifp, name, ifs)
3766 int action, v;
3767 void *ifp;
3768 char *name;
3769 ipf_stack_t *ifs;
3770 {
3771 	int i;
3772 
3773 	WRITE_ENTER(&ifs->ifs_ipf_mutex);
3774 	frsynclist(action, v, ifp, name, ifs->ifs_ipacct[0][ifs->ifs_fr_active], ifs);
3775 	frsynclist(action, v, ifp, name, ifs->ifs_ipacct[1][ifs->ifs_fr_active], ifs);
3776 	frsynclist(action, v, ifp, name, ifs->ifs_ipfilter[0][ifs->ifs_fr_active], ifs);
3777 	frsynclist(action, v, ifp, name, ifs->ifs_ipfilter[1][ifs->ifs_fr_active], ifs);
3778 	frsynclist(action, v, ifp, name, ifs->ifs_ipacct6[0][ifs->ifs_fr_active], ifs);
3779 	frsynclist(action, v, ifp, name, ifs->ifs_ipacct6[1][ifs->ifs_fr_active], ifs);
3780 	frsynclist(action, v, ifp, name, ifs->ifs_ipfilter6[0][ifs->ifs_fr_active], ifs);
3781 	frsynclist(action, v, ifp, name, ifs->ifs_ipfilter6[1][ifs->ifs_fr_active], ifs);
3782 
3783 	for (i = 0; i < IPL_LOGSIZE; i++) {
3784 		frgroup_t *g;
3785 
3786 		for (g = ifs->ifs_ipfgroups[i][0]; g != NULL; g = g->fg_next)
3787 			frsynclist(action, v, ifp, name, g->fg_start, ifs);
3788 		for (g = ifs->ifs_ipfgroups[i][1]; g != NULL; g = g->fg_next)
3789 			frsynclist(action, v, ifp, name, g->fg_start, ifs);
3790 	}
3791 	RWLOCK_EXIT(&ifs->ifs_ipf_mutex);
3792 }
3793 
3794 
3795 /*
3796  * In the functions below, bcopy() is called because the pointer being
3797  * copied _from_ in this instance is a pointer to a char buf (which could
3798  * end up being unaligned) and on the kernel's local stack.
3799  */
3800 /* ------------------------------------------------------------------------ */
3801 /* Function:    copyinptr                                                   */
3802 /* Returns:     int - 0 = success, else failure                             */
3803 /* Parameters:  src(I)  - pointer to the source address                     */
3804 /*              dst(I)  - destination address                               */
3805 /*              size(I) - number of bytes to copy                           */
3806 /*                                                                          */
3807 /* Copy a block of data in from user space, given a pointer to the pointer  */
3808 /* to start copying from (src) and a pointer to where to store it (dst).    */
3809 /* NB: src - pointer to user space pointer, dst - kernel space pointer      */
3810 /* ------------------------------------------------------------------------ */
3811 int copyinptr(src, dst, size)
3812 void *src, *dst;
3813 size_t size;
3814 {
3815 	caddr_t ca;
3816 	int err;
3817 
3818 # if SOLARIS
3819 	err = COPYIN(src, (caddr_t)&ca, sizeof(ca));
3820 	if (err != 0)
3821 		return err;
3822 # else
3823 	bcopy(src, (caddr_t)&ca, sizeof(ca));
3824 # endif
3825 	err = COPYIN(ca, dst, size);
3826 	return err;
3827 }
3828 
3829 
3830 /* ------------------------------------------------------------------------ */
3831 /* Function:    copyoutptr                                                  */
3832 /* Returns:     int - 0 = success, else failure                             */
3833 /* Parameters:  src(I)  - pointer to the source address                     */
3834 /*              dst(I)  - destination address                               */
3835 /*              size(I) - number of bytes to copy                           */
3836 /*                                                                          */
3837 /* Copy a block of data out to user space, given a pointer to the pointer   */
3838 /* to start copying from (src) and a pointer to where to store it (dst).    */
3839 /* NB: src - kernel space pointer, dst - pointer to user space pointer.     */
3840 /* ------------------------------------------------------------------------ */
3841 int copyoutptr(src, dst, size)
3842 void *src, *dst;
3843 size_t size;
3844 {
3845 	caddr_t ca;
3846 	int err;
3847 
3848 # if SOLARIS
3849 	err = COPYIN(dst, (caddr_t)&ca, sizeof(ca));
3850 	if (err != 0)
3851 		return err;
3852 # else
3853 	bcopy(dst, (caddr_t)&ca, sizeof(ca));
3854 # endif
3855 	err = COPYOUT(src, ca, size);
3856 	return err;
3857 }
3858 #endif
3859 
3860 
3861 /* ------------------------------------------------------------------------ */
3862 /* Function:    fr_lock                                                     */
3863 /* Returns:     (void)                                                      */
3864 /* Parameters:  data(I)  - pointer to lock value to set                     */
3865 /*              lockp(O) - pointer to location to store old lock value      */
3866 /*                                                                          */
3867 /* Get the new value for the lock integer, set it and return the old value  */
3868 /* in *lockp.                                                               */
3869 /* ------------------------------------------------------------------------ */
3870 void fr_lock(data, lockp)
3871 caddr_t data;
3872 int *lockp;
3873 {
3874 	int arg;
3875 
3876 	BCOPYIN(data, (caddr_t)&arg, sizeof(arg));
3877 	BCOPYOUT((caddr_t)lockp, data, sizeof(*lockp));
3878 	*lockp = arg;
3879 }
3880 
3881 
3882 /* ------------------------------------------------------------------------ */
3883 /* Function:    fr_getstat                                                  */
3884 /* Returns:     Nil                                                         */
3885 /* Parameters:  fiop(I)  - pointer to ipfilter stats structure              */
3886 /*                                                                          */
3887 /* Stores a copy of current pointers, counters, etc, in the friostat        */
3888 /* structure.                                                               */
3889 /* ------------------------------------------------------------------------ */
3890 void fr_getstat(fiop, ifs)
3891 friostat_t *fiop;
3892 ipf_stack_t *ifs;
3893 {
3894 	int i, j;
3895 
3896 	bcopy((char *)&ifs->ifs_frstats, (char *)fiop->f_st,
3897 	    sizeof(filterstats_t) * 2);
3898 	fiop->f_locks[IPL_LOGSTATE] = ifs->ifs_fr_state_lock;
3899 	fiop->f_locks[IPL_LOGNAT] = ifs->ifs_fr_nat_lock;
3900 	fiop->f_locks[IPL_LOGIPF] = ifs->ifs_fr_frag_lock;
3901 	fiop->f_locks[IPL_LOGAUTH] = ifs->ifs_fr_auth_lock;
3902 
3903 	for (i = 0; i < 2; i++)
3904 		for (j = 0; j < 2; j++) {
3905 			fiop->f_ipf[i][j] = ifs->ifs_ipfilter[i][j];
3906 			fiop->f_acct[i][j] = ifs->ifs_ipacct[i][j];
3907 			fiop->f_ipf6[i][j] = ifs->ifs_ipfilter6[i][j];
3908 			fiop->f_acct6[i][j] = ifs->ifs_ipacct6[i][j];
3909 		}
3910 
3911 	fiop->f_ticks = ifs->ifs_fr_ticks;
3912 	fiop->f_active = ifs->ifs_fr_active;
3913 	fiop->f_froute[0] = ifs->ifs_fr_frouteok[0];
3914 	fiop->f_froute[1] = ifs->ifs_fr_frouteok[1];
3915 
3916 	fiop->f_running = ifs->ifs_fr_running;
3917 	for (i = 0; i < IPL_LOGSIZE; i++) {
3918 		fiop->f_groups[i][0] = ifs->ifs_ipfgroups[i][0];
3919 		fiop->f_groups[i][1] = ifs->ifs_ipfgroups[i][1];
3920 	}
3921 #ifdef  IPFILTER_LOG
3922 	fiop->f_logging = 1;
3923 #else
3924 	fiop->f_logging = 0;
3925 #endif
3926 	fiop->f_defpass = ifs->ifs_fr_pass;
3927 	fiop->f_features = fr_features;
3928 	(void) strncpy(fiop->f_version, ipfilter_version,
3929 		       sizeof(fiop->f_version));
3930 }
3931 
3932 
3933 #ifdef	USE_INET6
3934 int icmptoicmp6types[ICMP_MAXTYPE+1] = {
3935 	ICMP6_ECHO_REPLY,	/* 0: ICMP_ECHOREPLY */
3936 	-1,			/* 1: UNUSED */
3937 	-1,			/* 2: UNUSED */
3938 	ICMP6_DST_UNREACH,	/* 3: ICMP_UNREACH */
3939 	-1,			/* 4: ICMP_SOURCEQUENCH */
3940 	ND_REDIRECT,		/* 5: ICMP_REDIRECT */
3941 	-1,			/* 6: UNUSED */
3942 	-1,			/* 7: UNUSED */
3943 	ICMP6_ECHO_REQUEST,	/* 8: ICMP_ECHO */
3944 	-1,			/* 9: UNUSED */
3945 	-1,			/* 10: UNUSED */
3946 	ICMP6_TIME_EXCEEDED,	/* 11: ICMP_TIMXCEED */
3947 	ICMP6_PARAM_PROB,	/* 12: ICMP_PARAMPROB */
3948 	-1,			/* 13: ICMP_TSTAMP */
3949 	-1,			/* 14: ICMP_TSTAMPREPLY */
3950 	-1,			/* 15: ICMP_IREQ */
3951 	-1,			/* 16: ICMP_IREQREPLY */
3952 	-1,			/* 17: ICMP_MASKREQ */
3953 	-1,			/* 18: ICMP_MASKREPLY */
3954 };
3955 
3956 
3957 int	icmptoicmp6unreach[ICMP_MAX_UNREACH] = {
3958 	ICMP6_DST_UNREACH_ADDR,		/* 0: ICMP_UNREACH_NET */
3959 	ICMP6_DST_UNREACH_ADDR,		/* 1: ICMP_UNREACH_HOST */
3960 	-1,				/* 2: ICMP_UNREACH_PROTOCOL */
3961 	ICMP6_DST_UNREACH_NOPORT,	/* 3: ICMP_UNREACH_PORT */
3962 	-1,				/* 4: ICMP_UNREACH_NEEDFRAG */
3963 	ICMP6_DST_UNREACH_NOTNEIGHBOR,	/* 5: ICMP_UNREACH_SRCFAIL */
3964 	ICMP6_DST_UNREACH_ADDR,		/* 6: ICMP_UNREACH_NET_UNKNOWN */
3965 	ICMP6_DST_UNREACH_ADDR,		/* 7: ICMP_UNREACH_HOST_UNKNOWN */
3966 	-1,				/* 8: ICMP_UNREACH_ISOLATED */
3967 	ICMP6_DST_UNREACH_ADMIN,	/* 9: ICMP_UNREACH_NET_PROHIB */
3968 	ICMP6_DST_UNREACH_ADMIN,	/* 10: ICMP_UNREACH_HOST_PROHIB */
3969 	-1,				/* 11: ICMP_UNREACH_TOSNET */
3970 	-1,				/* 12: ICMP_UNREACH_TOSHOST */
3971 	ICMP6_DST_UNREACH_ADMIN,	/* 13: ICMP_UNREACH_ADMIN_PROHIBIT */
3972 };
3973 int	icmpreplytype6[ICMP6_MAXTYPE + 1];
3974 #endif
3975 
3976 int	icmpreplytype4[ICMP_MAXTYPE + 1];
3977 
3978 
3979 /* ------------------------------------------------------------------------ */
3980 /* Function:    fr_matchicmpqueryreply                                      */
3981 /* Returns:     int - 1 if "icmp" is a valid reply to "ic" else 0.          */
3982 /* Parameters:  v(I)    - IP protocol version (4 or 6)                      */
3983 /*              ic(I)   - ICMP information                                  */
3984 /*              icmp(I) - ICMP packet header                                */
3985 /*              rev(I)  - direction (0 = forward/1 = reverse) of packet     */
3986 /*                                                                          */
3987 /* Check if the ICMP packet defined by the header pointed to by icmp is a   */
3988 /* reply to one as described by what's in ic.  If it is a match, return 1,  */
3989 /* else return 0 for no match.                                              */
3990 /* ------------------------------------------------------------------------ */
3991 int fr_matchicmpqueryreply(v, ic, icmp, rev)
3992 int v;
3993 icmpinfo_t *ic;
3994 icmphdr_t *icmp;
3995 int rev;
3996 {
3997 	int ictype;
3998 
3999 	ictype = ic->ici_type;
4000 
4001 	if (v == 4) {
4002 		/*
4003 		 * If we matched its type on the way in, then when going out
4004 		 * it will still be the same type.
4005 		 */
4006 		if ((!rev && (icmp->icmp_type == ictype)) ||
4007 		    (rev && (icmpreplytype4[ictype] == icmp->icmp_type))) {
4008 			if (icmp->icmp_type != ICMP_ECHOREPLY)
4009 				return 1;
4010 			if (icmp->icmp_id == ic->ici_id)
4011 				return 1;
4012 		}
4013 	}
4014 #ifdef	USE_INET6
4015 	else if (v == 6) {
4016 		if ((!rev && (icmp->icmp_type == ictype)) ||
4017 		    (rev && (icmpreplytype6[ictype] == icmp->icmp_type))) {
4018 			if (icmp->icmp_type != ICMP6_ECHO_REPLY)
4019 				return 1;
4020 			if (icmp->icmp_id == ic->ici_id)
4021 				return 1;
4022 		}
4023 	}
4024 #endif
4025 	return 0;
4026 }
4027 
4028 
4029 #ifdef	IPFILTER_LOOKUP
4030 /* ------------------------------------------------------------------------ */
4031 /* Function:    fr_resolvelookup                                            */
4032 /* Returns:     void * - NULL = failure, else success.                      */
4033 /* Parameters:  type(I)     - type of lookup these parameters are for.      */
4034 /*              number(I)   - table number to use when searching            */
4035 /*              funcptr(IO) - pointer to pointer for storing IP address     */
4036 /*                           searching function.                            */
4037 /*                                                                          */
4038 /* Search for the "table" number passed in amongst those configured for     */
4039 /* that particular type.  If the type is recognised then the function to    */
4040 /* call to do the IP address search will be change, regardless of whether   */
4041 /* or not the "table" number exists.                                        */
4042 /* ------------------------------------------------------------------------ */
4043 static void *fr_resolvelookup(type, number, funcptr, ifs)
4044 u_int type, number;
4045 lookupfunc_t *funcptr;
4046 ipf_stack_t *ifs;
4047 {
4048 	char name[FR_GROUPLEN];
4049 	iphtable_t *iph;
4050 	ip_pool_t *ipo;
4051 	void *ptr;
4052 
4053 #if defined(SNPRINTF) && defined(_KERNEL)
4054 	(void) SNPRINTF(name, sizeof(name), "%u", number);
4055 #else
4056 	(void) sprintf(name, "%u", number);
4057 #endif
4058 
4059 	READ_ENTER(&ifs->ifs_ip_poolrw);
4060 
4061 	switch (type)
4062 	{
4063 	case IPLT_POOL :
4064 # if (defined(__osf__) && defined(_KERNEL))
4065 		ptr = NULL;
4066 		*funcptr = NULL;
4067 # else
4068 		ipo = ip_pool_find(IPL_LOGIPF, name, ifs);
4069 		ptr = ipo;
4070 		if (ipo != NULL) {
4071 			ATOMIC_INC32(ipo->ipo_ref);
4072 		}
4073 		*funcptr = ip_pool_search;
4074 # endif
4075 		break;
4076 	case IPLT_HASH :
4077 		iph = fr_findhtable(IPL_LOGIPF, name, ifs);
4078 		ptr = iph;
4079 		if (iph != NULL) {
4080 			ATOMIC_INC32(iph->iph_ref);
4081 		}
4082 		*funcptr = fr_iphmfindip;
4083 		break;
4084 	default:
4085 		ptr = NULL;
4086 		*funcptr = NULL;
4087 		break;
4088 	}
4089 	RWLOCK_EXIT(&ifs->ifs_ip_poolrw);
4090 
4091 	return ptr;
4092 }
4093 #endif
4094 
4095 
4096 /* ------------------------------------------------------------------------ */
4097 /* Function:    frrequest                                                   */
4098 /* Returns:     int - 0 == success, > 0 == errno value                      */
4099 /* Parameters:  unit(I)     - device for which this is for                  */
4100 /*              req(I)      - ioctl command (SIOC*)                         */
4101 /*              data(I)     - pointr to ioctl data                          */
4102 /*              set(I)      - 1 or 0 (filter set)                           */
4103 /*              makecopy(I) - flag indicating whether data points to a rule */
4104 /*                            in kernel space & hence doesn't need copying. */
4105 /*                                                                          */
4106 /* This function handles all the requests which operate on the list of      */
4107 /* filter rules.  This includes adding, deleting, insertion.  It is also    */
4108 /* responsible for creating groups when a "head" rule is loaded.  Interface */
4109 /* names are resolved here and other sanity checks are made on the content  */
4110 /* of the rule structure being loaded.  If a rule has user defined timeouts */
4111 /* then make sure they are created and initialised before exiting.          */
4112 /* ------------------------------------------------------------------------ */
4113 int frrequest(unit, req, data, set, makecopy, ifs)
4114 int unit;
4115 ioctlcmd_t req;
4116 int set, makecopy;
4117 caddr_t data;
4118 ipf_stack_t *ifs;
4119 {
4120 	frentry_t frd, *fp, *f, **fprev, **ftail;
4121 	int error = 0, in, v;
4122 	void *ptr, *uptr;
4123 	u_int *p, *pp;
4124 	frgroup_t *fg;
4125 	char *group;
4126 
4127 	fg = NULL;
4128 	fp = &frd;
4129 	if (makecopy != 0) {
4130 		error = fr_inobj(data, fp, IPFOBJ_FRENTRY);
4131 		if (error)
4132 			return EFAULT;
4133 		if ((fp->fr_flags & FR_T_BUILTIN) != 0)
4134 			return EINVAL;
4135 		fp->fr_ref = 0;
4136 		fp->fr_flags |= FR_COPIED;
4137 	} else {
4138 		fp = (frentry_t *)data;
4139 		if ((fp->fr_type & FR_T_BUILTIN) == 0)
4140 			return EINVAL;
4141 		fp->fr_flags &= ~FR_COPIED;
4142 	}
4143 
4144 	if (((fp->fr_dsize == 0) && (fp->fr_data != NULL)) ||
4145 	    ((fp->fr_dsize != 0) && (fp->fr_data == NULL)))
4146 		return EINVAL;
4147 
4148 	v = fp->fr_v;
4149 	uptr = fp->fr_data;
4150 
4151 	/*
4152 	 * Only filter rules for IPv4 or IPv6 are accepted.
4153 	 */
4154 	if (v == 4)
4155 		/*EMPTY*/;
4156 #ifdef	USE_INET6
4157 	else if (v == 6)
4158 		/*EMPTY*/;
4159 #endif
4160 	else {
4161 		return EINVAL;
4162 	}
4163 
4164 	/*
4165 	 * If the rule is being loaded from user space, i.e. we had to copy it
4166 	 * into kernel space, then do not trust the function pointer in the
4167 	 * rule.
4168 	 */
4169 	if ((makecopy == 1) && (fp->fr_func != NULL)) {
4170 		if (fr_findfunc(fp->fr_func) == NULL)
4171 			return ESRCH;
4172 		error = fr_funcinit(fp, ifs);
4173 		if (error != 0)
4174 			return error;
4175 	}
4176 
4177 	ptr = NULL;
4178 	/*
4179 	 * Check that the group number does exist and that its use (in/out)
4180 	 * matches what the rule is.
4181 	 */
4182 	if (!strncmp(fp->fr_grhead, "0", FR_GROUPLEN))
4183 		*fp->fr_grhead = '\0';
4184 	group = fp->fr_group;
4185 	if (!strncmp(group, "0", FR_GROUPLEN))
4186 		*group = '\0';
4187 
4188 	if (FR_ISACCOUNT(fp->fr_flags))
4189 		unit = IPL_LOGCOUNT;
4190 
4191 	if ((req != (int)SIOCZRLST) && (*group != '\0')) {
4192 		fg = fr_findgroup(group, unit, set, NULL, ifs);
4193 		if (fg == NULL)
4194 			return ESRCH;
4195 		if (fg->fg_flags == 0)
4196 			fg->fg_flags = fp->fr_flags & FR_INOUT;
4197 		else if (fg->fg_flags != (fp->fr_flags & FR_INOUT))
4198 			return ESRCH;
4199 	}
4200 
4201 	in = (fp->fr_flags & FR_INQUE) ? 0 : 1;
4202 
4203 	/*
4204 	 * Work out which rule list this change is being applied to.
4205 	 */
4206 	ftail = NULL;
4207 	fprev = NULL;
4208 	if (unit == IPL_LOGAUTH)
4209 		fprev = &ifs->ifs_ipauth;
4210 	else if (v == 4) {
4211 		if (FR_ISACCOUNT(fp->fr_flags))
4212 			fprev = &ifs->ifs_ipacct[in][set];
4213 		else if ((fp->fr_flags & (FR_OUTQUE|FR_INQUE)) != 0)
4214 			fprev = &ifs->ifs_ipfilter[in][set];
4215 	} else if (v == 6) {
4216 		if (FR_ISACCOUNT(fp->fr_flags))
4217 			fprev = &ifs->ifs_ipacct6[in][set];
4218 		else if ((fp->fr_flags & (FR_OUTQUE|FR_INQUE)) != 0)
4219 			fprev = &ifs->ifs_ipfilter6[in][set];
4220 	}
4221 	if (fprev == NULL)
4222 		return ESRCH;
4223 
4224 	if (*group != '\0') {
4225 	    if (!fg && !(fg = fr_findgroup(group, unit, set, NULL, ifs)))
4226 			return ESRCH;
4227 		fprev = &fg->fg_start;
4228 	}
4229 
4230 	ftail = fprev;
4231 	for (f = *ftail; (f = *ftail) != NULL; ftail = &f->fr_next) {
4232 		if (fp->fr_collect <= f->fr_collect) {
4233 			ftail = fprev;
4234 			f = NULL;
4235 			break;
4236 		}
4237 		fprev = ftail;
4238 	}
4239 
4240 	/*
4241 	 * Copy in extra data for the rule.
4242 	 */
4243 	if (fp->fr_dsize != 0) {
4244 		if (makecopy != 0) {
4245 			KMALLOCS(ptr, void *, fp->fr_dsize);
4246 			if (!ptr)
4247 				return ENOMEM;
4248 			error = COPYIN(uptr, ptr, fp->fr_dsize);
4249 		} else {
4250 			ptr = uptr;
4251 			error = 0;
4252 		}
4253 		if (error != 0) {
4254 			KFREES(ptr, fp->fr_dsize);
4255 			return ENOMEM;
4256 		}
4257 		fp->fr_data = ptr;
4258 	} else
4259 		fp->fr_data = NULL;
4260 
4261 	/*
4262 	 * Perform per-rule type sanity checks of their members.
4263 	 */
4264 	switch (fp->fr_type & ~FR_T_BUILTIN)
4265 	{
4266 #if defined(IPFILTER_BPF)
4267 	case FR_T_BPFOPC :
4268 		if (fp->fr_dsize == 0)
4269 			return EINVAL;
4270 		if (!bpf_validate(ptr, fp->fr_dsize/sizeof(struct bpf_insn))) {
4271 			if (makecopy && fp->fr_data != NULL) {
4272 				KFREES(fp->fr_data, fp->fr_dsize);
4273 			}
4274 			return EINVAL;
4275 		}
4276 		break;
4277 #endif
4278 	case FR_T_IPF :
4279 		if (fp->fr_dsize != sizeof(fripf_t))
4280 			return EINVAL;
4281 
4282 		/*
4283 		 * Allowing a rule with both "keep state" and "with oow" is
4284 		 * pointless because adding a state entry to the table will
4285 		 * fail with the out of window (oow) flag set.
4286 		 */
4287 		if ((fp->fr_flags & FR_KEEPSTATE) && (fp->fr_flx & FI_OOW))
4288 			return EINVAL;
4289 
4290 		switch (fp->fr_satype)
4291 		{
4292 		case FRI_BROADCAST :
4293 		case FRI_DYNAMIC :
4294 		case FRI_NETWORK :
4295 		case FRI_NETMASKED :
4296 		case FRI_PEERADDR :
4297 			if (fp->fr_sifpidx < 0 || fp->fr_sifpidx > 3) {
4298 				if (makecopy && fp->fr_data != NULL) {
4299 					KFREES(fp->fr_data, fp->fr_dsize);
4300 				}
4301 				return EINVAL;
4302 			}
4303 			break;
4304 #ifdef	IPFILTER_LOOKUP
4305 		case FRI_LOOKUP :
4306 			fp->fr_srcptr = fr_resolvelookup(fp->fr_srctype,
4307 							 fp->fr_srcnum,
4308 							 &fp->fr_srcfunc, ifs);
4309 			break;
4310 #endif
4311 		default :
4312 			break;
4313 		}
4314 
4315 		switch (fp->fr_datype)
4316 		{
4317 		case FRI_BROADCAST :
4318 		case FRI_DYNAMIC :
4319 		case FRI_NETWORK :
4320 		case FRI_NETMASKED :
4321 		case FRI_PEERADDR :
4322 			if (fp->fr_difpidx < 0 || fp->fr_difpidx > 3) {
4323 				if (makecopy && fp->fr_data != NULL) {
4324 					KFREES(fp->fr_data, fp->fr_dsize);
4325 				}
4326 				return EINVAL;
4327 			}
4328 			break;
4329 #ifdef	IPFILTER_LOOKUP
4330 		case FRI_LOOKUP :
4331 			fp->fr_dstptr = fr_resolvelookup(fp->fr_dsttype,
4332 							 fp->fr_dstnum,
4333 							 &fp->fr_dstfunc, ifs);
4334 			break;
4335 #endif
4336 		default :
4337 			break;
4338 		}
4339 		break;
4340 	case FR_T_NONE :
4341 		break;
4342 	case FR_T_CALLFUNC :
4343 		break;
4344 	case FR_T_COMPIPF :
4345 		break;
4346 	default :
4347 		if (makecopy && fp->fr_data != NULL) {
4348 			KFREES(fp->fr_data, fp->fr_dsize);
4349 		}
4350 		return EINVAL;
4351 	}
4352 
4353 	/*
4354 	 * Lookup all the interface names that are part of the rule.
4355 	 */
4356 	frsynclist(0, 0, NULL, NULL, fp, ifs);
4357 	fp->fr_statecnt = 0;
4358 
4359 	/*
4360 	 * Look for an existing matching filter rule, but don't include the
4361 	 * next or interface pointer in the comparison (fr_next, fr_ifa).
4362 	 * This elminates rules which are indentical being loaded.  Checksum
4363 	 * the constant part of the filter rule to make comparisons quicker
4364 	 * (this meaning no pointers are included).
4365 	 */
4366 	for (fp->fr_cksum = 0, p = (u_int *)&fp->fr_func, pp = &fp->fr_cksum;
4367 	     p < pp; p++)
4368 		fp->fr_cksum += *p;
4369 	pp = (u_int *)(fp->fr_caddr + fp->fr_dsize);
4370 	for (p = (u_int *)fp->fr_data; p < pp; p++)
4371 		fp->fr_cksum += *p;
4372 
4373 	WRITE_ENTER(&ifs->ifs_ipf_mutex);
4374 	bzero((char *)&ifs->ifs_frcache, sizeof (ifs->ifs_frcache));
4375 
4376 	for (; (f = *ftail) != NULL; ftail = &f->fr_next) {
4377 		if ((fp->fr_cksum != f->fr_cksum) ||
4378 		    (f->fr_dsize != fp->fr_dsize))
4379 			continue;
4380 		if (bcmp((char *)&f->fr_func, (char *)&fp->fr_func, FR_CMPSIZ))
4381 			continue;
4382 		if ((!ptr && !f->fr_data) ||
4383 		    (ptr && f->fr_data &&
4384 		     !bcmp((char *)ptr, (char *)f->fr_data, f->fr_dsize)))
4385 			break;
4386 	}
4387 
4388 	/*
4389 	 * If zero'ing statistics, copy current to caller and zero.
4390 	 */
4391 	if (req == (ioctlcmd_t)SIOCZRLST) {
4392 		if (f == NULL)
4393 			error = ESRCH;
4394 		else {
4395 			/*
4396 			 * Copy and reduce lock because of impending copyout.
4397 			 * Well we should, but if we do then the atomicity of
4398 			 * this call and the correctness of fr_hits and
4399 			 * fr_bytes cannot be guaranteed.  As it is, this code
4400 			 * only resets them to 0 if they are successfully
4401 			 * copied out into user space.
4402 			 */
4403 			bcopy((char *)f, (char *)fp, sizeof(*f));
4404 			/* MUTEX_DOWNGRADE(&ipf_mutex); */
4405 
4406 			/*
4407 			 * When we copy this rule back out, set the data
4408 			 * pointer to be what it was in user space.
4409 			 */
4410 			fp->fr_data = uptr;
4411 			error = fr_outobj(data, fp, IPFOBJ_FRENTRY);
4412 
4413 			if (error == 0) {
4414 				if ((f->fr_dsize != 0) && (uptr != NULL))
4415 					error = COPYOUT(f->fr_data, uptr,
4416 							f->fr_dsize);
4417 				if (error == 0) {
4418 					f->fr_hits = 0;
4419 					f->fr_bytes = 0;
4420 				}
4421 			}
4422 		}
4423 
4424 		if ((ptr != NULL) && (makecopy != 0)) {
4425 			KFREES(ptr, fp->fr_dsize);
4426 		}
4427 		RWLOCK_EXIT(&ifs->ifs_ipf_mutex);
4428 		return error;
4429 	}
4430 
4431 	if (!f) {
4432 		/*
4433 		 * At the end of this, ftail must point to the place where the
4434 		 * new rule is to be saved/inserted/added.
4435 		 * For SIOCAD*FR, this should be the last rule in the group of
4436 		 * rules that have equal fr_collect fields.
4437 		 * For SIOCIN*FR, ...
4438 		 */
4439 		if (req == (ioctlcmd_t)SIOCADAFR ||
4440 		    req == (ioctlcmd_t)SIOCADIFR) {
4441 
4442 			for (ftail = fprev; (f = *ftail) != NULL; ) {
4443 				if (f->fr_collect > fp->fr_collect)
4444 					break;
4445 				ftail = &f->fr_next;
4446 			}
4447 			f = NULL;
4448 			ptr = NULL;
4449 			error = 0;
4450 		} else if (req == (ioctlcmd_t)SIOCINAFR ||
4451 			   req == (ioctlcmd_t)SIOCINIFR) {
4452 			while ((f = *fprev) != NULL) {
4453 				if (f->fr_collect >= fp->fr_collect)
4454 					break;
4455 				fprev = &f->fr_next;
4456 			}
4457 			ftail = fprev;
4458 			if (fp->fr_hits != 0) {
4459 				while (fp->fr_hits && (f = *ftail)) {
4460 					if (f->fr_collect != fp->fr_collect)
4461 						break;
4462 					fprev = ftail;
4463 					ftail = &f->fr_next;
4464 					fp->fr_hits--;
4465 				}
4466 			}
4467 			f = NULL;
4468 			ptr = NULL;
4469 			error = 0;
4470 		}
4471 	}
4472 
4473 	/*
4474 	 * Request to remove a rule.
4475 	 */
4476 	if (req == (ioctlcmd_t)SIOCRMAFR || req == (ioctlcmd_t)SIOCRMIFR) {
4477 		if (!f)
4478 			error = ESRCH;
4479 		else {
4480 			/*
4481 			 * Do not allow activity from user space to interfere
4482 			 * with rules not loaded that way.
4483 			 */
4484 			if ((makecopy == 1) && !(f->fr_flags & FR_COPIED)) {
4485 				error = EPERM;
4486 				goto done;
4487 			}
4488 
4489 			/*
4490 			 * Return EBUSY if the rule is being reference by
4491 			 * something else (eg state information.
4492 			 */
4493 			if (f->fr_ref > 1) {
4494 				error = EBUSY;
4495 				goto done;
4496 			}
4497 #ifdef	IPFILTER_SCAN
4498 			if (f->fr_isctag[0] != '\0' &&
4499 			    (f->fr_isc != (struct ipscan *)-1))
4500 				ipsc_detachfr(f);
4501 #endif
4502 			if (unit == IPL_LOGAUTH) {
4503 				error = fr_preauthcmd(req, f, ftail, ifs);
4504 				goto done;
4505 			}
4506 			if (*f->fr_grhead != '\0')
4507 				fr_delgroup(f->fr_grhead, unit, set, ifs);
4508 			fr_fixskip(ftail, f, -1);
4509 			*ftail = f->fr_next;
4510 			f->fr_next = NULL;
4511 			(void)fr_derefrule(&f, ifs);
4512 		}
4513 	} else {
4514 		/*
4515 		 * Not removing, so we must be adding/inserting a rule.
4516 		 */
4517 		if (f)
4518 			error = EEXIST;
4519 		else {
4520 			if (unit == IPL_LOGAUTH) {
4521 				error = fr_preauthcmd(req, fp, ftail, ifs);
4522 				goto done;
4523 			}
4524 			if (makecopy) {
4525 				KMALLOC(f, frentry_t *);
4526 			} else
4527 				f = fp;
4528 			if (f != NULL) {
4529 				if (fp != f)
4530 					bcopy((char *)fp, (char *)f,
4531 					      sizeof(*f));
4532 				MUTEX_NUKE(&f->fr_lock);
4533 				MUTEX_INIT(&f->fr_lock, "filter rule lock");
4534 #ifdef	IPFILTER_SCAN
4535 				if (f->fr_isctag[0] != '\0' &&
4536 				    ipsc_attachfr(f))
4537 					f->fr_isc = (struct ipscan *)-1;
4538 #endif
4539 				f->fr_hits = 0;
4540 				if (makecopy != 0)
4541 					f->fr_ref = 1;
4542 				f->fr_next = *ftail;
4543 				*ftail = f;
4544 				if (req == (ioctlcmd_t)SIOCINIFR ||
4545 				    req == (ioctlcmd_t)SIOCINAFR)
4546 					fr_fixskip(ftail, f, 1);
4547 				f->fr_grp = NULL;
4548 				group = f->fr_grhead;
4549 				if (*group != '\0') {
4550 					fg = fr_addgroup(group, f, f->fr_flags,
4551 							 unit, set, ifs);
4552 					if (fg != NULL)
4553 						f->fr_grp = &fg->fg_start;
4554 				}
4555 			} else
4556 				error = ENOMEM;
4557 		}
4558 	}
4559 done:
4560 	RWLOCK_EXIT(&ifs->ifs_ipf_mutex);
4561 	if ((ptr != NULL) && (error != 0) && (makecopy != 0)) {
4562 		KFREES(ptr, fp->fr_dsize);
4563 	}
4564 	return (error);
4565 }
4566 
4567 
4568 /* ------------------------------------------------------------------------ */
4569 /* Function:    fr_funcinit                                                 */
4570 /* Returns:     int - 0 == success, else ESRCH: cannot resolve rule details */
4571 /* Parameters:  fr(I) - pointer to filter rule                              */
4572 /*                                                                          */
4573 /* If a rule is a call rule, then check if the function it points to needs  */
4574 /* an init function to be called now the rule has been loaded.              */
4575 /* ------------------------------------------------------------------------ */
4576 static int fr_funcinit(fr, ifs)
4577 frentry_t *fr;
4578 ipf_stack_t *ifs;
4579 {
4580 	ipfunc_resolve_t *ft;
4581 	int err;
4582 
4583 	err = ESRCH;
4584 
4585 	for (ft = fr_availfuncs; ft->ipfu_addr != NULL; ft++)
4586 		if (ft->ipfu_addr == fr->fr_func) {
4587 			err = 0;
4588 			if (ft->ipfu_init != NULL)
4589 				err = (*ft->ipfu_init)(fr, ifs);
4590 			break;
4591 		}
4592 	return err;
4593 }
4594 
4595 
4596 /* ------------------------------------------------------------------------ */
4597 /* Function:    fr_findfunc                                                 */
4598 /* Returns:     ipfunc_t - pointer to function if found, else NULL          */
4599 /* Parameters:  funcptr(I) - function pointer to lookup                     */
4600 /*                                                                          */
4601 /* Look for a function in the table of known functions.                     */
4602 /* ------------------------------------------------------------------------ */
4603 static ipfunc_t fr_findfunc(funcptr)
4604 ipfunc_t funcptr;
4605 {
4606 	ipfunc_resolve_t *ft;
4607 
4608 	for (ft = fr_availfuncs; ft->ipfu_addr != NULL; ft++)
4609 		if (ft->ipfu_addr == funcptr)
4610 			return funcptr;
4611 	return NULL;
4612 }
4613 
4614 
4615 /* ------------------------------------------------------------------------ */
4616 /* Function:    fr_resolvefunc                                              */
4617 /* Returns:     int - 0 == success, else error                              */
4618 /* Parameters:  data(IO) - ioctl data pointer to ipfunc_resolve_t struct    */
4619 /*                                                                          */
4620 /* Copy in a ipfunc_resolve_t structure and then fill in the missing field. */
4621 /* This will either be the function name (if the pointer is set) or the     */
4622 /* function pointer if the name is set.  When found, fill in the other one  */
4623 /* so that the entire, complete, structure can be copied back to user space.*/
4624 /* ------------------------------------------------------------------------ */
4625 int fr_resolvefunc(data)
4626 void *data;
4627 {
4628 	ipfunc_resolve_t res, *ft;
4629 
4630 	BCOPYIN(data, &res, sizeof(res));
4631 
4632 	if (res.ipfu_addr == NULL && res.ipfu_name[0] != '\0') {
4633 		for (ft = fr_availfuncs; ft->ipfu_addr != NULL; ft++)
4634 			if (strncmp(res.ipfu_name, ft->ipfu_name,
4635 				    sizeof(res.ipfu_name)) == 0) {
4636 				res.ipfu_addr = ft->ipfu_addr;
4637 				res.ipfu_init = ft->ipfu_init;
4638 				if (COPYOUT(&res, data, sizeof(res)) != 0)
4639 					return EFAULT;
4640 				return 0;
4641 			}
4642 	}
4643 	if (res.ipfu_addr != NULL && res.ipfu_name[0] == '\0') {
4644 		for (ft = fr_availfuncs; ft->ipfu_addr != NULL; ft++)
4645 			if (ft->ipfu_addr == res.ipfu_addr) {
4646 				(void) strncpy(res.ipfu_name, ft->ipfu_name,
4647 					       sizeof(res.ipfu_name));
4648 				res.ipfu_init = ft->ipfu_init;
4649 				if (COPYOUT(&res, data, sizeof(res)) != 0)
4650 					return EFAULT;
4651 				return 0;
4652 			}
4653 	}
4654 	return ESRCH;
4655 }
4656 
4657 
4658 #if !defined(_KERNEL) || (!defined(__NetBSD__) && !defined(__OpenBSD__) && !defined(__FreeBSD__)) || \
4659     (defined(__FreeBSD__) && (__FreeBSD_version < 490000)) || \
4660     (defined(__NetBSD__) && (__NetBSD_Version__ < 105000000)) || \
4661     (defined(__OpenBSD__) && (OpenBSD < 200006))
4662 /*
4663  * From: NetBSD
4664  * ppsratecheck(): packets (or events) per second limitation.
4665  */
4666 int
4667 ppsratecheck(lasttime, curpps, maxpps)
4668 	struct timeval *lasttime;
4669 	int *curpps;
4670 	int maxpps;	/* maximum pps allowed */
4671 {
4672 	struct timeval tv, delta;
4673 	int rv;
4674 
4675 	GETKTIME(&tv);
4676 
4677 	delta.tv_sec = tv.tv_sec - lasttime->tv_sec;
4678 	delta.tv_usec = tv.tv_usec - lasttime->tv_usec;
4679 	if (delta.tv_usec < 0) {
4680 		delta.tv_sec--;
4681 		delta.tv_usec += 1000000;
4682 	}
4683 
4684 	/*
4685 	 * check for 0,0 is so that the message will be seen at least once.
4686 	 * if more than one second have passed since the last update of
4687 	 * lasttime, reset the counter.
4688 	 *
4689 	 * we do increment *curpps even in *curpps < maxpps case, as some may
4690 	 * try to use *curpps for stat purposes as well.
4691 	 */
4692 	if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
4693 	    delta.tv_sec >= 1) {
4694 		*lasttime = tv;
4695 		*curpps = 0;
4696 		rv = 1;
4697 	} else if (maxpps < 0)
4698 		rv = 1;
4699 	else if (*curpps < maxpps)
4700 		rv = 1;
4701 	else
4702 		rv = 0;
4703 	*curpps = *curpps + 1;
4704 
4705 	return (rv);
4706 }
4707 #endif
4708 
4709 
4710 /* ------------------------------------------------------------------------ */
4711 /* Function:    fr_derefrule                                                */
4712 /* Returns:     int   - 0 == rule freed up, else rule not freed             */
4713 /* Parameters:  fr(I) - pointer to filter rule                              */
4714 /*                                                                          */
4715 /* Decrement the reference counter to a rule by one.  If it reaches zero,   */
4716 /* free it and any associated storage space being used by it.               */
4717 /* ------------------------------------------------------------------------ */
4718 int fr_derefrule(frp, ifs)
4719 frentry_t **frp;
4720 ipf_stack_t *ifs;
4721 {
4722 	frentry_t *fr;
4723 
4724 	fr = *frp;
4725 
4726 	MUTEX_ENTER(&fr->fr_lock);
4727 	fr->fr_ref--;
4728 	if (fr->fr_ref == 0) {
4729 		MUTEX_EXIT(&fr->fr_lock);
4730 		MUTEX_DESTROY(&fr->fr_lock);
4731 
4732 #ifdef IPFILTER_LOOKUP
4733 		if (fr->fr_type == FR_T_IPF && fr->fr_satype == FRI_LOOKUP)
4734 		    ip_lookup_deref(fr->fr_srctype, fr->fr_srcptr, ifs);
4735 		if (fr->fr_type == FR_T_IPF && fr->fr_datype == FRI_LOOKUP)
4736 		    ip_lookup_deref(fr->fr_dsttype, fr->fr_dstptr, ifs);
4737 #endif
4738 
4739 		if (fr->fr_dsize) {
4740 			KFREES(fr->fr_data, fr->fr_dsize);
4741 		}
4742 		if ((fr->fr_flags & FR_COPIED) != 0) {
4743 			KFREE(fr);
4744 			return 0;
4745 		}
4746 		return 1;
4747 	} else {
4748 		MUTEX_EXIT(&fr->fr_lock);
4749 	}
4750 	*frp = NULL;
4751 	return -1;
4752 }
4753 
4754 
4755 #ifdef	IPFILTER_LOOKUP
4756 /* ------------------------------------------------------------------------ */
4757 /* Function:    fr_grpmapinit                                               */
4758 /* Returns:     int - 0 == success, else ESRCH because table entry not found*/
4759 /* Parameters:  fr(I) - pointer to rule to find hash table for              */
4760 /*                                                                          */
4761 /* Looks for group hash table fr_arg and stores a pointer to it in fr_ptr.  */
4762 /* fr_ptr is later used by fr_srcgrpmap and fr_dstgrpmap.                   */
4763 /* ------------------------------------------------------------------------ */
4764 static int fr_grpmapinit(fr, ifs)
4765 frentry_t *fr;
4766 ipf_stack_t *ifs;
4767 {
4768 	char name[FR_GROUPLEN];
4769 	iphtable_t *iph;
4770 
4771 #if defined(SNPRINTF) && defined(_KERNEL)
4772 	(void) SNPRINTF(name, sizeof(name), "%d", fr->fr_arg);
4773 #else
4774 	(void) sprintf(name, "%d", fr->fr_arg);
4775 #endif
4776 	iph = fr_findhtable(IPL_LOGIPF, name, ifs);
4777 	if (iph == NULL)
4778 		return ESRCH;
4779 	if ((iph->iph_flags & FR_INOUT) != (fr->fr_flags & FR_INOUT))
4780 		return ESRCH;
4781 	fr->fr_ptr = iph;
4782 	return 0;
4783 }
4784 
4785 
4786 /* ------------------------------------------------------------------------ */
4787 /* Function:    fr_srcgrpmap                                                */
4788 /* Returns:     frentry_t * - pointer to "new last matching" rule or NULL   */
4789 /* Parameters:  fin(I)    - pointer to packet information                   */
4790 /*              passp(IO) - pointer to current/new filter decision (unused) */
4791 /*                                                                          */
4792 /* Look for a rule group head in a hash table, using the source address as  */
4793 /* the key, and descend into that group and continue matching rules against */
4794 /* the packet.                                                              */
4795 /* ------------------------------------------------------------------------ */
4796 frentry_t *fr_srcgrpmap(fin, passp)
4797 fr_info_t *fin;
4798 u_32_t *passp;
4799 {
4800 	frgroup_t *fg;
4801 	void *rval;
4802 	ipf_stack_t *ifs = fin->fin_ifs;
4803 
4804 	rval = fr_iphmfindgroup(fin->fin_fr->fr_ptr, fin->fin_v, &fin->fin_src, ifs);
4805 	if (rval == NULL)
4806 		return NULL;
4807 
4808 	fg = rval;
4809 	fin->fin_fr = fg->fg_start;
4810 	(void) fr_scanlist(fin, *passp);
4811 	return fin->fin_fr;
4812 }
4813 
4814 
4815 /* ------------------------------------------------------------------------ */
4816 /* Function:    fr_dstgrpmap                                                */
4817 /* Returns:     frentry_t * - pointer to "new last matching" rule or NULL   */
4818 /* Parameters:  fin(I)    - pointer to packet information                   */
4819 /*              passp(IO) - pointer to current/new filter decision (unused) */
4820 /*                                                                          */
4821 /* Look for a rule group head in a hash table, using the destination        */
4822 /* address as the key, and descend into that group and continue matching    */
4823 /* rules against  the packet.                                               */
4824 /* ------------------------------------------------------------------------ */
4825 frentry_t *fr_dstgrpmap(fin, passp)
4826 fr_info_t *fin;
4827 u_32_t *passp;
4828 {
4829 	frgroup_t *fg;
4830 	void *rval;
4831 	ipf_stack_t *ifs = fin->fin_ifs;
4832 
4833 	rval = fr_iphmfindgroup(fin->fin_fr->fr_ptr, fin->fin_v, &fin->fin_dst, ifs);
4834 	if (rval == NULL)
4835 		return NULL;
4836 
4837 	fg = rval;
4838 	fin->fin_fr = fg->fg_start;
4839 	(void) fr_scanlist(fin, *passp);
4840 	return fin->fin_fr;
4841 }
4842 #endif /* IPFILTER_LOOKUP */
4843 
4844 /*
4845  * Queue functions
4846  * ===============
4847  * These functions manage objects on queues for efficient timeouts.  There are
4848  * a number of system defined queues as well as user defined timeouts.  It is
4849  * expected that a lock is held in the domain in which the queue belongs
4850  * (i.e. either state or NAT) when calling any of these functions that prevents
4851  * fr_freetimeoutqueue() from being called at the same time as any other.
4852  */
4853 
4854 
4855 /* ------------------------------------------------------------------------ */
4856 /* Function:    fr_addtimeoutqueue                                          */
4857 /* Returns:     struct ifqtq * - NULL if malloc fails, else pointer to      */
4858 /*                               timeout queue with given interval.         */
4859 /* Parameters:  parent(I)  - pointer to pointer to parent node of this list */
4860 /*                           of interface queues.                           */
4861 /*              seconds(I) - timeout value in seconds for this queue.       */
4862 /*                                                                          */
4863 /* This routine first looks for a timeout queue that matches the interval   */
4864 /* being requested.  If it finds one, increments the reference counter and  */
4865 /* returns a pointer to it.  If none are found, it allocates a new one and  */
4866 /* inserts it at the top of the list.                                       */
4867 /*                                                                          */
4868 /* Locking.                                                                 */
4869 /* It is assumed that the caller of this function has an appropriate lock   */
4870 /* held (exclusively) in the domain that encompases 'parent'.               */
4871 /* ------------------------------------------------------------------------ */
4872 ipftq_t *fr_addtimeoutqueue(parent, seconds, ifs)
4873 ipftq_t **parent;
4874 u_int seconds;
4875 ipf_stack_t *ifs;
4876 {
4877 	ipftq_t *ifq;
4878 	u_int period;
4879 
4880 	period = seconds * IPF_HZ_DIVIDE;
4881 
4882 	MUTEX_ENTER(&ifs->ifs_ipf_timeoutlock);
4883 	for (ifq = *parent; ifq != NULL; ifq = ifq->ifq_next) {
4884 		if (ifq->ifq_ttl == period) {
4885 			/*
4886 			 * Reset the delete flag, if set, so the structure
4887 			 * gets reused rather than freed and reallocated.
4888 			 */
4889 			MUTEX_ENTER(&ifq->ifq_lock);
4890 			ifq->ifq_flags &= ~IFQF_DELETE;
4891 			ifq->ifq_ref++;
4892 			MUTEX_EXIT(&ifq->ifq_lock);
4893 			MUTEX_EXIT(&ifs->ifs_ipf_timeoutlock);
4894 
4895 			return ifq;
4896 		}
4897 	}
4898 
4899 	KMALLOC(ifq, ipftq_t *);
4900 	if (ifq != NULL) {
4901 		ifq->ifq_ttl = period;
4902 		ifq->ifq_head = NULL;
4903 		ifq->ifq_tail = &ifq->ifq_head;
4904 		ifq->ifq_next = *parent;
4905 		ifq->ifq_pnext = parent;
4906 		ifq->ifq_ref = 1;
4907 		ifq->ifq_flags = IFQF_USER;
4908 		*parent = ifq;
4909 		ifs->ifs_fr_userifqs++;
4910 		MUTEX_NUKE(&ifq->ifq_lock);
4911 		MUTEX_INIT(&ifq->ifq_lock, "ipftq mutex");
4912 	}
4913 	MUTEX_EXIT(&ifs->ifs_ipf_timeoutlock);
4914 	return ifq;
4915 }
4916 
4917 
4918 /* ------------------------------------------------------------------------ */
4919 /* Function:    fr_deletetimeoutqueue                                       */
4920 /* Returns:     int    - new reference count value of the timeout queue     */
4921 /* Parameters:  ifq(I) - timeout queue which is losing a reference.         */
4922 /* Locks:       ifq->ifq_lock                                               */
4923 /*                                                                          */
4924 /* This routine must be called when we're discarding a pointer to a timeout */
4925 /* queue object, taking care of the reference counter.                      */
4926 /*                                                                          */
4927 /* Now that this just sets a DELETE flag, it requires the expire code to    */
4928 /* check the list of user defined timeout queues and call the free function */
4929 /* below (currently commented out) to stop memory leaking.  It is done this */
4930 /* way because the locking may not be sufficient to safely do a free when   */
4931 /* this function is called.                                                 */
4932 /* ------------------------------------------------------------------------ */
4933 int fr_deletetimeoutqueue(ifq)
4934 ipftq_t *ifq;
4935 {
4936 
4937 	ifq->ifq_ref--;
4938 	if ((ifq->ifq_ref == 0) && ((ifq->ifq_flags & IFQF_USER) != 0)) {
4939 		ifq->ifq_flags |= IFQF_DELETE;
4940 	}
4941 
4942 	return ifq->ifq_ref;
4943 }
4944 
4945 
4946 /* ------------------------------------------------------------------------ */
4947 /* Function:    fr_freetimeoutqueue                                         */
4948 /* Parameters:  ifq(I) - timeout queue which is losing a reference.         */
4949 /* Returns:     Nil                                                         */
4950 /*                                                                          */
4951 /* Locking:                                                                 */
4952 /* It is assumed that the caller of this function has an appropriate lock   */
4953 /* held (exclusively) in the domain that encompases the callers "domain".   */
4954 /* The ifq_lock for this structure should not be held.                      */
4955 /*                                                                          */
4956 /* Remove a user definde timeout queue from the list of queues it is in and */
4957 /* tidy up after this is done.                                              */
4958 /* ------------------------------------------------------------------------ */
4959 void fr_freetimeoutqueue(ifq, ifs)
4960 ipftq_t *ifq;
4961 ipf_stack_t *ifs;
4962 {
4963 
4964 
4965 	if (((ifq->ifq_flags & IFQF_DELETE) == 0) || (ifq->ifq_ref != 0) ||
4966 	    ((ifq->ifq_flags & IFQF_USER) == 0)) {
4967 		printf("fr_freetimeoutqueue(%lx) flags 0x%x ttl %d ref %d\n",
4968 		       (u_long)ifq, ifq->ifq_flags, ifq->ifq_ttl,
4969 		       ifq->ifq_ref);
4970 		return;
4971 	}
4972 
4973 	/*
4974 	 * Remove from its position in the list.
4975 	 */
4976 	*ifq->ifq_pnext = ifq->ifq_next;
4977 	if (ifq->ifq_next != NULL)
4978 		ifq->ifq_next->ifq_pnext = ifq->ifq_pnext;
4979 
4980 	MUTEX_DESTROY(&ifq->ifq_lock);
4981 	ifs->ifs_fr_userifqs--;
4982 	KFREE(ifq);
4983 }
4984 
4985 
4986 /* ------------------------------------------------------------------------ */
4987 /* Function:    fr_deletequeueentry                                         */
4988 /* Returns:     Nil                                                         */
4989 /* Parameters:  tqe(I) - timeout queue entry to delete                      */
4990 /*              ifq(I) - timeout queue to remove entry from                 */
4991 /*                                                                          */
4992 /* Remove a tail queue entry from its queue and make it an orphan.          */
4993 /* fr_deletetimeoutqueue is called to make sure the reference count on the  */
4994 /* queue is correct.  We can't, however, call fr_freetimeoutqueue because   */
4995 /* the correct lock(s) may not be held that would make it safe to do so.    */
4996 /* ------------------------------------------------------------------------ */
4997 void fr_deletequeueentry(tqe)
4998 ipftqent_t *tqe;
4999 {
5000 	ipftq_t *ifq;
5001 
5002 	ifq = tqe->tqe_ifq;
5003 	if (ifq == NULL)
5004 		return;
5005 
5006 	MUTEX_ENTER(&ifq->ifq_lock);
5007 
5008 	if (tqe->tqe_pnext != NULL) {
5009 		*tqe->tqe_pnext = tqe->tqe_next;
5010 		if (tqe->tqe_next != NULL)
5011 			tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5012 		else    /* we must be the tail anyway */
5013 			ifq->ifq_tail = tqe->tqe_pnext;
5014 
5015 		tqe->tqe_pnext = NULL;
5016 		tqe->tqe_ifq = NULL;
5017 	}
5018 
5019 	(void) fr_deletetimeoutqueue(ifq);
5020 
5021 	MUTEX_EXIT(&ifq->ifq_lock);
5022 }
5023 
5024 
5025 /* ------------------------------------------------------------------------ */
5026 /* Function:    fr_queuefront                                               */
5027 /* Returns:     Nil                                                         */
5028 /* Parameters:  tqe(I) - pointer to timeout queue entry                     */
5029 /*                                                                          */
5030 /* Move a queue entry to the front of the queue, if it isn't already there. */
5031 /* ------------------------------------------------------------------------ */
5032 void fr_queuefront(tqe)
5033 ipftqent_t *tqe;
5034 {
5035 	ipftq_t *ifq;
5036 
5037 	ifq = tqe->tqe_ifq;
5038 	if (ifq == NULL)
5039 		return;
5040 
5041 	MUTEX_ENTER(&ifq->ifq_lock);
5042 	if (ifq->ifq_head != tqe) {
5043 		*tqe->tqe_pnext = tqe->tqe_next;
5044 		if (tqe->tqe_next)
5045 			tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5046 		else
5047 			ifq->ifq_tail = tqe->tqe_pnext;
5048 
5049 		tqe->tqe_next = ifq->ifq_head;
5050 		ifq->ifq_head->tqe_pnext = &tqe->tqe_next;
5051 		ifq->ifq_head = tqe;
5052 		tqe->tqe_pnext = &ifq->ifq_head;
5053 	}
5054 	MUTEX_EXIT(&ifq->ifq_lock);
5055 }
5056 
5057 
5058 /* ------------------------------------------------------------------------ */
5059 /* Function:    fr_queueback                                                */
5060 /* Returns:     Nil                                                         */
5061 /* Parameters:  tqe(I) - pointer to timeout queue entry                     */
5062 /*                                                                          */
5063 /* Move a queue entry to the back of the queue, if it isn't already there.  */
5064 /* ------------------------------------------------------------------------ */
5065 void fr_queueback(tqe, ifs)
5066 ipftqent_t *tqe;
5067 ipf_stack_t *ifs;
5068 {
5069 	ipftq_t *ifq;
5070 
5071 	ifq = tqe->tqe_ifq;
5072 	if (ifq == NULL)
5073 		return;
5074 	tqe->tqe_die = ifs->ifs_fr_ticks + ifq->ifq_ttl;
5075 
5076 	MUTEX_ENTER(&ifq->ifq_lock);
5077 	if (tqe->tqe_next == NULL) {		/* at the end already ? */
5078 		MUTEX_EXIT(&ifq->ifq_lock);
5079 		return;
5080 	}
5081 
5082 	/*
5083 	 * Remove from list
5084 	 */
5085 	*tqe->tqe_pnext = tqe->tqe_next;
5086 	tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5087 
5088 	/*
5089 	 * Make it the last entry.
5090 	 */
5091 	tqe->tqe_next = NULL;
5092 	tqe->tqe_pnext = ifq->ifq_tail;
5093 	*ifq->ifq_tail = tqe;
5094 	ifq->ifq_tail = &tqe->tqe_next;
5095 	MUTEX_EXIT(&ifq->ifq_lock);
5096 }
5097 
5098 
5099 /* ------------------------------------------------------------------------ */
5100 /* Function:    fr_queueappend                                              */
5101 /* Returns:     Nil                                                         */
5102 /* Parameters:  tqe(I)    - pointer to timeout queue entry                  */
5103 /*              ifq(I)    - pointer to timeout queue                        */
5104 /*              parent(I) - owing object pointer                            */
5105 /*                                                                          */
5106 /* Add a new item to this queue and put it on the very end.                 */
5107 /* ------------------------------------------------------------------------ */
5108 void fr_queueappend(tqe, ifq, parent, ifs)
5109 ipftqent_t *tqe;
5110 ipftq_t *ifq;
5111 void *parent;
5112 ipf_stack_t *ifs;
5113 {
5114 
5115 	MUTEX_ENTER(&ifq->ifq_lock);
5116 	tqe->tqe_parent = parent;
5117 	tqe->tqe_pnext = ifq->ifq_tail;
5118 	*ifq->ifq_tail = tqe;
5119 	ifq->ifq_tail = &tqe->tqe_next;
5120 	tqe->tqe_next = NULL;
5121 	tqe->tqe_ifq = ifq;
5122 	tqe->tqe_die = ifs->ifs_fr_ticks + ifq->ifq_ttl;
5123 	ifq->ifq_ref++;
5124 	MUTEX_EXIT(&ifq->ifq_lock);
5125 }
5126 
5127 
5128 /* ------------------------------------------------------------------------ */
5129 /* Function:    fr_movequeue                                                */
5130 /* Returns:     Nil                                                         */
5131 /* Parameters:  tq(I)   - pointer to timeout queue information              */
5132 /*              oifp(I) - old timeout queue entry was on                    */
5133 /*              nifp(I) - new timeout queue to put entry on                 */
5134 /*                                                                          */
5135 /* Move a queue entry from one timeout queue to another timeout queue.      */
5136 /* If it notices that the current entry is already last and does not need   */
5137 /* to move queue, the return.                                               */
5138 /* ------------------------------------------------------------------------ */
5139 void fr_movequeue(tqe, oifq, nifq, ifs)
5140 ipftqent_t *tqe;
5141 ipftq_t *oifq, *nifq;
5142 ipf_stack_t *ifs;
5143 {
5144 	/*
5145 	 * Is the operation here going to be a no-op ?
5146 	 */
5147 	MUTEX_ENTER(&oifq->ifq_lock);
5148 	if (oifq == nifq && *oifq->ifq_tail == tqe) {
5149 		MUTEX_EXIT(&oifq->ifq_lock);
5150 		return;
5151 	}
5152 
5153 	/*
5154 	 * Remove from the old queue
5155 	 */
5156 	*tqe->tqe_pnext = tqe->tqe_next;
5157 	if (tqe->tqe_next)
5158 		tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5159 	else
5160 		oifq->ifq_tail = tqe->tqe_pnext;
5161 	tqe->tqe_next = NULL;
5162 
5163 	/*
5164 	 * If we're moving from one queue to another, release the lock on the
5165 	 * old queue and get a lock on the new queue.  For user defined queues,
5166 	 * if we're moving off it, call delete in case it can now be freed.
5167 	 */
5168 	if (oifq != nifq) {
5169 		tqe->tqe_ifq = NULL;
5170 
5171 		(void) fr_deletetimeoutqueue(oifq);
5172 
5173 		MUTEX_EXIT(&oifq->ifq_lock);
5174 
5175 		MUTEX_ENTER(&nifq->ifq_lock);
5176 
5177 		tqe->tqe_ifq = nifq;
5178 		nifq->ifq_ref++;
5179 	}
5180 
5181 	/*
5182 	 * Add to the bottom of the new queue
5183 	 */
5184 	tqe->tqe_die = ifs->ifs_fr_ticks + nifq->ifq_ttl;
5185 	tqe->tqe_pnext = nifq->ifq_tail;
5186 	*nifq->ifq_tail = tqe;
5187 	nifq->ifq_tail = &tqe->tqe_next;
5188 	MUTEX_EXIT(&nifq->ifq_lock);
5189 }
5190 
5191 
5192 /* ------------------------------------------------------------------------ */
5193 /* Function:    fr_updateipid                                               */
5194 /* Returns:     int - 0 == success, -1 == error (packet should be droppped) */
5195 /* Parameters:  fin(I) - pointer to packet information                      */
5196 /*                                                                          */
5197 /* When we are doing NAT, change the IP of every packet to represent a      */
5198 /* single sequence of packets coming from the host, hiding any host         */
5199 /* specific sequencing that might otherwise be revealed.  If the packet is  */
5200 /* a fragment, then store the 'new' IPid in the fragment cache and look up  */
5201 /* the fragment cache for non-leading fragments.  If a non-leading fragment */
5202 /* has no match in the cache, return an error.                              */
5203 /* ------------------------------------------------------------------------ */
5204 static INLINE int fr_updateipid(fin)
5205 fr_info_t *fin;
5206 {
5207 	u_short id, ido, sums;
5208 	u_32_t sumd, sum;
5209 	ip_t *ip;
5210 
5211 	if (fin->fin_off != 0) {
5212 		sum = fr_ipid_knownfrag(fin);
5213 		if (sum == 0xffffffff)
5214 			return -1;
5215 		sum &= 0xffff;
5216 		id = (u_short)sum;
5217 	} else {
5218 		id = fr_nextipid(fin);
5219 		if (fin->fin_off == 0 && (fin->fin_flx & FI_FRAG) != 0)
5220 			(void) fr_ipid_newfrag(fin, (u_32_t)id);
5221 	}
5222 
5223 	ip = fin->fin_ip;
5224 	ido = ntohs(ip->ip_id);
5225 	if (id == ido)
5226 		return 0;
5227 	ip->ip_id = htons(id);
5228 	CALC_SUMD(ido, id, sumd);	/* DESTRUCTIVE MACRO! id,ido change */
5229 	sum = (~ntohs(ip->ip_sum)) & 0xffff;
5230 	sum += sumd;
5231 	sum = (sum >> 16) + (sum & 0xffff);
5232 	sum = (sum >> 16) + (sum & 0xffff);
5233 	sums = ~(u_short)sum;
5234 	ip->ip_sum = htons(sums);
5235 	return 0;
5236 }
5237 
5238 
5239 #ifdef	NEED_FRGETIFNAME
5240 /* ------------------------------------------------------------------------ */
5241 /* Function:    fr_getifname                                                */
5242 /* Returns:     char *    - pointer to interface name                       */
5243 /* Parameters:  ifp(I)    - pointer to network interface                    */
5244 /*              buffer(O) - pointer to where to store interface name        */
5245 /*                                                                          */
5246 /* Constructs an interface name in the buffer passed.  The buffer passed is */
5247 /* expected to be at least LIFNAMSIZ in bytes big.  If buffer is passed in  */
5248 /* as a NULL pointer then return a pointer to a static array.               */
5249 /* ------------------------------------------------------------------------ */
5250 char *fr_getifname(ifp, buffer)
5251 struct ifnet *ifp;
5252 char *buffer;
5253 {
5254 	static char namebuf[LIFNAMSIZ];
5255 # if defined(MENTAT) || defined(__FreeBSD__) || defined(__osf__) || \
5256      defined(__sgi) || defined(linux) || defined(_AIX51) || \
5257      (defined(sun) && !defined(__SVR4) && !defined(__svr4__))
5258 	int unit, space;
5259 	char temp[20];
5260 	char *s;
5261 # endif
5262 
5263 	ASSERT(buffer != NULL);
5264 #ifdef notdef
5265 	if (buffer == NULL)
5266 		buffer = namebuf;
5267 #endif
5268 	(void) strncpy(buffer, ifp->if_name, LIFNAMSIZ);
5269 	buffer[LIFNAMSIZ - 1] = '\0';
5270 # if defined(MENTAT) || defined(__FreeBSD__) || defined(__osf__) || \
5271      defined(__sgi) || defined(_AIX51) || \
5272      (defined(sun) && !defined(__SVR4) && !defined(__svr4__))
5273 	for (s = buffer; *s; s++)
5274 		;
5275 	unit = ifp->if_unit;
5276 	space = LIFNAMSIZ - (s - buffer);
5277 	if (space > 0) {
5278 #  if defined(SNPRINTF) && defined(_KERNEL)
5279 		(void) SNPRINTF(temp, sizeof(temp), "%d", unit);
5280 #  else
5281 		(void) sprintf(temp, "%d", unit);
5282 #  endif
5283 		(void) strncpy(s, temp, space);
5284 	}
5285 # endif
5286 	return buffer;
5287 }
5288 #endif
5289 
5290 
5291 /* ------------------------------------------------------------------------ */
5292 /* Function:    fr_ioctlswitch                                              */
5293 /* Returns:     int     - -1 continue processing, else ioctl return value   */
5294 /* Parameters:  unit(I) - device unit opened                                */
5295 /*              data(I) - pointer to ioctl data                             */
5296 /*              cmd(I)  - ioctl command                                     */
5297 /*              mode(I) - mode value                                        */
5298 /*                                                                          */
5299 /* Based on the value of unit, call the appropriate ioctl handler or return */
5300 /* EIO if ipfilter is not running.   Also checks if write perms are req'd   */
5301 /* for the device in order to execute the ioctl.                            */
5302 /* ------------------------------------------------------------------------ */
5303 INLINE int fr_ioctlswitch(unit, data, cmd, mode, uid, ctx, ifs)
5304 int unit, mode, uid;
5305 ioctlcmd_t cmd;
5306 void *data, *ctx;
5307 ipf_stack_t *ifs;
5308 {
5309 	int error = 0;
5310 
5311 	switch (unit)
5312 	{
5313 	case IPL_LOGIPF :
5314 		error = -1;
5315 		break;
5316 	case IPL_LOGNAT :
5317 		if (ifs->ifs_fr_running > 0)
5318 			error = fr_nat_ioctl(data, cmd, mode, uid, ctx, ifs);
5319 		else
5320 			error = EIO;
5321 		break;
5322 	case IPL_LOGSTATE :
5323 		if (ifs->ifs_fr_running > 0)
5324 			error = fr_state_ioctl(data, cmd, mode, uid, ctx, ifs);
5325 		else
5326 			error = EIO;
5327 		break;
5328 	case IPL_LOGAUTH :
5329 		if (ifs->ifs_fr_running > 0) {
5330 			if ((cmd == (ioctlcmd_t)SIOCADAFR) ||
5331 			    (cmd == (ioctlcmd_t)SIOCRMAFR)) {
5332 				if (!(mode & FWRITE)) {
5333 					error = EPERM;
5334 				} else {
5335 					error = frrequest(unit, cmd, data,
5336 						  ifs->ifs_fr_active, 1, ifs);
5337 				}
5338 			} else {
5339 				error = fr_auth_ioctl(data, cmd, mode, uid, ctx, ifs);
5340 			}
5341 		} else
5342 			error = EIO;
5343 		break;
5344 	case IPL_LOGSYNC :
5345 #ifdef IPFILTER_SYNC
5346 		if (ifs->ifs_fr_running > 0)
5347 			error = fr_sync_ioctl(data, cmd, mode, ifs);
5348 		else
5349 #endif
5350 			error = EIO;
5351 		break;
5352 	case IPL_LOGSCAN :
5353 #ifdef IPFILTER_SCAN
5354 		if (ifs->ifs_fr_running > 0)
5355 			error = fr_scan_ioctl(data, cmd, mode, ifs);
5356 		else
5357 #endif
5358 			error = EIO;
5359 		break;
5360 	case IPL_LOGLOOKUP :
5361 #ifdef IPFILTER_LOOKUP
5362 		if (ifs->ifs_fr_running > 0)
5363 			error = ip_lookup_ioctl(data, cmd, mode, uid, ctx, ifs);
5364 		else
5365 #endif
5366 			error = EIO;
5367 		break;
5368 	default :
5369 		error = EIO;
5370 		break;
5371 	}
5372 
5373 	return error;
5374 }
5375 
5376 
5377 /*
5378  * This array defines the expected size of objects coming into the kernel
5379  * for the various recognised object types.
5380  */
5381 #define	NUM_OBJ_TYPES	19
5382 
5383 static	int	fr_objbytes[NUM_OBJ_TYPES][2] = {
5384 	{ 1,	sizeof(struct frentry) },		/* frentry */
5385 	{ 0,	sizeof(struct friostat) },
5386 	{ 0,	sizeof(struct fr_info) },
5387 	{ 0,	sizeof(struct fr_authstat) },
5388 	{ 0,	sizeof(struct ipfrstat) },
5389 	{ 0,	sizeof(struct ipnat) },
5390 	{ 0,	sizeof(struct natstat) },
5391 	{ 0,	sizeof(struct ipstate_save) },
5392 	{ 1,	sizeof(struct nat_save) },		/* nat_save */
5393 	{ 0,	sizeof(struct natlookup) },
5394 	{ 1,	sizeof(struct ipstate) },		/* ipstate */
5395 	{ 0,	sizeof(struct ips_stat) },
5396 	{ 0,	sizeof(struct frauth) },
5397 	{ 0,	sizeof(struct ipftune) },
5398 	{ 0,	sizeof(struct nat) },                   /* nat_t */
5399 	{ 0,	sizeof(struct ipfruleiter) },
5400 	{ 0,	sizeof(struct ipfgeniter) },
5401 	{ 0,	sizeof(struct ipftable) },
5402 	{ 0,	sizeof(struct ipflookupiter) }
5403 };
5404 
5405 
5406 /* ------------------------------------------------------------------------ */
5407 /* Function:    fr_inobj                                                    */
5408 /* Returns:     int     - 0 = success, else failure                         */
5409 /* Parameters:  data(I) - pointer to ioctl data                             */
5410 /*              ptr(I)  - pointer to store real data in                     */
5411 /*              type(I) - type of structure being moved                     */
5412 /*                                                                          */
5413 /* Copy in the contents of what the ipfobj_t points to.  In future, we      */
5414 /* add things to check for version numbers, sizes, etc, to make it backward */
5415 /* compatible at the ABI for user land.                                     */
5416 /* ------------------------------------------------------------------------ */
5417 int fr_inobj(data, ptr, type)
5418 void *data;
5419 void *ptr;
5420 int type;
5421 {
5422 	ipfobj_t obj;
5423 	int error = 0;
5424 
5425 	if ((type < 0) || (type > NUM_OBJ_TYPES-1))
5426 		return EINVAL;
5427 
5428 	BCOPYIN((caddr_t)data, (caddr_t)&obj, sizeof(obj));
5429 
5430 	if (obj.ipfo_type != type)
5431 		return EINVAL;
5432 
5433 #ifndef	IPFILTER_COMPAT
5434 	if ((fr_objbytes[type][0] & 1) != 0) {
5435 		if (obj.ipfo_size < fr_objbytes[type][1])
5436 			return EINVAL;
5437 	} else if (obj.ipfo_size != fr_objbytes[type][1])
5438 		return EINVAL;
5439 #else
5440 	if (obj.ipfo_rev != IPFILTER_VERSION)
5441 		/* XXX compatibility hook here */
5442 		;
5443 	if ((fr_objbytes[type][0] & 1) != 0) {
5444 		if (obj.ipfo_size < fr_objbytes[type][1])
5445 			/* XXX compatibility hook here */
5446 			return EINVAL;
5447 	} else if (obj.ipfo_size != fr_objbytes[type][1])
5448 		/* XXX compatibility hook here */
5449 		return EINVAL;
5450 #endif
5451 
5452 	if ((fr_objbytes[type][0] & 1) != 0) {
5453 		error = COPYIN((caddr_t)obj.ipfo_ptr, (caddr_t)ptr,
5454 				fr_objbytes[type][1]);
5455 	} else {
5456 		error = COPYIN((caddr_t)obj.ipfo_ptr, (caddr_t)ptr,
5457 				obj.ipfo_size);
5458 	}
5459 	return error;
5460 }
5461 
5462 
5463 /* ------------------------------------------------------------------------ */
5464 /* Function:    fr_inobjsz                                                  */
5465 /* Returns:     int     - 0 = success, else failure                         */
5466 /* Parameters:  data(I) - pointer to ioctl data                             */
5467 /*              ptr(I)  - pointer to store real data in                     */
5468 /*              type(I) - type of structure being moved                     */
5469 /*              sz(I)   - size of data to copy                              */
5470 /*                                                                          */
5471 /* As per fr_inobj, except the size of the object to copy in is passed in   */
5472 /* but it must not be smaller than the size defined for the type and the    */
5473 /* type must allow for varied sized objects.  The extra requirement here is */
5474 /* that sz must match the size of the object being passed in - this is not  */
5475 /* not possible nor required in fr_inobj().                                 */
5476 /* ------------------------------------------------------------------------ */
5477 int fr_inobjsz(data, ptr, type, sz)
5478 void *data;
5479 void *ptr;
5480 int type, sz;
5481 {
5482 	ipfobj_t obj;
5483 	int error;
5484 
5485 	if ((type < 0) || (type > NUM_OBJ_TYPES-1))
5486 		return EINVAL;
5487 	if (((fr_objbytes[type][0] & 1) == 0) || (sz < fr_objbytes[type][1]))
5488 		return EINVAL;
5489 
5490 	BCOPYIN((caddr_t)data, (caddr_t)&obj, sizeof(obj));
5491 
5492 	if (obj.ipfo_type != type)
5493 		return EINVAL;
5494 
5495 #ifndef	IPFILTER_COMPAT
5496 	if (obj.ipfo_size != sz)
5497 		return EINVAL;
5498 #else
5499 	if (obj.ipfo_rev != IPFILTER_VERSION)
5500 		/* XXX compatibility hook here */
5501 		;
5502 	if (obj.ipfo_size != sz)
5503 		/* XXX compatibility hook here */
5504 		return EINVAL;
5505 #endif
5506 
5507 	error = COPYIN((caddr_t)obj.ipfo_ptr, (caddr_t)ptr, sz);
5508 	return error;
5509 }
5510 
5511 
5512 /* ------------------------------------------------------------------------ */
5513 /* Function:    fr_outobjsz                                                 */
5514 /* Returns:     int     - 0 = success, else failure                         */
5515 /* Parameters:  data(I) - pointer to ioctl data                             */
5516 /*              ptr(I)  - pointer to store real data in                     */
5517 /*              type(I) - type of structure being moved                     */
5518 /*              sz(I)   - size of data to copy                              */
5519 /*                                                                          */
5520 /* As per fr_outobj, except the size of the object to copy out is passed in */
5521 /* but it must not be smaller than the size defined for the type and the    */
5522 /* type must allow for varied sized objects.  The extra requirement here is */
5523 /* that sz must match the size of the object being passed in - this is not  */
5524 /* not possible nor required in fr_outobj().                                */
5525 /* ------------------------------------------------------------------------ */
5526 int fr_outobjsz(data, ptr, type, sz)
5527 void *data;
5528 void *ptr;
5529 int type, sz;
5530 {
5531 	ipfobj_t obj;
5532 	int error;
5533 
5534 	if ((type < 0) || (type > NUM_OBJ_TYPES-1) ||
5535 	    ((fr_objbytes[type][0] & 1) == 0) ||
5536 	    (sz < fr_objbytes[type][1]))
5537 		return EINVAL;
5538 
5539 	BCOPYIN((caddr_t)data, (caddr_t)&obj, sizeof(obj));
5540 
5541 	if (obj.ipfo_type != type)
5542 		return EINVAL;
5543 
5544 #ifndef	IPFILTER_COMPAT
5545 	if (obj.ipfo_size != sz)
5546 		return EINVAL;
5547 #else
5548 	if (obj.ipfo_rev != IPFILTER_VERSION)
5549 		/* XXX compatibility hook here */
5550 		;
5551 	if (obj.ipfo_size != sz)
5552 		/* XXX compatibility hook here */
5553 		return EINVAL;
5554 #endif
5555 
5556 	error = COPYOUT((caddr_t)ptr, (caddr_t)obj.ipfo_ptr, sz);
5557 	return error;
5558 }
5559 
5560 
5561 /* ------------------------------------------------------------------------ */
5562 /* Function:    fr_outobj                                                   */
5563 /* Returns:     int     - 0 = success, else failure                         */
5564 /* Parameters:  data(I) - pointer to ioctl data                             */
5565 /*              ptr(I)  - pointer to store real data in                     */
5566 /*              type(I) - type of structure being moved                     */
5567 /*                                                                          */
5568 /* Copy out the contents of what ptr is to where ipfobj points to.  In      */
5569 /* future, we add things to check for version numbers, sizes, etc, to make  */
5570 /* it backward  compatible at the ABI for user land.                        */
5571 /* ------------------------------------------------------------------------ */
5572 int fr_outobj(data, ptr, type)
5573 void *data;
5574 void *ptr;
5575 int type;
5576 {
5577 	ipfobj_t obj;
5578 	int error;
5579 
5580 	if ((type < 0) || (type > NUM_OBJ_TYPES-1))
5581 		return EINVAL;
5582 
5583 	BCOPYIN((caddr_t)data, (caddr_t)&obj, sizeof(obj));
5584 
5585 	if (obj.ipfo_type != type)
5586 		return EINVAL;
5587 
5588 #ifndef	IPFILTER_COMPAT
5589 	if ((fr_objbytes[type][0] & 1) != 0) {
5590 		if (obj.ipfo_size < fr_objbytes[type][1])
5591 			return EINVAL;
5592 	} else if (obj.ipfo_size != fr_objbytes[type][1])
5593 		return EINVAL;
5594 #else
5595 	if (obj.ipfo_rev != IPFILTER_VERSION)
5596 		/* XXX compatibility hook here */
5597 		;
5598 	if ((fr_objbytes[type][0] & 1) != 0) {
5599 		if (obj.ipfo_size < fr_objbytes[type][1])
5600 			/* XXX compatibility hook here */
5601 			return EINVAL;
5602 	} else if (obj.ipfo_size != fr_objbytes[type][1])
5603 		/* XXX compatibility hook here */
5604 		return EINVAL;
5605 #endif
5606 
5607 	error = COPYOUT((caddr_t)ptr, (caddr_t)obj.ipfo_ptr, obj.ipfo_size);
5608 	return error;
5609 }
5610 
5611 
5612 /* ------------------------------------------------------------------------ */
5613 /* Function:    fr_checkl4sum                                               */
5614 /* Returns:     int     - 0 = good, -1 = bad, 1 = cannot check              */
5615 /* Parameters:  fin(I) - pointer to packet information                      */
5616 /*                                                                          */
5617 /* If possible, calculate the layer 4 checksum for the packet.  If this is  */
5618 /* not possible, return without indicating a failure or success but in a    */
5619 /* way that is ditinguishable.                                              */
5620 /* ------------------------------------------------------------------------ */
5621 int fr_checkl4sum(fin)
5622 fr_info_t *fin;
5623 {
5624 	u_short sum, hdrsum, *csump;
5625 	udphdr_t *udp;
5626 	int dosum;
5627 	ipf_stack_t *ifs = fin->fin_ifs;
5628 
5629 #if SOLARIS && defined(_KERNEL) && (SOLARIS2 >= 6)
5630 	net_data_t net_data_p;
5631 	if (fin->fin_v == 4)
5632 		net_data_p = ifs->ifs_ipf_ipv4;
5633 	else
5634 		net_data_p = ifs->ifs_ipf_ipv6;
5635 #endif
5636 
5637 	if ((fin->fin_flx & FI_NOCKSUM) != 0)
5638 		return 0;
5639 
5640 	/*
5641 	 * If the TCP packet isn't a fragment, isn't too short and otherwise
5642 	 * isn't already considered "bad", then validate the checksum.  If
5643 	 * this check fails then considered the packet to be "bad".
5644 	 */
5645 	if ((fin->fin_flx & (FI_FRAG|FI_SHORT|FI_BAD)) != 0)
5646 		return 1;
5647 
5648 	csump = NULL;
5649 	hdrsum = 0;
5650 	dosum = 0;
5651 	sum = 0;
5652 
5653 #if SOLARIS && defined(_KERNEL) && (SOLARIS2 >= 6)
5654 	ASSERT(fin->fin_m != NULL);
5655 	if (NET_IS_HCK_L4_FULL(net_data_p, fin->fin_m) ||
5656 	    NET_IS_HCK_L4_PART(net_data_p, fin->fin_m)) {
5657 			hdrsum = 0;
5658 			sum = 0;
5659 	} else {
5660 #endif
5661 		switch (fin->fin_p)
5662 		{
5663 		case IPPROTO_TCP :
5664 			csump = &((tcphdr_t *)fin->fin_dp)->th_sum;
5665 			dosum = 1;
5666 			break;
5667 
5668 		case IPPROTO_UDP :
5669 			udp = fin->fin_dp;
5670 			if (udp->uh_sum != 0) {
5671 				csump = &udp->uh_sum;
5672 				dosum = 1;
5673 			}
5674 			break;
5675 
5676 		case IPPROTO_ICMP :
5677 			csump = &((struct icmp *)fin->fin_dp)->icmp_cksum;
5678 			dosum = 1;
5679 			break;
5680 
5681 		default :
5682 			return 1;
5683 			/*NOTREACHED*/
5684 		}
5685 
5686 		if (csump != NULL)
5687 			hdrsum = *csump;
5688 
5689 		if (dosum)
5690 			sum = fr_cksum(fin->fin_m, fin->fin_ip,
5691 				       fin->fin_p, fin->fin_dp);
5692 #if SOLARIS && defined(_KERNEL) && (SOLARIS2 >= 6)
5693 	}
5694 #endif
5695 #if !defined(_KERNEL)
5696 	if (sum == hdrsum) {
5697 		FR_DEBUG(("checkl4sum: %hx == %hx\n", sum, hdrsum));
5698 	} else {
5699 		FR_DEBUG(("checkl4sum: %hx != %hx\n", sum, hdrsum));
5700 	}
5701 #endif
5702 	if (hdrsum == sum)
5703 		return 0;
5704 	return -1;
5705 }
5706 
5707 
5708 /* ------------------------------------------------------------------------ */
5709 /* Function:    fr_ifpfillv4addr                                            */
5710 /* Returns:     int     - 0 = address update, -1 = address not updated      */
5711 /* Parameters:  atype(I)   - type of network address update to perform      */
5712 /*              sin(I)     - pointer to source of address information       */
5713 /*              mask(I)    - pointer to source of netmask information       */
5714 /*              inp(I)     - pointer to destination address store           */
5715 /*              inpmask(I) - pointer to destination netmask store           */
5716 /*                                                                          */
5717 /* Given a type of network address update (atype) to perform, copy          */
5718 /* information from sin/mask into inp/inpmask.  If ipnmask is NULL then no  */
5719 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in  */
5720 /* which case the operation fails.  For all values of atype other than      */
5721 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s  */
5722 /* value.                                                                   */
5723 /* ------------------------------------------------------------------------ */
5724 int fr_ifpfillv4addr(atype, sin, mask, inp, inpmask)
5725 int atype;
5726 struct sockaddr_in *sin, *mask;
5727 struct in_addr *inp, *inpmask;
5728 {
5729 	if (inpmask != NULL && atype != FRI_NETMASKED)
5730 		inpmask->s_addr = 0xffffffff;
5731 
5732 	if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
5733 		if (atype == FRI_NETMASKED) {
5734 			if (inpmask == NULL)
5735 				return -1;
5736 			inpmask->s_addr = mask->sin_addr.s_addr;
5737 		}
5738 		inp->s_addr = sin->sin_addr.s_addr & mask->sin_addr.s_addr;
5739 	} else {
5740 		inp->s_addr = sin->sin_addr.s_addr;
5741 	}
5742 	return 0;
5743 }
5744 
5745 
5746 #ifdef	USE_INET6
5747 /* ------------------------------------------------------------------------ */
5748 /* Function:    fr_ifpfillv6addr                                            */
5749 /* Returns:     int     - 0 = address update, -1 = address not updated      */
5750 /* Parameters:  atype(I)   - type of network address update to perform      */
5751 /*              sin(I)     - pointer to source of address information       */
5752 /*              mask(I)    - pointer to source of netmask information       */
5753 /*              inp(I)     - pointer to destination address store           */
5754 /*              inpmask(I) - pointer to destination netmask store           */
5755 /*                                                                          */
5756 /* Given a type of network address update (atype) to perform, copy          */
5757 /* information from sin/mask into inp/inpmask.  If ipnmask is NULL then no  */
5758 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in  */
5759 /* which case the operation fails.  For all values of atype other than      */
5760 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s  */
5761 /* value.                                                                   */
5762 /* ------------------------------------------------------------------------ */
5763 int fr_ifpfillv6addr(atype, sin, mask, inp, inpmask)
5764 int atype;
5765 struct sockaddr_in6 *sin, *mask;
5766 struct in_addr *inp, *inpmask;
5767 {
5768 	i6addr_t *src, *dst, *and, *dmask;
5769 
5770 	src = (i6addr_t *)&sin->sin6_addr;
5771 	and = (i6addr_t *)&mask->sin6_addr;
5772 	dst = (i6addr_t *)inp;
5773 	dmask = (i6addr_t *)inpmask;
5774 
5775 	if (inpmask != NULL && atype != FRI_NETMASKED) {
5776 		dmask->i6[0] = 0xffffffff;
5777 		dmask->i6[1] = 0xffffffff;
5778 		dmask->i6[2] = 0xffffffff;
5779 		dmask->i6[3] = 0xffffffff;
5780 	}
5781 
5782 	if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
5783 		if (atype == FRI_NETMASKED) {
5784 			if (inpmask == NULL)
5785 				return -1;
5786 			dmask->i6[0] = and->i6[0];
5787 			dmask->i6[1] = and->i6[1];
5788 			dmask->i6[2] = and->i6[2];
5789 			dmask->i6[3] = and->i6[3];
5790 		}
5791 
5792 		dst->i6[0] = src->i6[0] & and->i6[0];
5793 		dst->i6[1] = src->i6[1] & and->i6[1];
5794 		dst->i6[2] = src->i6[2] & and->i6[2];
5795 		dst->i6[3] = src->i6[3] & and->i6[3];
5796 	} else {
5797 		dst->i6[0] = src->i6[0];
5798 		dst->i6[1] = src->i6[1];
5799 		dst->i6[2] = src->i6[2];
5800 		dst->i6[3] = src->i6[3];
5801 	}
5802 	return 0;
5803 }
5804 #endif
5805 
5806 
5807 /* ------------------------------------------------------------------------ */
5808 /* Function:    fr_matchtag                                                 */
5809 /* Returns:     0 == mismatch, 1 == match.                                  */
5810 /* Parameters:  tag1(I) - pointer to first tag to compare                   */
5811 /*              tag2(I) - pointer to second tag to compare                  */
5812 /*                                                                          */
5813 /* Returns true (non-zero) or false(0) if the two tag structures can be     */
5814 /* considered to be a match or not match, respectively.  The tag is 16      */
5815 /* bytes long (16 characters) but that is overlayed with 4 32bit ints so    */
5816 /* compare the ints instead, for speed. tag1 is the master of the           */
5817 /* comparison.  This function should only be called with both tag1 and tag2 */
5818 /* as non-NULL pointers.                                                    */
5819 /* ------------------------------------------------------------------------ */
5820 int fr_matchtag(tag1, tag2)
5821 ipftag_t *tag1, *tag2;
5822 {
5823 	if (tag1 == tag2)
5824 		return 1;
5825 
5826 	if ((tag1->ipt_num[0] == 0) && (tag2->ipt_num[0] == 0))
5827 		return 1;
5828 
5829 	if ((tag1->ipt_num[0] == tag2->ipt_num[0]) &&
5830 	    (tag1->ipt_num[1] == tag2->ipt_num[1]) &&
5831 	    (tag1->ipt_num[2] == tag2->ipt_num[2]) &&
5832 	    (tag1->ipt_num[3] == tag2->ipt_num[3]))
5833 		return 1;
5834 	return 0;
5835 }
5836 
5837 
5838 /* ------------------------------------------------------------------------ */
5839 /* Function:    fr_coalesce                                                 */
5840 /* Returns:     1 == success, -1 == failure, 0 == no change                 */
5841 /* Parameters:  fin(I) - pointer to packet information                      */
5842 /*                                                                          */
5843 /* Attempt to get all of the packet data into a single, contiguous buffer.  */
5844 /* If this call returns a failure then the buffers have also been freed.    */
5845 /* ------------------------------------------------------------------------ */
5846 int fr_coalesce(fin)
5847 fr_info_t *fin;
5848 {
5849 	ipf_stack_t *ifs = fin->fin_ifs;
5850 	if ((fin->fin_flx & FI_COALESCE) != 0)
5851 		return 1;
5852 
5853 	/*
5854 	 * If the mbuf pointers indicate that there is no mbuf to work with,
5855 	 * return but do not indicate success or failure.
5856 	 */
5857 	if (fin->fin_m == NULL || fin->fin_mp == NULL)
5858 		return 0;
5859 
5860 #if defined(_KERNEL)
5861 	if (fr_pullup(fin->fin_m, fin, fin->fin_plen) == NULL) {
5862 		ATOMIC_INCL(ifs->ifs_fr_badcoalesces[fin->fin_out]);
5863 # ifdef MENTAT
5864 		FREE_MB_T(*fin->fin_mp);
5865 # endif
5866 		*fin->fin_mp = NULL;
5867 		fin->fin_m = NULL;
5868 		return -1;
5869 	}
5870 #else
5871 	fin = fin;	/* LINT */
5872 #endif
5873 	return 1;
5874 }
5875 
5876 
5877 /*
5878  * The following table lists all of the tunable variables that can be
5879  * accessed via SIOCIPFGET/SIOCIPFSET/SIOCIPFGETNEXT.  The format of each row
5880  * in the table below is as follows:
5881  *
5882  * pointer to value, name of value, minimum, maximum, size of the value's
5883  *     container, value attribute flags
5884  *
5885  * For convienience, IPFT_RDONLY means the value is read-only, IPFT_WRDISABLED
5886  * means the value can only be written to when IPFilter is loaded but disabled.
5887  * The obvious implication is if neither of these are set then the value can be
5888  * changed at any time without harm.
5889  */
5890 ipftuneable_t lcl_ipf_tuneables[] = {
5891 	/* filtering */
5892 	{ { NULL },	"fr_flags",		0,	0xffffffff,
5893 			0,		0 },
5894 	{ { NULL },	"fr_active",		0,	0,
5895 			0,		IPFT_RDONLY },
5896 	{ { NULL },	"fr_control_forwarding",	0, 1,
5897 			0,		0 },
5898 	{ { NULL },	"fr_update_ipid",	0,	1,
5899 			0,		0 },
5900 	{ { NULL },	"fr_chksrc",		0,	1,
5901 			0,		0 },
5902 	{ { NULL },	"fr_minttl",		0,	1,
5903 			0,		0 },
5904 	{ { NULL }, 	"fr_icmpminfragmtu",	0,	1,
5905 			0,		0 },
5906 	{ { NULL },		"fr_pass",		0,	0xffffffff,
5907 			0,		0 },
5908 #if SOLARIS2 >= 10
5909 	{ { NULL },	"ipf_loopback",		0,	1,
5910 			0,		IPFT_WRDISABLED },
5911 #endif
5912 	/* state */
5913 	{ { NULL }, "fr_tcpidletimeout",	1,	0x7fffffff,
5914 			0,	IPFT_WRDISABLED },
5915 	{ { NULL },	"fr_tcpclosewait",	1,	0x7fffffff,
5916 			0,	IPFT_WRDISABLED },
5917 	{ { NULL },	"fr_tcplastack",	1,	0x7fffffff,
5918 			0,		IPFT_WRDISABLED },
5919 	{ { NULL },	"fr_tcptimeout",	1,	0x7fffffff,
5920 			0,		IPFT_WRDISABLED },
5921 	{ { NULL },	"fr_tcpclosed",		1,	0x7fffffff,
5922 			0,		IPFT_WRDISABLED },
5923 	{ { NULL },	"fr_tcphalfclosed",	1,	0x7fffffff,
5924 			0,	IPFT_WRDISABLED },
5925 	{ { NULL },	"fr_udptimeout",	1,	0x7fffffff,
5926 			0,		IPFT_WRDISABLED },
5927 	{ { NULL }, "fr_udpacktimeout",	1,	0x7fffffff,
5928 			0,	IPFT_WRDISABLED },
5929 	{ { NULL },	"fr_icmptimeout",	1,	0x7fffffff,
5930 			0,		IPFT_WRDISABLED },
5931 	{ { NULL }, "fr_icmpacktimeout",	1,	0x7fffffff,
5932 			0,	IPFT_WRDISABLED },
5933 	{ { NULL }, "fr_iptimeout",		1,	0x7fffffff,
5934 			0,		IPFT_WRDISABLED },
5935 	{ { NULL },	"fr_statemax",		1,	0x7fffffff,
5936 			0,		0 },
5937 	{ { NULL },	"fr_statesize",		1,	0x7fffffff,
5938 			0,		IPFT_WRDISABLED },
5939 	{ { NULL },	"fr_state_lock",	0,	1,
5940 			0,		IPFT_RDONLY },
5941 	{ { NULL }, "fr_state_maxbucket", 1,	0x7fffffff,
5942 			0,	IPFT_WRDISABLED },
5943 	{ { NULL }, "fr_state_maxbucket_reset",	0, 1,
5944 			0, IPFT_WRDISABLED },
5945 	{ { NULL },	"ipstate_logging",	0,	1,
5946 			0,	0 },
5947 	/* nat */
5948 	{ { NULL },		"fr_nat_lock",		0,	1,
5949 			0,		IPFT_RDONLY },
5950 	{ { NULL },	"ipf_nattable_sz",	1,	0x7fffffff,
5951 			0,	IPFT_WRDISABLED },
5952 	{ { NULL }, "ipf_nattable_max",	1,	0x7fffffff,
5953 			0,	0 },
5954 	{ { NULL },	"ipf_natrules_sz",	1,	0x7fffffff,
5955 			0,	IPFT_WRDISABLED },
5956 	{ { NULL },	"ipf_rdrrules_sz",	1,	0x7fffffff,
5957 			0,	IPFT_WRDISABLED },
5958 	{ { NULL },	"ipf_hostmap_sz",	1,	0x7fffffff,
5959 			0,		IPFT_WRDISABLED },
5960 	{ { NULL }, "fr_nat_maxbucket",	1,	0x7fffffff,
5961 			0,	IPFT_WRDISABLED },
5962 	{ { NULL },	"fr_nat_maxbucket_reset",	0, 1,
5963 			0,	IPFT_WRDISABLED },
5964 	{ { NULL },		"nat_logging",		0,	1,
5965 			0,		0 },
5966 	{ { NULL },	"fr_defnatage",		1,	0x7fffffff,
5967 			0,		IPFT_WRDISABLED },
5968 	{ { NULL },	"fr_defnatipage",	1,	0x7fffffff,
5969 			0,		IPFT_WRDISABLED },
5970 	{ { NULL }, "fr_defnaticmpage",	1,	0x7fffffff,
5971 			0,	IPFT_WRDISABLED },
5972 	{ { NULL },	"nat_flush_lvl_hi",	1,	100,
5973 			0,		0 },
5974 	{ { NULL },	"nat_flush_lvl_lo",	1,	100,
5975 			0,		0 },
5976 	/* frag */
5977 	{ { NULL },	"ipfr_size",		1,	0x7fffffff,
5978 			0,		IPFT_WRDISABLED },
5979 	{ { NULL },	"fr_ipfrttl",		1,	0x7fffffff,
5980 			0,		IPFT_WRDISABLED },
5981 #ifdef IPFILTER_LOG
5982 	/* log */
5983 	{ { NULL },	"ipl_suppress",		0,	1,
5984 			0,		0 },
5985 	{ { NULL },	"ipl_buffer_sz",	0,	0,
5986 			0,		IPFT_RDONLY },
5987 	{ { NULL },	"ipl_logmax",		0,	0x7fffffff,
5988 			0,		IPFT_WRDISABLED },
5989 	{ { NULL },	"ipl_logall",		0,	1,
5990 			0,		0 },
5991 	{ { NULL },	"ipl_logsize",		0,	0x80000,
5992 			0,		0 },
5993 #endif
5994 	{ { NULL },		NULL,			0,	0 }
5995 };
5996 
5997 static ipftuneable_t *
5998 tune_lookup(ipf_stack_t *ifs, char *name)
5999 {
6000     int i;
6001 
6002     for (i = 0; ifs->ifs_ipf_tuneables[i].ipft_name != NULL; i++) {
6003 	if (strcmp(ifs->ifs_ipf_tuneables[i].ipft_name, name) == 0)
6004 	    return (&ifs->ifs_ipf_tuneables[i]);
6005     }
6006     return (NULL);
6007 }
6008 
6009 #ifdef _KERNEL
6010 extern dev_info_t *ipf_dev_info;
6011 extern int ipf_property_update __P((dev_info_t *, ipf_stack_t *));
6012 #endif
6013 
6014 /* -------------------------------------------------------------------- */
6015 /* Function:	ipftuneable_setdefs()					*/
6016 /* Returns:		void						*/
6017 /* Parameters:	ifs - pointer to newly allocated IPF instance		*/
6018 /*				assigned to	IP instance		*/
6019 /*									*/
6020 /* Function initializes IPF instance variables. Function is invoked	*/
6021 /* from	ipftuneable_alloc(). ipftuneable_alloc() is called only one	*/
6022 /* time during IP instance lifetime - at the time of IP instance	*/
6023 /* creation. Anytime IP	instance is being created new private IPF	*/
6024 /* instance is allocated and assigned to it. The moment of IP 		*/
6025 /* instance creation is the right time to initialize those IPF 		*/
6026 /* variables.								*/
6027 /*									*/
6028 /* -------------------------------------------------------------------- */
6029 static void ipftuneable_setdefs(ipf_stack_t *ifs)
6030 {
6031 	ifs->ifs_ipfr_size = IPFT_SIZE;
6032 	ifs->ifs_fr_ipfrttl = 120;	/* 60 seconds */
6033 
6034 	/* it comes from fr_authinit() in IPF auth */
6035 	ifs->ifs_fr_authsize = FR_NUMAUTH;
6036 	ifs->ifs_fr_defaultauthage = 600;
6037 
6038 	/* it comes from fr_stateinit() in IPF state */
6039 	ifs->ifs_fr_tcpidletimeout = IPF_TTLVAL(3600 * 24 * 5);	/* five days */
6040 	ifs->ifs_fr_tcpclosewait = IPF_TTLVAL(TCP_MSL);
6041 	ifs->ifs_fr_tcplastack = IPF_TTLVAL(TCP_MSL);
6042 	ifs->ifs_fr_tcptimeout = IPF_TTLVAL(TCP_MSL);
6043 	ifs->ifs_fr_tcpclosed = IPF_TTLVAL(60);
6044 	ifs->ifs_fr_tcphalfclosed = IPF_TTLVAL(2 * 3600);	/* 2 hours */
6045 	ifs->ifs_fr_udptimeout = IPF_TTLVAL(120);
6046 	ifs->ifs_fr_udpacktimeout = IPF_TTLVAL(12);
6047 	ifs->ifs_fr_icmptimeout = IPF_TTLVAL(60);
6048 	ifs->ifs_fr_icmpacktimeout = IPF_TTLVAL(6);
6049 	ifs->ifs_fr_iptimeout = IPF_TTLVAL(60);
6050 	ifs->ifs_fr_statemax = IPSTATE_MAX;
6051 	ifs->ifs_fr_statesize = IPSTATE_SIZE;
6052 	ifs->ifs_fr_state_maxbucket_reset = 1;
6053 
6054 	/* it comes from fr_natinit() in ipnat */
6055 	ifs->ifs_ipf_nattable_sz = NAT_TABLE_SZ;
6056 	ifs->ifs_ipf_nattable_max = NAT_TABLE_MAX;
6057 	ifs->ifs_ipf_natrules_sz = NAT_SIZE;
6058 	ifs->ifs_ipf_rdrrules_sz = RDR_SIZE;
6059 	ifs->ifs_ipf_hostmap_sz = HOSTMAP_SIZE;
6060 	ifs->ifs_fr_nat_maxbucket_reset = 1;
6061 	ifs->ifs_fr_defnatage = DEF_NAT_AGE;
6062 	ifs->ifs_fr_defnatipage = 120;		/* 60 seconds */
6063 	ifs->ifs_fr_defnaticmpage = 6;		/* 3 seconds */
6064 	ifs->ifs_nat_flush_lvl_hi = NAT_FLUSH_HI;
6065 	ifs->ifs_nat_flush_lvl_lo = NAT_FLUSH_LO;
6066 
6067 #ifdef IPFILTER_LOG
6068 	/* it comes from fr_loginit() in IPF log */
6069 	ifs->ifs_ipl_suppress = 1;
6070 	ifs->ifs_ipl_logmax = IPL_LOGMAX;
6071 	ifs->ifs_ipl_logsize = IPFILTER_LOGSIZE;
6072 
6073 	/* from fr_natinit() */
6074 	ifs->ifs_nat_logging = 1;
6075 
6076 	/* from fr_stateinit() */
6077 	ifs->ifs_ipstate_logging = 1;
6078 #else
6079 	/* from fr_natinit() */
6080 	ifs->ifs_nat_logging = 0;
6081 
6082 	/* from fr_stateinit() */
6083 	ifs->ifs_ipstate_logging = 0;
6084 #endif
6085 	ifs->ifs_ipf_loopback = 0;
6086 
6087 }
6088 /*
6089  * Allocate a per-stack tuneable and copy in the names. Then
6090  * set it to point to each of the per-stack tunables.
6091  */
6092 void
6093 ipftuneable_alloc(ipf_stack_t *ifs)
6094 {
6095     ipftuneable_t *item;
6096 
6097     KMALLOCS(ifs->ifs_ipf_tuneables, ipftuneable_t *,
6098 	sizeof (lcl_ipf_tuneables));
6099     bcopy(lcl_ipf_tuneables, ifs->ifs_ipf_tuneables,
6100 	sizeof (lcl_ipf_tuneables));
6101 
6102 #define TUNE_SET(_ifs, _name, _field)			\
6103     item = tune_lookup((_ifs), (_name));		\
6104     if (item != NULL) {					\
6105 	item->ipft_una.ipftp_int = (unsigned int *)&((_ifs)->_field);	\
6106 	item->ipft_sz = sizeof ((_ifs)->_field);	\
6107     }
6108 
6109     TUNE_SET(ifs, "fr_flags", ifs_fr_flags);
6110     TUNE_SET(ifs, "fr_active", ifs_fr_active);
6111     TUNE_SET(ifs, "fr_control_forwarding", ifs_fr_control_forwarding);
6112     TUNE_SET(ifs, "fr_update_ipid", ifs_fr_update_ipid);
6113     TUNE_SET(ifs, "fr_chksrc", ifs_fr_chksrc);
6114     TUNE_SET(ifs, "fr_minttl", ifs_fr_minttl);
6115     TUNE_SET(ifs, "fr_icmpminfragmtu", ifs_fr_icmpminfragmtu);
6116     TUNE_SET(ifs, "fr_pass", ifs_fr_pass);
6117     TUNE_SET(ifs, "fr_tcpidletimeout", ifs_fr_tcpidletimeout);
6118     TUNE_SET(ifs, "fr_tcpclosewait", ifs_fr_tcpclosewait);
6119     TUNE_SET(ifs, "fr_tcplastack", ifs_fr_tcplastack);
6120     TUNE_SET(ifs, "fr_tcptimeout", ifs_fr_tcptimeout);
6121     TUNE_SET(ifs, "fr_tcpclosed", ifs_fr_tcpclosed);
6122     TUNE_SET(ifs, "fr_tcphalfclosed", ifs_fr_tcphalfclosed);
6123     TUNE_SET(ifs, "fr_udptimeout", ifs_fr_udptimeout);
6124     TUNE_SET(ifs, "fr_udpacktimeout", ifs_fr_udpacktimeout);
6125     TUNE_SET(ifs, "fr_icmptimeout", ifs_fr_icmptimeout);
6126     TUNE_SET(ifs, "fr_icmpacktimeout", ifs_fr_icmpacktimeout);
6127     TUNE_SET(ifs, "fr_iptimeout", ifs_fr_iptimeout);
6128     TUNE_SET(ifs, "fr_statemax", ifs_fr_statemax);
6129     TUNE_SET(ifs, "fr_statesize", ifs_fr_statesize);
6130     TUNE_SET(ifs, "fr_state_lock", ifs_fr_state_lock);
6131     TUNE_SET(ifs, "fr_state_maxbucket", ifs_fr_state_maxbucket);
6132     TUNE_SET(ifs, "fr_state_maxbucket_reset", ifs_fr_state_maxbucket_reset);
6133     TUNE_SET(ifs, "ipstate_logging", ifs_ipstate_logging);
6134     TUNE_SET(ifs, "fr_nat_lock", ifs_fr_nat_lock);
6135     TUNE_SET(ifs, "ipf_nattable_sz", ifs_ipf_nattable_sz);
6136     TUNE_SET(ifs, "ipf_nattable_max", ifs_ipf_nattable_max);
6137     TUNE_SET(ifs, "ipf_natrules_sz", ifs_ipf_natrules_sz);
6138     TUNE_SET(ifs, "ipf_rdrrules_sz", ifs_ipf_rdrrules_sz);
6139     TUNE_SET(ifs, "ipf_hostmap_sz", ifs_ipf_hostmap_sz);
6140     TUNE_SET(ifs, "fr_nat_maxbucket", ifs_fr_nat_maxbucket);
6141     TUNE_SET(ifs, "fr_nat_maxbucket_reset", ifs_fr_nat_maxbucket_reset);
6142     TUNE_SET(ifs, "nat_logging", ifs_nat_logging);
6143     TUNE_SET(ifs, "fr_defnatage", ifs_fr_defnatage);
6144     TUNE_SET(ifs, "fr_defnatipage", ifs_fr_defnatipage);
6145     TUNE_SET(ifs, "fr_defnaticmpage", ifs_fr_defnaticmpage);
6146     TUNE_SET(ifs, "nat_flush_lvl_hi", ifs_nat_flush_lvl_hi);
6147     TUNE_SET(ifs, "nat_flush_lvl_lo", ifs_nat_flush_lvl_lo);
6148     TUNE_SET(ifs, "ipfr_size", ifs_ipfr_size);
6149     TUNE_SET(ifs, "fr_ipfrttl", ifs_fr_ipfrttl);
6150     TUNE_SET(ifs, "ipf_loopback", ifs_ipf_loopback);
6151 #ifdef IPFILTER_LOG
6152     TUNE_SET(ifs, "ipl_suppress", ifs_ipl_suppress);
6153     TUNE_SET(ifs, "ipl_buffer_sz", ifs_ipl_buffer_sz);
6154     TUNE_SET(ifs, "ipl_logmax", ifs_ipl_logmax);
6155     TUNE_SET(ifs, "ipl_logall", ifs_ipl_logall);
6156     TUNE_SET(ifs, "ipl_logsize", ifs_ipl_logsize);
6157 #endif
6158 #undef TUNE_SET
6159 
6160 	ipftuneable_setdefs(ifs);
6161 
6162 #ifdef _KERNEL
6163     (void) ipf_property_update(ipf_dev_info, ifs);
6164 #endif
6165 }
6166 
6167 void
6168 ipftuneable_free(ipf_stack_t *ifs)
6169 {
6170 	KFREES(ifs->ifs_ipf_tuneables, sizeof (lcl_ipf_tuneables));
6171 	ifs->ifs_ipf_tuneables = NULL;
6172 }
6173 
6174 /* ------------------------------------------------------------------------ */
6175 /* Function:    fr_findtunebycookie                                         */
6176 /* Returns:     NULL = search failed, else pointer to tune struct           */
6177 /* Parameters:  cookie(I) - cookie value to search for amongst tuneables    */
6178 /*              next(O)   - pointer to place to store the cookie for the    */
6179 /*                          "next" tuneable, if it is desired.              */
6180 /*                                                                          */
6181 /* This function is used to walk through all of the existing tunables with  */
6182 /* successive calls.  It searches the known tunables for the one which has  */
6183 /* a matching value for "cookie" - ie its address.  When returning a match, */
6184 /* the next one to be found may be returned inside next.                    */
6185 /* ------------------------------------------------------------------------ */
6186 static ipftuneable_t *fr_findtunebycookie(cookie, next, ifs)
6187 void *cookie, **next;
6188 ipf_stack_t * ifs;
6189 {
6190 	ipftuneable_t *ta, **tap;
6191 
6192 	for (ta = ifs->ifs_ipf_tuneables; ta->ipft_name != NULL; ta++)
6193 		if (ta == cookie) {
6194 			if (next != NULL) {
6195 				/*
6196 				 * If the next entry in the array has a name
6197 				 * present, then return a pointer to it for
6198 				 * where to go next, else return a pointer to
6199 				 * the dynaminc list as a key to search there
6200 				 * next.  This facilitates a weak linking of
6201 				 * the two "lists" together.
6202 				 */
6203 				if ((ta + 1)->ipft_name != NULL)
6204 					*next = ta + 1;
6205 				else
6206 					*next = &ifs->ifs_ipf_tunelist;
6207 			}
6208 			return ta;
6209 		}
6210 
6211 	for (tap = &ifs->ifs_ipf_tunelist; (ta = *tap) != NULL; tap = &ta->ipft_next)
6212 		if (tap == cookie) {
6213 			if (next != NULL)
6214 				*next = &ta->ipft_next;
6215 			return ta;
6216 		}
6217 
6218 	if (next != NULL)
6219 		*next = NULL;
6220 	return NULL;
6221 }
6222 
6223 
6224 /* ------------------------------------------------------------------------ */
6225 /* Function:    fr_findtunebyname                                           */
6226 /* Returns:     NULL = search failed, else pointer to tune struct           */
6227 /* Parameters:  name(I) - name of the tuneable entry to find.               */
6228 /*                                                                          */
6229 /* Search the static array of tuneables and the list of dynamic tuneables   */
6230 /* for an entry with a matching name.  If we can find one, return a pointer */
6231 /* to the matching structure.                                               */
6232 /* ------------------------------------------------------------------------ */
6233 static ipftuneable_t *fr_findtunebyname(name, ifs)
6234 const char *name;
6235 ipf_stack_t *ifs;
6236 {
6237 	ipftuneable_t *ta;
6238 
6239 	for (ta = ifs->ifs_ipf_tuneables; ta->ipft_name != NULL; ta++)
6240 		if (!strcmp(ta->ipft_name, name)) {
6241 			return ta;
6242 		}
6243 
6244 	for (ta = ifs->ifs_ipf_tunelist; ta != NULL; ta = ta->ipft_next)
6245 		if (!strcmp(ta->ipft_name, name)) {
6246 			return ta;
6247 		}
6248 
6249 	return NULL;
6250 }
6251 
6252 
6253 /* ------------------------------------------------------------------------ */
6254 /* Function:    fr_addipftune                                               */
6255 /* Returns:     int - 0 == success, else failure                            */
6256 /* Parameters:  newtune - pointer to new tune struct to add to tuneables    */
6257 /*                                                                          */
6258 /* Appends the tune structure pointer to by "newtune" to the end of the     */
6259 /* current list of "dynamic" tuneable parameters.  Once added, the owner    */
6260 /* of the object is not expected to ever change "ipft_next".                */
6261 /* ------------------------------------------------------------------------ */
6262 int fr_addipftune(newtune, ifs)
6263 ipftuneable_t *newtune;
6264 ipf_stack_t *ifs;
6265 {
6266 	ipftuneable_t *ta, **tap;
6267 
6268 	ta = fr_findtunebyname(newtune->ipft_name, ifs);
6269 	if (ta != NULL)
6270 		return EEXIST;
6271 
6272 	for (tap = &ifs->ifs_ipf_tunelist; *tap != NULL; tap = &(*tap)->ipft_next)
6273 		;
6274 
6275 	newtune->ipft_next = NULL;
6276 	*tap = newtune;
6277 	return 0;
6278 }
6279 
6280 
6281 /* ------------------------------------------------------------------------ */
6282 /* Function:    fr_delipftune                                               */
6283 /* Returns:     int - 0 == success, else failure                            */
6284 /* Parameters:  oldtune - pointer to tune struct to remove from the list of */
6285 /*                        current dynamic tuneables                         */
6286 /*                                                                          */
6287 /* Search for the tune structure, by pointer, in the list of those that are */
6288 /* dynamically added at run time.  If found, adjust the list so that this   */
6289 /* structure is no longer part of it.                                       */
6290 /* ------------------------------------------------------------------------ */
6291 int fr_delipftune(oldtune, ifs)
6292 ipftuneable_t *oldtune;
6293 ipf_stack_t *ifs;
6294 {
6295 	ipftuneable_t *ta, **tap;
6296 
6297 	for (tap = &ifs->ifs_ipf_tunelist; (ta = *tap) != NULL; tap = &ta->ipft_next)
6298 		if (ta == oldtune) {
6299 			*tap = oldtune->ipft_next;
6300 			oldtune->ipft_next = NULL;
6301 			return 0;
6302 		}
6303 
6304 	return ESRCH;
6305 }
6306 
6307 
6308 /* ------------------------------------------------------------------------ */
6309 /* Function:    fr_ipftune                                                  */
6310 /* Returns:     int - 0 == success, else failure                            */
6311 /* Parameters:  cmd(I)  - ioctl command number                              */
6312 /*              data(I) - pointer to ioctl data structure                   */
6313 /*                                                                          */
6314 /* Implement handling of SIOCIPFGETNEXT, SIOCIPFGET and SIOCIPFSET.  These  */
6315 /* three ioctls provide the means to access and control global variables    */
6316 /* within IPFilter, allowing (for example) timeouts and table sizes to be   */
6317 /* changed without rebooting, reloading or recompiling.  The initialisation */
6318 /* and 'destruction' routines of the various components of ipfilter are all */
6319 /* each responsible for handling their own values being too big.            */
6320 /* ------------------------------------------------------------------------ */
6321 int fr_ipftune(cmd, data, ifs)
6322 ioctlcmd_t cmd;
6323 void *data;
6324 ipf_stack_t *ifs;
6325 {
6326 	ipftuneable_t *ta;
6327 	ipftune_t tu;
6328 	void *cookie;
6329 	int error;
6330 
6331 	error = fr_inobj(data, &tu, IPFOBJ_TUNEABLE);
6332 	if (error != 0)
6333 		return error;
6334 
6335 	tu.ipft_name[sizeof(tu.ipft_name) - 1] = '\0';
6336 	cookie = tu.ipft_cookie;
6337 	ta = NULL;
6338 
6339 	switch (cmd)
6340 	{
6341 	case SIOCIPFGETNEXT :
6342 		/*
6343 		 * If cookie is non-NULL, assume it to be a pointer to the last
6344 		 * entry we looked at, so find it (if possible) and return a
6345 		 * pointer to the next one after it.  The last entry in the
6346 		 * the table is a NULL entry, so when we get to it, set cookie
6347 		 * to NULL and return that, indicating end of list, erstwhile
6348 		 * if we come in with cookie set to NULL, we are starting anew
6349 		 * at the front of the list.
6350 		 */
6351 		if (cookie != NULL) {
6352 			ta = fr_findtunebycookie(cookie, &tu.ipft_cookie, ifs);
6353 		} else {
6354 			ta = ifs->ifs_ipf_tuneables;
6355 			tu.ipft_cookie = ta + 1;
6356 		}
6357 		if (ta != NULL) {
6358 			/*
6359 			 * Entry found, but does the data pointed to by that
6360 			 * row fit in what we can return?
6361 			 */
6362 			if (ta->ipft_sz > sizeof(tu.ipft_un))
6363 				return EINVAL;
6364 
6365 			tu.ipft_vlong = 0;
6366 			if (ta->ipft_sz == sizeof(u_long))
6367 				tu.ipft_vlong = *ta->ipft_plong;
6368 			else if (ta->ipft_sz == sizeof(u_int))
6369 				tu.ipft_vint = *ta->ipft_pint;
6370 			else if (ta->ipft_sz == sizeof(u_short))
6371 				tu.ipft_vshort = *ta->ipft_pshort;
6372 			else if (ta->ipft_sz == sizeof(u_char))
6373 				tu.ipft_vchar = *ta->ipft_pchar;
6374 
6375 			tu.ipft_sz = ta->ipft_sz;
6376 			tu.ipft_min = ta->ipft_min;
6377 			tu.ipft_max = ta->ipft_max;
6378 			tu.ipft_flags = ta->ipft_flags;
6379 			bcopy(ta->ipft_name, tu.ipft_name,
6380 			      MIN(sizeof(tu.ipft_name),
6381 				  strlen(ta->ipft_name) + 1));
6382 		}
6383 		error = fr_outobj(data, &tu, IPFOBJ_TUNEABLE);
6384 		break;
6385 
6386 	case SIOCIPFGET :
6387 	case SIOCIPFSET :
6388 		/*
6389 		 * Search by name or by cookie value for a particular entry
6390 		 * in the tuning paramter table.
6391 		 */
6392 		error = ESRCH;
6393 		if (cookie != NULL) {
6394 			ta = fr_findtunebycookie(cookie, NULL, ifs);
6395 			if (ta != NULL)
6396 				error = 0;
6397 		} else if (tu.ipft_name[0] != '\0') {
6398 			ta = fr_findtunebyname(tu.ipft_name, ifs);
6399 			if (ta != NULL)
6400 				error = 0;
6401 		}
6402 		if (error != 0)
6403 			break;
6404 
6405 		if (cmd == (ioctlcmd_t)SIOCIPFGET) {
6406 			/*
6407 			 * Fetch the tuning parameters for a particular value
6408 			 */
6409 			tu.ipft_vlong = 0;
6410 			if (ta->ipft_sz == sizeof(u_long))
6411 				tu.ipft_vlong = *ta->ipft_plong;
6412 			else if (ta->ipft_sz == sizeof(u_int))
6413 				tu.ipft_vint = *ta->ipft_pint;
6414 			else if (ta->ipft_sz == sizeof(u_short))
6415 				tu.ipft_vshort = *ta->ipft_pshort;
6416 			else if (ta->ipft_sz == sizeof(u_char))
6417 				tu.ipft_vchar = *ta->ipft_pchar;
6418 			tu.ipft_cookie = ta;
6419 			tu.ipft_sz = ta->ipft_sz;
6420 			tu.ipft_min = ta->ipft_min;
6421 			tu.ipft_max = ta->ipft_max;
6422 			tu.ipft_flags = ta->ipft_flags;
6423 			error = fr_outobj(data, &tu, IPFOBJ_TUNEABLE);
6424 
6425 		} else if (cmd == (ioctlcmd_t)SIOCIPFSET) {
6426 			/*
6427 			 * Set an internal parameter.  The hard part here is
6428 			 * getting the new value safely and correctly out of
6429 			 * the kernel (given we only know its size, not type.)
6430 			 */
6431 			u_long in;
6432 
6433 			if (((ta->ipft_flags & IPFT_WRDISABLED) != 0) &&
6434 			    (ifs->ifs_fr_running > 0)) {
6435 				error = EBUSY;
6436 				break;
6437 			}
6438 
6439 			in = tu.ipft_vlong;
6440 			if (in < ta->ipft_min || in > ta->ipft_max) {
6441 				error = EINVAL;
6442 				break;
6443 			}
6444 
6445 			if (ta->ipft_sz == sizeof(u_long)) {
6446 				tu.ipft_vlong = *ta->ipft_plong;
6447 				*ta->ipft_plong = in;
6448 			} else if (ta->ipft_sz == sizeof(u_int)) {
6449 				tu.ipft_vint = *ta->ipft_pint;
6450 				*ta->ipft_pint = (u_int)(in & 0xffffffff);
6451 			} else if (ta->ipft_sz == sizeof(u_short)) {
6452 				tu.ipft_vshort = *ta->ipft_pshort;
6453 				*ta->ipft_pshort = (u_short)(in & 0xffff);
6454 			} else if (ta->ipft_sz == sizeof(u_char)) {
6455 				tu.ipft_vchar = *ta->ipft_pchar;
6456 				*ta->ipft_pchar = (u_char)(in & 0xff);
6457 			}
6458 			error = fr_outobj(data, &tu, IPFOBJ_TUNEABLE);
6459 		}
6460 		break;
6461 
6462 	default :
6463 		error = EINVAL;
6464 		break;
6465 	}
6466 
6467 	return error;
6468 }
6469 
6470 
6471 /* ------------------------------------------------------------------------ */
6472 /* Function:    fr_initialise                                               */
6473 /* Returns:     int - 0 == success,  < 0 == failure                         */
6474 /* Parameters:  None.                                                       */
6475 /*                                                                          */
6476 /* Call of the initialise functions for all the various subsystems inside   */
6477 /* of IPFilter.  If any of them should fail, return immeadiately a failure  */
6478 /* BUT do not try to recover from the error here.                           */
6479 /* ------------------------------------------------------------------------ */
6480 int fr_initialise(ifs)
6481 ipf_stack_t *ifs;
6482 {
6483 	int i;
6484 
6485 #ifdef IPFILTER_LOG
6486 	i = fr_loginit(ifs);
6487 	if (i < 0)
6488 		return -10 + i;
6489 #endif
6490 	i = fr_natinit(ifs);
6491 	if (i < 0)
6492 		return -20 + i;
6493 
6494 	i = fr_stateinit(ifs);
6495 	if (i < 0)
6496 		return -30 + i;
6497 
6498 	i = fr_authinit(ifs);
6499 	if (i < 0)
6500 		return -40 + i;
6501 
6502 	i = fr_fraginit(ifs);
6503 	if (i < 0)
6504 		return -50 + i;
6505 
6506 	i = appr_init(ifs);
6507 	if (i < 0)
6508 		return -60 + i;
6509 
6510 #ifdef IPFILTER_SYNC
6511 	i = ipfsync_init(ifs);
6512 	if (i < 0)
6513 		return -70 + i;
6514 #endif
6515 #ifdef IPFILTER_SCAN
6516 	i = ipsc_init(ifs);
6517 	if (i < 0)
6518 		return -80 + i;
6519 #endif
6520 #ifdef IPFILTER_LOOKUP
6521 	i = ip_lookup_init(ifs);
6522 	if (i < 0)
6523 		return -90 + i;
6524 #endif
6525 #ifdef IPFILTER_COMPILED
6526 	ipfrule_add(ifs);
6527 #endif
6528 	return 0;
6529 }
6530 
6531 
6532 /* ------------------------------------------------------------------------ */
6533 /* Function:    fr_deinitialise                                             */
6534 /* Returns:     None.                                                       */
6535 /* Parameters:  None.                                                       */
6536 /*                                                                          */
6537 /* Call all the various subsystem cleanup routines to deallocate memory or  */
6538 /* destroy locks or whatever they've done that they need to now undo.       */
6539 /* The order here IS important as there are some cross references of        */
6540 /* internal data structures.                                                */
6541 /* ------------------------------------------------------------------------ */
6542 void fr_deinitialise(ifs)
6543 ipf_stack_t *ifs;
6544 {
6545 	fr_fragunload(ifs);
6546 	fr_authunload(ifs);
6547 	fr_natunload(ifs);
6548 	fr_stateunload(ifs);
6549 #ifdef IPFILTER_SCAN
6550 	fr_scanunload(ifs);
6551 #endif
6552 	appr_unload(ifs);
6553 
6554 #ifdef IPFILTER_COMPILED
6555 	ipfrule_remove(ifs);
6556 #endif
6557 
6558 	(void) frflush(IPL_LOGIPF, 0, FR_INQUE|FR_OUTQUE|FR_INACTIVE, ifs);
6559 	(void) frflush(IPL_LOGIPF, 0, FR_INQUE|FR_OUTQUE, ifs);
6560 	(void) frflush(IPL_LOGCOUNT, 0, FR_INQUE|FR_OUTQUE|FR_INACTIVE, ifs);
6561 	(void) frflush(IPL_LOGCOUNT, 0, FR_INQUE|FR_OUTQUE, ifs);
6562 
6563 #ifdef IPFILTER_LOOKUP
6564 	ip_lookup_unload(ifs);
6565 #endif
6566 
6567 #ifdef IPFILTER_LOG
6568 	fr_logunload(ifs);
6569 #endif
6570 }
6571 
6572 
6573 /* ------------------------------------------------------------------------ */
6574 /* Function:    fr_zerostats                                                */
6575 /* Returns:     int - 0 = success, else failure                             */
6576 /* Parameters:  data(O) - pointer to pointer for copying data back to       */
6577 /*                                                                          */
6578 /* Copies the current statistics out to userspace and then zero's the       */
6579 /* current ones in the kernel. The lock is only held across the bzero() as  */
6580 /* the copyout may result in paging (ie network activity.)                  */
6581 /* ------------------------------------------------------------------------ */
6582 int	fr_zerostats(data, ifs)
6583 caddr_t	data;
6584 ipf_stack_t *ifs;
6585 {
6586 	friostat_t fio;
6587 	int error;
6588 
6589 	fr_getstat(&fio, ifs);
6590 	error = copyoutptr(&fio, data, sizeof(fio));
6591 	if (error)
6592 		return EFAULT;
6593 
6594 	WRITE_ENTER(&ifs->ifs_ipf_mutex);
6595 	bzero((char *)ifs->ifs_frstats, sizeof(*ifs->ifs_frstats) * 2);
6596 	RWLOCK_EXIT(&ifs->ifs_ipf_mutex);
6597 
6598 	return 0;
6599 }
6600 
6601 
6602 #ifdef _KERNEL
6603 /* ------------------------------------------------------------------------ */
6604 /* Function:    fr_resolvedest                                              */
6605 /* Returns:     Nil                                                         */
6606 /* Parameters:  fdp(IO) - pointer to destination information to resolve     */
6607 /*              v(I)    - IP protocol version to match                      */
6608 /*                                                                          */
6609 /* Looks up an interface name in the frdest structure pointed to by fdp and */
6610 /* if a matching name can be found for the particular IP protocol version   */
6611 /* then store the interface pointer in the frdest struct.  If no match is   */
6612 /* found, then set the interface pointer to be -1 as NULL is considered to  */
6613 /* indicate there is no information at all in the structure.                */
6614 /* ------------------------------------------------------------------------ */
6615 void fr_resolvedest(fdp, v, ifs)
6616 frdest_t *fdp;
6617 int v;
6618 ipf_stack_t *ifs;
6619 {
6620 	fdp->fd_ifp = NULL;
6621 
6622   	if (*fdp->fd_ifname != '\0') {
6623  		fdp->fd_ifp = GETIFP(fdp->fd_ifname, v, ifs);
6624 		if (fdp->fd_ifp == NULL)
6625 			fdp->fd_ifp = (void *)-1;
6626 	}
6627 }
6628 #endif /* _KERNEL */
6629 
6630 
6631 /* ------------------------------------------------------------------------ */
6632 /* Function:    fr_resolvenic                                               */
6633 /* Returns:     void* - NULL = wildcard name, -1 = failed to find NIC, else */
6634 /*                      pointer to interface structure for NIC              */
6635 /* Parameters:  name(I) - complete interface name                           */
6636 /*              v(I)    - IP protocol version                               */
6637 /*                                                                          */
6638 /* Look for a network interface structure that firstly has a matching name  */
6639 /* to that passed in and that is also being used for that IP protocol       */
6640 /* version (necessary on some platforms where there are separate listings   */
6641 /* for both IPv4 and IPv6 on the same physical NIC.                         */
6642 /*                                                                          */
6643 /* One might wonder why name gets terminated with a \0 byte in here.  The   */
6644 /* reason is an interface name could get into the kernel structures of ipf  */
6645 /* in any number of ways and so long as they all use the same sized array   */
6646 /* to put the name in, it makes sense to ensure it gets null terminated     */
6647 /* before it is used for its intended purpose - finding its match in the    */
6648 /* kernel's list of configured interfaces.                                  */
6649 /*                                                                          */
6650 /* NOTE: This SHOULD ONLY be used with IPFilter structures that have an     */
6651 /*       array for the name that is LIFNAMSIZ bytes (at least) in length.   */
6652 /* ------------------------------------------------------------------------ */
6653 void *fr_resolvenic(name, v, ifs)
6654 char *name;
6655 int v;
6656 ipf_stack_t *ifs;
6657 {
6658 	void *nic;
6659 
6660 	if (name[0] == '\0')
6661 		return NULL;
6662 
6663 	if ((name[1] == '\0') && ((name[0] == '-') || (name[0] == '*'))) {
6664 		return NULL;
6665 	}
6666 
6667 	name[LIFNAMSIZ - 1] = '\0';
6668 
6669 	nic = GETIFP(name, v, ifs);
6670 	if (nic == NULL)
6671 		nic = (void *)-1;
6672 	return nic;
6673 }
6674 
6675 
6676 /* ------------------------------------------------------------------------ */
6677 /* Function:    ipf_expiretokens                                            */
6678 /* Returns:     None.                                                       */
6679 /* Parameters:  ifs - ipf stack instance                                    */
6680 /*                                                                          */
6681 /* This function is run every ipf tick to see if there are any tokens that  */
6682 /* have been held for too long and need to be freed up.                     */
6683 /* ------------------------------------------------------------------------ */
6684 void ipf_expiretokens(ifs)
6685 ipf_stack_t *ifs;
6686 {
6687 	ipftoken_t *it;
6688 
6689 	WRITE_ENTER(&ifs->ifs_ipf_tokens);
6690 	while ((it = ifs->ifs_ipftokenhead) != NULL) {
6691 		if (it->ipt_die > ifs->ifs_fr_ticks)
6692 			break;
6693 
6694 		ipf_freetoken(it, ifs);
6695 	}
6696 	RWLOCK_EXIT(&ifs->ifs_ipf_tokens);
6697 }
6698 
6699 
6700 /* ------------------------------------------------------------------------ */
6701 /* Function:    ipf_deltoken                                                */
6702 /* Returns:     int - 0 = success, else error                               */
6703 /* Parameters:  type(I) - the token type to match                           */
6704 /*              uid(I)  - uid owning the token                              */
6705 /*              ptr(I)  - context pointer for the token                     */
6706 /*              ifs - ipf stack instance                                    */
6707 /*                                                                          */
6708 /* This function looks for a a token in the current list that matches up    */
6709 /* the fields (type, uid, ptr).  If none is found, ESRCH is returned, else  */
6710 /* call ipf_freetoken() to remove it from the list.                         */
6711 /* ------------------------------------------------------------------------ */
6712 int ipf_deltoken(type, uid, ptr, ifs)
6713 int type, uid;
6714 void *ptr;
6715 ipf_stack_t *ifs;
6716 {
6717 	ipftoken_t *it;
6718 	int error = ESRCH;
6719 
6720 	WRITE_ENTER(&ifs->ifs_ipf_tokens);
6721 	for (it = ifs->ifs_ipftokenhead; it != NULL; it = it->ipt_next)
6722 		if (ptr == it->ipt_ctx && type == it->ipt_type &&
6723 		    uid == it->ipt_uid) {
6724 			ipf_freetoken(it, ifs);
6725 			error = 0;
6726 			break;
6727 	}
6728 	RWLOCK_EXIT(&ifs->ifs_ipf_tokens);
6729 
6730 	return error;
6731 }
6732 
6733 
6734 /* ------------------------------------------------------------------------ */
6735 /* Function:    ipf_unlinktoken                                             */
6736 /* Returns:     None.                                                       */
6737 /* Parameters:  token(I) - pointer to token structure                       */
6738 /*              ifs - ipf stack instance                                    */
6739 /*                                                                          */
6740 /* This function unlinks a token structure from the linked list of tokens   */
6741 /* that it belongs to.  The head pointer never needs to be explicitly       */
6742 /* adjusted, but the tail does due to the linked list implementation.       */
6743 /* ------------------------------------------------------------------------ */
6744 static void ipf_unlinktoken(token, ifs)
6745 ipftoken_t *token;
6746 ipf_stack_t *ifs;
6747 {
6748 
6749 	if (ifs->ifs_ipftokentail == &token->ipt_next)
6750 		ifs->ifs_ipftokentail = token->ipt_pnext;
6751 
6752 	*token->ipt_pnext = token->ipt_next;
6753 	if (token->ipt_next != NULL)
6754 		token->ipt_next->ipt_pnext = token->ipt_pnext;
6755 }
6756 
6757 
6758 /* ------------------------------------------------------------------------ */
6759 /* Function:    ipf_findtoken                                               */
6760 /* Returns:     ipftoken_t * - NULL if no memory, else pointer to token     */
6761 /* Parameters:  type(I) - the token type to match                           */
6762 /*              uid(I) - uid owning the token                               */
6763 /*              ptr(I) - context pointer for the token                      */
6764 /*              ifs - ipf stack instance                                    */
6765 /*                                                                          */
6766 /* This function looks for a live token in the list of current tokens that  */
6767 /* matches the tuple (type, uid, ptr).  If one cannot be found then one is  */
6768 /* allocated.  If one is found then it is moved to the top of the list of   */
6769 /* currently active tokens.                                                 */
6770 /*                                                                          */
6771 /* NOTE: It is by design that this function returns holding a read lock on  */
6772 /*       ipf_tokens.  Callers must make sure they release it!               */
6773 /* ------------------------------------------------------------------------ */
6774 ipftoken_t *ipf_findtoken(type, uid, ptr, ifs)
6775 int type, uid;
6776 void *ptr;
6777 ipf_stack_t *ifs;
6778 {
6779 	ipftoken_t *it, *new;
6780 
6781 	KMALLOC(new, ipftoken_t *);
6782 
6783 	WRITE_ENTER(&ifs->ifs_ipf_tokens);
6784 	for (it = ifs->ifs_ipftokenhead; it != NULL; it = it->ipt_next) {
6785 		if (it->ipt_alive == 0)
6786 			continue;
6787 		if (ptr == it->ipt_ctx && type == it->ipt_type &&
6788 		    uid == it->ipt_uid)
6789 			break;
6790 	}
6791 
6792 	if (it == NULL) {
6793 		it = new;
6794 		new = NULL;
6795 		if (it == NULL)
6796 			return NULL;
6797 		it->ipt_data = NULL;
6798 		it->ipt_ctx = ptr;
6799 		it->ipt_uid = uid;
6800 		it->ipt_type = type;
6801 		it->ipt_next = NULL;
6802 		it->ipt_alive = 1;
6803 	} else {
6804 		if (new != NULL) {
6805 			KFREE(new);
6806 			new = NULL;
6807 		}
6808 
6809 		ipf_unlinktoken(it, ifs);
6810 	}
6811 	it->ipt_pnext = ifs->ifs_ipftokentail;
6812 	*ifs->ifs_ipftokentail = it;
6813 	ifs->ifs_ipftokentail = &it->ipt_next;
6814 	it->ipt_next = NULL;
6815 
6816 	it->ipt_die = ifs->ifs_fr_ticks + 2;
6817 
6818 	MUTEX_DOWNGRADE(&ifs->ifs_ipf_tokens);
6819 
6820 	return it;
6821 }
6822 
6823 
6824 /* ------------------------------------------------------------------------ */
6825 /* Function:    ipf_freetoken                                               */
6826 /* Returns:     None.                                                       */
6827 /* Parameters:  token(I) - pointer to token structure                       */
6828 /*              ifs - ipf stack instance                                    */
6829 /*                                                                          */
6830 /* This function unlinks a token from the linked list and on the path to    */
6831 /* free'ing the data, it calls the dereference function that is associated  */
6832 /* with the type of data pointed to by the token as it is considered to     */
6833 /* hold a reference to it.                                                  */
6834 /* ------------------------------------------------------------------------ */
6835 void ipf_freetoken(token, ifs)
6836 ipftoken_t *token;
6837 ipf_stack_t *ifs;
6838 {
6839 	void *data, **datap;
6840 
6841 	ipf_unlinktoken(token, ifs);
6842 
6843 	data = token->ipt_data;
6844 	datap = &data;
6845 
6846 	if ((data != NULL) && (data != (void *)-1)) {
6847 		switch (token->ipt_type)
6848 		{
6849 		case IPFGENITER_IPF :
6850 			(void)fr_derefrule((frentry_t **)datap, ifs);
6851 			break;
6852 		case IPFGENITER_IPNAT :
6853 			WRITE_ENTER(&ifs->ifs_ipf_nat);
6854 			fr_ipnatderef((ipnat_t **)datap, ifs);
6855 			RWLOCK_EXIT(&ifs->ifs_ipf_nat);
6856 			break;
6857 		case IPFGENITER_NAT :
6858 			fr_natderef((nat_t **)datap, ifs);
6859 			break;
6860 		case IPFGENITER_STATE :
6861 			fr_statederef((ipstate_t **)datap, ifs);
6862 			break;
6863 		case IPFGENITER_FRAG :
6864 			fr_fragderef((ipfr_t **)datap, &ifs->ifs_ipf_frag, ifs);
6865 			break;
6866 		case IPFGENITER_NATFRAG :
6867  			fr_fragderef((ipfr_t **)datap,
6868 				     &ifs->ifs_ipf_natfrag, ifs);
6869 			break;
6870 		case IPFGENITER_HOSTMAP :
6871 			WRITE_ENTER(&ifs->ifs_ipf_nat);
6872 			fr_hostmapdel((hostmap_t **)datap);
6873 			RWLOCK_EXIT(&ifs->ifs_ipf_nat);
6874 			break;
6875 		default :
6876 			(void) ip_lookup_iterderef(token->ipt_type, data, ifs);
6877 			break;
6878 		}
6879 	}
6880 
6881 	KFREE(token);
6882 }
6883 
6884 
6885 /* ------------------------------------------------------------------------ */
6886 /* Function:    ipf_getnextrule                                             */
6887 /* Returns:     int - 0 = success, else error                               */
6888 /* Parameters:  t(I)   - pointer to destination information to resolve      */
6889 /*              ptr(I) - pointer to ipfobj_t to copyin from user space      */
6890 /*              ifs - ipf stack instance                                    */
6891 /*                                                                          */
6892 /* This function's first job is to bring in the ipfruleiter_t structure via */
6893 /* the ipfobj_t structure to determine what should be the next rule to      */
6894 /* return. Once the ipfruleiter_t has been brought in, it then tries to     */
6895 /* find the 'next rule'.  This may include searching rule group lists or    */
6896 /* just be as simple as looking at the 'next' field in the rule structure.  */
6897 /* When we have found the rule to return, increase its reference count and  */
6898 /* if we used an existing rule to get here, decrease its reference count.   */
6899 /* ------------------------------------------------------------------------ */
6900 int ipf_getnextrule(t, ptr, ifs)
6901 ipftoken_t *t;
6902 void *ptr;
6903 ipf_stack_t *ifs;
6904 {
6905 	frentry_t *fr, *next, zero;
6906 	int error, out, count;
6907 	ipfruleiter_t it;
6908 	frgroup_t *fg;
6909 	char *dst;
6910 
6911 	if (t == NULL || ptr == NULL)
6912 		return EFAULT;
6913 	error = fr_inobj(ptr, &it, IPFOBJ_IPFITER);
6914 	if (error != 0)
6915 		return error;
6916 	if ((it.iri_ver != AF_INET) && (it.iri_ver != AF_INET6))
6917 		return EINVAL;
6918 	if ((it.iri_inout < 0) || (it.iri_inout > 3))
6919 		return EINVAL;
6920 	if (it.iri_nrules == 0)
6921 		return EINVAL;
6922 	if ((it.iri_active != 0) && (it.iri_active != 1))
6923 		return EINVAL;
6924 	if (it.iri_rule == NULL)
6925 		return EFAULT;
6926 
6927 	/*
6928 	 * Use bitmask on it.iri_inout to determine direction.
6929 	 * F_OUT (1) and F_ACOUT (3) mask to out = 1, while
6930 	 * F_IN (0) and F_ACIN (2) mask to out = 0.
6931 	 */
6932 	out = it.iri_inout & F_OUT;
6933 	READ_ENTER(&ifs->ifs_ipf_mutex);
6934 
6935 	/*
6936 	 * Retrieve "previous" entry from token and find the next entry.
6937 	 */
6938 	fr = t->ipt_data;
6939 	if (fr == NULL) {
6940 		if (*it.iri_group == '\0') {
6941 			/*
6942 			 * Use bitmask again to determine accounting or not.
6943 			 * F_ACIN will mask to accounting cases F_ACIN (2)
6944 			 * or F_ACOUT (3), but not F_IN or F_OUT.
6945 			 */
6946 			if ((it.iri_inout & F_ACIN) != 0) {
6947 				if (it.iri_ver == AF_INET)
6948 					next = ifs->ifs_ipacct
6949 					    [out][it.iri_active];
6950 				else
6951 					next = ifs->ifs_ipacct6
6952 					    [out][it.iri_active];
6953 			} else {
6954 				if (it.iri_ver == AF_INET)
6955 					next = ifs->ifs_ipfilter
6956 					    [out][it.iri_active];
6957 				else
6958 					next = ifs->ifs_ipfilter6
6959 					    [out][it.iri_active];
6960 			}
6961 		} else {
6962 			fg = fr_findgroup(it.iri_group, IPL_LOGIPF,
6963 					  it.iri_active, NULL, ifs);
6964 			if (fg != NULL)
6965 				next = fg->fg_start;
6966 			else
6967 				next = NULL;
6968 		}
6969 	} else {
6970 		next = fr->fr_next;
6971 	}
6972 
6973 	dst = (char *)it.iri_rule;
6974 	/*
6975 	 * The ipfruleiter may ask for more than 1 rule at a time to be
6976 	 * copied out, so long as that many exist in the list to start with!
6977 	 */
6978 	for (count = it.iri_nrules; count > 0; count--) {
6979 		/*
6980 		 * If we found an entry, add reference to it and update token.
6981 		 * Otherwise, zero out data to be returned and NULL out token.
6982 		 */
6983 		if (next != NULL) {
6984 			MUTEX_ENTER(&next->fr_lock);
6985 			next->fr_ref++;
6986 			MUTEX_EXIT(&next->fr_lock);
6987 			t->ipt_data = next;
6988 		} else {
6989 			bzero(&zero, sizeof(zero));
6990 			next = &zero;
6991 			t->ipt_data = NULL;
6992 		}
6993 
6994 		/*
6995 		 * Now that we have ref, it's save to give up lock.
6996 		 */
6997 		RWLOCK_EXIT(&ifs->ifs_ipf_mutex);
6998 
6999 		/*
7000 		 * Copy out data and clean up references and token as needed.
7001 		 */
7002 		error = COPYOUT(next, dst, sizeof(*next));
7003 		if (error != 0)
7004 			error = EFAULT;
7005 		if (t->ipt_data == NULL) {
7006 			ipf_freetoken(t, ifs);
7007 			break;
7008 		} else {
7009 			if (fr != NULL)
7010 				(void) fr_derefrule(&fr, ifs);
7011 			if (next->fr_data != NULL) {
7012 				dst += sizeof(*next);
7013 				error = COPYOUT(next->fr_data, dst,
7014 						next->fr_dsize);
7015 				if (error != 0)
7016 					error = EFAULT;
7017 				else
7018 					dst += next->fr_dsize;
7019 			}
7020 			if (next->fr_next == NULL) {
7021 				ipf_freetoken(t, ifs);
7022 				break;
7023 			}
7024 		}
7025 
7026 		if ((count == 1) || (error != 0))
7027 			break;
7028 
7029 		READ_ENTER(&ifs->ifs_ipf_mutex);
7030 		fr = next;
7031 		next = fr->fr_next;
7032 	}
7033 
7034 	return error;
7035 }
7036 
7037 
7038 /* ------------------------------------------------------------------------ */
7039 /* Function:    fr_frruleiter                                               */
7040 /* Returns:     int - 0 = success, else error                               */
7041 /* Parameters:  data(I) - the token type to match                           */
7042 /*              uid(I) - uid owning the token                               */
7043 /*              ptr(I) - context pointer for the token                      */
7044 /*              ifs - ipf stack instance                                    */
7045 /*                                                                          */
7046 /* This function serves as a stepping stone between fr_ipf_ioctl and        */
7047 /* ipf_getnextrule.  It's role is to find the right token in the kernel for */
7048 /* the process doing the ioctl and use that to ask for the next rule.       */
7049 /* ------------------------------------------------------------------------ */
7050 int ipf_frruleiter(data, uid, ctx, ifs)
7051 void *data, *ctx;
7052 int uid;
7053 ipf_stack_t *ifs;
7054 {
7055 	ipftoken_t *token;
7056 	int error;
7057 
7058 	token = ipf_findtoken(IPFGENITER_IPF, uid, ctx, ifs);
7059 	if (token != NULL)
7060 		error = ipf_getnextrule(token, data, ifs);
7061 	else
7062 		error = EFAULT;
7063 	RWLOCK_EXIT(&ifs->ifs_ipf_tokens);
7064 
7065 	return error;
7066 }
7067 
7068 
7069 /* ------------------------------------------------------------------------ */
7070 /* Function:    ipf_geniter                                                 */
7071 /* Returns:     int - 0 = success, else error                               */
7072 /* Parameters:  token(I) - pointer to ipftoken structure                    */
7073 /*              itp(I) - pointer to ipfgeniter structure                    */
7074 /*              ifs - ipf stack instance                                    */
7075 /*                                                                          */
7076 /* Generic iterator called from ipf_genericiter.  Currently only used for   */
7077 /* walking through list of fragments.                                       */
7078 /* ------------------------------------------------------------------------ */
7079 int ipf_geniter(token, itp, ifs)
7080 ipftoken_t *token;
7081 ipfgeniter_t *itp;
7082 ipf_stack_t *ifs;
7083 {
7084 	int error;
7085 
7086 	switch (itp->igi_type)
7087 	{
7088 	case IPFGENITER_FRAG :
7089 		error = fr_nextfrag(token, itp, &ifs->ifs_ipfr_list,
7090 				    &ifs->ifs_ipfr_tail, &ifs->ifs_ipf_frag,
7091 				    ifs);
7092 		break;
7093 	default :
7094 		error = EINVAL;
7095 		break;
7096 	}
7097 
7098 	return error;
7099 }
7100 
7101 
7102 /* ------------------------------------------------------------------------ */
7103 /* Function:    ipf_genericiter                                             */
7104 /* Returns:     int - 0 = success, else error                               */
7105 /* Parameters:  data(I) - the token type to match                           */
7106 /*              uid(I) - uid owning the token                               */
7107 /*              ptr(I) - context pointer for the token                      */
7108 /*              ifs - ipf stack instance                                    */
7109 /*                                                                          */
7110 /* This function serves as a stepping stone between fr_ipf_ioctl and        */
7111 /* ipf_geniter when handling SIOCGENITER.  It's role is to find the right   */
7112 /* token in the kernel for the process using the ioctl, and to use that     */
7113 /* token when calling ipf_geniter.                                          */
7114 /* ------------------------------------------------------------------------ */
7115 int ipf_genericiter(data, uid, ctx, ifs)
7116 void *data, *ctx;
7117 int uid;
7118 ipf_stack_t *ifs;
7119 {
7120 	ipftoken_t *token;
7121 	ipfgeniter_t iter;
7122 	int error;
7123 
7124 	error = fr_inobj(data, &iter, IPFOBJ_GENITER);
7125 	if (error != 0)
7126 		return error;
7127 
7128 	token = ipf_findtoken(iter.igi_type, uid, ctx, ifs);
7129 	if (token != NULL) {
7130 		token->ipt_subtype = iter.igi_type;
7131 		error = ipf_geniter(token, &iter, ifs);
7132 	} else
7133 		error = EFAULT;
7134 	RWLOCK_EXIT(&ifs->ifs_ipf_tokens);
7135 
7136 	return error;
7137 }
7138