Home | History | Annotate | Line # | Download | only in netinet
fil.c revision 1.25
      1 /*	$NetBSD: fil.c,v 1.25 2019/02/04 07:59:01 mrg Exp $	*/
      2 
      3 /*
      4  * Copyright (C) 2012 by Darren Reed.
      5  *
      6  * See the IPFILTER.LICENCE file for details on licencing.
      7  *
      8  * Id: fil.c,v 1.1.1.2 2012/07/22 13:45:07 darrenr Exp $
      9  *
     10  */
     11 #if defined(KERNEL) || defined(_KERNEL)
     12 # undef KERNEL
     13 # undef _KERNEL
     14 # define        KERNEL	1
     15 # define        _KERNEL	1
     16 #endif
     17 #include <sys/errno.h>
     18 #include <sys/types.h>
     19 #include <sys/param.h>
     20 #include <sys/time.h>
     21 #if defined(_KERNEL) && defined(__FreeBSD_version) && \
     22     (__FreeBSD_version >= 220000)
     23 # if (__FreeBSD_version >= 400000)
     24 #  if !defined(IPFILTER_LKM)
     25 #   include "opt_inet6.h"
     26 #  endif
     27 #  if (__FreeBSD_version == 400019)
     28 #   define CSUM_DELAY_DATA
     29 #  endif
     30 # endif
     31 # include <sys/filio.h>
     32 #else
     33 # include <sys/ioctl.h>
     34 #endif
     35 #if (defined(__SVR4) || defined(__svr4__)) && defined(sun)
     36 # include <sys/filio.h>
     37 #endif
     38 #if !defined(_AIX51)
     39 # include <sys/fcntl.h>
     40 #endif
     41 #if defined(_KERNEL)
     42 # include <sys/systm.h>
     43 # include <sys/file.h>
     44 #else
     45 # include <stdio.h>
     46 # include <string.h>
     47 # include <stdlib.h>
     48 # include <stddef.h>
     49 # include <sys/file.h>
     50 # define _KERNEL
     51 # ifdef __OpenBSD__
     52 struct file;
     53 # endif
     54 # include <sys/uio.h>
     55 # undef _KERNEL
     56 #endif
     57 #if !defined(__SVR4) && !defined(__svr4__) && !defined(__hpux) && \
     58     !defined(linux)
     59 # include <sys/mbuf.h>
     60 #else
     61 # if !defined(linux)
     62 #  include <sys/byteorder.h>
     63 # endif
     64 # if (SOLARIS2 < 5) && defined(sun)
     65 #  include <sys/dditypes.h>
     66 # endif
     67 #endif
     68 #ifdef __hpux
     69 # define _NET_ROUTE_INCLUDED
     70 #endif
     71 #if !defined(linux)
     72 # include <sys/protosw.h>
     73 #endif
     74 #include <sys/socket.h>
     75 #include <net/if.h>
     76 #ifdef sun
     77 # include <net/af.h>
     78 #endif
     79 #include <netinet/in.h>
     80 #include <netinet/in_systm.h>
     81 #include <netinet/ip.h>
     82 #if defined(__sgi) && defined(IFF_DRVRLOCK) /* IRIX 6 */
     83 # include <sys/hashing.h>
     84 # include <netinet/in_var.h>
     85 #endif
     86 #include <netinet/tcp.h>
     87 #if (!defined(__sgi) && !defined(AIX)) || defined(_KERNEL)
     88 # include <netinet/udp.h>
     89 # include <netinet/ip_icmp.h>
     90 #endif
     91 #ifdef __hpux
     92 # undef _NET_ROUTE_INCLUDED
     93 #endif
     94 #ifdef __osf__
     95 # undef _RADIX_H_
     96 #endif
     97 #include "netinet/ip_compat.h"
     98 #ifdef	USE_INET6
     99 # include <netinet/icmp6.h>
    100 # if !SOLARIS && defined(_KERNEL) && !defined(__osf__) && !defined(__hpux)
    101 #  include <netinet6/in6_var.h>
    102 # endif
    103 #endif
    104 #include "netinet/ip_fil.h"
    105 #include "netinet/ip_nat.h"
    106 #include "netinet/ip_frag.h"
    107 #include "netinet/ip_state.h"
    108 #include "netinet/ip_proxy.h"
    109 #include "netinet/ip_auth.h"
    110 #ifdef IPFILTER_SCAN
    111 # include "netinet/ip_scan.h"
    112 #endif
    113 #include "netinet/ip_sync.h"
    114 #include "netinet/ip_lookup.h"
    115 #include "netinet/ip_pool.h"
    116 #include "netinet/ip_htable.h"
    117 #ifdef IPFILTER_COMPILED
    118 # include "netinet/ip_rules.h"
    119 #endif
    120 #if defined(IPFILTER_BPF) && defined(_KERNEL)
    121 # include <net/bpf.h>
    122 #endif
    123 #if defined(__FreeBSD_version) && (__FreeBSD_version >= 300000)
    124 # include <sys/malloc.h>
    125 #endif
    126 #include "netinet/ipl.h"
    127 
    128 #if defined(__NetBSD__) && (__NetBSD_Version__ >= 104230000)
    129 # include <sys/callout.h>
    130 extern struct callout ipf_slowtimer_ch;
    131 #endif
    132 #if defined(__OpenBSD__)
    133 # include <sys/timeout.h>
    134 extern struct timeout ipf_slowtimer_ch;
    135 #endif
    136 #if defined(__NetBSD__)
    137 #include <netinet/in_offload.h>
    138 #endif
    139 /* END OF INCLUDES */
    140 
    141 #if !defined(lint)
    142 #if defined(__NetBSD__)
    143 #include <sys/cdefs.h>
    144 __KERNEL_RCSID(0, "$NetBSD: fil.c,v 1.25 2019/02/04 07:59:01 mrg Exp $");
    145 #else
    146 static const char sccsid[] = "@(#)fil.c	1.36 6/5/96 (C) 1993-2000 Darren Reed";
    147 static const char rcsid[] = "@(#)Id: fil.c,v 1.1.1.2 2012/07/22 13:45:07 darrenr Exp $";
    148 #endif
    149 #endif
    150 
    151 #ifndef	_KERNEL
    152 # include "ipf.h"
    153 # include "ipt.h"
    154 extern	int	opts;
    155 extern	int	blockreason;
    156 #endif /* _KERNEL */
    157 
    158 #define	LBUMP(x)	softc->x++
    159 #define	LBUMPD(x, y)	do { softc->x.y++; DT(y); } while (0)
    160 
    161 static	INLINE int	ipf_check_ipf(fr_info_t *, frentry_t *, int);
    162 static	u_32_t		ipf_checkcipso(fr_info_t *, u_char *, int);
    163 static	u_32_t		ipf_checkripso(u_char *);
    164 static	u_32_t		ipf_decaps(fr_info_t *, u_32_t, int);
    165 #ifdef	IPFILTER_LOG
    166 static	frentry_t	*ipf_dolog(fr_info_t *, u_32_t *);
    167 #endif
    168 static	int		ipf_flushlist(ipf_main_softc_t *, int *, frentry_t **);
    169 static	int		ipf_flush_groups(ipf_main_softc_t *, frgroup_t **, int);
    170 static	ipfunc_t	ipf_findfunc(ipfunc_t);
    171 static	void		*ipf_findlookup(ipf_main_softc_t *, int, frentry_t *,
    172 					i6addr_t *, i6addr_t *);
    173 static	frentry_t	*ipf_firewall(fr_info_t *, u_32_t *);
    174 static	int		ipf_fr_matcharray(fr_info_t *, int *);
    175 static	int		ipf_frruleiter(ipf_main_softc_t *, void *, int, void *);
    176 static	void		ipf_funcfini(ipf_main_softc_t *, frentry_t *);;
    177 static	int		ipf_funcinit(ipf_main_softc_t *, frentry_t *);
    178 static	int		ipf_geniter(ipf_main_softc_t *, ipftoken_t *,
    179 				    ipfgeniter_t *);
    180 static	void		ipf_getstat(ipf_main_softc_t *,
    181 				    struct friostat *, int);
    182 static	int		ipf_group_flush(ipf_main_softc_t *, frgroup_t *);
    183 static	void		ipf_group_free(frgroup_t *);
    184 static	int		ipf_grpmapfini(struct ipf_main_softc_s *, frentry_t *);
    185 static	int		ipf_grpmapinit(struct ipf_main_softc_s *, frentry_t *);
    186 static	frentry_t	*ipf_nextrule(ipf_main_softc_t *, int, int,
    187 					frentry_t *, int);
    188 static	int		ipf_portcheck(frpcmp_t *, u_32_t);
    189 static	INLINE int	ipf_pr_ah(fr_info_t *);
    190 static	INLINE void	ipf_pr_esp(fr_info_t *);
    191 static	INLINE void	ipf_pr_gre(fr_info_t *);
    192 static	INLINE void	ipf_pr_udp(fr_info_t *);
    193 static	INLINE void	ipf_pr_tcp(fr_info_t *);
    194 static	INLINE void	ipf_pr_icmp(fr_info_t *);
    195 static	INLINE void	ipf_pr_ipv4hdr(fr_info_t *);
    196 static	INLINE void	ipf_pr_short(fr_info_t *, int);
    197 static	INLINE int	ipf_pr_tcpcommon(fr_info_t *);
    198 static	INLINE int	ipf_pr_udpcommon(fr_info_t *);
    199 static	void		ipf_rule_delete(ipf_main_softc_t *, frentry_t *f,
    200 					int, int);
    201 static	void		ipf_rule_expire_insert(ipf_main_softc_t *,
    202 					       frentry_t *, int);
    203 static	int		ipf_synclist(ipf_main_softc_t *, frentry_t *, void *);
    204 static	void		ipf_token_flush(ipf_main_softc_t *);
    205 static	void		ipf_token_unlink(ipf_main_softc_t *, ipftoken_t *);
    206 static	ipftuneable_t	*ipf_tune_findbyname(ipftuneable_t *, const char *);
    207 static	ipftuneable_t	*ipf_tune_findbycookie(ipftuneable_t **, void *,
    208 					       void **);
    209 static	int		ipf_updateipid(fr_info_t *);
    210 static	int		ipf_settimeout(struct ipf_main_softc_s *,
    211 				       struct ipftuneable *, ipftuneval_t *);
    212 
    213 
    214 /*
    215  * bit values for identifying presence of individual IP options
    216  * All of these tables should be ordered by increasing key value on the left
    217  * hand side to allow for binary searching of the array and include a trailer
    218  * with a 0 for the bitmask for linear searches to easily find the end with.
    219  */
    220 static const	struct	optlist	ipopts[20] = {
    221 	{ IPOPT_NOP,	0x000001 },
    222 	{ IPOPT_RR,	0x000002 },
    223 	{ IPOPT_ZSU,	0x000004 },
    224 	{ IPOPT_MTUP,	0x000008 },
    225 	{ IPOPT_MTUR,	0x000010 },
    226 	{ IPOPT_ENCODE,	0x000020 },
    227 	{ IPOPT_TS,	0x000040 },
    228 	{ IPOPT_TR,	0x000080 },
    229 	{ IPOPT_SECURITY, 0x000100 },
    230 	{ IPOPT_LSRR,	0x000200 },
    231 	{ IPOPT_E_SEC,	0x000400 },
    232 	{ IPOPT_CIPSO,	0x000800 },
    233 	{ IPOPT_SATID,	0x001000 },
    234 	{ IPOPT_SSRR,	0x002000 },
    235 	{ IPOPT_ADDEXT,	0x004000 },
    236 	{ IPOPT_VISA,	0x008000 },
    237 	{ IPOPT_IMITD,	0x010000 },
    238 	{ IPOPT_EIP,	0x020000 },
    239 	{ IPOPT_FINN,	0x040000 },
    240 	{ 0,		0x000000 }
    241 };
    242 
    243 #ifdef USE_INET6
    244 static const struct optlist ip6exthdr[] = {
    245 	{ IPPROTO_HOPOPTS,		0x000001 },
    246 	{ IPPROTO_IPV6,			0x000002 },
    247 	{ IPPROTO_ROUTING,		0x000004 },
    248 	{ IPPROTO_FRAGMENT,		0x000008 },
    249 	{ IPPROTO_ESP,			0x000010 },
    250 	{ IPPROTO_AH,			0x000020 },
    251 	{ IPPROTO_NONE,			0x000040 },
    252 	{ IPPROTO_DSTOPTS,		0x000080 },
    253 	{ IPPROTO_MOBILITY,		0x000100 },
    254 	{ 0,				0 }
    255 };
    256 #endif
    257 
    258 /*
    259  * bit values for identifying presence of individual IP security options
    260  */
    261 static const	struct	optlist	secopt[8] = {
    262 	{ IPSO_CLASS_RES4,	0x01 },
    263 	{ IPSO_CLASS_TOPS,	0x02 },
    264 	{ IPSO_CLASS_SECR,	0x04 },
    265 	{ IPSO_CLASS_RES3,	0x08 },
    266 	{ IPSO_CLASS_CONF,	0x10 },
    267 	{ IPSO_CLASS_UNCL,	0x20 },
    268 	{ IPSO_CLASS_RES2,	0x40 },
    269 	{ IPSO_CLASS_RES1,	0x80 }
    270 };
    271 
    272 char	ipfilter_version[] = IPL_VERSION;
    273 
    274 int	ipf_features = 0
    275 #ifdef	IPFILTER_LKM
    276 		| IPF_FEAT_LKM
    277 #endif
    278 #ifdef	IPFILTER_LOG
    279 		| IPF_FEAT_LOG
    280 #endif
    281 		| IPF_FEAT_LOOKUP
    282 #ifdef	IPFILTER_BPF
    283 		| IPF_FEAT_BPF
    284 #endif
    285 #ifdef	IPFILTER_COMPILED
    286 		| IPF_FEAT_COMPILED
    287 #endif
    288 #ifdef	IPFILTER_CKSUM
    289 		| IPF_FEAT_CKSUM
    290 #endif
    291 		| IPF_FEAT_SYNC
    292 #ifdef	IPFILTER_SCAN
    293 		| IPF_FEAT_SCAN
    294 #endif
    295 #ifdef	USE_INET6
    296 		| IPF_FEAT_IPV6
    297 #endif
    298 	;
    299 
    300 
    301 /*
    302  * Table of functions available for use with call rules.
    303  */
    304 static ipfunc_resolve_t ipf_availfuncs[] = {
    305 	{ "srcgrpmap", ipf_srcgrpmap, ipf_grpmapinit, ipf_grpmapfini },
    306 	{ "dstgrpmap", ipf_dstgrpmap, ipf_grpmapinit, ipf_grpmapfini },
    307 	{ "",	       NULL,	      NULL,	      NULL }
    308 };
    309 
    310 static const ipftuneable_t ipf_main_tuneables[] = {
    311 	{ { (void *)offsetof(struct ipf_main_softc_s, ipf_flags) },
    312 		"ipf_flags",		0,	0xffffffff,
    313 		stsizeof(ipf_main_softc_t, ipf_flags),
    314 		0,			NULL,	NULL },
    315 	{ { (void *)offsetof(struct ipf_main_softc_s, ipf_active) },
    316 		"active",		0,	0,
    317 		stsizeof(ipf_main_softc_t, ipf_active),
    318 		IPFT_RDONLY,		NULL,	NULL },
    319 	{ { (void *)offsetof(ipf_main_softc_t, ipf_control_forwarding) },
    320 		"control_forwarding",	0, 1,
    321 		stsizeof(ipf_main_softc_t, ipf_control_forwarding),
    322 		0,			NULL,	NULL },
    323 	{ { (void *)offsetof(ipf_main_softc_t, ipf_update_ipid) },
    324 		"update_ipid",		0,	1,
    325 		stsizeof(ipf_main_softc_t, ipf_update_ipid),
    326 		0,			NULL,	NULL },
    327 	{ { (void *)offsetof(ipf_main_softc_t, ipf_chksrc) },
    328 		"chksrc",		0,	1,
    329 		stsizeof(ipf_main_softc_t, ipf_chksrc),
    330 		0,			NULL,	NULL },
    331 	{ { (void *)offsetof(ipf_main_softc_t, ipf_minttl) },
    332 		"min_ttl",		0,	1,
    333 		stsizeof(ipf_main_softc_t, ipf_minttl),
    334 		0,			NULL,	NULL },
    335 	{ { (void *)offsetof(ipf_main_softc_t, ipf_icmpminfragmtu) },
    336 		"icmp_minfragmtu",	0,	1,
    337 		stsizeof(ipf_main_softc_t, ipf_icmpminfragmtu),
    338 		0,			NULL,	NULL },
    339 	{ { (void *)offsetof(ipf_main_softc_t, ipf_pass) },
    340 		"default_pass",		0,	0xffffffff,
    341 		stsizeof(ipf_main_softc_t, ipf_pass),
    342 		0,			NULL,	NULL },
    343 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpidletimeout) },
    344 		"tcp_idle_timeout",	1,	0x7fffffff,
    345 		stsizeof(ipf_main_softc_t, ipf_tcpidletimeout),
    346 		0,			NULL,	ipf_settimeout },
    347 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosewait) },
    348 		"tcp_close_wait",	1,	0x7fffffff,
    349 		stsizeof(ipf_main_softc_t, ipf_tcpclosewait),
    350 		0,			NULL,	ipf_settimeout },
    351 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcplastack) },
    352 		"tcp_last_ack",		1,	0x7fffffff,
    353 		stsizeof(ipf_main_softc_t, ipf_tcplastack),
    354 		0,			NULL,	ipf_settimeout },
    355 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcptimeout) },
    356 		"tcp_timeout",		1,	0x7fffffff,
    357 		stsizeof(ipf_main_softc_t, ipf_tcptimeout),
    358 		0,			NULL,	ipf_settimeout },
    359 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynsent) },
    360 		"tcp_syn_sent",		1,	0x7fffffff,
    361 		stsizeof(ipf_main_softc_t, ipf_tcpsynsent),
    362 		0,			NULL,	ipf_settimeout },
    363 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynrecv) },
    364 		"tcp_syn_received",	1,	0x7fffffff,
    365 		stsizeof(ipf_main_softc_t, ipf_tcpsynrecv),
    366 		0,			NULL,	ipf_settimeout },
    367 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosed) },
    368 		"tcp_closed",		1,	0x7fffffff,
    369 		stsizeof(ipf_main_softc_t, ipf_tcpclosed),
    370 		0,			NULL,	ipf_settimeout },
    371 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcphalfclosed) },
    372 		"tcp_half_closed",	1,	0x7fffffff,
    373 		stsizeof(ipf_main_softc_t, ipf_tcphalfclosed),
    374 		0,			NULL,	ipf_settimeout },
    375 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcptimewait) },
    376 		"tcp_time_wait",	1,	0x7fffffff,
    377 		stsizeof(ipf_main_softc_t, ipf_tcptimewait),
    378 		0,			NULL,	ipf_settimeout },
    379 	{ { (void *)offsetof(ipf_main_softc_t, ipf_udptimeout) },
    380 		"udp_timeout",		1,	0x7fffffff,
    381 		stsizeof(ipf_main_softc_t, ipf_udptimeout),
    382 		0,			NULL,	ipf_settimeout },
    383 	{ { (void *)offsetof(ipf_main_softc_t, ipf_udpacktimeout) },
    384 		"udp_ack_timeout",	1,	0x7fffffff,
    385 		stsizeof(ipf_main_softc_t, ipf_udpacktimeout),
    386 		0,			NULL,	ipf_settimeout },
    387 	{ { (void *)offsetof(ipf_main_softc_t, ipf_icmptimeout) },
    388 		"icmp_timeout",		1,	0x7fffffff,
    389 		stsizeof(ipf_main_softc_t, ipf_icmptimeout),
    390 		0,			NULL,	ipf_settimeout },
    391 	{ { (void *)offsetof(ipf_main_softc_t, ipf_icmpacktimeout) },
    392 		"icmp_ack_timeout",	1,	0x7fffffff,
    393 		stsizeof(ipf_main_softc_t, ipf_icmpacktimeout),
    394 		0,			NULL,	ipf_settimeout },
    395 	{ { (void *)offsetof(ipf_main_softc_t, ipf_iptimeout) },
    396 		"ip_timeout",		1,	0x7fffffff,
    397 		stsizeof(ipf_main_softc_t, ipf_iptimeout),
    398 		0,			NULL,	ipf_settimeout },
    399 #if defined(INSTANCES) && defined(_KERNEL)
    400 	{ { (void *)offsetof(ipf_main_softc_t, ipf_get_loopback) },
    401 		"intercept_loopback",	0,	1,
    402 		stsizeof(ipf_main_softc_t, ipf_get_loopback),
    403 		0,			NULL,	ipf_set_loopback },
    404 #endif
    405 	{ { 0 },
    406 		NULL,			0,	0,
    407 		0,
    408 		0,			NULL,	NULL }
    409 };
    410 
    411 
    412 /*
    413  * The next section of code is a a collection of small routines that set
    414  * fields in the fr_info_t structure passed based on properties of the
    415  * current packet.  There are different routines for the same protocol
    416  * for each of IPv4 and IPv6.  Adding a new protocol, for which there
    417  * will "special" inspection for setup, is now more easily done by adding
    418  * a new routine and expanding the ipf_pr_ipinit*() function rather than by
    419  * adding more code to a growing switch statement.
    420  */
    421 #ifdef USE_INET6
    422 static	INLINE int	ipf_pr_ah6(fr_info_t *);
    423 static	INLINE void	ipf_pr_esp6(fr_info_t *);
    424 static	INLINE void	ipf_pr_gre6(fr_info_t *);
    425 static	INLINE void	ipf_pr_udp6(fr_info_t *);
    426 static	INLINE void	ipf_pr_tcp6(fr_info_t *);
    427 static	INLINE void	ipf_pr_icmp6(fr_info_t *);
    428 static	INLINE void	ipf_pr_ipv6hdr(fr_info_t *);
    429 static	INLINE void	ipf_pr_short6(fr_info_t *, int);
    430 static	INLINE int	ipf_pr_hopopts6(fr_info_t *);
    431 static	INLINE int	ipf_pr_mobility6(fr_info_t *);
    432 static	INLINE int	ipf_pr_routing6(fr_info_t *);
    433 static	INLINE int	ipf_pr_dstopts6(fr_info_t *);
    434 static	INLINE int	ipf_pr_fragment6(fr_info_t *);
    435 static	INLINE struct ip6_ext *ipf_pr_ipv6exthdr(fr_info_t *, int, int);
    436 
    437 
    438 /* ------------------------------------------------------------------------ */
    439 /* Function:    ipf_pr_short6                                               */
    440 /* Returns:     void                                                        */
    441 /* Parameters:  fin(I)  - pointer to packet information                     */
    442 /*              xmin(I) - minimum header size                               */
    443 /*                                                                          */
    444 /* IPv6 Only                                                                */
    445 /* This is function enforces the 'is a packet too short to be legit' rule   */
    446 /* for IPv6 and marks the packet with FI_SHORT if so.  See function comment */
    447 /* for ipf_pr_short() for more details.                                     */
    448 /* ------------------------------------------------------------------------ */
    449 static INLINE void
    450 ipf_pr_short6(fr_info_t *fin, int xmin)
    451 {
    452 
    453 	if (fin->fin_dlen < xmin)
    454 		fin->fin_flx |= FI_SHORT;
    455 }
    456 
    457 
    458 /* ------------------------------------------------------------------------ */
    459 /* Function:    ipf_pr_ipv6hdr                                              */
    460 /* Returns:     void                                                        */
    461 /* Parameters:  fin(I) - pointer to packet information                      */
    462 /*                                                                          */
    463 /* IPv6 Only                                                                */
    464 /* Copy values from the IPv6 header into the fr_info_t struct and call the  */
    465 /* per-protocol analyzer if it exists.  In validating the packet, a protocol*/
    466 /* analyzer may pullup or free the packet itself so we need to be vigiliant */
    467 /* of that possibility arising.                                             */
    468 /* ------------------------------------------------------------------------ */
    469 static INLINE void
    470 ipf_pr_ipv6hdr(fr_info_t *fin)
    471 {
    472 	ip6_t *ip6 = (ip6_t *)fin->fin_ip;
    473 	int p, go = 1, i, hdrcount;
    474 	fr_ip_t *fi = &fin->fin_fi;
    475 
    476 	fin->fin_off = 0;
    477 
    478 	fi->fi_tos = 0;
    479 	fi->fi_optmsk = 0;
    480 	fi->fi_secmsk = 0;
    481 	fi->fi_auth = 0;
    482 
    483 	p = ip6->ip6_nxt;
    484 	fin->fin_crc = p;
    485 	fi->fi_ttl = ip6->ip6_hlim;
    486 	fi->fi_src.in6 = ip6->ip6_src;
    487 	fin->fin_crc += fi->fi_src.i6[0];
    488 	fin->fin_crc += fi->fi_src.i6[1];
    489 	fin->fin_crc += fi->fi_src.i6[2];
    490 	fin->fin_crc += fi->fi_src.i6[3];
    491 	fi->fi_dst.in6 = ip6->ip6_dst;
    492 	fin->fin_crc += fi->fi_dst.i6[0];
    493 	fin->fin_crc += fi->fi_dst.i6[1];
    494 	fin->fin_crc += fi->fi_dst.i6[2];
    495 	fin->fin_crc += fi->fi_dst.i6[3];
    496 	fin->fin_id = 0;
    497 	if (IN6_IS_ADDR_MULTICAST(&fi->fi_dst.in6))
    498 		fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
    499 
    500 	hdrcount = 0;
    501 	while (go && !(fin->fin_flx & FI_SHORT)) {
    502 		switch (p)
    503 		{
    504 		case IPPROTO_UDP :
    505 			ipf_pr_udp6(fin);
    506 			go = 0;
    507 			break;
    508 
    509 		case IPPROTO_TCP :
    510 			ipf_pr_tcp6(fin);
    511 			go = 0;
    512 			break;
    513 
    514 		case IPPROTO_ICMPV6 :
    515 			ipf_pr_icmp6(fin);
    516 			go = 0;
    517 			break;
    518 
    519 		case IPPROTO_GRE :
    520 			ipf_pr_gre6(fin);
    521 			go = 0;
    522 			break;
    523 
    524 		case IPPROTO_HOPOPTS :
    525 			p = ipf_pr_hopopts6(fin);
    526 			break;
    527 
    528 		case IPPROTO_MOBILITY :
    529 			p = ipf_pr_mobility6(fin);
    530 			break;
    531 
    532 		case IPPROTO_DSTOPTS :
    533 			p = ipf_pr_dstopts6(fin);
    534 			break;
    535 
    536 		case IPPROTO_ROUTING :
    537 			p = ipf_pr_routing6(fin);
    538 			break;
    539 
    540 		case IPPROTO_AH :
    541 			p = ipf_pr_ah6(fin);
    542 			break;
    543 
    544 		case IPPROTO_ESP :
    545 			ipf_pr_esp6(fin);
    546 			go = 0;
    547 			break;
    548 
    549 		case IPPROTO_IPV6 :
    550 			for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
    551 				if (ip6exthdr[i].ol_val == p) {
    552 					fin->fin_flx |= ip6exthdr[i].ol_bit;
    553 					break;
    554 				}
    555 			go = 0;
    556 			break;
    557 
    558 		case IPPROTO_NONE :
    559 			go = 0;
    560 			break;
    561 
    562 		case IPPROTO_FRAGMENT :
    563 			p = ipf_pr_fragment6(fin);
    564 			/*
    565 			 * Given that the only fragments we want to let through
    566 			 * (where fin_off != 0) are those where the non-first
    567 			 * fragments only have data, we can safely stop looking
    568 			 * at headers if this is a non-leading fragment.
    569 			 */
    570 			if (fin->fin_off != 0)
    571 				go = 0;
    572 			break;
    573 
    574 		default :
    575 			go = 0;
    576 			break;
    577 		}
    578 		hdrcount++;
    579 
    580 		/*
    581 		 * It is important to note that at this point, for the
    582 		 * extension headers (go != 0), the entire header may not have
    583 		 * been pulled up when the code gets to this point.  This is
    584 		 * only done for "go != 0" because the other header handlers
    585 		 * will all pullup their complete header.  The other indicator
    586 		 * of an incomplete packet is that this was just an extension
    587 		 * header.
    588 		 */
    589 		if ((go != 0) && (p != IPPROTO_NONE) &&
    590 		    (ipf_pr_pullup(fin, 0) == -1)) {
    591 			p = IPPROTO_NONE;
    592 			break;
    593 		}
    594 	}
    595 
    596 	/*
    597 	 * Some of the above functions, like ipf_pr_esp6(), can call ipf_pullup
    598 	 * and destroy whatever packet was here.  The caller of this function
    599 	 * expects us to return if there is a problem with ipf_pullup.
    600 	 */
    601 	if (fin->fin_m == NULL) {
    602 		ipf_main_softc_t *softc = fin->fin_main_soft;
    603 
    604 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_bad);
    605 		return;
    606 	}
    607 
    608 	fi->fi_p = p;
    609 
    610 	/*
    611 	 * IPv6 fragment case 1 - see comment for ipf_pr_fragment6().
    612 	 * "go != 0" imples the above loop hasn't arrived at a layer 4 header.
    613 	 */
    614 	if ((go != 0) && (fin->fin_flx & FI_FRAG) && (fin->fin_off == 0)) {
    615 		ipf_main_softc_t *softc = fin->fin_main_soft;
    616 
    617 		fin->fin_flx |= FI_BAD;
    618 		DT2(ipf_fi_bad_ipv6_frag_1, fr_info_t *, fin, int, go);
    619 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_badfrag);
    620 		LBUMP(ipf_stats[fin->fin_out].fr_v6_bad);
    621 	}
    622 }
    623 
    624 
    625 /* ------------------------------------------------------------------------ */
    626 /* Function:    ipf_pr_ipv6exthdr                                           */
    627 /* Returns:     struct ip6_ext * - pointer to the start of the next header  */
    628 /*                                 or NULL if there is a prolblem.          */
    629 /* Parameters:  fin(I)      - pointer to packet information                 */
    630 /*              multiple(I) - flag indicating yes/no if multiple occurances */
    631 /*                            of this extension header are allowed.         */
    632 /*              proto(I)    - protocol number for this extension header     */
    633 /*                                                                          */
    634 /* IPv6 Only                                                                */
    635 /* This function embodies a number of common checks that all IPv6 extension */
    636 /* headers must be subjected to.  For example, making sure the packet is    */
    637 /* big enough for it to be in, checking if it is repeated and setting a     */
    638 /* flag to indicate its presence.                                           */
    639 /* ------------------------------------------------------------------------ */
    640 static INLINE struct ip6_ext *
    641 ipf_pr_ipv6exthdr(fr_info_t *fin, int multiple, int proto)
    642 {
    643 	ipf_main_softc_t *softc = fin->fin_main_soft;
    644 	struct ip6_ext *hdr;
    645 	u_short shift;
    646 	int i;
    647 
    648 	fin->fin_flx |= FI_V6EXTHDR;
    649 
    650 				/* 8 is default length of extension hdr */
    651 	if ((fin->fin_dlen - 8) < 0) {
    652 		fin->fin_flx |= FI_SHORT;
    653 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_short);
    654 		return NULL;
    655 	}
    656 
    657 	if (ipf_pr_pullup(fin, 8) == -1) {
    658 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_pullup);
    659 		return NULL;
    660 	}
    661 
    662 	hdr = fin->fin_dp;
    663 	switch (proto)
    664 	{
    665 	case IPPROTO_FRAGMENT :
    666 		shift = 8;
    667 		break;
    668 	default :
    669 		shift = 8 + (hdr->ip6e_len << 3);
    670 		break;
    671 	}
    672 
    673 	if (shift > fin->fin_dlen) {	/* Nasty extension header length? */
    674 		fin->fin_flx |= FI_BAD;
    675 		DT3(ipf_fi_bad_pr_ipv6exthdr_len, fr_info_t *, fin, u_short, shift, u_short, fin->fin_dlen);
    676 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_hlen);
    677 		return NULL;
    678 	}
    679 
    680 	fin->fin_dp = (char *)fin->fin_dp + shift;
    681 	fin->fin_dlen -= shift;
    682 
    683 	/*
    684 	 * If we have seen a fragment header, do not set any flags to indicate
    685 	 * the presence of this extension header as it has no impact on the
    686 	 * end result until after it has been defragmented.
    687 	 */
    688 	if (fin->fin_flx & FI_FRAG)
    689 		return hdr;
    690 
    691 	for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
    692 		if (ip6exthdr[i].ol_val == proto) {
    693 			/*
    694 			 * Most IPv6 extension headers are only allowed once.
    695 			 */
    696 			if ((multiple == 0) &&
    697 			    ((fin->fin_optmsk & ip6exthdr[i].ol_bit) != 0)) {
    698 				fin->fin_flx |= FI_BAD;
    699 				DT2(ipf_fi_bad_ipv6exthdr_once, fr_info_t *, fin, u_int, (fin->fin_optmsk & ip6exthdr[i].ol_bit));
    700 			} else
    701 				fin->fin_optmsk |= ip6exthdr[i].ol_bit;
    702 			break;
    703 		}
    704 
    705 	return hdr;
    706 }
    707 
    708 
    709 /* ------------------------------------------------------------------------ */
    710 /* Function:    ipf_pr_hopopts6                                             */
    711 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
    712 /* Parameters:  fin(I) - pointer to packet information                      */
    713 /*                                                                          */
    714 /* IPv6 Only                                                                */
    715 /* This is function checks pending hop by hop options extension header      */
    716 /* ------------------------------------------------------------------------ */
    717 static INLINE int
    718 ipf_pr_hopopts6(fr_info_t *fin)
    719 {
    720 	struct ip6_ext *hdr;
    721 
    722 	hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
    723 	if (hdr == NULL)
    724 		return IPPROTO_NONE;
    725 	return hdr->ip6e_nxt;
    726 }
    727 
    728 
    729 /* ------------------------------------------------------------------------ */
    730 /* Function:    ipf_pr_mobility6                                            */
    731 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
    732 /* Parameters:  fin(I) - pointer to packet information                      */
    733 /*                                                                          */
    734 /* IPv6 Only                                                                */
    735 /* This is function checks the IPv6 mobility extension header               */
    736 /* ------------------------------------------------------------------------ */
    737 static INLINE int
    738 ipf_pr_mobility6(fr_info_t *fin)
    739 {
    740 	struct ip6_ext *hdr;
    741 
    742 	hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_MOBILITY);
    743 	if (hdr == NULL)
    744 		return IPPROTO_NONE;
    745 	return hdr->ip6e_nxt;
    746 }
    747 
    748 
    749 /* ------------------------------------------------------------------------ */
    750 /* Function:    ipf_pr_routing6                                             */
    751 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
    752 /* Parameters:  fin(I) - pointer to packet information                      */
    753 /*                                                                          */
    754 /* IPv6 Only                                                                */
    755 /* This is function checks pending routing extension header                 */
    756 /* ------------------------------------------------------------------------ */
    757 static INLINE int
    758 ipf_pr_routing6(fr_info_t *fin)
    759 {
    760 	struct ip6_routing *hdr;
    761 
    762 	hdr = (struct ip6_routing *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_ROUTING);
    763 	if (hdr == NULL)
    764 		return IPPROTO_NONE;
    765 
    766 	switch (hdr->ip6r_type)
    767 	{
    768 	case 0 :
    769 		/*
    770 		 * Nasty extension header length?
    771 		 */
    772 		if (((hdr->ip6r_len >> 1) < hdr->ip6r_segleft) ||
    773 		    (hdr->ip6r_segleft && (hdr->ip6r_len & 1))) {
    774 			ipf_main_softc_t *softc = fin->fin_main_soft;
    775 
    776 			fin->fin_flx |= FI_BAD;
    777 			DT1(ipf_fi_bad_routing6, fr_info_t *, fin);
    778 			LBUMPD(ipf_stats[fin->fin_out], fr_v6_rh_bad);
    779 			return IPPROTO_NONE;
    780 		}
    781 		break;
    782 
    783 	default :
    784 		break;
    785 	}
    786 
    787 	return hdr->ip6r_nxt;
    788 }
    789 
    790 
    791 /* ------------------------------------------------------------------------ */
    792 /* Function:    ipf_pr_fragment6                                            */
    793 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
    794 /* Parameters:  fin(I) - pointer to packet information                      */
    795 /*                                                                          */
    796 /* IPv6 Only                                                                */
    797 /* Examine the IPv6 fragment header and extract fragment offset information.*/
    798 /*                                                                          */
    799 /* Fragments in IPv6 are extraordinarily difficult to deal with - much more */
    800 /* so than in IPv4.  There are 5 cases of fragments with IPv6 that all      */
    801 /* packets with a fragment header can fit into.  They are as follows:       */
    802 /*                                                                          */
    803 /* 1.  [IPv6][0-n EH][FH][0-n EH] (no L4HDR present)                        */
    804 /* 2.  [IPV6][0-n EH][FH][0-n EH][L4HDR part] (short)                       */
    805 /* 3.  [IPV6][0-n EH][FH][L4HDR part][0-n data] (short)                     */
    806 /* 4.  [IPV6][0-n EH][FH][0-n EH][L4HDR][0-n data]                          */
    807 /* 5.  [IPV6][0-n EH][FH][data]                                             */
    808 /*                                                                          */
    809 /* IPV6 = IPv6 header, FH = Fragment Header,                                */
    810 /* 0-n EH = 0 or more extension headers, 0-n data = 0 or more bytes of data */
    811 /*                                                                          */
    812 /* Packets that match 1, 2, 3 will be dropped as the only reasonable        */
    813 /* scenario in which they happen is in extreme circumstances that are most  */
    814 /* likely to be an indication of an attack rather than normal traffic.      */
    815 /* A type 3 packet may be sent by an attacked after a type 4 packet.  There */
    816 /* are two rules that can be used to guard against type 3 packets: L4       */
    817 /* headers must always be in a packet that has the offset field set to 0    */
    818 /* and no packet is allowed to overlay that where offset = 0.               */
    819 /* ------------------------------------------------------------------------ */
    820 static INLINE int
    821 ipf_pr_fragment6(fr_info_t *fin)
    822 {
    823 	ipf_main_softc_t *softc = fin->fin_main_soft;
    824 	struct ip6_frag *frag;
    825 
    826 	fin->fin_flx |= FI_FRAG;
    827 
    828 	frag = (struct ip6_frag *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_FRAGMENT);
    829 	if (frag == NULL) {
    830 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_frag_bad);
    831 		return IPPROTO_NONE;
    832 	}
    833 
    834 	if ((frag->ip6f_offlg & IP6F_MORE_FRAG) != 0) {
    835 		/*
    836 		 * Any fragment that isn't the last fragment must have its
    837 		 * length as a multiple of 8.
    838 		 */
    839 		if ((fin->fin_plen & 7) != 0) {
    840 			fin->fin_flx |= FI_BAD;
    841 			DT2(ipf_fi_bad_frag_not_8, fr_info_t *, fin, u_int, (fin->fin_plen & 7));
    842 		}
    843 	}
    844 
    845 	fin->fin_fraghdr = frag;
    846 	fin->fin_id = frag->ip6f_ident;
    847 	fin->fin_off = ntohs(frag->ip6f_offlg & IP6F_OFF_MASK);
    848 	if (fin->fin_off != 0)
    849 		fin->fin_flx |= FI_FRAGBODY;
    850 
    851 	/*
    852 	 * Jumbograms aren't handled, so the max. length is 64k
    853 	 */
    854 	if ((fin->fin_off << 3) + fin->fin_dlen > 65535) {
    855 		  fin->fin_flx |= FI_BAD;
    856 		  DT2(ipf_fi_bad_jumbogram, fr_info_t *, fin, u_int, ((fin->fin_off << 3) + fin->fin_dlen));
    857 	}
    858 
    859 	/*
    860 	 * We don't know where the transport layer header (or whatever is next
    861 	 * is), as it could be behind destination options (amongst others) so
    862 	 * return the fragment header as the type of packet this is.  Note that
    863 	 * this effectively disables the fragment cache for > 1 protocol at a
    864 	 * time.
    865 	 */
    866 	return frag->ip6f_nxt;
    867 }
    868 
    869 
    870 /* ------------------------------------------------------------------------ */
    871 /* Function:    ipf_pr_dstopts6                                             */
    872 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
    873 /* Parameters:  fin(I) - pointer to packet information                      */
    874 /*                                                                          */
    875 /* IPv6 Only                                                                */
    876 /* This is function checks pending destination options extension header     */
    877 /* ------------------------------------------------------------------------ */
    878 static INLINE int
    879 ipf_pr_dstopts6(fr_info_t *fin)
    880 {
    881 	ipf_main_softc_t *softc = fin->fin_main_soft;
    882 	struct ip6_ext *hdr;
    883 
    884 	hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_DSTOPTS);
    885 	if (hdr == NULL) {
    886 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_dst_bad);
    887 		return IPPROTO_NONE;
    888 	}
    889 	return hdr->ip6e_nxt;
    890 }
    891 
    892 
    893 /* ------------------------------------------------------------------------ */
    894 /* Function:    ipf_pr_icmp6                                                */
    895 /* Returns:     void                                                        */
    896 /* Parameters:  fin(I) - pointer to packet information                      */
    897 /*                                                                          */
    898 /* IPv6 Only                                                                */
    899 /* This routine is mainly concerned with determining the minimum valid size */
    900 /* for an ICMPv6 packet.                                                    */
    901 /* ------------------------------------------------------------------------ */
    902 static INLINE void
    903 ipf_pr_icmp6(fr_info_t *fin)
    904 {
    905 	int minicmpsz = sizeof(struct icmp6_hdr);
    906 	struct icmp6_hdr *icmp6;
    907 
    908 	if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN - sizeof(ip6_t)) == -1) {
    909 		ipf_main_softc_t *softc = fin->fin_main_soft;
    910 
    911 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_icmp6_pullup);
    912 		return;
    913 	}
    914 
    915 	if (fin->fin_dlen > 1) {
    916 		ip6_t *ip6;
    917 
    918 		icmp6 = fin->fin_dp;
    919 
    920 		fin->fin_data[0] = *(u_short *)icmp6;
    921 
    922 		if ((icmp6->icmp6_type & ICMP6_INFOMSG_MASK) != 0)
    923 			fin->fin_flx |= FI_ICMPQUERY;
    924 
    925 		switch (icmp6->icmp6_type)
    926 		{
    927 		case ICMP6_ECHO_REPLY :
    928 		case ICMP6_ECHO_REQUEST :
    929 			if (fin->fin_dlen >= 6)
    930 				fin->fin_data[1] = icmp6->icmp6_id;
    931 			minicmpsz = ICMP6ERR_MINPKTLEN - sizeof(ip6_t);
    932 			break;
    933 
    934 		case ICMP6_DST_UNREACH :
    935 		case ICMP6_PACKET_TOO_BIG :
    936 		case ICMP6_TIME_EXCEEDED :
    937 		case ICMP6_PARAM_PROB :
    938 			fin->fin_flx |= FI_ICMPERR;
    939 			minicmpsz = ICMP6ERR_IPICMPHLEN - sizeof(ip6_t);
    940 			if (fin->fin_plen < ICMP6ERR_IPICMPHLEN)
    941 				break;
    942 
    943 			if (M_LEN(fin->fin_m) < fin->fin_plen) {
    944 				if (ipf_coalesce(fin) != 1)
    945 					return;
    946 			}
    947 
    948 			if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN) == -1)
    949 				return;
    950 
    951 			/*
    952 			 * If the destination of this packet doesn't match the
    953 			 * source of the original packet then this packet is
    954 			 * not correct.
    955 			 */
    956 			icmp6 = fin->fin_dp;
    957 			ip6 = (ip6_t *)((char *)icmp6 + ICMPERR_ICMPHLEN);
    958 			if (IP6_NEQ(&fin->fin_fi.fi_dst,
    959 				    &ip6->ip6_src)) {
    960 				fin->fin_flx |= FI_BAD;
    961 				DT1(ipf_fi_bad_icmp6, fr_info_t *, fin);
    962 			}
    963 			break;
    964 		default :
    965 			break;
    966 		}
    967 	}
    968 
    969 	ipf_pr_short6(fin, minicmpsz);
    970 	if ((fin->fin_flx & (FI_SHORT|FI_BAD)) == 0) {
    971 		u_char p = fin->fin_p;
    972 
    973 		fin->fin_p = IPPROTO_ICMPV6;
    974 		ipf_checkv6sum(fin);
    975 		fin->fin_p = p;
    976 	}
    977 }
    978 
    979 
    980 /* ------------------------------------------------------------------------ */
    981 /* Function:    ipf_pr_udp6                                                 */
    982 /* Returns:     void                                                        */
    983 /* Parameters:  fin(I) - pointer to packet information                      */
    984 /*                                                                          */
    985 /* IPv6 Only                                                                */
    986 /* Analyse the packet for IPv6/UDP properties.                              */
    987 /* Is not expected to be called for fragmented packets.                     */
    988 /* ------------------------------------------------------------------------ */
    989 static INLINE void
    990 ipf_pr_udp6(fr_info_t *fin)
    991 {
    992 
    993 	if (ipf_pr_udpcommon(fin) == 0) {
    994 		u_char p = fin->fin_p;
    995 
    996 		fin->fin_p = IPPROTO_UDP;
    997 		ipf_checkv6sum(fin);
    998 		fin->fin_p = p;
    999 	}
   1000 }
   1001 
   1002 
   1003 /* ------------------------------------------------------------------------ */
   1004 /* Function:    ipf_pr_tcp6                                                 */
   1005 /* Returns:     void                                                        */
   1006 /* Parameters:  fin(I) - pointer to packet information                      */
   1007 /*                                                                          */
   1008 /* IPv6 Only                                                                */
   1009 /* Analyse the packet for IPv6/TCP properties.                              */
   1010 /* Is not expected to be called for fragmented packets.                     */
   1011 /* ------------------------------------------------------------------------ */
   1012 static INLINE void
   1013 ipf_pr_tcp6(fr_info_t *fin)
   1014 {
   1015 
   1016 	if (ipf_pr_tcpcommon(fin) == 0) {
   1017 		u_char p = fin->fin_p;
   1018 
   1019 		fin->fin_p = IPPROTO_TCP;
   1020 		ipf_checkv6sum(fin);
   1021 		fin->fin_p = p;
   1022 	}
   1023 }
   1024 
   1025 
   1026 /* ------------------------------------------------------------------------ */
   1027 /* Function:    ipf_pr_esp6                                                 */
   1028 /* Returns:     void                                                        */
   1029 /* Parameters:  fin(I) - pointer to packet information                      */
   1030 /*                                                                          */
   1031 /* IPv6 Only                                                                */
   1032 /* Analyse the packet for ESP properties.                                   */
   1033 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits)  */
   1034 /* even though the newer ESP packets must also have a sequence number that  */
   1035 /* is 32bits as well, it is not possible(?) to determine the version from a */
   1036 /* simple packet header.                                                    */
   1037 /* ------------------------------------------------------------------------ */
   1038 static INLINE void
   1039 ipf_pr_esp6(fr_info_t *fin)
   1040 {
   1041 
   1042 	if ((fin->fin_off == 0) && (ipf_pr_pullup(fin, 8) == -1)) {
   1043 		ipf_main_softc_t *softc = fin->fin_main_soft;
   1044 
   1045 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_esp_pullup);
   1046 		return;
   1047 	}
   1048 }
   1049 
   1050 
   1051 /* ------------------------------------------------------------------------ */
   1052 /* Function:    ipf_pr_ah6                                                  */
   1053 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
   1054 /* Parameters:  fin(I) - pointer to packet information                      */
   1055 /*                                                                          */
   1056 /* IPv6 Only                                                                */
   1057 /* Analyse the packet for AH properties.                                    */
   1058 /* The minimum length is taken to be the combination of all fields in the   */
   1059 /* header being present and no authentication data (null algorithm used.)   */
   1060 /* ------------------------------------------------------------------------ */
   1061 static INLINE int
   1062 ipf_pr_ah6(fr_info_t *fin)
   1063 {
   1064 	authhdr_t *ah;
   1065 
   1066 	fin->fin_flx |= FI_AH;
   1067 
   1068 	ah = (authhdr_t *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
   1069 	if (ah == NULL) {
   1070 		ipf_main_softc_t *softc = fin->fin_main_soft;
   1071 
   1072 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ah_bad);
   1073 		return IPPROTO_NONE;
   1074 	}
   1075 
   1076 	ipf_pr_short6(fin, sizeof(*ah));
   1077 
   1078 	/*
   1079 	 * No need for another pullup, ipf_pr_ipv6exthdr() will pullup
   1080 	 * enough data to satisfy ah_next (the very first one.)
   1081 	 */
   1082 	return ah->ah_next;
   1083 }
   1084 
   1085 
   1086 /* ------------------------------------------------------------------------ */
   1087 /* Function:    ipf_pr_gre6                                                 */
   1088 /* Returns:     void                                                        */
   1089 /* Parameters:  fin(I) - pointer to packet information                      */
   1090 /*                                                                          */
   1091 /* Analyse the packet for GRE properties.                                   */
   1092 /* ------------------------------------------------------------------------ */
   1093 static INLINE void
   1094 ipf_pr_gre6(fr_info_t *fin)
   1095 {
   1096 	grehdr_t *gre;
   1097 
   1098 	if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
   1099 		ipf_main_softc_t *softc = fin->fin_main_soft;
   1100 
   1101 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_gre_pullup);
   1102 		return;
   1103 	}
   1104 
   1105 	gre = fin->fin_dp;
   1106 	if (GRE_REV(gre->gr_flags) == 1)
   1107 		fin->fin_data[0] = gre->gr_call;
   1108 }
   1109 #endif	/* USE_INET6 */
   1110 
   1111 
   1112 /* ------------------------------------------------------------------------ */
   1113 /* Function:    ipf_pr_pullup                                               */
   1114 /* Returns:     int     - 0 == pullup succeeded, -1 == failure              */
   1115 /* Parameters:  fin(I)  - pointer to packet information                     */
   1116 /*              plen(I) - length (excluding L3 header) to pullup            */
   1117 /*                                                                          */
   1118 /* Short inline function to cut down on code duplication to perform a call  */
   1119 /* to ipf_pullup to ensure there is the required amount of data,            */
   1120 /* consecutively in the packet buffer.                                      */
   1121 /*                                                                          */
   1122 /* This function pulls up 'extra' data at the location of fin_dp.  fin_dp   */
   1123 /* points to the first byte after the complete layer 3 header, which will   */
   1124 /* include all of the known extension headers for IPv6 or options for IPv4. */
   1125 /*                                                                          */
   1126 /* Since fr_pullup() expects the total length of bytes to be pulled up, it  */
   1127 /* is necessary to add those we can already assume to be pulled up (fin_dp  */
   1128 /* - fin_ip) to what is passed through.                                     */
   1129 /* ------------------------------------------------------------------------ */
   1130 int
   1131 ipf_pr_pullup(fr_info_t *fin, int plen)
   1132 {
   1133 	ipf_main_softc_t *softc = fin->fin_main_soft;
   1134 
   1135 	if (fin->fin_m != NULL) {
   1136 		if (fin->fin_dp != NULL)
   1137 			plen += (char *)fin->fin_dp -
   1138 				((char *)fin->fin_ip + fin->fin_hlen);
   1139 		plen += fin->fin_hlen;
   1140 		if (M_LEN(fin->fin_m) < plen + fin->fin_ipoff) {
   1141 #if defined(_KERNEL)
   1142 			if (ipf_pullup(fin->fin_m, fin, plen) == NULL) {
   1143 				DT(ipf_pullup_fail);
   1144 				LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
   1145 				return -1;
   1146 			}
   1147 			LBUMP(ipf_stats[fin->fin_out].fr_pull[0]);
   1148 #else
   1149 			LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
   1150 			/*
   1151 			 * Fake ipf_pullup failing
   1152 			 */
   1153 			fin->fin_reason = FRB_PULLUP;
   1154 			*fin->fin_mp = NULL;
   1155 			fin->fin_m = NULL;
   1156 			fin->fin_ip = NULL;
   1157 			return -1;
   1158 #endif
   1159 		}
   1160 	}
   1161 	return 0;
   1162 }
   1163 
   1164 
   1165 /* ------------------------------------------------------------------------ */
   1166 /* Function:    ipf_pr_short                                                */
   1167 /* Returns:     void                                                        */
   1168 /* Parameters:  fin(I)  - pointer to packet information                     */
   1169 /*              xmin(I) - minimum header size                               */
   1170 /*                                                                          */
   1171 /* Check if a packet is "short" as defined by xmin.  The rule we are        */
   1172 /* applying here is that the packet must not be fragmented within the layer */
   1173 /* 4 header.  That is, it must not be a fragment that has its offset set to */
   1174 /* start within the layer 4 header (hdrmin) or if it is at offset 0, the    */
   1175 /* entire layer 4 header must be present (min).                             */
   1176 /* ------------------------------------------------------------------------ */
   1177 static INLINE void
   1178 ipf_pr_short(fr_info_t *fin, int xmin)
   1179 {
   1180 
   1181 	if (fin->fin_off == 0) {
   1182 		if (fin->fin_dlen < xmin)
   1183 			fin->fin_flx |= FI_SHORT;
   1184 	} else if (fin->fin_off < xmin) {
   1185 		fin->fin_flx |= FI_SHORT;
   1186 	}
   1187 }
   1188 
   1189 
   1190 /* ------------------------------------------------------------------------ */
   1191 /* Function:    ipf_pr_icmp                                                 */
   1192 /* Returns:     void                                                        */
   1193 /* Parameters:  fin(I) - pointer to packet information                      */
   1194 /*                                                                          */
   1195 /* IPv4 Only                                                                */
   1196 /* Do a sanity check on the packet for ICMP (v4).  In nearly all cases,     */
   1197 /* except extrememly bad packets, both type and code will be present.       */
   1198 /* The expected minimum size of an ICMP packet is very much dependent on    */
   1199 /* the type of it.                                                          */
   1200 /*                                                                          */
   1201 /* XXX - other ICMP sanity checks?                                          */
   1202 /* ------------------------------------------------------------------------ */
   1203 static INLINE void
   1204 ipf_pr_icmp(fr_info_t *fin)
   1205 {
   1206 	ipf_main_softc_t *softc = fin->fin_main_soft;
   1207 	int minicmpsz = sizeof(struct icmp);
   1208 	icmphdr_t *icmp;
   1209 	ip_t *oip;
   1210 
   1211 	ipf_pr_short(fin, ICMPERR_ICMPHLEN);
   1212 
   1213 	if (fin->fin_off != 0) {
   1214 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_frag);
   1215 		return;
   1216 	}
   1217 
   1218 	if (ipf_pr_pullup(fin, ICMPERR_ICMPHLEN) == -1) {
   1219 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_pullup);
   1220 		return;
   1221 	}
   1222 
   1223 	icmp = fin->fin_dp;
   1224 
   1225 	fin->fin_data[0] = *(u_short *)icmp;
   1226 	fin->fin_data[1] = icmp->icmp_id;
   1227 
   1228 	switch (icmp->icmp_type)
   1229 	{
   1230 	case ICMP_ECHOREPLY :
   1231 	case ICMP_ECHO :
   1232 	/* Router discovery messaes - RFC 1256 */
   1233 	case ICMP_ROUTERADVERT :
   1234 	case ICMP_ROUTERSOLICIT :
   1235 		fin->fin_flx |= FI_ICMPQUERY;
   1236 		minicmpsz = ICMP_MINLEN;
   1237 		break;
   1238 	/*
   1239 	 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
   1240 	 * 3 * timestamp(3 * 4)
   1241 	 */
   1242 	case ICMP_TSTAMP :
   1243 	case ICMP_TSTAMPREPLY :
   1244 		fin->fin_flx |= FI_ICMPQUERY;
   1245 		minicmpsz = 20;
   1246 		break;
   1247 	/*
   1248 	 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
   1249 	 * mask(4)
   1250 	 */
   1251 	case ICMP_IREQ :
   1252 	case ICMP_IREQREPLY :
   1253 	case ICMP_MASKREQ :
   1254 	case ICMP_MASKREPLY :
   1255 		fin->fin_flx |= FI_ICMPQUERY;
   1256 		minicmpsz = 12;
   1257 		break;
   1258 	/*
   1259 	 * type(1) + code(1) + cksum(2) + id(2) seq(2) + ip(20+)
   1260 	 */
   1261 	case ICMP_UNREACH :
   1262 #ifdef icmp_nextmtu
   1263 		if (icmp->icmp_code == ICMP_UNREACH_NEEDFRAG) {
   1264 			if (icmp->icmp_nextmtu < softc->ipf_icmpminfragmtu) {
   1265 				fin->fin_flx |= FI_BAD;
   1266 				DT3(ipf_fi_bad_icmp_nextmtu, fr_info_t *, fin, u_int, icmp->icmp_nextmtu, u_int, softc->ipf_icmpminfragmtu);
   1267 			}
   1268 		}
   1269 #endif
   1270 		/* FALLTHROUGH */
   1271 	case ICMP_SOURCEQUENCH :
   1272 	case ICMP_REDIRECT :
   1273 	case ICMP_TIMXCEED :
   1274 	case ICMP_PARAMPROB :
   1275 		fin->fin_flx |= FI_ICMPERR;
   1276 		if (ipf_coalesce(fin) != 1) {
   1277 			LBUMPD(ipf_stats[fin->fin_out], fr_icmp_coalesce);
   1278 			return;
   1279 		}
   1280 
   1281 		/*
   1282 		 * ICMP error packets should not be generated for IP
   1283 		 * packets that are a fragment that isn't the first
   1284 		 * fragment.
   1285 		 */
   1286 		oip = (ip_t *)((char *)fin->fin_dp + ICMPERR_ICMPHLEN);
   1287 		if ((ntohs(oip->ip_off) & IP_OFFMASK) != 0) {
   1288 			fin->fin_flx |= FI_BAD;
   1289 			DT2(ipf_fi_bad_icmp_err, fr_info_t, fin, u_int, (ntohs(oip->ip_off) & IP_OFFMASK));
   1290 		}
   1291 
   1292 		/*
   1293 		 * If the destination of this packet doesn't match the
   1294 		 * source of the original packet then this packet is
   1295 		 * not correct.
   1296 		 */
   1297 		if (oip->ip_src.s_addr != fin->fin_daddr) {
   1298 			fin->fin_flx |= FI_BAD;
   1299 			DT1(ipf_fi_bad_src_ne_dst, fr_info_t *, fin);
   1300 		}
   1301 		break;
   1302 	default :
   1303 		break;
   1304 	}
   1305 
   1306 	ipf_pr_short(fin, minicmpsz);
   1307 
   1308 	ipf_checkv4sum(fin);
   1309 }
   1310 
   1311 
   1312 /* ------------------------------------------------------------------------ */
   1313 /* Function:    ipf_pr_tcpcommon                                            */
   1314 /* Returns:     int    - 0 = header ok, 1 = bad packet, -1 = buffer error   */
   1315 /* Parameters:  fin(I) - pointer to packet information                      */
   1316 /*                                                                          */
   1317 /* TCP header sanity checking.  Look for bad combinations of TCP flags,     */
   1318 /* and make some checks with how they interact with other fields.           */
   1319 /* If compiled with IPFILTER_CKSUM, check to see if the TCP checksum is     */
   1320 /* valid and mark the packet as bad if not.                                 */
   1321 /* ------------------------------------------------------------------------ */
   1322 static INLINE int
   1323 ipf_pr_tcpcommon(fr_info_t *fin)
   1324 {
   1325 	ipf_main_softc_t *softc = fin->fin_main_soft;
   1326 	int flags, tlen;
   1327 	tcphdr_t *tcp;
   1328 
   1329 	fin->fin_flx |= FI_TCPUDP;
   1330 	if (fin->fin_off != 0) {
   1331 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_frag);
   1332 		return 0;
   1333 	}
   1334 
   1335 	if (ipf_pr_pullup(fin, sizeof(*tcp)) == -1) {
   1336 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
   1337 		return -1;
   1338 	}
   1339 
   1340 	tcp = fin->fin_dp;
   1341 	if (fin->fin_dlen > 3) {
   1342 		fin->fin_sport = ntohs(tcp->th_sport);
   1343 		fin->fin_dport = ntohs(tcp->th_dport);
   1344 	}
   1345 
   1346 	if ((fin->fin_flx & FI_SHORT) != 0) {
   1347 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_short);
   1348 		return 1;
   1349 	}
   1350 
   1351 	/*
   1352 	 * Use of the TCP data offset *must* result in a value that is at
   1353 	 * least the same size as the TCP header.
   1354 	 */
   1355 	tlen = TCP_OFF(tcp) << 2;
   1356 	if (tlen < sizeof(tcphdr_t)) {
   1357 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_small);
   1358 		fin->fin_flx |= FI_BAD;
   1359 		DT3(ipf_fi_bad_tlen, fr_info_t, fin, u_int, tlen, u_int, sizeof(tcphdr_t));
   1360 		return 1;
   1361 	}
   1362 
   1363 	flags = tcp->th_flags;
   1364 	fin->fin_tcpf = tcp->th_flags;
   1365 
   1366 	/*
   1367 	 * If the urgent flag is set, then the urgent pointer must
   1368 	 * also be set and vice versa.  Good TCP packets do not have
   1369 	 * just one of these set.
   1370 	 */
   1371 	if ((flags & TH_URG) != 0 && (tcp->th_urp == 0)) {
   1372 		fin->fin_flx |= FI_BAD;
   1373 		DT3(ipf_fi_bad_th_urg, fr_info_t*, fin, u_int, (flags & TH_URG), u_int, tcp->th_urp);
   1374 #if 0
   1375 	} else if ((flags & TH_URG) == 0 && (tcp->th_urp != 0)) {
   1376 		/*
   1377 		 * Ignore this case (#if 0) as it shows up in "real"
   1378 		 * traffic with bogus values in the urgent pointer field.
   1379 		 */
   1380 		fin->fin_flx |= FI_BAD;
   1381 		DT3(ipf_fi_bad_th_urg0, fr_info_t *, fin, u_int, (flags & TH_URG), u_int, tcp->th_urp);
   1382 #endif
   1383 	} else if (((flags & (TH_SYN|TH_FIN)) != 0) &&
   1384 		   ((flags & (TH_RST|TH_ACK)) == TH_RST)) {
   1385 		/* TH_FIN|TH_RST|TH_ACK seems to appear "naturally" */
   1386 		fin->fin_flx |= FI_BAD;
   1387 		DT1(ipf_fi_bad_th_fin_rst_ack, fr_info_t, fin);
   1388 #if 1
   1389 	} else if (((flags & TH_SYN) != 0) &&
   1390 		   ((flags & (TH_URG|TH_PUSH)) != 0)) {
   1391 		/*
   1392 		 * SYN with URG and PUSH set is not for normal TCP but it is
   1393 		 * possible(?) with T/TCP...but who uses T/TCP?
   1394 		 */
   1395 		fin->fin_flx |= FI_BAD;
   1396 		DT1(ipf_fi_bad_th_syn_urg_psh, fr_info_t *, fin);
   1397 #endif
   1398 	} else if (!(flags & TH_ACK)) {
   1399 		/*
   1400 		 * If the ack bit isn't set, then either the SYN or
   1401 		 * RST bit must be set.  If the SYN bit is set, then
   1402 		 * we expect the ACK field to be 0.  If the ACK is
   1403 		 * not set and if URG, PSH or FIN are set, consdier
   1404 		 * that to indicate a bad TCP packet.
   1405 		 */
   1406 		if ((flags == TH_SYN) && (tcp->th_ack != 0)) {
   1407 			/*
   1408 			 * Cisco PIX sets the ACK field to a random value.
   1409 			 * In light of this, do not set FI_BAD until a patch
   1410 			 * is available from Cisco to ensure that
   1411 			 * interoperability between existing systems is
   1412 			 * achieved.
   1413 			 */
   1414 			/*fin->fin_flx |= FI_BAD*/;
   1415 			/*DT1(ipf_fi_bad_th_syn_ack, fr_info_t *, fin);*/
   1416 		} else if (!(flags & (TH_RST|TH_SYN))) {
   1417 			fin->fin_flx |= FI_BAD;
   1418 			DT1(ipf_fi_bad_th_rst_syn, fr_info_t *, fin);
   1419 		} else if ((flags & (TH_URG|TH_PUSH|TH_FIN)) != 0) {
   1420 			fin->fin_flx |= FI_BAD;
   1421 			DT1(ipf_fi_bad_th_urg_push_fin, fr_info_t *, fin);
   1422 		}
   1423 	}
   1424 	if (fin->fin_flx & FI_BAD) {
   1425 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_bad_flags);
   1426 		return 1;
   1427 	}
   1428 
   1429 	/*
   1430 	 * At this point, it's not exactly clear what is to be gained by
   1431 	 * marking up which TCP options are and are not present.  The one we
   1432 	 * are most interested in is the TCP window scale.  This is only in
   1433 	 * a SYN packet [RFC1323] so we don't need this here...?
   1434 	 * Now if we were to analyse the header for passive fingerprinting,
   1435 	 * then that might add some weight to adding this...
   1436 	 */
   1437 	if (tlen == sizeof(tcphdr_t)) {
   1438 		return 0;
   1439 	}
   1440 
   1441 	if (ipf_pr_pullup(fin, tlen) == -1) {
   1442 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
   1443 		return -1;
   1444 	}
   1445 
   1446 #if 0
   1447 	tcp = fin->fin_dp;
   1448 	ip = fin->fin_ip;
   1449 	s = (u_char *)(tcp + 1);
   1450 	off = IP_HL(ip) << 2;
   1451 # ifdef _KERNEL
   1452 	if (fin->fin_mp != NULL) {
   1453 		mb_t *m = *fin->fin_mp;
   1454 
   1455 		if (off + tlen > M_LEN(m))
   1456 			return;
   1457 	}
   1458 # endif
   1459 	for (tlen -= (int)sizeof(*tcp); tlen > 0; ) {
   1460 		opt = *s;
   1461 		if (opt == '\0')
   1462 			break;
   1463 		else if (opt == TCPOPT_NOP)
   1464 			ol = 1;
   1465 		else {
   1466 			if (tlen < 2)
   1467 				break;
   1468 			ol = (int)*(s + 1);
   1469 			if (ol < 2 || ol > tlen)
   1470 				break;
   1471 		}
   1472 
   1473 		for (i = 9, mv = 4; mv >= 0; ) {
   1474 			op = ipopts + i;
   1475 			if (opt == (u_char)op->ol_val) {
   1476 				optmsk |= op->ol_bit;
   1477 				break;
   1478 			}
   1479 		}
   1480 		tlen -= ol;
   1481 		s += ol;
   1482 	}
   1483 #endif /* 0 */
   1484 
   1485 	return 0;
   1486 }
   1487 
   1488 
   1489 
   1490 /* ------------------------------------------------------------------------ */
   1491 /* Function:    ipf_pr_udpcommon                                            */
   1492 /* Returns:     int    - 0 = header ok, 1 = bad packet                      */
   1493 /* Parameters:  fin(I) - pointer to packet information                      */
   1494 /*                                                                          */
   1495 /* Extract the UDP source and destination ports, if present.  If compiled   */
   1496 /* with IPFILTER_CKSUM, check to see if the UDP checksum is valid.          */
   1497 /* ------------------------------------------------------------------------ */
   1498 static INLINE int
   1499 ipf_pr_udpcommon(fr_info_t *fin)
   1500 {
   1501 	udphdr_t *udp;
   1502 
   1503 	fin->fin_flx |= FI_TCPUDP;
   1504 
   1505 	if (!fin->fin_off && (fin->fin_dlen > 3)) {
   1506 		if (ipf_pr_pullup(fin, sizeof(*udp)) == -1) {
   1507 			ipf_main_softc_t *softc = fin->fin_main_soft;
   1508 
   1509 			fin->fin_flx |= FI_SHORT;
   1510 			LBUMPD(ipf_stats[fin->fin_out], fr_udp_pullup);
   1511 			return 1;
   1512 		}
   1513 
   1514 		udp = fin->fin_dp;
   1515 
   1516 		fin->fin_sport = ntohs(udp->uh_sport);
   1517 		fin->fin_dport = ntohs(udp->uh_dport);
   1518 	}
   1519 
   1520 	return 0;
   1521 }
   1522 
   1523 
   1524 /* ------------------------------------------------------------------------ */
   1525 /* Function:    ipf_pr_tcp                                                  */
   1526 /* Returns:     void                                                        */
   1527 /* Parameters:  fin(I) - pointer to packet information                      */
   1528 /*                                                                          */
   1529 /* IPv4 Only                                                                */
   1530 /* Analyse the packet for IPv4/TCP properties.                              */
   1531 /* ------------------------------------------------------------------------ */
   1532 static INLINE void
   1533 ipf_pr_tcp(fr_info_t *fin)
   1534 {
   1535 
   1536 	ipf_pr_short(fin, sizeof(tcphdr_t));
   1537 
   1538 	if (ipf_pr_tcpcommon(fin) == 0)
   1539 		ipf_checkv4sum(fin);
   1540 }
   1541 
   1542 
   1543 /* ------------------------------------------------------------------------ */
   1544 /* Function:    ipf_pr_udp                                                  */
   1545 /* Returns:     void                                                        */
   1546 /* Parameters:  fin(I) - pointer to packet information                      */
   1547 /*                                                                          */
   1548 /* IPv4 Only                                                                */
   1549 /* Analyse the packet for IPv4/UDP properties.                              */
   1550 /* ------------------------------------------------------------------------ */
   1551 static INLINE void
   1552 ipf_pr_udp(fr_info_t *fin)
   1553 {
   1554 
   1555 	ipf_pr_short(fin, sizeof(udphdr_t));
   1556 
   1557 	if (ipf_pr_udpcommon(fin) == 0)
   1558 		ipf_checkv4sum(fin);
   1559 }
   1560 
   1561 
   1562 /* ------------------------------------------------------------------------ */
   1563 /* Function:    ipf_pr_esp                                                  */
   1564 /* Returns:     void                                                        */
   1565 /* Parameters:  fin(I) - pointer to packet information                      */
   1566 /*                                                                          */
   1567 /* Analyse the packet for ESP properties.                                   */
   1568 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits)  */
   1569 /* even though the newer ESP packets must also have a sequence number that  */
   1570 /* is 32bits as well, it is not possible(?) to determine the version from a */
   1571 /* simple packet header.                                                    */
   1572 /* ------------------------------------------------------------------------ */
   1573 static INLINE void
   1574 ipf_pr_esp(fr_info_t *fin)
   1575 {
   1576 
   1577 	if (fin->fin_off == 0) {
   1578 		ipf_pr_short(fin, 8);
   1579 		if (ipf_pr_pullup(fin, 8) == -1) {
   1580 			ipf_main_softc_t *softc = fin->fin_main_soft;
   1581 
   1582 			LBUMPD(ipf_stats[fin->fin_out], fr_v4_esp_pullup);
   1583 		}
   1584 	}
   1585 }
   1586 
   1587 
   1588 /* ------------------------------------------------------------------------ */
   1589 /* Function:    ipf_pr_ah                                                   */
   1590 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
   1591 /* Parameters:  fin(I) - pointer to packet information                      */
   1592 /*                                                                          */
   1593 /* Analyse the packet for AH properties.                                    */
   1594 /* The minimum length is taken to be the combination of all fields in the   */
   1595 /* header being present and no authentication data (null algorithm used.)   */
   1596 /* ------------------------------------------------------------------------ */
   1597 static INLINE int
   1598 ipf_pr_ah(fr_info_t *fin)
   1599 {
   1600 	ipf_main_softc_t *softc = fin->fin_main_soft;
   1601 	authhdr_t *ah;
   1602 	int len;
   1603 
   1604 	fin->fin_flx |= FI_AH;
   1605 	ipf_pr_short(fin, sizeof(*ah));
   1606 
   1607 	if (((fin->fin_flx & FI_SHORT) != 0) || (fin->fin_off != 0)) {
   1608 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_ah_bad);
   1609 		return IPPROTO_NONE;
   1610 	}
   1611 
   1612 	if (ipf_pr_pullup(fin, sizeof(*ah)) == -1) {
   1613 		DT(fr_v4_ah_pullup_1);
   1614 		LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
   1615 		return IPPROTO_NONE;
   1616 	}
   1617 
   1618 	ah = (authhdr_t *)fin->fin_dp;
   1619 
   1620 	len = (ah->ah_plen + 2) << 2;
   1621 	ipf_pr_short(fin, len);
   1622 	if (ipf_pr_pullup(fin, len) == -1) {
   1623 		DT(fr_v4_ah_pullup_2);
   1624 		LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
   1625 		return IPPROTO_NONE;
   1626 	}
   1627 
   1628 	/*
   1629 	 * Adjust fin_dp and fin_dlen for skipping over the authentication
   1630 	 * header.
   1631 	 */
   1632 	fin->fin_dp = (char *)fin->fin_dp + len;
   1633 	fin->fin_dlen -= len;
   1634 	return ah->ah_next;
   1635 }
   1636 
   1637 
   1638 /* ------------------------------------------------------------------------ */
   1639 /* Function:    ipf_pr_gre                                                  */
   1640 /* Returns:     void                                                        */
   1641 /* Parameters:  fin(I) - pointer to packet information                      */
   1642 /*                                                                          */
   1643 /* Analyse the packet for GRE properties.                                   */
   1644 /* ------------------------------------------------------------------------ */
   1645 static INLINE void
   1646 ipf_pr_gre(fr_info_t *fin)
   1647 {
   1648 	ipf_main_softc_t *softc = fin->fin_main_soft;
   1649 	grehdr_t *gre;
   1650 
   1651 	ipf_pr_short(fin, sizeof(grehdr_t));
   1652 
   1653 	if (fin->fin_off != 0) {
   1654 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_frag);
   1655 		return;
   1656 	}
   1657 
   1658 	if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
   1659 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_pullup);
   1660 		return;
   1661 	}
   1662 
   1663 	gre = fin->fin_dp;
   1664 	if (GRE_REV(gre->gr_flags) == 1)
   1665 		fin->fin_data[0] = gre->gr_call;
   1666 }
   1667 
   1668 
   1669 /* ------------------------------------------------------------------------ */
   1670 /* Function:    ipf_pr_ipv4hdr                                              */
   1671 /* Returns:     void                                                        */
   1672 /* Parameters:  fin(I) - pointer to packet information                      */
   1673 /*                                                                          */
   1674 /* IPv4 Only                                                                */
   1675 /* Analyze the IPv4 header and set fields in the fr_info_t structure.       */
   1676 /* Check all options present and flag their presence if any exist.          */
   1677 /* ------------------------------------------------------------------------ */
   1678 static INLINE void
   1679 ipf_pr_ipv4hdr(fr_info_t *fin)
   1680 {
   1681 	u_short optmsk = 0, secmsk = 0, auth = 0;
   1682 	int hlen, ol, mv, p, i;
   1683 	const struct optlist *op;
   1684 	u_char *s, opt;
   1685 	u_short off;
   1686 	fr_ip_t *fi;
   1687 	ip_t *ip;
   1688 
   1689 	fi = &fin->fin_fi;
   1690 	hlen = fin->fin_hlen;
   1691 
   1692 	ip = fin->fin_ip;
   1693 	p = ip->ip_p;
   1694 	fi->fi_p = p;
   1695 	fin->fin_crc = p;
   1696 	fi->fi_tos = ip->ip_tos;
   1697 	fin->fin_id = ip->ip_id;
   1698 	off = ntohs(ip->ip_off);
   1699 
   1700 	/* Get both TTL and protocol */
   1701 	fi->fi_p = ip->ip_p;
   1702 	fi->fi_ttl = ip->ip_ttl;
   1703 
   1704 	/* Zero out bits not used in IPv6 address */
   1705 	fi->fi_src.i6[1] = 0;
   1706 	fi->fi_src.i6[2] = 0;
   1707 	fi->fi_src.i6[3] = 0;
   1708 	fi->fi_dst.i6[1] = 0;
   1709 	fi->fi_dst.i6[2] = 0;
   1710 	fi->fi_dst.i6[3] = 0;
   1711 
   1712 	fi->fi_saddr = ip->ip_src.s_addr;
   1713 	fin->fin_crc += fi->fi_saddr;
   1714 	fi->fi_daddr = ip->ip_dst.s_addr;
   1715 	fin->fin_crc += fi->fi_daddr;
   1716 	if (IN_CLASSD(fi->fi_daddr))
   1717 		fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
   1718 
   1719 	/*
   1720 	 * set packet attribute flags based on the offset and
   1721 	 * calculate the byte offset that it represents.
   1722 	 */
   1723 	off &= IP_MF|IP_OFFMASK;
   1724 	if (off != 0) {
   1725 		int morefrag = off & IP_MF;
   1726 
   1727 		fi->fi_flx |= FI_FRAG;
   1728 		off &= IP_OFFMASK;
   1729 		if (off != 0) {
   1730 			fin->fin_flx |= FI_FRAGBODY;
   1731 			off <<= 3;
   1732 			if ((off + fin->fin_dlen > 65535) ||
   1733 			    (fin->fin_dlen == 0) ||
   1734 			    ((morefrag != 0) && ((fin->fin_dlen & 7) != 0))) {
   1735 				/*
   1736 				 * The length of the packet, starting at its
   1737 				 * offset cannot exceed 65535 (0xffff) as the
   1738 				 * length of an IP packet is only 16 bits.
   1739 				 *
   1740 				 * Any fragment that isn't the last fragment
   1741 				 * must have a length greater than 0 and it
   1742 				 * must be an even multiple of 8.
   1743 				 */
   1744 				fi->fi_flx |= FI_BAD;
   1745 				DT1(ipf_fi_bad_fragbody_gt_65535, fr_info_t *, fin);
   1746 			}
   1747 		}
   1748 	}
   1749 	fin->fin_off = off;
   1750 
   1751 	/*
   1752 	 * Call per-protocol setup and checking
   1753 	 */
   1754 	if (p == IPPROTO_AH) {
   1755 		/*
   1756 		 * Treat AH differently because we expect there to be another
   1757 		 * layer 4 header after it.
   1758 		 */
   1759 		p = ipf_pr_ah(fin);
   1760 	}
   1761 
   1762 	switch (p)
   1763 	{
   1764 	case IPPROTO_UDP :
   1765 		ipf_pr_udp(fin);
   1766 		break;
   1767 	case IPPROTO_TCP :
   1768 		ipf_pr_tcp(fin);
   1769 		break;
   1770 	case IPPROTO_ICMP :
   1771 		ipf_pr_icmp(fin);
   1772 		break;
   1773 	case IPPROTO_ESP :
   1774 		ipf_pr_esp(fin);
   1775 		break;
   1776 	case IPPROTO_GRE :
   1777 		ipf_pr_gre(fin);
   1778 		break;
   1779 	}
   1780 
   1781 	ip = fin->fin_ip;
   1782 	if (ip == NULL)
   1783 		return;
   1784 
   1785 	/*
   1786 	 * If it is a standard IP header (no options), set the flag fields
   1787 	 * which relate to options to 0.
   1788 	 */
   1789 	if (hlen == sizeof(*ip)) {
   1790 		fi->fi_optmsk = 0;
   1791 		fi->fi_secmsk = 0;
   1792 		fi->fi_auth = 0;
   1793 		return;
   1794 	}
   1795 
   1796 	/*
   1797 	 * So the IP header has some IP options attached.  Walk the entire
   1798 	 * list of options present with this packet and set flags to indicate
   1799 	 * which ones are here and which ones are not.  For the somewhat out
   1800 	 * of date and obscure security classification options, set a flag to
   1801 	 * represent which classification is present.
   1802 	 */
   1803 	fi->fi_flx |= FI_OPTIONS;
   1804 
   1805 	for (s = (u_char *)(ip + 1), hlen -= (int)sizeof(*ip); hlen > 0; ) {
   1806 		opt = *s;
   1807 		if (opt == '\0')
   1808 			break;
   1809 		else if (opt == IPOPT_NOP)
   1810 			ol = 1;
   1811 		else {
   1812 			if (hlen < 2)
   1813 				break;
   1814 			ol = (int)*(s + 1);
   1815 			if (ol < 2 || ol > hlen)
   1816 				break;
   1817 		}
   1818 		for (i = 9, mv = 4; mv >= 0; ) {
   1819 			op = ipopts + i;
   1820 
   1821 			if ((opt == (u_char)op->ol_val) && (ol > 4)) {
   1822 				u_32_t doi;
   1823 
   1824 				switch (opt)
   1825 				{
   1826 				case IPOPT_SECURITY :
   1827 					if (optmsk & op->ol_bit) {
   1828 						fin->fin_flx |= FI_BAD;
   1829 						DT2(ipf_fi_bad_ipopt_security, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
   1830 					} else {
   1831 						doi = ipf_checkripso(s);
   1832 						secmsk = doi >> 16;
   1833 						auth = doi & 0xffff;
   1834 					}
   1835 					break;
   1836 
   1837 				case IPOPT_CIPSO :
   1838 
   1839 					if (optmsk & op->ol_bit) {
   1840 						fin->fin_flx |= FI_BAD;
   1841 						DT2(ipf_fi_bad_ipopt_cipso, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
   1842 					} else {
   1843 						doi = ipf_checkcipso(fin,
   1844 								     s, ol);
   1845 						secmsk = doi >> 16;
   1846 						auth = doi & 0xffff;
   1847 					}
   1848 					break;
   1849 				}
   1850 				optmsk |= op->ol_bit;
   1851 			}
   1852 
   1853 			if (opt < op->ol_val)
   1854 				i -= mv;
   1855 			else
   1856 				i += mv;
   1857 			mv--;
   1858 		}
   1859 		hlen -= ol;
   1860 		s += ol;
   1861 	}
   1862 
   1863 	/*
   1864 	 *
   1865 	 */
   1866 	if (auth && !(auth & 0x0100))
   1867 		auth &= 0xff00;
   1868 	fi->fi_optmsk = optmsk;
   1869 	fi->fi_secmsk = secmsk;
   1870 	fi->fi_auth = auth;
   1871 }
   1872 
   1873 
   1874 /* ------------------------------------------------------------------------ */
   1875 /* Function:    ipf_checkripso                                              */
   1876 /* Returns:     void                                                        */
   1877 /* Parameters:  s(I)   - pointer to start of RIPSO option                   */
   1878 /*                                                                          */
   1879 /* ------------------------------------------------------------------------ */
   1880 static u_32_t
   1881 ipf_checkripso(u_char *s)
   1882 {
   1883 	const struct optlist *sp;
   1884 	u_short secmsk = 0, auth = 0;
   1885 	u_char sec;
   1886 	int j, m;
   1887 
   1888 	sec = *(s + 2);	/* classification */
   1889 	for (j = 3, m = 2; m >= 0; ) {
   1890 		sp = secopt + j;
   1891 		if (sec == sp->ol_val) {
   1892 			secmsk |= sp->ol_bit;
   1893 			auth = *(s + 3);
   1894 			auth *= 256;
   1895 			auth += *(s + 4);
   1896 			break;
   1897 		}
   1898 		if (sec < sp->ol_val)
   1899 			j -= m;
   1900 		else
   1901 			j += m;
   1902 		m--;
   1903 	}
   1904 
   1905 	return (secmsk << 16) | auth;
   1906 }
   1907 
   1908 
   1909 /* ------------------------------------------------------------------------ */
   1910 /* Function:    ipf_checkcipso                                              */
   1911 /* Returns:     u_32_t  - 0 = failure, else the doi from the header         */
   1912 /* Parameters:  fin(IO) - pointer to packet information                     */
   1913 /*              s(I)    - pointer to start of CIPSO option                  */
   1914 /*              ol(I)   - length of CIPSO option field                      */
   1915 /*                                                                          */
   1916 /* This function returns the domain of integrity (DOI) field from the CIPSO */
   1917 /* header and returns that whilst also storing the highest sensitivity      */
   1918 /* value found in the fr_info_t structure.                                  */
   1919 /*                                                                          */
   1920 /* No attempt is made to extract the category bitmaps as these are defined  */
   1921 /* by the user (rather than the protocol) and can be rather numerous on the */
   1922 /* end nodes.                                                               */
   1923 /* ------------------------------------------------------------------------ */
   1924 static u_32_t
   1925 ipf_checkcipso(fr_info_t *fin, u_char *s, int ol)
   1926 {
   1927 	ipf_main_softc_t *softc = fin->fin_main_soft;
   1928 	fr_ip_t *fi;
   1929 	u_32_t doi;
   1930 	u_char *t, tag, tlen, sensitivity;
   1931 	int len;
   1932 
   1933 	if (ol < 6 || ol > 40) {
   1934 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_bad);
   1935 		fin->fin_flx |= FI_BAD;
   1936 		DT2(ipf_fi_bad_checkcipso_ol, fr_info_t *, fin, u_int, ol);
   1937 		return 0;
   1938 	}
   1939 
   1940 	fi = &fin->fin_fi;
   1941 	fi->fi_sensitivity = 0;
   1942 	/*
   1943 	 * The DOI field MUST be there.
   1944 	 */
   1945 	bcopy(s + 2, &doi, sizeof(doi));
   1946 
   1947 	t = (u_char *)s + 6;
   1948 	for (len = ol - 6; len >= 2; len -= tlen, t+= tlen) {
   1949 		tag = *t;
   1950 		tlen = *(t + 1);
   1951 		if (tlen > len || tlen < 4 || tlen > 34) {
   1952 			LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_tlen);
   1953 			fin->fin_flx |= FI_BAD;
   1954 			DT2(ipf_fi_bad_checkcipso_tlen, fr_info_t *, fin, u_int, tlen);
   1955 			return 0;
   1956 		}
   1957 
   1958 		sensitivity = 0;
   1959 		/*
   1960 		 * Tag numbers 0, 1, 2, 5 are laid out in the CIPSO Internet
   1961 		 * draft (16 July 1992) that has expired.
   1962 		 */
   1963 		if (tag == 0) {
   1964 			fin->fin_flx |= FI_BAD;
   1965 			DT2(ipf_fi_bad_checkcipso_tag, fr_info_t *, fin, u_int, tag);
   1966 			continue;
   1967 		} else if (tag == 1) {
   1968 			if (*(t + 2) != 0) {
   1969 				fin->fin_flx |= FI_BAD;
   1970 				DT2(ipf_fi_bad_checkcipso_tag1_t2, fr_info_t *, fin, u_int, (*t + 2));
   1971 				continue;
   1972 			}
   1973 			sensitivity = *(t + 3);
   1974 			/* Category bitmap for categories 0-239 */
   1975 
   1976 		} else if (tag == 4) {
   1977 			if (*(t + 2) != 0) {
   1978 				fin->fin_flx |= FI_BAD;
   1979 				DT2(ipf_fi_bad_checkcipso_tag4_t2, fr_info_t *, fin, u_int, (*t + 2));
   1980 				continue;
   1981 			}
   1982 			sensitivity = *(t + 3);
   1983 			/* Enumerated categories, 16bits each, upto 15 */
   1984 
   1985 		} else if (tag == 5) {
   1986 			if (*(t + 2) != 0) {
   1987 				fin->fin_flx |= FI_BAD;
   1988 				DT2(ipf_fi_bad_checkcipso_tag5_t2, fr_info_t *, fin, u_int, (*t + 2));
   1989 				continue;
   1990 			}
   1991 			sensitivity = *(t + 3);
   1992 			/* Range of categories (2*16bits), up to 7 pairs */
   1993 
   1994 		} else if (tag > 127) {
   1995 			/* Custom defined DOI */
   1996 			;
   1997 		} else {
   1998 			DT2(ipf_fi_bad_checkcipso_tag127, fr_info_t *, fin, u_int, tag);
   1999 			fin->fin_flx |= FI_BAD;
   2000 			continue;
   2001 		}
   2002 
   2003 		if (sensitivity > fi->fi_sensitivity)
   2004 			fi->fi_sensitivity = sensitivity;
   2005 	}
   2006 
   2007 	return doi;
   2008 }
   2009 
   2010 
   2011 /* ------------------------------------------------------------------------ */
   2012 /* Function:    ipf_makefrip                                                */
   2013 /* Returns:     int     - 0 == packet ok, -1 == packet freed                */
   2014 /* Parameters:  hlen(I) - length of IP packet header                        */
   2015 /*              ip(I)   - pointer to the IP header                          */
   2016 /*              fin(IO) - pointer to packet information                     */
   2017 /*                                                                          */
   2018 /* Compact the IP header into a structure which contains just the info.     */
   2019 /* which is useful for comparing IP headers with and store this information */
   2020 /* in the fr_info_t structure pointer to by fin.  At present, it is assumed */
   2021 /* this function will be called with either an IPv4 or IPv6 packet.         */
   2022 /* ------------------------------------------------------------------------ */
   2023 int
   2024 ipf_makefrip(int hlen, ip_t *ip, fr_info_t *fin)
   2025 {
   2026 	ipf_main_softc_t *softc = fin->fin_main_soft;
   2027 	int v;
   2028 
   2029 	fin->fin_depth = 0;
   2030 	fin->fin_hlen = (u_short)hlen;
   2031 	fin->fin_ip = ip;
   2032 	fin->fin_rule = 0xffffffff;
   2033 	fin->fin_group[0] = -1;
   2034 	fin->fin_group[1] = '\0';
   2035 	fin->fin_dp = (char *)ip + hlen;
   2036 
   2037 	v = fin->fin_v;
   2038 	if (v == 4) {
   2039 		fin->fin_plen = ntohs(ip->ip_len);
   2040 		fin->fin_dlen = fin->fin_plen - hlen;
   2041 		ipf_pr_ipv4hdr(fin);
   2042 #ifdef	USE_INET6
   2043 	} else if (v == 6) {
   2044 		fin->fin_plen = ntohs(((ip6_t *)ip)->ip6_plen);
   2045 		fin->fin_dlen = fin->fin_plen;
   2046 		fin->fin_plen += hlen;
   2047 
   2048 		ipf_pr_ipv6hdr(fin);
   2049 #endif
   2050 	}
   2051 	if (fin->fin_ip == NULL) {
   2052 		LBUMP(ipf_stats[fin->fin_out].fr_ip_freed);
   2053 		return -1;
   2054 	}
   2055 	return 0;
   2056 }
   2057 
   2058 
   2059 /* ------------------------------------------------------------------------ */
   2060 /* Function:    ipf_portcheck                                               */
   2061 /* Returns:     int - 1 == port matched, 0 == port match failed             */
   2062 /* Parameters:  frp(I) - pointer to port check `expression'                 */
   2063 /*              pop(I) - port number to evaluate                            */
   2064 /*                                                                          */
   2065 /* Perform a comparison of a port number against some other(s), using a     */
   2066 /* structure with compare information stored in it.                         */
   2067 /* ------------------------------------------------------------------------ */
   2068 static INLINE int
   2069 ipf_portcheck(frpcmp_t *frp, u_32_t pop)
   2070 {
   2071 	int err = 1;
   2072 	u_32_t po;
   2073 
   2074 	po = frp->frp_port;
   2075 
   2076 	/*
   2077 	 * Do opposite test to that required and continue if that succeeds.
   2078 	 */
   2079 	switch (frp->frp_cmp)
   2080 	{
   2081 	case FR_EQUAL :
   2082 		if (pop != po) /* EQUAL */
   2083 			err = 0;
   2084 		break;
   2085 	case FR_NEQUAL :
   2086 		if (pop == po) /* NOTEQUAL */
   2087 			err = 0;
   2088 		break;
   2089 	case FR_LESST :
   2090 		if (pop >= po) /* LESSTHAN */
   2091 			err = 0;
   2092 		break;
   2093 	case FR_GREATERT :
   2094 		if (pop <= po) /* GREATERTHAN */
   2095 			err = 0;
   2096 		break;
   2097 	case FR_LESSTE :
   2098 		if (pop > po) /* LT or EQ */
   2099 			err = 0;
   2100 		break;
   2101 	case FR_GREATERTE :
   2102 		if (pop < po) /* GT or EQ */
   2103 			err = 0;
   2104 		break;
   2105 	case FR_OUTRANGE :
   2106 		if (pop >= po && pop <= frp->frp_top) /* Out of range */
   2107 			err = 0;
   2108 		break;
   2109 	case FR_INRANGE :
   2110 		if (pop <= po || pop >= frp->frp_top) /* In range */
   2111 			err = 0;
   2112 		break;
   2113 	case FR_INCRANGE :
   2114 		if (pop < po || pop > frp->frp_top) /* Inclusive range */
   2115 			err = 0;
   2116 		break;
   2117 	default :
   2118 		break;
   2119 	}
   2120 	return err;
   2121 }
   2122 
   2123 
   2124 /* ------------------------------------------------------------------------ */
   2125 /* Function:    ipf_tcpudpchk                                               */
   2126 /* Returns:     int - 1 == protocol matched, 0 == check failed              */
   2127 /* Parameters:  fda(I) - pointer to packet information                      */
   2128 /*              ft(I)  - pointer to structure with comparison data          */
   2129 /*                                                                          */
   2130 /* Compares the current pcket (assuming it is TCP/UDP) information with a   */
   2131 /* structure containing information that we want to match against.          */
   2132 /* ------------------------------------------------------------------------ */
   2133 int
   2134 ipf_tcpudpchk(fr_ip_t *fi, frtuc_t *ft)
   2135 {
   2136 	int err = 1;
   2137 
   2138 	/*
   2139 	 * Both ports should *always* be in the first fragment.
   2140 	 * So far, I cannot find any cases where they can not be.
   2141 	 *
   2142 	 * compare destination ports
   2143 	 */
   2144 	if (ft->ftu_dcmp)
   2145 		err = ipf_portcheck(&ft->ftu_dst, fi->fi_ports[1]);
   2146 
   2147 	/*
   2148 	 * compare source ports
   2149 	 */
   2150 	if (err && ft->ftu_scmp)
   2151 		err = ipf_portcheck(&ft->ftu_src, fi->fi_ports[0]);
   2152 
   2153 	/*
   2154 	 * If we don't have all the TCP/UDP header, then how can we
   2155 	 * expect to do any sort of match on it ?  If we were looking for
   2156 	 * TCP flags, then NO match.  If not, then match (which should
   2157 	 * satisfy the "short" class too).
   2158 	 */
   2159 	if (err && (fi->fi_p == IPPROTO_TCP)) {
   2160 		if (fi->fi_flx & FI_SHORT)
   2161 			return !(ft->ftu_tcpf | ft->ftu_tcpfm);
   2162 		/*
   2163 		 * Match the flags ?  If not, abort this match.
   2164 		 */
   2165 		if (ft->ftu_tcpfm &&
   2166 		    ft->ftu_tcpf != (fi->fi_tcpf & ft->ftu_tcpfm)) {
   2167 			FR_DEBUG(("f. %#x & %#x != %#x\n", fi->fi_tcpf,
   2168 				 ft->ftu_tcpfm, ft->ftu_tcpf));
   2169 			err = 0;
   2170 		}
   2171 	}
   2172 	return err;
   2173 }
   2174 
   2175 
   2176 /* ------------------------------------------------------------------------ */
   2177 /* Function:    ipf_check_ipf                                               */
   2178 /* Returns:     int - 0 == match, else no match                             */
   2179 /* Parameters:  fin(I)     - pointer to packet information                  */
   2180 /*              fr(I)      - pointer to filter rule                         */
   2181 /*              portcmp(I) - flag indicating whether to attempt matching on */
   2182 /*                           TCP/UDP port data.                             */
   2183 /*                                                                          */
   2184 /* Check to see if a packet matches an IPFilter rule.  Checks of addresses, */
   2185 /* port numbers, etc, for "standard" IPFilter rules are all orchestrated in */
   2186 /* this function.                                                           */
   2187 /* ------------------------------------------------------------------------ */
   2188 static INLINE int
   2189 ipf_check_ipf(fr_info_t *fin, frentry_t *fr, int portcmp)
   2190 {
   2191 	u_32_t	*ld, *lm, *lip;
   2192 	fripf_t *fri;
   2193 	fr_ip_t *fi;
   2194 	int i;
   2195 
   2196 	fi = &fin->fin_fi;
   2197 	fri = fr->fr_ipf;
   2198 	lip = (u_32_t *)fi;
   2199 	lm = (u_32_t *)&fri->fri_mip;
   2200 	ld = (u_32_t *)&fri->fri_ip;
   2201 
   2202 	/*
   2203 	 * first 32 bits to check coversion:
   2204 	 * IP version, TOS, TTL, protocol
   2205 	 */
   2206 	i = ((*lip & *lm) != *ld);
   2207 	FR_DEBUG(("0. %#08x & %#08x != %#08x\n",
   2208 		   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
   2209 	if (i)
   2210 		return 1;
   2211 
   2212 	/*
   2213 	 * Next 32 bits is a constructed bitmask indicating which IP options
   2214 	 * are present (if any) in this packet.
   2215 	 */
   2216 	lip++, lm++, ld++;
   2217 	i = ((*lip & *lm) != *ld);
   2218 	FR_DEBUG(("1. %#08x & %#08x != %#08x\n",
   2219 		   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
   2220 	if (i != 0)
   2221 		return 1;
   2222 
   2223 	lip++, lm++, ld++;
   2224 	/*
   2225 	 * Unrolled loops (4 each, for 32 bits) for address checks.
   2226 	 */
   2227 	/*
   2228 	 * Check the source address.
   2229 	 */
   2230 	if (fr->fr_satype == FRI_LOOKUP) {
   2231 		i = (*fr->fr_srcfunc)(fin->fin_main_soft, fr->fr_srcptr,
   2232 				      fi->fi_v, lip, fin->fin_plen);
   2233 		if (i == -1)
   2234 			return 1;
   2235 		lip += 3;
   2236 		lm += 3;
   2237 		ld += 3;
   2238 	} else {
   2239 		i = ((*lip & *lm) != *ld);
   2240 		FR_DEBUG(("2a. %#08x & %#08x != %#08x\n",
   2241 			   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
   2242 		if (fi->fi_v == 6) {
   2243 			lip++, lm++, ld++;
   2244 			i |= ((*lip & *lm) != *ld);
   2245 			FR_DEBUG(("2b. %#08x & %#08x != %#08x\n",
   2246 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
   2247 			lip++, lm++, ld++;
   2248 			i |= ((*lip & *lm) != *ld);
   2249 			FR_DEBUG(("2c. %#08x & %#08x != %#08x\n",
   2250 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
   2251 			lip++, lm++, ld++;
   2252 			i |= ((*lip & *lm) != *ld);
   2253 			FR_DEBUG(("2d. %#08x & %#08x != %#08x\n",
   2254 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
   2255 		} else {
   2256 			lip += 3;
   2257 			lm += 3;
   2258 			ld += 3;
   2259 		}
   2260 	}
   2261 	i ^= (fr->fr_flags & FR_NOTSRCIP) >> 6;
   2262 	if (i != 0)
   2263 		return 1;
   2264 
   2265 	/*
   2266 	 * Check the destination address.
   2267 	 */
   2268 	lip++, lm++, ld++;
   2269 	if (fr->fr_datype == FRI_LOOKUP) {
   2270 		i = (*fr->fr_dstfunc)(fin->fin_main_soft, fr->fr_dstptr,
   2271 				      fi->fi_v, lip, fin->fin_plen);
   2272 		if (i == -1)
   2273 			return 1;
   2274 		lip += 3;
   2275 		lm += 3;
   2276 		ld += 3;
   2277 	} else {
   2278 		i = ((*lip & *lm) != *ld);
   2279 		FR_DEBUG(("3a. %#08x & %#08x != %#08x\n",
   2280 			   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
   2281 		if (fi->fi_v == 6) {
   2282 			lip++, lm++, ld++;
   2283 			i |= ((*lip & *lm) != *ld);
   2284 			FR_DEBUG(("3b. %#08x & %#08x != %#08x\n",
   2285 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
   2286 			lip++, lm++, ld++;
   2287 			i |= ((*lip & *lm) != *ld);
   2288 			FR_DEBUG(("3c. %#08x & %#08x != %#08x\n",
   2289 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
   2290 			lip++, lm++, ld++;
   2291 			i |= ((*lip & *lm) != *ld);
   2292 			FR_DEBUG(("3d. %#08x & %#08x != %#08x\n",
   2293 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
   2294 		} else {
   2295 			lip += 3;
   2296 			lm += 3;
   2297 			ld += 3;
   2298 		}
   2299 	}
   2300 	i ^= (fr->fr_flags & FR_NOTDSTIP) >> 7;
   2301 	if (i != 0)
   2302 		return 1;
   2303 	/*
   2304 	 * IP addresses matched.  The next 32bits contains:
   2305 	 * mast of old IP header security & authentication bits.
   2306 	 */
   2307 	lip++, lm++, ld++;
   2308 	i = (*ld - (*lip & *lm));
   2309 	FR_DEBUG(("4. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
   2310 
   2311 	/*
   2312 	 * Next we have 32 bits of packet flags.
   2313 	 */
   2314 	lip++, lm++, ld++;
   2315 	i |= (*ld - (*lip & *lm));
   2316 	FR_DEBUG(("5. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
   2317 
   2318 	if (i == 0) {
   2319 		/*
   2320 		 * If a fragment, then only the first has what we're
   2321 		 * looking for here...
   2322 		 */
   2323 		if (portcmp) {
   2324 			if (!ipf_tcpudpchk(&fin->fin_fi, &fr->fr_tuc))
   2325 				i = 1;
   2326 		} else {
   2327 			if (fr->fr_dcmp || fr->fr_scmp ||
   2328 			    fr->fr_tcpf || fr->fr_tcpfm)
   2329 				i = 1;
   2330 			if (fr->fr_icmpm || fr->fr_icmp) {
   2331 				if (((fi->fi_p != IPPROTO_ICMP) &&
   2332 				     (fi->fi_p != IPPROTO_ICMPV6)) ||
   2333 				    fin->fin_off || (fin->fin_dlen < 2))
   2334 					i = 1;
   2335 				else if ((fin->fin_data[0] & fr->fr_icmpm) !=
   2336 					 fr->fr_icmp) {
   2337 					FR_DEBUG(("i. %#x & %#x != %#x\n",
   2338 						 fin->fin_data[0],
   2339 						 fr->fr_icmpm, fr->fr_icmp));
   2340 					i = 1;
   2341 				}
   2342 			}
   2343 		}
   2344 	}
   2345 	return i;
   2346 }
   2347 
   2348 
   2349 /* ------------------------------------------------------------------------ */
   2350 /* Function:    ipf_scanlist                                                */
   2351 /* Returns:     int - result flags of scanning filter list                  */
   2352 /* Parameters:  fin(I) - pointer to packet information                      */
   2353 /*              pass(I) - default result to return for filtering            */
   2354 /*                                                                          */
   2355 /* Check the input/output list of rules for a match to the current packet.  */
   2356 /* If a match is found, the value of fr_flags from the rule becomes the     */
   2357 /* return value and fin->fin_fr points to the matched rule.                 */
   2358 /*                                                                          */
   2359 /* This function may be called recusively upto 16 times (limit inbuilt.)    */
   2360 /* When unwinding, it should finish up with fin_depth as 0.                 */
   2361 /*                                                                          */
   2362 /* Could be per interface, but this gets real nasty when you don't have,    */
   2363 /* or can't easily change, the kernel source code to .                      */
   2364 /* ------------------------------------------------------------------------ */
   2365 int
   2366 ipf_scanlist(fr_info_t *fin, u_32_t pass)
   2367 {
   2368 	ipf_main_softc_t *softc = fin->fin_main_soft;
   2369 	int rulen, portcmp, off, skip;
   2370 	struct frentry *fr, *fnext;
   2371 	u_32_t passt, passo;
   2372 
   2373 	/*
   2374 	 * Do not allow nesting deeper than 16 levels.
   2375 	 */
   2376 	if (fin->fin_depth >= 16)
   2377 		return pass;
   2378 
   2379 	fr = fin->fin_fr;
   2380 
   2381 	/*
   2382 	 * If there are no rules in this list, return now.
   2383 	 */
   2384 	if (fr == NULL)
   2385 		return pass;
   2386 
   2387 	skip = 0;
   2388 	portcmp = 0;
   2389 	fin->fin_depth++;
   2390 	fin->fin_fr = NULL;
   2391 	off = fin->fin_off;
   2392 
   2393 	if ((fin->fin_flx & FI_TCPUDP) && (fin->fin_dlen > 3) && !off)
   2394 		portcmp = 1;
   2395 
   2396 	for (rulen = 0; fr; fr = fnext, rulen++) {
   2397 		fnext = fr->fr_next;
   2398 		if (skip != 0) {
   2399 			FR_VERBOSE(("SKIP %d (%#x)\n", skip, fr->fr_flags));
   2400 			skip--;
   2401 			continue;
   2402 		}
   2403 
   2404 		/*
   2405 		 * In all checks below, a null (zero) value in the
   2406 		 * filter struture is taken to mean a wildcard.
   2407 		 *
   2408 		 * check that we are working for the right interface
   2409 		 */
   2410 #ifdef	_KERNEL
   2411 		if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
   2412 			continue;
   2413 #else
   2414 		if (opts & (OPT_VERBOSE|OPT_DEBUG))
   2415 			printf("\n");
   2416 		FR_VERBOSE(("%c", FR_ISSKIP(pass) ? 's' :
   2417 				  FR_ISPASS(pass) ? 'p' :
   2418 				  FR_ISACCOUNT(pass) ? 'A' :
   2419 				  FR_ISAUTH(pass) ? 'a' :
   2420 				  (pass & FR_NOMATCH) ? 'n' :'b'));
   2421 		if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
   2422 			continue;
   2423 		FR_VERBOSE((":i"));
   2424 #endif
   2425 
   2426 		switch (fr->fr_type)
   2427 		{
   2428 		case FR_T_IPF :
   2429 		case FR_T_IPF_BUILTIN :
   2430 			if (ipf_check_ipf(fin, fr, portcmp))
   2431 				continue;
   2432 			break;
   2433 #if defined(IPFILTER_BPF)
   2434 		case FR_T_BPFOPC :
   2435 		case FR_T_BPFOPC_BUILTIN :
   2436 		    {
   2437 			u_char *mc;
   2438 			int wlen;
   2439 
   2440 			if (*fin->fin_mp == NULL)
   2441 				continue;
   2442 			if (fin->fin_family != fr->fr_family)
   2443 				continue;
   2444 			mc = (u_char *)fin->fin_m;
   2445 			wlen = fin->fin_dlen + fin->fin_hlen;
   2446 			if (!bpf_filter(fr->fr_data, mc, wlen, 0))
   2447 				continue;
   2448 			break;
   2449 		    }
   2450 #endif
   2451 		case FR_T_CALLFUNC_BUILTIN :
   2452 		    {
   2453 			frentry_t *f;
   2454 
   2455 			f = (*fr->fr_func)(fin, &pass);
   2456 			if (f != NULL)
   2457 				fr = f;
   2458 			else
   2459 				continue;
   2460 			break;
   2461 		    }
   2462 
   2463 		case FR_T_IPFEXPR :
   2464 		case FR_T_IPFEXPR_BUILTIN :
   2465 			if (fin->fin_family != fr->fr_family)
   2466 				continue;
   2467 			if (ipf_fr_matcharray(fin, fr->fr_data) == 0)
   2468 				continue;
   2469 			break;
   2470 
   2471 		default :
   2472 			break;
   2473 		}
   2474 
   2475 		if ((fin->fin_out == 0) && (fr->fr_nattag.ipt_num[0] != 0)) {
   2476 			if (fin->fin_nattag == NULL)
   2477 				continue;
   2478 			if (ipf_matchtag(&fr->fr_nattag, fin->fin_nattag) == 0)
   2479 				continue;
   2480 		}
   2481 		FR_VERBOSE(("=%d/%d.%d *", fr->fr_grhead, fr->fr_group, rulen));
   2482 
   2483 		passt = fr->fr_flags;
   2484 
   2485 		/*
   2486 		 * If the rule is a "call now" rule, then call the function
   2487 		 * in the rule, if it exists and use the results from that.
   2488 		 * If the function pointer is bad, just make like we ignore
   2489 		 * it, except for increasing the hit counter.
   2490 		 */
   2491 		if ((passt & FR_CALLNOW) != 0) {
   2492 			frentry_t *frs;
   2493 
   2494 			ATOMIC_INC64(fr->fr_hits);
   2495 			if ((fr->fr_func == NULL) ||
   2496 			    (fr->fr_func == (ipfunc_t)-1))
   2497 				continue;
   2498 
   2499 			frs = fin->fin_fr;
   2500 			fin->fin_fr = fr;
   2501 			fr = (*fr->fr_func)(fin, &passt);
   2502 			if (fr == NULL) {
   2503 				fin->fin_fr = frs;
   2504 				continue;
   2505 			}
   2506 			passt = fr->fr_flags;
   2507 		}
   2508 		fin->fin_fr = fr;
   2509 
   2510 #ifdef  IPFILTER_LOG
   2511 		/*
   2512 		 * Just log this packet...
   2513 		 */
   2514 		if ((passt & FR_LOGMASK) == FR_LOG) {
   2515 			if (ipf_log_pkt(fin, passt) == -1) {
   2516 				if (passt & FR_LOGORBLOCK) {
   2517 					DT(frb_logfail);
   2518 					passt &= ~FR_CMDMASK;
   2519 					passt |= FR_BLOCK|FR_QUICK;
   2520 					fin->fin_reason = FRB_LOGFAIL;
   2521 				}
   2522 			}
   2523 		}
   2524 #endif /* IPFILTER_LOG */
   2525 
   2526 		MUTEX_ENTER(&fr->fr_lock);
   2527 		fr->fr_bytes += (U_QUAD_T)fin->fin_plen;
   2528 		fr->fr_hits++;
   2529 		MUTEX_EXIT(&fr->fr_lock);
   2530 		fin->fin_rule = rulen;
   2531 
   2532 		passo = pass;
   2533 		if (FR_ISSKIP(passt)) {
   2534 			skip = fr->fr_arg;
   2535 			continue;
   2536 		} else if (((passt & FR_LOGMASK) != FR_LOG) &&
   2537 			   ((passt & FR_LOGMASK) != FR_DECAPSULATE)) {
   2538 			pass = passt;
   2539 		}
   2540 
   2541 		if (passt & (FR_RETICMP|FR_FAKEICMP))
   2542 			fin->fin_icode = fr->fr_icode;
   2543 
   2544 		if (fr->fr_group != -1) {
   2545 			(void) strncpy(fin->fin_group,
   2546 				       FR_NAME(fr, fr_group),
   2547 				       strlen(FR_NAME(fr, fr_group)));
   2548 		} else {
   2549 			fin->fin_group[0] = '\0';
   2550 		}
   2551 
   2552 		FR_DEBUG(("pass %#x/%#x/%x\n", passo, pass, passt));
   2553 
   2554 		if (fr->fr_grphead != NULL) {
   2555 			fin->fin_fr = fr->fr_grphead->fg_start;
   2556 			FR_VERBOSE(("group %s\n", FR_NAME(fr, fr_grhead)));
   2557 
   2558 			if (FR_ISDECAPS(passt))
   2559 				passt = ipf_decaps(fin, pass, fr->fr_icode);
   2560 			else
   2561 				passt = ipf_scanlist(fin, pass);
   2562 
   2563 			if (fin->fin_fr == NULL) {
   2564 				fin->fin_rule = rulen;
   2565 				if (fr->fr_group != -1)
   2566 					(void) strncpy(fin->fin_group,
   2567 						       fr->fr_names +
   2568 						       fr->fr_group,
   2569 						       strlen(fr->fr_names +
   2570 							      fr->fr_group));
   2571 				fin->fin_fr = fr;
   2572 				passt = pass;
   2573 			}
   2574 			pass = passt;
   2575 		}
   2576 
   2577 		if (pass & FR_QUICK) {
   2578 			/*
   2579 			 * Finally, if we've asked to track state for this
   2580 			 * packet, set it up.  Add state for "quick" rules
   2581 			 * here so that if the action fails we can consider
   2582 			 * the rule to "not match" and keep on processing
   2583 			 * filter rules.
   2584 			 */
   2585 			if ((pass & FR_KEEPSTATE) && !FR_ISAUTH(pass) &&
   2586 			    !(fin->fin_flx & FI_STATE)) {
   2587 				int out = fin->fin_out;
   2588 
   2589 				fin->fin_fr = fr;
   2590 				if (ipf_state_add(softc, fin, NULL, 0) == 0) {
   2591 					LBUMPD(ipf_stats[out], fr_ads);
   2592 				} else {
   2593 					LBUMPD(ipf_stats[out], fr_bads);
   2594 					pass = passo;
   2595 					continue;
   2596 				}
   2597 			}
   2598 			break;
   2599 		}
   2600 	}
   2601 	fin->fin_depth--;
   2602 	return pass;
   2603 }
   2604 
   2605 
   2606 /* ------------------------------------------------------------------------ */
   2607 /* Function:    ipf_acctpkt                                                 */
   2608 /* Returns:     frentry_t* - always returns NULL                            */
   2609 /* Parameters:  fin(I) - pointer to packet information                      */
   2610 /*              passp(IO) - pointer to current/new filter decision (unused) */
   2611 /*                                                                          */
   2612 /* Checks a packet against accounting rules, if there are any for the given */
   2613 /* IP protocol version.                                                     */
   2614 /*                                                                          */
   2615 /* N.B.: this function returns NULL to match the prototype used by other    */
   2616 /* functions called from the IPFilter "mainline" in ipf_check().            */
   2617 /* ------------------------------------------------------------------------ */
   2618 frentry_t *
   2619 ipf_acctpkt(fr_info_t *fin, u_32_t *passp)
   2620 {
   2621 	ipf_main_softc_t *softc = fin->fin_main_soft;
   2622 	char group[FR_GROUPLEN];
   2623 	frentry_t *fr, *frsave;
   2624 	u_32_t pass, rulen;
   2625 
   2626 	passp = passp;
   2627 	fr = softc->ipf_acct[fin->fin_out][softc->ipf_active];
   2628 
   2629 	if (fr != NULL) {
   2630 		frsave = fin->fin_fr;
   2631 		bcopy(fin->fin_group, group, FR_GROUPLEN);
   2632 		rulen = fin->fin_rule;
   2633 		fin->fin_fr = fr;
   2634 		pass = ipf_scanlist(fin, FR_NOMATCH);
   2635 		if (FR_ISACCOUNT(pass)) {
   2636 			LBUMPD(ipf_stats[0], fr_acct);
   2637 		}
   2638 		fin->fin_fr = frsave;
   2639 		bcopy(group, fin->fin_group, FR_GROUPLEN);
   2640 		fin->fin_rule = rulen;
   2641 	}
   2642 	return NULL;
   2643 }
   2644 
   2645 
   2646 /* ------------------------------------------------------------------------ */
   2647 /* Function:    ipf_firewall                                                */
   2648 /* Returns:     frentry_t* - returns pointer to matched rule, if no matches */
   2649 /*                           were found, returns NULL.                      */
   2650 /* Parameters:  fin(I) - pointer to packet information                      */
   2651 /*              passp(IO) - pointer to current/new filter decision (unused) */
   2652 /*                                                                          */
   2653 /* Applies an appropriate set of firewall rules to the packet, to see if    */
   2654 /* there are any matches.  The first check is to see if a match can be seen */
   2655 /* in the cache.  If not, then search an appropriate list of rules.  Once a */
   2656 /* matching rule is found, take any appropriate actions as defined by the   */
   2657 /* rule - except logging.                                                   */
   2658 /* ------------------------------------------------------------------------ */
   2659 static frentry_t *
   2660 ipf_firewall(fr_info_t *fin, u_32_t *passp)
   2661 {
   2662 	ipf_main_softc_t *softc = fin->fin_main_soft;
   2663 	frentry_t *fr;
   2664 	u_32_t pass;
   2665 	int out;
   2666 
   2667 	out = fin->fin_out;
   2668 	pass = *passp;
   2669 
   2670 	/*
   2671 	 * This rule cache will only affect packets that are not being
   2672 	 * statefully filtered.
   2673 	 */
   2674 	fin->fin_fr = softc->ipf_rules[out][softc->ipf_active];
   2675 	if (fin->fin_fr != NULL)
   2676 		pass = ipf_scanlist(fin, softc->ipf_pass);
   2677 
   2678 	if ((pass & FR_NOMATCH)) {
   2679 		LBUMPD(ipf_stats[out], fr_nom);
   2680 	}
   2681 	fr = fin->fin_fr;
   2682 
   2683 	/*
   2684 	 * Apply packets per second rate-limiting to a rule as required.
   2685 	 */
   2686 	if ((fr != NULL) && (fr->fr_pps != 0) &&
   2687 	    !ppsratecheck(&fr->fr_lastpkt, &fr->fr_curpps, fr->fr_pps)) {
   2688 		DT2(frb_ppsrate, fr_info_t *, fin, frentry_t *, fr);
   2689 		pass &= ~(FR_CMDMASK|FR_RETICMP|FR_RETRST);
   2690 		pass |= FR_BLOCK;
   2691 		LBUMPD(ipf_stats[out], fr_ppshit);
   2692 		fin->fin_reason = FRB_PPSRATE;
   2693 	}
   2694 
   2695 	/*
   2696 	 * If we fail to add a packet to the authorization queue, then we
   2697 	 * drop the packet later.  However, if it was added then pretend
   2698 	 * we've dropped it already.
   2699 	 */
   2700 	if (FR_ISAUTH(pass)) {
   2701 		if (ipf_auth_new(fin->fin_m, fin) != 0) {
   2702 			DT1(frb_authnew, fr_info_t *, fin);
   2703 			fin->fin_m = *fin->fin_mp = NULL;
   2704 			fin->fin_reason = FRB_AUTHNEW;
   2705 			fin->fin_error = 0;
   2706 		} else {
   2707 			IPFERROR(1);
   2708 			fin->fin_error = ENOSPC;
   2709 		}
   2710 	}
   2711 
   2712 	if ((fr != NULL) && (fr->fr_func != NULL) &&
   2713 	    (fr->fr_func != (ipfunc_t)-1) && !(pass & FR_CALLNOW))
   2714 		(void) (*fr->fr_func)(fin, &pass);
   2715 
   2716 	/*
   2717 	 * If a rule is a pre-auth rule, check again in the list of rules
   2718 	 * loaded for authenticated use.  It does not particulary matter
   2719 	 * if this search fails because a "preauth" result, from a rule,
   2720 	 * is treated as "not a pass", hence the packet is blocked.
   2721 	 */
   2722 	if (FR_ISPREAUTH(pass)) {
   2723 		pass = ipf_auth_pre_scanlist(softc, fin, pass);
   2724 	}
   2725 
   2726 	/*
   2727 	 * If the rule has "keep frag" and the packet is actually a fragment,
   2728 	 * then create a fragment state entry.
   2729 	 */
   2730 	if (pass & FR_KEEPFRAG) {
   2731 		if (fin->fin_flx & FI_FRAG) {
   2732 			if (ipf_frag_new(softc, fin, pass) == -1) {
   2733 				LBUMP(ipf_stats[out].fr_bnfr);
   2734 			} else {
   2735 				LBUMP(ipf_stats[out].fr_nfr);
   2736 			}
   2737 		} else {
   2738 			LBUMP(ipf_stats[out].fr_cfr);
   2739 		}
   2740 	}
   2741 
   2742 	fr = fin->fin_fr;
   2743 	*passp = pass;
   2744 
   2745 	return fr;
   2746 }
   2747 
   2748 
   2749 /* ------------------------------------------------------------------------ */
   2750 /* Function:    ipf_check                                                   */
   2751 /* Returns:     int -  0 == packet allowed through,                         */
   2752 /*              User space:                                                 */
   2753 /*                    -1 == packet blocked                                  */
   2754 /*                     1 == packet not matched                              */
   2755 /*                    -2 == requires authentication                         */
   2756 /*              Kernel:                                                     */
   2757 /*                   > 0 == filter error # for packet                       */
   2758 /* Parameters: ip(I)   - pointer to start of IPv4/6 packet                  */
   2759 /*             hlen(I) - length of header                                   */
   2760 /*             ifp(I)  - pointer to interface this packet is on             */
   2761 /*             out(I)  - 0 == packet going in, 1 == packet going out        */
   2762 /*             mp(IO)  - pointer to caller's buffer pointer that holds this */
   2763 /*                       IP packet.                                         */
   2764 /* Solaris & HP-UX ONLY :                                                   */
   2765 /*             qpi(I)  - pointer to STREAMS queue information for this      */
   2766 /*                       interface & direction.                             */
   2767 /*                                                                          */
   2768 /* ipf_check() is the master function for all IPFilter packet processing.   */
   2769 /* It orchestrates: Network Address Translation (NAT), checking for packet  */
   2770 /* authorisation (or pre-authorisation), presence of related state info.,   */
   2771 /* generating log entries, IP packet accounting, routing of packets as      */
   2772 /* directed by firewall rules and of course whether or not to allow the     */
   2773 /* packet to be further processed by the kernel.                            */
   2774 /*                                                                          */
   2775 /* For packets blocked, the contents of "mp" will be NULL'd and the buffer  */
   2776 /* freed.  Packets passed may be returned with the pointer pointed to by    */
   2777 /* by "mp" changed to a new buffer.                                         */
   2778 /* ------------------------------------------------------------------------ */
   2779 int
   2780 ipf_check(void *ctx, ip_t *ip, int hlen, void *ifp, int out,
   2781 #if defined(_KERNEL) && defined(MENTAT)
   2782     void *qif,
   2783 #endif
   2784     mb_t **mp)
   2785 {
   2786 	/*
   2787 	 * The above really sucks, but short of writing a diff
   2788 	 */
   2789 	ipf_main_softc_t *softc = ctx;
   2790 	fr_info_t frinfo;
   2791 	fr_info_t *fin = &frinfo;
   2792 	u_32_t pass = softc->ipf_pass;
   2793 	frentry_t *fr = NULL;
   2794 	int v = IP_V(ip);
   2795 	mb_t *mc = NULL;
   2796 	mb_t *m;
   2797 	/*
   2798 	 * The first part of ipf_check() deals with making sure that what goes
   2799 	 * into the filtering engine makes some sense.  Information about the
   2800 	 * the packet is distilled, collected into a fr_info_t structure and
   2801 	 * the an attempt to ensure the buffer the packet is in is big enough
   2802 	 * to hold all the required packet headers.
   2803 	 */
   2804 #ifdef	_KERNEL
   2805 # ifdef MENTAT
   2806 	qpktinfo_t *qpi = qif;
   2807 
   2808 #  ifdef __sparc
   2809 	if ((u_int)ip & 0x3)
   2810 		return 2;
   2811 #  endif
   2812 # else
   2813 	SPL_INT(s);
   2814 # endif
   2815 
   2816 	if (softc->ipf_running <= 0) {
   2817 		return 0;
   2818 	}
   2819 
   2820 	bzero((char *)fin, sizeof(*fin));
   2821 
   2822 # ifdef MENTAT
   2823 	if (qpi->qpi_flags & QF_BROADCAST)
   2824 		fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
   2825 	if (qpi->qpi_flags & QF_MULTICAST)
   2826 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
   2827 	m = qpi->qpi_m;
   2828 	fin->fin_qfm = m;
   2829 	fin->fin_qpi = qpi;
   2830 # else /* MENTAT */
   2831 
   2832 	m = *mp;
   2833 
   2834 #  if defined(M_MCAST)
   2835 	if ((m->m_flags & M_MCAST) != 0)
   2836 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
   2837 #  endif
   2838 #  if defined(M_MLOOP)
   2839 	if ((m->m_flags & M_MLOOP) != 0)
   2840 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
   2841 #  endif
   2842 #  if defined(M_BCAST)
   2843 	if ((m->m_flags & M_BCAST) != 0)
   2844 		fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
   2845 #  endif
   2846 #  ifdef M_CANFASTFWD
   2847 	/*
   2848 	 * XXX For now, IP Filter and fast-forwarding of cached flows
   2849 	 * XXX are mutually exclusive.  Eventually, IP Filter should
   2850 	 * XXX get a "can-fast-forward" filter rule.
   2851 	 */
   2852 	m->m_flags &= ~M_CANFASTFWD;
   2853 #  endif /* M_CANFASTFWD */
   2854 #  if defined(CSUM_DELAY_DATA) && (!defined(__FreeBSD_version) || \
   2855 				   (__FreeBSD_version < 501108))
   2856 	/*
   2857 	 * disable delayed checksums.
   2858 	 */
   2859 	if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
   2860 		in_undefer_cksum_tcpudp(m);
   2861 		m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
   2862 	}
   2863 #  endif /* CSUM_DELAY_DATA */
   2864 # endif /* MENTAT */
   2865 #else
   2866 	bzero((char *)fin, sizeof(*fin));
   2867 	m = *mp;
   2868 # if defined(M_MCAST)
   2869 	if ((m->m_flags & M_MCAST) != 0)
   2870 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
   2871 # endif
   2872 # if defined(M_MLOOP)
   2873 	if ((m->m_flags & M_MLOOP) != 0)
   2874 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
   2875 # endif
   2876 # if defined(M_BCAST)
   2877 	if ((m->m_flags & M_BCAST) != 0)
   2878 		fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
   2879 # endif
   2880 #endif /* _KERNEL */
   2881 
   2882 	fin->fin_v = v;
   2883 	fin->fin_m = m;
   2884 	fin->fin_ip = ip;
   2885 	fin->fin_mp = mp;
   2886 	fin->fin_out = out;
   2887 	fin->fin_ifp = ifp;
   2888 	fin->fin_error = ENETUNREACH;
   2889 	fin->fin_hlen = (u_short)hlen;
   2890 	fin->fin_dp = (char *)ip + hlen;
   2891 	fin->fin_main_soft = softc;
   2892 
   2893 	fin->fin_ipoff = (char *)ip - MTOD(m, char *);
   2894 
   2895 	SPL_NET(s);
   2896 
   2897 #ifdef	USE_INET6
   2898 	if (v == 6) {
   2899 		LBUMP(ipf_stats[out].fr_ipv6);
   2900 		/*
   2901 		 * Jumbo grams are quite likely too big for internal buffer
   2902 		 * structures to handle comfortably, for now, so just drop
   2903 		 * them.
   2904 		 */
   2905 		if (((ip6_t *)ip)->ip6_plen == 0) {
   2906 			DT1(frb_jumbo, ip6_t *, (ip6_t *)ip);
   2907 			pass = FR_BLOCK|FR_NOMATCH;
   2908 			fin->fin_reason = FRB_JUMBO;
   2909 			goto finished;
   2910 		}
   2911 		fin->fin_family = AF_INET6;
   2912 	} else
   2913 #endif
   2914 	{
   2915 		fin->fin_family = AF_INET;
   2916 	}
   2917 
   2918 	if (ipf_makefrip(hlen, ip, fin) == -1) {
   2919 		DT1(frb_makefrip, fr_info_t *, fin);
   2920 		pass = FR_BLOCK|FR_NOMATCH;
   2921 		fin->fin_reason = FRB_MAKEFRIP;
   2922 		goto finished;
   2923 	}
   2924 
   2925 	/*
   2926 	 * For at least IPv6 packets, if a m_pullup() fails then this pointer
   2927 	 * becomes NULL and so we have no packet to free.
   2928 	 */
   2929 	if (*fin->fin_mp == NULL)
   2930 		goto finished;
   2931 
   2932 	if (!out) {
   2933 		if (v == 4) {
   2934 			if (softc->ipf_chksrc && !ipf_verifysrc(fin)) {
   2935 				LBUMPD(ipf_stats[0], fr_v4_badsrc);
   2936 				fin->fin_flx |= FI_BADSRC;
   2937 			}
   2938 			if (fin->fin_ip->ip_ttl < softc->ipf_minttl) {
   2939 				LBUMPD(ipf_stats[0], fr_v4_badttl);
   2940 				fin->fin_flx |= FI_LOWTTL;
   2941 			}
   2942 		}
   2943 #ifdef USE_INET6
   2944 		else  if (v == 6) {
   2945 			if (((ip6_t *)ip)->ip6_hlim < softc->ipf_minttl) {
   2946 				LBUMPD(ipf_stats[0], fr_v6_badttl);
   2947 				fin->fin_flx |= FI_LOWTTL;
   2948 			}
   2949 		}
   2950 #endif
   2951 	}
   2952 
   2953 	if (fin->fin_flx & FI_SHORT) {
   2954 		LBUMPD(ipf_stats[out], fr_short);
   2955 	}
   2956 
   2957 	READ_ENTER(&softc->ipf_mutex);
   2958 
   2959 	if (!out) {
   2960 		switch (fin->fin_v)
   2961 		{
   2962 		case 4 :
   2963 			if (ipf_nat_checkin(fin, &pass) == -1) {
   2964 				goto filterdone;
   2965 			}
   2966 			break;
   2967 #ifdef USE_INET6
   2968 		case 6 :
   2969 			if (ipf_nat6_checkin(fin, &pass) == -1) {
   2970 				goto filterdone;
   2971 			}
   2972 			break;
   2973 #endif
   2974 		default :
   2975 			break;
   2976 		}
   2977 	}
   2978 	/*
   2979 	 * Check auth now.
   2980 	 * If a packet is found in the auth table, then skip checking
   2981 	 * the access lists for permission but we do need to consider
   2982 	 * the result as if it were from the ACL's.  In addition, being
   2983 	 * found in the auth table means it has been seen before, so do
   2984 	 * not pass it through accounting (again), lest it be counted twice.
   2985 	 */
   2986 	fr = ipf_auth_check(fin, &pass);
   2987 	if (!out && (fr == NULL))
   2988 		(void) ipf_acctpkt(fin, NULL);
   2989 
   2990 	if (fr == NULL) {
   2991 		if ((fin->fin_flx & FI_FRAG) != 0)
   2992 			fr = ipf_frag_known(fin, &pass);
   2993 
   2994 		if (fr == NULL)
   2995 			fr = ipf_state_check(fin, &pass);
   2996 	}
   2997 
   2998 	if ((pass & FR_NOMATCH) || (fr == NULL))
   2999 		fr = ipf_firewall(fin, &pass);
   3000 
   3001 	/*
   3002 	 * If we've asked to track state for this packet, set it up.
   3003 	 * Here rather than ipf_firewall because ipf_checkauth may decide
   3004 	 * to return a packet for "keep state"
   3005 	 */
   3006 	if ((pass & FR_KEEPSTATE) && (fin->fin_m != NULL) &&
   3007 	    !(fin->fin_flx & FI_STATE)) {
   3008 		if (ipf_state_add(softc, fin, NULL, 0) == 0) {
   3009 			LBUMP(ipf_stats[out].fr_ads);
   3010 		} else {
   3011 			LBUMP(ipf_stats[out].fr_bads);
   3012 			if (FR_ISPASS(pass)) {
   3013 				DT(frb_stateadd);
   3014 				pass &= ~FR_CMDMASK;
   3015 				pass |= FR_BLOCK;
   3016 				fin->fin_reason = FRB_STATEADD;
   3017 			}
   3018 		}
   3019 	}
   3020 
   3021 	fin->fin_fr = fr;
   3022 	if ((fr != NULL) && !(fin->fin_flx & FI_STATE)) {
   3023 		fin->fin_dif = &fr->fr_dif;
   3024 		fin->fin_tif = &fr->fr_tifs[fin->fin_rev];
   3025 	}
   3026 
   3027 	/*
   3028 	 * Only count/translate packets which will be passed on, out the
   3029 	 * interface.
   3030 	 */
   3031 	if (out && FR_ISPASS(pass)) {
   3032 		(void) ipf_acctpkt(fin, NULL);
   3033 
   3034 		switch (fin->fin_v)
   3035 		{
   3036 		case 4 :
   3037 			if (ipf_nat_checkout(fin, &pass) == -1) {
   3038 				;
   3039 			} else if ((softc->ipf_update_ipid != 0) && (v == 4)) {
   3040 				if (ipf_updateipid(fin) == -1) {
   3041 					DT(frb_updateipid);
   3042 					LBUMP(ipf_stats[1].fr_ipud);
   3043 					pass &= ~FR_CMDMASK;
   3044 					pass |= FR_BLOCK;
   3045 					fin->fin_reason = FRB_UPDATEIPID;
   3046 				} else {
   3047 					LBUMP(ipf_stats[0].fr_ipud);
   3048 				}
   3049 			}
   3050 			break;
   3051 #ifdef USE_INET6
   3052 		case 6 :
   3053 			(void) ipf_nat6_checkout(fin, &pass);
   3054 			break;
   3055 #endif
   3056 		default :
   3057 			break;
   3058 		}
   3059 	}
   3060 
   3061 filterdone:
   3062 #ifdef	IPFILTER_LOG
   3063 	if ((softc->ipf_flags & FF_LOGGING) || (pass & FR_LOGMASK)) {
   3064 		(void) ipf_dolog(fin, &pass);
   3065 	}
   3066 #endif
   3067 
   3068 	/*
   3069 	 * The FI_STATE flag is cleared here so that calling ipf_state_check
   3070 	 * will work when called from inside of fr_fastroute.  Although
   3071 	 * there is a similar flag, FI_NATED, for NAT, it does have the same
   3072 	 * impact on code execution.
   3073 	 */
   3074 	fin->fin_flx &= ~FI_STATE;
   3075 
   3076 #if defined(FASTROUTE_RECURSION)
   3077 	/*
   3078 	 * Up the reference on fr_lock and exit ipf_mutex. The generation of
   3079 	 * a packet below can sometimes cause a recursive call into IPFilter.
   3080 	 * On those platforms where that does happen, we need to hang onto
   3081 	 * the filter rule just in case someone decides to remove or flush it
   3082 	 * in the meantime.
   3083 	 */
   3084 	if (fr != NULL) {
   3085 		MUTEX_ENTER(&fr->fr_lock);
   3086 		fr->fr_ref++;
   3087 		MUTEX_EXIT(&fr->fr_lock);
   3088 	}
   3089 
   3090 	RWLOCK_EXIT(&softc->ipf_mutex);
   3091 #endif
   3092 
   3093 	if ((pass & FR_RETMASK) != 0) {
   3094 		/*
   3095 		 * Should we return an ICMP packet to indicate error
   3096 		 * status passing through the packet filter ?
   3097 		 * WARNING: ICMP error packets AND TCP RST packets should
   3098 		 * ONLY be sent in repsonse to incoming packets.  Sending
   3099 		 * them in response to outbound packets can result in a
   3100 		 * panic on some operating systems.
   3101 		 */
   3102 		if (!out) {
   3103 			if (pass & FR_RETICMP) {
   3104 				int dst;
   3105 
   3106 				if ((pass & FR_RETMASK) == FR_FAKEICMP)
   3107 					dst = 1;
   3108 				else
   3109 					dst = 0;
   3110 				(void) ipf_send_icmp_err(ICMP_UNREACH, fin,
   3111 							 dst);
   3112 				LBUMP(ipf_stats[0].fr_ret);
   3113 			} else if (((pass & FR_RETMASK) == FR_RETRST) &&
   3114 				   !(fin->fin_flx & FI_SHORT)) {
   3115 				if (((fin->fin_flx & FI_OOW) != 0) ||
   3116 				    (ipf_send_reset(fin) == 0)) {
   3117 					LBUMP(ipf_stats[1].fr_ret);
   3118 				}
   3119 			}
   3120 
   3121 			/*
   3122 			 * When using return-* with auth rules, the auth code
   3123 			 * takes over disposing of this packet.
   3124 			 */
   3125 			if (FR_ISAUTH(pass) && (fin->fin_m != NULL)) {
   3126 				DT1(frb_authcapture, fr_info_t *, fin);
   3127 				fin->fin_m = *fin->fin_mp = NULL;
   3128 				fin->fin_reason = FRB_AUTHCAPTURE;
   3129 				m = NULL;
   3130 			}
   3131 		} else {
   3132 			if (pass & FR_RETRST) {
   3133 				fin->fin_error = ECONNRESET;
   3134 			}
   3135 		}
   3136 	}
   3137 
   3138 	/*
   3139 	 * After the above so that ICMP unreachables and TCP RSTs get
   3140 	 * created properly.
   3141 	 */
   3142 	if (FR_ISBLOCK(pass) && (fin->fin_flx & FI_NEWNAT))
   3143 		ipf_nat_uncreate(fin);
   3144 
   3145 	/*
   3146 	 * If we didn't drop off the bottom of the list of rules (and thus
   3147 	 * the 'current' rule fr is not NULL), then we may have some extra
   3148 	 * instructions about what to do with a packet.
   3149 	 * Once we're finished return to our caller, freeing the packet if
   3150 	 * we are dropping it.
   3151 	 */
   3152 	if (fr != NULL) {
   3153 		frdest_t *fdp;
   3154 
   3155 		/*
   3156 		 * Generate a duplicated packet first because ipf_fastroute
   3157 		 * can lead to fin_m being free'd... not good.
   3158 		 */
   3159 		fdp = fin->fin_dif;
   3160 		if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
   3161 		    (fdp->fd_ptr != (void *)-1) && (fin->fin_m != NULL)) {
   3162 			mc = M_COPY(fin->fin_m);
   3163 			if (mc != NULL)
   3164 				ipf_fastroute(mc, &mc, fin, fdp);
   3165 		}
   3166 
   3167 		fdp = fin->fin_tif;
   3168 		if (!out && (pass & FR_FASTROUTE)) {
   3169 			/*
   3170 			 * For fastroute rule, no destination interface defined
   3171 			 * so pass NULL as the frdest_t parameter
   3172 			 */
   3173 			(void) ipf_fastroute(fin->fin_m, mp, fin, NULL);
   3174 			m = *mp = NULL;
   3175 		} else if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
   3176 			   (fdp->fd_ptr != (struct ifnet *)-1)) {
   3177 			/* this is for to rules: */
   3178 			ipf_fastroute(fin->fin_m, mp, fin, fdp);
   3179 			m = *mp = NULL;
   3180 		}
   3181 
   3182 #if defined(FASTROUTE_RECURSION)
   3183 		(void) ipf_derefrule(softc, &fr);
   3184 #endif
   3185 	}
   3186 #if !defined(FASTROUTE_RECURSION)
   3187 	RWLOCK_EXIT(&softc->ipf_mutex);
   3188 #endif
   3189 
   3190 finished:
   3191 	if (!FR_ISPASS(pass)) {
   3192 		LBUMP(ipf_stats[out].fr_block);
   3193 		if (*mp != NULL) {
   3194 #ifdef _KERNEL
   3195 			FREE_MB_T(*mp);
   3196 #endif
   3197 			m = *mp = NULL;
   3198 		}
   3199 	} else {
   3200 		LBUMP(ipf_stats[out].fr_pass);
   3201 #if defined(_KERNEL) && defined(__sgi)
   3202 		if ((fin->fin_hbuf != NULL) &&
   3203 		    (mtod(fin->fin_m, struct ip *) != fin->fin_ip)) {
   3204 			COPYBACK(fin->fin_m, 0, fin->fin_plen, fin->fin_hbuf);
   3205 		}
   3206 #endif
   3207 	}
   3208 
   3209 	SPL_X(s);
   3210 
   3211 #ifdef _KERNEL
   3212 	if (FR_ISPASS(pass))
   3213 		return 0;
   3214 	LBUMP(ipf_stats[out].fr_blocked[fin->fin_reason]);
   3215 	return fin->fin_error;
   3216 #else /* _KERNEL */
   3217 	if (*mp != NULL)
   3218 		(*mp)->mb_ifp = fin->fin_ifp;
   3219 	blockreason = fin->fin_reason;
   3220 	FR_VERBOSE(("fin_flx %#x pass %#x ", fin->fin_flx, pass));
   3221 	/*if ((pass & FR_CMDMASK) == (softc->ipf_pass & FR_CMDMASK))*/
   3222 		if ((pass & FR_NOMATCH) != 0)
   3223 			return 1;
   3224 
   3225 	if ((pass & FR_RETMASK) != 0)
   3226 		switch (pass & FR_RETMASK)
   3227 		{
   3228 		case FR_RETRST :
   3229 			return 3;
   3230 		case FR_RETICMP :
   3231 			return 4;
   3232 		case FR_FAKEICMP :
   3233 			return 5;
   3234 		}
   3235 
   3236 	switch (pass & FR_CMDMASK)
   3237 	{
   3238 	case FR_PASS :
   3239 		return 0;
   3240 	case FR_BLOCK :
   3241 		return -1;
   3242 	case FR_AUTH :
   3243 		return -2;
   3244 	case FR_ACCOUNT :
   3245 		return -3;
   3246 	case FR_PREAUTH :
   3247 		return -4;
   3248 	}
   3249 	return 2;
   3250 #endif /* _KERNEL */
   3251 }
   3252 
   3253 
   3254 #ifdef	IPFILTER_LOG
   3255 /* ------------------------------------------------------------------------ */
   3256 /* Function:    ipf_dolog                                                   */
   3257 /* Returns:     frentry_t* - returns contents of fin_fr (no change made)    */
   3258 /* Parameters:  fin(I) - pointer to packet information                      */
   3259 /*              passp(IO) - pointer to current/new filter decision (unused) */
   3260 /*                                                                          */
   3261 /* Checks flags set to see how a packet should be logged, if it is to be    */
   3262 /* logged.  Adjust statistics based on its success or not.                  */
   3263 /* ------------------------------------------------------------------------ */
   3264 frentry_t *
   3265 ipf_dolog(fr_info_t *fin, u_32_t *passp)
   3266 {
   3267 	ipf_main_softc_t *softc = fin->fin_main_soft;
   3268 	u_32_t pass;
   3269 	int out;
   3270 
   3271 	out = fin->fin_out;
   3272 	pass = *passp;
   3273 
   3274 	if ((softc->ipf_flags & FF_LOGNOMATCH) && (pass & FR_NOMATCH)) {
   3275 		pass |= FF_LOGNOMATCH;
   3276 		LBUMPD(ipf_stats[out], fr_npkl);
   3277 		goto logit;
   3278 
   3279 	} else if (((pass & FR_LOGMASK) == FR_LOGP) ||
   3280 	    (FR_ISPASS(pass) && (softc->ipf_flags & FF_LOGPASS))) {
   3281 		if ((pass & FR_LOGMASK) != FR_LOGP)
   3282 			pass |= FF_LOGPASS;
   3283 		LBUMPD(ipf_stats[out], fr_ppkl);
   3284 		goto logit;
   3285 
   3286 	} else if (((pass & FR_LOGMASK) == FR_LOGB) ||
   3287 		   (FR_ISBLOCK(pass) && (softc->ipf_flags & FF_LOGBLOCK))) {
   3288 		if ((pass & FR_LOGMASK) != FR_LOGB)
   3289 			pass |= FF_LOGBLOCK;
   3290 		LBUMPD(ipf_stats[out], fr_bpkl);
   3291 
   3292 logit:
   3293 		if (ipf_log_pkt(fin, pass) == -1) {
   3294 			/*
   3295 			 * If the "or-block" option has been used then
   3296 			 * block the packet if we failed to log it.
   3297 			 */
   3298 			if ((pass & FR_LOGORBLOCK) && FR_ISPASS(pass)) {
   3299 				DT1(frb_logfail2, u_int, pass);
   3300 				pass &= ~FR_CMDMASK;
   3301 				pass |= FR_BLOCK;
   3302 				fin->fin_reason = FRB_LOGFAIL2;
   3303 			}
   3304 		}
   3305 		*passp = pass;
   3306 	}
   3307 
   3308 	return fin->fin_fr;
   3309 }
   3310 #endif /* IPFILTER_LOG */
   3311 
   3312 
   3313 /* ------------------------------------------------------------------------ */
   3314 /* Function:    ipf_cksum                                                   */
   3315 /* Returns:     u_short - IP header checksum                                */
   3316 /* Parameters:  addr(I) - pointer to start of buffer to checksum            */
   3317 /*              len(I)  - length of buffer in bytes                         */
   3318 /*                                                                          */
   3319 /* Calculate the two's complement 16 bit checksum of the buffer passed.     */
   3320 /*                                                                          */
   3321 /* N.B.: addr should be 16bit aligned.                                      */
   3322 /* ------------------------------------------------------------------------ */
   3323 u_short
   3324 ipf_cksum(u_short *addr, int len)
   3325 {
   3326 	u_32_t sum = 0;
   3327 
   3328 	for (sum = 0; len > 1; len -= 2)
   3329 		sum += *addr++;
   3330 
   3331 	/* mop up an odd byte, if necessary */
   3332 	if (len == 1)
   3333 		sum += *(u_char *)addr;
   3334 
   3335 	/*
   3336 	 * add back carry outs from top 16 bits to low 16 bits
   3337 	 */
   3338 	sum = (sum >> 16) + (sum & 0xffff);	/* add hi 16 to low 16 */
   3339 	sum += (sum >> 16);			/* add carry */
   3340 	return (u_short)(~sum);
   3341 }
   3342 
   3343 
   3344 /* ------------------------------------------------------------------------ */
   3345 /* Function:    fr_cksum                                                    */
   3346 /* Returns:     u_short - layer 4 checksum                                  */
   3347 /* Parameters:  fin(I)     - pointer to packet information                  */
   3348 /*              ip(I)      - pointer to IP header                           */
   3349 /*              l4proto(I) - protocol to caclulate checksum for             */
   3350 /*              l4hdr(I)   - pointer to layer 4 header                      */
   3351 /*                                                                          */
   3352 /* Calculates the TCP checksum for the packet held in "m", using the data   */
   3353 /* in the IP header "ip" to seed it.                                        */
   3354 /*                                                                          */
   3355 /* NB: This function assumes we've pullup'd enough for all of the IP header */
   3356 /* and the TCP header.  We also assume that data blocks aren't allocated in */
   3357 /* odd sizes.                                                               */
   3358 /*                                                                          */
   3359 /* Expects ip_len and ip_off to be in network byte order when called.       */
   3360 /* ------------------------------------------------------------------------ */
   3361 u_short
   3362 fr_cksum(fr_info_t *fin, ip_t *ip, int l4proto, void *l4hdr)
   3363 {
   3364 	u_short *sp, slen, sumsave, *csump;
   3365 	u_int sum, sum2;
   3366 	int hlen;
   3367 	int off;
   3368 #ifdef	USE_INET6
   3369 	ip6_t *ip6;
   3370 #endif
   3371 
   3372 	csump = NULL;
   3373 	sumsave = 0;
   3374 	sp = NULL;
   3375 	slen = 0;
   3376 	hlen = 0;
   3377 	sum = 0;
   3378 
   3379 	sum = htons((u_short)l4proto);
   3380 	/*
   3381 	 * Add up IP Header portion
   3382 	 */
   3383 #ifdef	USE_INET6
   3384 	if (IP_V(ip) == 4) {
   3385 #endif
   3386 		hlen = IP_HL(ip) << 2;
   3387 		off = hlen;
   3388 		sp = (u_short *)&ip->ip_src;
   3389 		sum += *sp++;	/* ip_src */
   3390 		sum += *sp++;
   3391 		sum += *sp++;	/* ip_dst */
   3392 		sum += *sp++;
   3393 #ifdef	USE_INET6
   3394 	} else if (IP_V(ip) == 6) {
   3395 		ip6 = (ip6_t *)ip;
   3396 		hlen = sizeof(*ip6);
   3397 		off = ((char *)fin->fin_dp - (char *)fin->fin_ip);
   3398 		sp = (u_short *)&ip6->ip6_src;
   3399 		sum += *sp++;	/* ip6_src */
   3400 		sum += *sp++;
   3401 		sum += *sp++;
   3402 		sum += *sp++;
   3403 		sum += *sp++;
   3404 		sum += *sp++;
   3405 		sum += *sp++;
   3406 		sum += *sp++;
   3407 		/* This needs to be routing header aware. */
   3408 		sum += *sp++;	/* ip6_dst */
   3409 		sum += *sp++;
   3410 		sum += *sp++;
   3411 		sum += *sp++;
   3412 		sum += *sp++;
   3413 		sum += *sp++;
   3414 		sum += *sp++;
   3415 		sum += *sp++;
   3416 	} else {
   3417 		return 0xffff;
   3418 	}
   3419 #endif
   3420 	slen = fin->fin_plen - off;
   3421 	sum += htons(slen);
   3422 
   3423 	switch (l4proto)
   3424 	{
   3425 	case IPPROTO_UDP :
   3426 		csump = &((udphdr_t *)l4hdr)->uh_sum;
   3427 		break;
   3428 
   3429 	case IPPROTO_TCP :
   3430 		csump = &((tcphdr_t *)l4hdr)->th_sum;
   3431 		break;
   3432 	case IPPROTO_ICMP :
   3433 		csump = &((icmphdr_t *)l4hdr)->icmp_cksum;
   3434 		sum = 0;	/* Pseudo-checksum is not included */
   3435 		break;
   3436 #ifdef USE_INET6
   3437 	case IPPROTO_ICMPV6 :
   3438 		csump = &((struct icmp6_hdr *)l4hdr)->icmp6_cksum;
   3439 		break;
   3440 #endif
   3441 	default :
   3442 		break;
   3443 	}
   3444 
   3445 	if (csump != NULL) {
   3446 		sumsave = *csump;
   3447 		*csump = 0;
   3448 	}
   3449 
   3450 	sum2 = ipf_pcksum(fin, off, sum);
   3451 	if (csump != NULL)
   3452 		*csump = sumsave;
   3453 	return sum2;
   3454 }
   3455 
   3456 
   3457 /* ------------------------------------------------------------------------ */
   3458 /* Function:    ipf_findgroup                                               */
   3459 /* Returns:     frgroup_t * - NULL = group not found, else pointer to group */
   3460 /* Parameters:  softc(I) - pointer to soft context main structure           */
   3461 /*              group(I) - group name to search for                         */
   3462 /*              unit(I)  - device to which this group belongs               */
   3463 /*              set(I)   - which set of rules (inactive/inactive) this is   */
   3464 /*              fgpp(O)  - pointer to place to store pointer to the pointer */
   3465 /*                         to where to add the next (last) group or where   */
   3466 /*                         to delete group from.                            */
   3467 /*                                                                          */
   3468 /* Search amongst the defined groups for a particular group number.         */
   3469 /* ------------------------------------------------------------------------ */
   3470 frgroup_t *
   3471 ipf_findgroup(ipf_main_softc_t *softc, char *group, minor_t unit, int set,
   3472     frgroup_t ***fgpp)
   3473 {
   3474 	frgroup_t *fg, **fgp;
   3475 
   3476 	/*
   3477 	 * Which list of groups to search in is dependent on which list of
   3478 	 * rules are being operated on.
   3479 	 */
   3480 	fgp = &softc->ipf_groups[unit][set];
   3481 
   3482 	while ((fg = *fgp) != NULL) {
   3483 		if (strncmp(group, fg->fg_name, FR_GROUPLEN) == 0)
   3484 			break;
   3485 		else
   3486 			fgp = &fg->fg_next;
   3487 	}
   3488 	if (fgpp != NULL)
   3489 		*fgpp = fgp;
   3490 	return fg;
   3491 }
   3492 
   3493 
   3494 /* ------------------------------------------------------------------------ */
   3495 /* Function:    ipf_group_add                                               */
   3496 /* Returns:     frgroup_t * - NULL == did not create group,                 */
   3497 /*                            != NULL == pointer to the group               */
   3498 /* Parameters:  softc(I) - pointer to soft context main structure           */
   3499 /*              num(I)   - group number to add                              */
   3500 /*              head(I)  - rule pointer that is using this as the head      */
   3501 /*              flags(I) - rule flags which describe the type of rule it is */
   3502 /*              unit(I)  - device to which this group will belong to        */
   3503 /*              set(I)   - which set of rules (inactive/inactive) this is   */
   3504 /* Write Locks: ipf_mutex                                                   */
   3505 /*                                                                          */
   3506 /* Add a new group head, or if it already exists, increase the reference    */
   3507 /* count to it.                                                             */
   3508 /* ------------------------------------------------------------------------ */
   3509 frgroup_t *
   3510 ipf_group_add(ipf_main_softc_t *softc, char *group, void *head, u_32_t flags,
   3511     minor_t unit, int set)
   3512 {
   3513 	frgroup_t *fg, **fgp;
   3514 	u_32_t gflags;
   3515 
   3516 	if (group == NULL)
   3517 		return NULL;
   3518 
   3519 	if (unit == IPL_LOGIPF && *group == '\0')
   3520 		return NULL;
   3521 
   3522 	fgp = NULL;
   3523 	gflags = flags & FR_INOUT;
   3524 
   3525 	fg = ipf_findgroup(softc, group, unit, set, &fgp);
   3526 	if (fg != NULL) {
   3527 		if (fg->fg_head == NULL && head != NULL)
   3528 			fg->fg_head = head;
   3529 		if (fg->fg_flags == 0)
   3530 			fg->fg_flags = gflags;
   3531 		else if (gflags != fg->fg_flags)
   3532 			return NULL;
   3533 		fg->fg_ref++;
   3534 		return fg;
   3535 	}
   3536 
   3537 	KMALLOC(fg, frgroup_t *);
   3538 	if (fg != NULL) {
   3539 		fg->fg_head = head;
   3540 		fg->fg_start = NULL;
   3541 		fg->fg_next = *fgp;
   3542 		bcopy(group, fg->fg_name, strlen(group) + 1);
   3543 		fg->fg_flags = gflags;
   3544 		fg->fg_ref = 1;
   3545 		fg->fg_set = &softc->ipf_groups[unit][set];
   3546 		*fgp = fg;
   3547 	}
   3548 	return fg;
   3549 }
   3550 
   3551 
   3552 /* ------------------------------------------------------------------------ */
   3553 /* Function:    ipf_group_del                                               */
   3554 /* Returns:     int      - number of rules deleted                          */
   3555 /* Parameters:  softc(I) - pointer to soft context main structure           */
   3556 /*              group(I) - group name to delete                             */
   3557 /*              fr(I)    - filter rule from which group is referenced       */
   3558 /* Write Locks: ipf_mutex                                                   */
   3559 /*                                                                          */
   3560 /* This function is called whenever a reference to a group is to be dropped */
   3561 /* and thus its reference count needs to be lowered and the group free'd if */
   3562 /* the reference count reaches zero. Passing in fr is really for the sole   */
   3563 /* purpose of knowing when the head rule is being deleted.                  */
   3564 /* ------------------------------------------------------------------------ */
   3565 void
   3566 ipf_group_del(ipf_main_softc_t *softc, frgroup_t *group, frentry_t *fr)
   3567 {
   3568 
   3569 	if (group->fg_head == fr)
   3570 		group->fg_head = NULL;
   3571 
   3572 	group->fg_ref--;
   3573 	if ((group->fg_ref == 0) && (group->fg_start == NULL))
   3574 		ipf_group_free(group);
   3575 }
   3576 
   3577 
   3578 /* ------------------------------------------------------------------------ */
   3579 /* Function:    ipf_group_free                                              */
   3580 /* Returns:     Nil                                                         */
   3581 /* Parameters:  group(I) - pointer to filter rule group                     */
   3582 /*                                                                          */
   3583 /* Remove the group from the list of groups and free it.                    */
   3584 /* ------------------------------------------------------------------------ */
   3585 static void
   3586 ipf_group_free(frgroup_t *group)
   3587 {
   3588 	frgroup_t **gp;
   3589 
   3590 	for (gp = group->fg_set; *gp != NULL; gp = &(*gp)->fg_next) {
   3591 		if (*gp == group) {
   3592 			*gp = group->fg_next;
   3593 			break;
   3594 		}
   3595 	}
   3596 	KFREE(group);
   3597 }
   3598 
   3599 
   3600 /* ------------------------------------------------------------------------ */
   3601 /* Function:    ipf_group_flush                                             */
   3602 /* Returns:     int      - number of rules flush from group                 */
   3603 /* Parameters:  softc(I) - pointer to soft context main structure           */
   3604 /* Parameters:  group(I) - pointer to filter rule group                     */
   3605 /*                                                                          */
   3606 /* Remove all of the rules that currently are listed under the given group. */
   3607 /* ------------------------------------------------------------------------ */
   3608 static int
   3609 ipf_group_flush(ipf_main_softc_t *softc, frgroup_t *group)
   3610 {
   3611 	int gone = 0;
   3612 
   3613 	(void) ipf_flushlist(softc, &gone, &group->fg_start);
   3614 
   3615 	return gone;
   3616 }
   3617 
   3618 
   3619 /* ------------------------------------------------------------------------ */
   3620 /* Function:    ipf_getrulen                                                */
   3621 /* Returns:     frentry_t * - NULL == not found, else pointer to rule n     */
   3622 /* Parameters:  softc(I) - pointer to soft context main structure           */
   3623 /* Parameters:  unit(I)  - device for which to count the rule's number      */
   3624 /*              flags(I) - which set of rules to find the rule in           */
   3625 /*              group(I) - group name                                       */
   3626 /*              n(I)     - rule number to find                              */
   3627 /*                                                                          */
   3628 /* Find rule # n in group # g and return a pointer to it.  Return NULl if   */
   3629 /* group # g doesn't exist or there are less than n rules in the group.     */
   3630 /* ------------------------------------------------------------------------ */
   3631 frentry_t *
   3632 ipf_getrulen(ipf_main_softc_t *softc, int unit, char *group, u_32_t n)
   3633 {
   3634 	frentry_t *fr;
   3635 	frgroup_t *fg;
   3636 
   3637 	fg = ipf_findgroup(softc, group, unit, softc->ipf_active, NULL);
   3638 	if (fg == NULL)
   3639 		return NULL;
   3640 	for (fr = fg->fg_start; fr && n; fr = fr->fr_next, n--)
   3641 		;
   3642 	if (n != 0)
   3643 		return NULL;
   3644 	return fr;
   3645 }
   3646 
   3647 
   3648 /* ------------------------------------------------------------------------ */
   3649 /* Function:    ipf_flushlist                                               */
   3650 /* Returns:     int - >= 0 - number of flushed rules                        */
   3651 /* Parameters:  softc(I)   - pointer to soft context main structure         */
   3652 /*              nfreedp(O) - pointer to int where flush count is stored     */
   3653 /*              listp(I)   - pointer to list to flush pointer               */
   3654 /* Write Locks: ipf_mutex                                                   */
   3655 /*                                                                          */
   3656 /* Recursively flush rules from the list, descending groups as they are     */
   3657 /* encountered.  if a rule is the head of a group and it has lost all its   */
   3658 /* group members, then also delete the group reference.  nfreedp is needed  */
   3659 /* to store the accumulating count of rules removed, whereas the returned   */
   3660 /* value is just the number removed from the current list.  The latter is   */
   3661 /* needed to correctly adjust reference counts on rules that define groups. */
   3662 /*                                                                          */
   3663 /* NOTE: Rules not loaded from user space cannot be flushed.                */
   3664 /* ------------------------------------------------------------------------ */
   3665 static int
   3666 ipf_flushlist(ipf_main_softc_t *softc, int *nfreedp, frentry_t **listp)
   3667 {
   3668 	int freed = 0;
   3669 	frentry_t *fp;
   3670 
   3671 	while ((fp = *listp) != NULL) {
   3672 		if ((fp->fr_type & FR_T_BUILTIN) ||
   3673 		    !(fp->fr_flags & FR_COPIED)) {
   3674 			listp = &fp->fr_next;
   3675 			continue;
   3676 		}
   3677 		*listp = fp->fr_next;
   3678 		if (fp->fr_next != NULL)
   3679 			fp->fr_next->fr_pnext = fp->fr_pnext;
   3680 		fp->fr_pnext = NULL;
   3681 
   3682 		if (fp->fr_grphead != NULL) {
   3683 			freed += ipf_group_flush(softc, fp->fr_grphead);
   3684 			fp->fr_names[fp->fr_grhead] = '\0';
   3685 		}
   3686 
   3687 		if (fp->fr_icmpgrp != NULL) {
   3688 			freed += ipf_group_flush(softc, fp->fr_icmpgrp);
   3689 			fp->fr_names[fp->fr_icmphead] = '\0';
   3690 		}
   3691 
   3692 		if (fp->fr_srctrack.ht_max_nodes)
   3693 			ipf_rb_ht_flush(&fp->fr_srctrack);
   3694 
   3695 		fp->fr_next = NULL;
   3696 
   3697 		ASSERT(fp->fr_ref > 0);
   3698 		if (ipf_derefrule(softc, &fp) == 0)
   3699 			freed++;
   3700 	}
   3701 	*nfreedp += freed;
   3702 	return freed;
   3703 }
   3704 
   3705 
   3706 /* ------------------------------------------------------------------------ */
   3707 /* Function:    ipf_flush                                                   */
   3708 /* Returns:     int - >= 0 - number of flushed rules                        */
   3709 /* Parameters:  softc(I) - pointer to soft context main structure           */
   3710 /*              unit(I)  - device for which to flush rules                  */
   3711 /*              flags(I) - which set of rules to flush                      */
   3712 /*                                                                          */
   3713 /* Calls flushlist() for all filter rules (accounting, firewall - both IPv4 */
   3714 /* and IPv6) as defined by the value of flags.                              */
   3715 /* ------------------------------------------------------------------------ */
   3716 int
   3717 ipf_flush(ipf_main_softc_t *softc, minor_t unit, int flags)
   3718 {
   3719 	int flushed = 0, set;
   3720 
   3721 	WRITE_ENTER(&softc->ipf_mutex);
   3722 
   3723 	set = softc->ipf_active;
   3724 	if ((flags & FR_INACTIVE) == FR_INACTIVE)
   3725 		set = 1 - set;
   3726 
   3727 	if (flags & FR_OUTQUE) {
   3728 		ipf_flushlist(softc, &flushed, &softc->ipf_rules[1][set]);
   3729 		ipf_flushlist(softc, &flushed, &softc->ipf_acct[1][set]);
   3730 	}
   3731 	if (flags & FR_INQUE) {
   3732 		ipf_flushlist(softc, &flushed, &softc->ipf_rules[0][set]);
   3733 		ipf_flushlist(softc, &flushed, &softc->ipf_acct[0][set]);
   3734 	}
   3735 
   3736 	flushed += ipf_flush_groups(softc, &softc->ipf_groups[unit][set],
   3737 				    flags & (FR_INQUE|FR_OUTQUE));
   3738 
   3739 	RWLOCK_EXIT(&softc->ipf_mutex);
   3740 
   3741 	if (unit == IPL_LOGIPF) {
   3742 		int tmp;
   3743 
   3744 		tmp = ipf_flush(softc, IPL_LOGCOUNT, flags);
   3745 		if (tmp >= 0)
   3746 			flushed += tmp;
   3747 	}
   3748 	return flushed;
   3749 }
   3750 
   3751 
   3752 /* ------------------------------------------------------------------------ */
   3753 /* Function:    ipf_flush_groups                                            */
   3754 /* Returns:     int - >= 0 - number of flushed rules                        */
   3755 /* Parameters:  softc(I)  - soft context pointerto work with                */
   3756 /*              grhead(I) - pointer to the start of the group list to flush */
   3757 /*              flags(I)  - which set of rules to flush                     */
   3758 /*                                                                          */
   3759 /* Walk through all of the groups under the given group head and remove all */
   3760 /* of those that match the flags passed in. The for loop here is bit more   */
   3761 /* complicated than usual because the removal of a rule with ipf_derefrule  */
   3762 /* may end up removing not only the structure pointed to by "fg" but also   */
   3763 /* what is fg_next and fg_next after that. So if a filter rule is actually  */
   3764 /* removed from the group then it is necessary to start again.              */
   3765 /* ------------------------------------------------------------------------ */
   3766 static int
   3767 ipf_flush_groups( ipf_main_softc_t *softc, frgroup_t **grhead, int flags)
   3768 {
   3769 	frentry_t *fr, **frp;
   3770 	frgroup_t *fg, **fgp;
   3771 	int flushed = 0;
   3772 	int removed = 0;
   3773 
   3774 	for (fgp = grhead; (fg = *fgp) != NULL; ) {
   3775 		while ((fg != NULL) && ((fg->fg_flags & flags) == 0))
   3776 			fg = fg->fg_next;
   3777 		if (fg == NULL)
   3778 			break;
   3779 		removed = 0;
   3780 		frp = &fg->fg_start;
   3781 		while ((removed == 0) && ((fr = *frp) != NULL)) {
   3782 			if ((fr->fr_flags & flags) == 0) {
   3783 				frp = &fr->fr_next;
   3784 			} else {
   3785 				if (fr->fr_next != NULL)
   3786 					fr->fr_next->fr_pnext = fr->fr_pnext;
   3787 				*frp = fr->fr_next;
   3788 				fr->fr_pnext = NULL;
   3789 				fr->fr_next = NULL;
   3790 				(void) ipf_derefrule(softc, &fr);
   3791 				flushed++;
   3792 				removed++;
   3793 			}
   3794 		}
   3795 		if (removed == 0)
   3796 			fgp = &fg->fg_next;
   3797 	}
   3798 	return flushed;
   3799 }
   3800 
   3801 
   3802 /* ------------------------------------------------------------------------ */
   3803 /* Function:    memstr                                                      */
   3804 /* Returns:     char *  - NULL if failed, != NULL pointer to matching bytes */
   3805 /* Parameters:  src(I)  - pointer to byte sequence to match                 */
   3806 /*              dst(I)  - pointer to byte sequence to search                */
   3807 /*              slen(I) - match length                                      */
   3808 /*              dlen(I) - length available to search in                     */
   3809 /*                                                                          */
   3810 /* Search dst for a sequence of bytes matching those at src and extend for  */
   3811 /* slen bytes.                                                              */
   3812 /* ------------------------------------------------------------------------ */
   3813 char *
   3814 memstr(const char *src, char *dst, size_t slen, size_t dlen)
   3815 {
   3816 	char *s = NULL;
   3817 
   3818 	while (dlen >= slen) {
   3819 		if (memcmp(src, dst, slen) == 0) {
   3820 			s = dst;
   3821 			break;
   3822 		}
   3823 		dst++;
   3824 		dlen--;
   3825 	}
   3826 	return s;
   3827 }
   3828 
   3829 
   3830 /* ------------------------------------------------------------------------ */
   3831 /* Function:    ipf_fixskip                                                 */
   3832 /* Returns:     Nil                                                         */
   3833 /* Parameters:  listp(IO)    - pointer to start of list with skip rule      */
   3834 /*              rp(I)        - rule added/removed with skip in it.          */
   3835 /*              addremove(I) - adjustment (-1/+1) to make to skip count,    */
   3836 /*                             depending on whether a rule was just added   */
   3837 /*                             or removed.                                  */
   3838 /*                                                                          */
   3839 /* Adjust all the rules in a list which would have skip'd past the position */
   3840 /* where we are inserting to skip to the right place given the change.      */
   3841 /* ------------------------------------------------------------------------ */
   3842 void
   3843 ipf_fixskip(frentry_t **listp, frentry_t *rp, int addremove)
   3844 {
   3845 	int rules, rn;
   3846 	frentry_t *fp;
   3847 
   3848 	rules = 0;
   3849 	for (fp = *listp; (fp != NULL) && (fp != rp); fp = fp->fr_next)
   3850 		rules++;
   3851 
   3852 	if (!fp)
   3853 		return;
   3854 
   3855 	for (rn = 0, fp = *listp; fp && (fp != rp); fp = fp->fr_next, rn++)
   3856 		if (FR_ISSKIP(fp->fr_flags) && (rn + fp->fr_arg >= rules))
   3857 			fp->fr_arg += addremove;
   3858 }
   3859 
   3860 
   3861 #ifdef	_KERNEL
   3862 /* ------------------------------------------------------------------------ */
   3863 /* Function:    count4bits                                                  */
   3864 /* Returns:     int - >= 0 - number of consecutive bits in input            */
   3865 /* Parameters:  ip(I) - 32bit IP address                                    */
   3866 /*                                                                          */
   3867 /* IPv4 ONLY                                                                */
   3868 /* count consecutive 1's in bit mask.  If the mask generated by counting    */
   3869 /* consecutive 1's is different to that passed, return -1, else return #    */
   3870 /* of bits.                                                                 */
   3871 /* ------------------------------------------------------------------------ */
   3872 int
   3873 count4bits(u_32_t ip)
   3874 {
   3875 	u_32_t	ipn;
   3876 	int	cnt = 0, i, j;
   3877 
   3878 	ip = ipn = ntohl(ip);
   3879 	for (i = 32; i; i--, ipn *= 2)
   3880 		if (ipn & 0x80000000)
   3881 			cnt++;
   3882 		else
   3883 			break;
   3884 	ipn = 0;
   3885 	for (i = 32, j = cnt; i; i--, j--) {
   3886 		ipn *= 2;
   3887 		if (j > 0)
   3888 			ipn++;
   3889 	}
   3890 	if (ipn == ip)
   3891 		return cnt;
   3892 	return -1;
   3893 }
   3894 
   3895 
   3896 /* ------------------------------------------------------------------------ */
   3897 /* Function:    count6bits                                                  */
   3898 /* Returns:     int - >= 0 - number of consecutive bits in input            */
   3899 /* Parameters:  msk(I) - pointer to start of IPv6 bitmask                   */
   3900 /*                                                                          */
   3901 /* IPv6 ONLY                                                                */
   3902 /* count consecutive 1's in bit mask.                                       */
   3903 /* ------------------------------------------------------------------------ */
   3904 # ifdef USE_INET6
   3905 int
   3906 count6bits(u_32_t *msk)
   3907 {
   3908 	int i = 0, k;
   3909 	u_32_t j;
   3910 
   3911 	for (k = 3; k >= 0; k--)
   3912 		if (msk[k] == 0xffffffff)
   3913 			i += 32;
   3914 		else {
   3915 			for (j = msk[k]; j; j <<= 1)
   3916 				if (j & 0x80000000)
   3917 					i++;
   3918 		}
   3919 	return i;
   3920 }
   3921 # endif
   3922 #endif /* _KERNEL */
   3923 
   3924 
   3925 /* ------------------------------------------------------------------------ */
   3926 /* Function:    ipf_synclist                                                */
   3927 /* Returns:     int    - 0 = no failures, else indication of first failure  */
   3928 /* Parameters:  fr(I)  - start of filter list to sync interface names for   */
   3929 /*              ifp(I) - interface pointer for limiting sync lookups        */
   3930 /* Write Locks: ipf_mutex                                                   */
   3931 /*                                                                          */
   3932 /* Walk through a list of filter rules and resolve any interface names into */
   3933 /* pointers.  Where dynamic addresses are used, also update the IP address  */
   3934 /* used in the rule.  The interface pointer is used to limit the lookups to */
   3935 /* a specific set of matching names if it is non-NULL.                      */
   3936 /* Errors can occur when resolving the destination name of to/dup-to fields */
   3937 /* when the name points to a pool and that pool doest not exist. If this    */
   3938 /* does happen then it is necessary to check if there are any lookup refs   */
   3939 /* that need to be dropped before returning with an error.                  */
   3940 /* ------------------------------------------------------------------------ */
   3941 static int
   3942 ipf_synclist(ipf_main_softc_t *softc, frentry_t *fr, void *ifp)
   3943 {
   3944 	frentry_t *frt, *start = fr;
   3945 	frdest_t *fdp;
   3946 	char *name;
   3947 	int error;
   3948 	void *ifa;
   3949 	int v, i;
   3950 
   3951 	error = 0;
   3952 
   3953 	for (; fr; fr = fr->fr_next) {
   3954 		if (fr->fr_family == AF_INET)
   3955 			v = 4;
   3956 		else if (fr->fr_family == AF_INET6)
   3957 			v = 6;
   3958 		else
   3959 			v = 0;
   3960 
   3961 		/*
   3962 		 * Lookup all the interface names that are part of the rule.
   3963 		 */
   3964 		for (i = 0; i < 4; i++) {
   3965 			if ((ifp != NULL) && (fr->fr_ifas[i] != ifp))
   3966 				continue;
   3967 			if (fr->fr_ifnames[i] == -1)
   3968 				continue;
   3969 			name = FR_NAME(fr, fr_ifnames[i]);
   3970 			fr->fr_ifas[i] = ipf_resolvenic(softc, name, v);
   3971 		}
   3972 
   3973 		if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
   3974 			if (fr->fr_satype != FRI_NORMAL &&
   3975 			    fr->fr_satype != FRI_LOOKUP) {
   3976 				ifa = ipf_resolvenic(softc, fr->fr_names +
   3977 						     fr->fr_sifpidx, v);
   3978 				ipf_ifpaddr(softc, v, fr->fr_satype, ifa,
   3979 					    &fr->fr_src6, &fr->fr_smsk6);
   3980 			}
   3981 			if (fr->fr_datype != FRI_NORMAL &&
   3982 			    fr->fr_datype != FRI_LOOKUP) {
   3983 				ifa = ipf_resolvenic(softc, fr->fr_names +
   3984 						     fr->fr_sifpidx, v);
   3985 				ipf_ifpaddr(softc, v, fr->fr_datype, ifa,
   3986 					    &fr->fr_dst6, &fr->fr_dmsk6);
   3987 			}
   3988 		}
   3989 
   3990 		fdp = &fr->fr_tifs[0];
   3991 		if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
   3992 			error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
   3993 			if (error != 0)
   3994 				goto unwind;
   3995 		}
   3996 
   3997 		fdp = &fr->fr_tifs[1];
   3998 		if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
   3999 			error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
   4000 			if (error != 0)
   4001 				goto unwind;
   4002 		}
   4003 
   4004 		fdp = &fr->fr_dif;
   4005 		if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
   4006 			error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
   4007 			if (error != 0)
   4008 				goto unwind;
   4009 		}
   4010 
   4011 		if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
   4012 		    (fr->fr_satype == FRI_LOOKUP) && (fr->fr_srcptr == NULL)) {
   4013 			fr->fr_srcptr = ipf_lookup_res_num(softc,
   4014 							   fr->fr_srctype,
   4015 							   IPL_LOGIPF,
   4016 							   fr->fr_srcnum,
   4017 							   &fr->fr_srcfunc);
   4018 		}
   4019 		if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
   4020 		    (fr->fr_datype == FRI_LOOKUP) && (fr->fr_dstptr == NULL)) {
   4021 			fr->fr_dstptr = ipf_lookup_res_num(softc,
   4022 							   fr->fr_dsttype,
   4023 							   IPL_LOGIPF,
   4024 							   fr->fr_dstnum,
   4025 							   &fr->fr_dstfunc);
   4026 		}
   4027 	}
   4028 	return 0;
   4029 
   4030 unwind:
   4031 	for (frt = start; frt != fr; fr = fr->fr_next) {
   4032 		if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
   4033 		    (frt->fr_satype == FRI_LOOKUP) && (frt->fr_srcptr != NULL))
   4034 				ipf_lookup_deref(softc, frt->fr_srctype,
   4035 						 frt->fr_srcptr);
   4036 		if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
   4037 		    (frt->fr_datype == FRI_LOOKUP) && (frt->fr_dstptr != NULL))
   4038 				ipf_lookup_deref(softc, frt->fr_dsttype,
   4039 						 frt->fr_dstptr);
   4040 	}
   4041 	return error;
   4042 }
   4043 
   4044 
   4045 /* ------------------------------------------------------------------------ */
   4046 /* Function:    ipf_sync                                                    */
   4047 /* Returns:     void                                                        */
   4048 /* Parameters:  Nil                                                         */
   4049 /*                                                                          */
   4050 /* ipf_sync() is called when we suspect that the interface list or          */
   4051 /* information about interfaces (like IP#) has changed.  Go through all     */
   4052 /* filter rules, NAT entries and the state table and check if anything      */
   4053 /* needs to be changed/updated.                                             */
   4054 /* ------------------------------------------------------------------------ */
   4055 int
   4056 ipf_sync(ipf_main_softc_t *softc, void *ifp)
   4057 {
   4058 	int i;
   4059 
   4060 # if !SOLARIS
   4061 	ipf_nat_sync(softc, ifp);
   4062 	ipf_state_sync(softc, ifp);
   4063 	ipf_lookup_sync(softc, ifp);
   4064 # endif
   4065 
   4066 	WRITE_ENTER(&softc->ipf_mutex);
   4067 	(void) ipf_synclist(softc, softc->ipf_acct[0][softc->ipf_active], ifp);
   4068 	(void) ipf_synclist(softc, softc->ipf_acct[1][softc->ipf_active], ifp);
   4069 	(void) ipf_synclist(softc, softc->ipf_rules[0][softc->ipf_active], ifp);
   4070 	(void) ipf_synclist(softc, softc->ipf_rules[1][softc->ipf_active], ifp);
   4071 
   4072 	for (i = 0; i < IPL_LOGSIZE; i++) {
   4073 		frgroup_t *g;
   4074 
   4075 		for (g = softc->ipf_groups[i][0]; g != NULL; g = g->fg_next)
   4076 			(void) ipf_synclist(softc, g->fg_start, ifp);
   4077 		for (g = softc->ipf_groups[i][1]; g != NULL; g = g->fg_next)
   4078 			(void) ipf_synclist(softc, g->fg_start, ifp);
   4079 	}
   4080 	RWLOCK_EXIT(&softc->ipf_mutex);
   4081 
   4082 	return 0;
   4083 }
   4084 
   4085 
   4086 /*
   4087  * In the functions below, bcopy() is called because the pointer being
   4088  * copied _from_ in this instance is a pointer to a char buf (which could
   4089  * end up being unaligned) and on the kernel's local stack.
   4090  */
   4091 /* ------------------------------------------------------------------------ */
   4092 /* Function:    copyinptr                                                   */
   4093 /* Returns:     int - 0 = success, else failure                             */
   4094 /* Parameters:  src(I)  - pointer to the source address                     */
   4095 /*              dst(I)  - destination address                               */
   4096 /*              size(I) - number of bytes to copy                           */
   4097 /*                                                                          */
   4098 /* Copy a block of data in from user space, given a pointer to the pointer  */
   4099 /* to start copying from (src) and a pointer to where to store it (dst).    */
   4100 /* NB: src - pointer to user space pointer, dst - kernel space pointer      */
   4101 /* ------------------------------------------------------------------------ */
   4102 int
   4103 copyinptr(ipf_main_softc_t *softc, void *src, void *dst, size_t size)
   4104 {
   4105 	void *ca;
   4106 	int error;
   4107 
   4108 # if SOLARIS
   4109 	error = COPYIN(src, &ca, sizeof(ca));
   4110 	if (error != 0)
   4111 		return error;
   4112 # else
   4113 	bcopy(src, (void *)&ca, sizeof(ca));
   4114 # endif
   4115 	error = COPYIN(ca, dst, size);
   4116 	if (error != 0) {
   4117 		IPFERROR(3);
   4118 		error = EFAULT;
   4119 	}
   4120 	return error;
   4121 }
   4122 
   4123 
   4124 /* ------------------------------------------------------------------------ */
   4125 /* Function:    copyoutptr                                                  */
   4126 /* Returns:     int - 0 = success, else failure                             */
   4127 /* Parameters:  src(I)  - pointer to the source address                     */
   4128 /*              dst(I)  - destination address                               */
   4129 /*              size(I) - number of bytes to copy                           */
   4130 /*                                                                          */
   4131 /* Copy a block of data out to user space, given a pointer to the pointer   */
   4132 /* to start copying from (src) and a pointer to where to store it (dst).    */
   4133 /* NB: src - kernel space pointer, dst - pointer to user space pointer.     */
   4134 /* ------------------------------------------------------------------------ */
   4135 int
   4136 copyoutptr(ipf_main_softc_t *softc, void *src, void *dst, size_t size)
   4137 {
   4138 	void *ca;
   4139 	int error;
   4140 
   4141 	bcopy(dst, &ca, sizeof(ca));
   4142 	error = COPYOUT(src, ca, size);
   4143 	if (error != 0) {
   4144 		IPFERROR(4);
   4145 		error = EFAULT;
   4146 	}
   4147 	return error;
   4148 }
   4149 #ifdef	_KERNEL
   4150 #endif
   4151 
   4152 
   4153 /* ------------------------------------------------------------------------ */
   4154 /* Function:    ipf_lock                                                    */
   4155 /* Returns:     int      - 0 = success, else error                          */
   4156 /* Parameters:  data(I)  - pointer to lock value to set                     */
   4157 /*              lockp(O) - pointer to location to store old lock value      */
   4158 /*                                                                          */
   4159 /* Get the new value for the lock integer, set it and return the old value  */
   4160 /* in *lockp.                                                               */
   4161 /* ------------------------------------------------------------------------ */
   4162 int
   4163 ipf_lock(void *data, int *lockp)
   4164 {
   4165 	int arg, err;
   4166 
   4167 	err = BCOPYIN(data, &arg, sizeof(arg));
   4168 	if (err != 0)
   4169 		return EFAULT;
   4170 	err = BCOPYOUT(lockp, data, sizeof(*lockp));
   4171 	if (err != 0)
   4172 		return EFAULT;
   4173 	*lockp = arg;
   4174 	return 0;
   4175 }
   4176 
   4177 
   4178 /* ------------------------------------------------------------------------ */
   4179 /* Function:    ipf_getstat                                                 */
   4180 /* Returns:     Nil                                                         */
   4181 /* Parameters:  softc(I) - pointer to soft context main structure           */
   4182 /*              fiop(I)  - pointer to ipfilter stats structure              */
   4183 /*              rev(I)   - version claim by program doing ioctl             */
   4184 /*                                                                          */
   4185 /* Stores a copy of current pointers, counters, etc, in the friostat        */
   4186 /* structure.                                                               */
   4187 /* If IPFILTER_COMPAT is compiled, we pretend to be whatever version the    */
   4188 /* program is looking for. This ensure that validation of the version it    */
   4189 /* expects will always succeed. Thus kernels with IPFILTER_COMPAT will      */
   4190 /* allow older binaries to work but kernels without it will not.            */
   4191 /* ------------------------------------------------------------------------ */
   4192 /*ARGSUSED*/
   4193 static void
   4194 ipf_getstat(ipf_main_softc_t *softc, friostat_t *fiop, int rev)
   4195 {
   4196 	int i;
   4197 
   4198 	bcopy((char *)softc->ipf_stats, (char *)fiop->f_st,
   4199 	      sizeof(ipf_statistics_t) * 2);
   4200 	fiop->f_locks[IPL_LOGSTATE] = -1;
   4201 	fiop->f_locks[IPL_LOGNAT] = -1;
   4202 	fiop->f_locks[IPL_LOGIPF] = -1;
   4203 	fiop->f_locks[IPL_LOGAUTH] = -1;
   4204 
   4205 	fiop->f_ipf[0][0] = softc->ipf_rules[0][0];
   4206 	fiop->f_acct[0][0] = softc->ipf_acct[0][0];
   4207 	fiop->f_ipf[0][1] = softc->ipf_rules[0][1];
   4208 	fiop->f_acct[0][1] = softc->ipf_acct[0][1];
   4209 	fiop->f_ipf[1][0] = softc->ipf_rules[1][0];
   4210 	fiop->f_acct[1][0] = softc->ipf_acct[1][0];
   4211 	fiop->f_ipf[1][1] = softc->ipf_rules[1][1];
   4212 	fiop->f_acct[1][1] = softc->ipf_acct[1][1];
   4213 
   4214 	fiop->f_ticks = softc->ipf_ticks;
   4215 	fiop->f_active = softc->ipf_active;
   4216 	fiop->f_froute[0] = softc->ipf_frouteok[0];
   4217 	fiop->f_froute[1] = softc->ipf_frouteok[1];
   4218 	fiop->f_rb_no_mem = softc->ipf_rb_no_mem;
   4219 	fiop->f_rb_node_max = softc->ipf_rb_node_max;
   4220 
   4221 	fiop->f_running = softc->ipf_running;
   4222 	for (i = 0; i < IPL_LOGSIZE; i++) {
   4223 		fiop->f_groups[i][0] = softc->ipf_groups[i][0];
   4224 		fiop->f_groups[i][1] = softc->ipf_groups[i][1];
   4225 	}
   4226 #ifdef  IPFILTER_LOG
   4227 	fiop->f_log_ok = ipf_log_logok(softc, IPL_LOGIPF);
   4228 	fiop->f_log_fail = ipf_log_failures(softc, IPL_LOGIPF);
   4229 	fiop->f_logging = 1;
   4230 #else
   4231 	fiop->f_log_ok = 0;
   4232 	fiop->f_log_fail = 0;
   4233 	fiop->f_logging = 0;
   4234 #endif
   4235 	fiop->f_defpass = softc->ipf_pass;
   4236 	fiop->f_features = ipf_features;
   4237 
   4238 #ifdef IPFILTER_COMPAT
   4239 	snprintf(fiop->f_version, sizeof(fiop->f_version),
   4240 		 "IP Filter: v%d.%d.%d", (rev / 1000000) % 100,
   4241 		 (rev / 10000) % 100, (rev / 100) % 100);
   4242 #else
   4243 	rev = rev;
   4244 	(void) strncpy(fiop->f_version, ipfilter_version,
   4245 		       sizeof(fiop->f_version));
   4246         fiop->f_version[sizeof(fiop->f_version) - 1] = '\0';
   4247 #endif
   4248 }
   4249 
   4250 
   4251 #ifdef	USE_INET6
   4252 int icmptoicmp6types[ICMP_MAXTYPE+1] = {
   4253 	ICMP6_ECHO_REPLY,	/* 0: ICMP_ECHOREPLY */
   4254 	-1,			/* 1: UNUSED */
   4255 	-1,			/* 2: UNUSED */
   4256 	ICMP6_DST_UNREACH,	/* 3: ICMP_UNREACH */
   4257 	-1,			/* 4: ICMP_SOURCEQUENCH */
   4258 	ND_REDIRECT,		/* 5: ICMP_REDIRECT */
   4259 	-1,			/* 6: UNUSED */
   4260 	-1,			/* 7: UNUSED */
   4261 	ICMP6_ECHO_REQUEST,	/* 8: ICMP_ECHO */
   4262 	-1,			/* 9: UNUSED */
   4263 	-1,			/* 10: UNUSED */
   4264 	ICMP6_TIME_EXCEEDED,	/* 11: ICMP_TIMXCEED */
   4265 	ICMP6_PARAM_PROB,	/* 12: ICMP_PARAMPROB */
   4266 	-1,			/* 13: ICMP_TSTAMP */
   4267 	-1,			/* 14: ICMP_TSTAMPREPLY */
   4268 	-1,			/* 15: ICMP_IREQ */
   4269 	-1,			/* 16: ICMP_IREQREPLY */
   4270 	-1,			/* 17: ICMP_MASKREQ */
   4271 	-1,			/* 18: ICMP_MASKREPLY */
   4272 };
   4273 
   4274 
   4275 int	icmptoicmp6unreach[ICMP_MAX_UNREACH] = {
   4276 	ICMP6_DST_UNREACH_ADDR,		/* 0: ICMP_UNREACH_NET */
   4277 	ICMP6_DST_UNREACH_ADDR,		/* 1: ICMP_UNREACH_HOST */
   4278 	-1,				/* 2: ICMP_UNREACH_PROTOCOL */
   4279 	ICMP6_DST_UNREACH_NOPORT,	/* 3: ICMP_UNREACH_PORT */
   4280 	-1,				/* 4: ICMP_UNREACH_NEEDFRAG */
   4281 	ICMP6_DST_UNREACH_NOTNEIGHBOR,	/* 5: ICMP_UNREACH_SRCFAIL */
   4282 	ICMP6_DST_UNREACH_ADDR,		/* 6: ICMP_UNREACH_NET_UNKNOWN */
   4283 	ICMP6_DST_UNREACH_ADDR,		/* 7: ICMP_UNREACH_HOST_UNKNOWN */
   4284 	-1,				/* 8: ICMP_UNREACH_ISOLATED */
   4285 	ICMP6_DST_UNREACH_ADMIN,	/* 9: ICMP_UNREACH_NET_PROHIB */
   4286 	ICMP6_DST_UNREACH_ADMIN,	/* 10: ICMP_UNREACH_HOST_PROHIB */
   4287 	-1,				/* 11: ICMP_UNREACH_TOSNET */
   4288 	-1,				/* 12: ICMP_UNREACH_TOSHOST */
   4289 	ICMP6_DST_UNREACH_ADMIN,	/* 13: ICMP_UNREACH_ADMIN_PROHIBIT */
   4290 };
   4291 int	icmpreplytype6[ICMP6_MAXTYPE + 1];
   4292 #endif
   4293 
   4294 int	icmpreplytype4[ICMP_MAXTYPE + 1];
   4295 
   4296 
   4297 /* ------------------------------------------------------------------------ */
   4298 /* Function:    ipf_matchicmpqueryreply                                     */
   4299 /* Returns:     int - 1 if "icmp" is a valid reply to "ic" else 0.          */
   4300 /* Parameters:  v(I)    - IP protocol version (4 or 6)                      */
   4301 /*              ic(I)   - ICMP information                                  */
   4302 /*              icmp(I) - ICMP packet header                                */
   4303 /*              rev(I)  - direction (0 = forward/1 = reverse) of packet     */
   4304 /*                                                                          */
   4305 /* Check if the ICMP packet defined by the header pointed to by icmp is a   */
   4306 /* reply to one as described by what's in ic.  If it is a match, return 1,  */
   4307 /* else return 0 for no match.                                              */
   4308 /* ------------------------------------------------------------------------ */
   4309 int
   4310 ipf_matchicmpqueryreply(int v, icmpinfo_t *ic, icmphdr_t *icmp, int rev)
   4311 {
   4312 	int ictype;
   4313 
   4314 	ictype = ic->ici_type;
   4315 
   4316 	if (v == 4) {
   4317 		/*
   4318 		 * If we matched its type on the way in, then when going out
   4319 		 * it will still be the same type.
   4320 		 */
   4321 		if ((!rev && (icmp->icmp_type == ictype)) ||
   4322 		    (rev && (icmpreplytype4[ictype] == icmp->icmp_type))) {
   4323 			if (icmp->icmp_type != ICMP_ECHOREPLY)
   4324 				return 1;
   4325 			if (icmp->icmp_id == ic->ici_id)
   4326 				return 1;
   4327 		}
   4328 	}
   4329 #ifdef	USE_INET6
   4330 	else if (v == 6) {
   4331 		if ((!rev && (icmp->icmp_type == ictype)) ||
   4332 		    (rev && (icmpreplytype6[ictype] == icmp->icmp_type))) {
   4333 			if (icmp->icmp_type != ICMP6_ECHO_REPLY)
   4334 				return 1;
   4335 			if (icmp->icmp_id == ic->ici_id)
   4336 				return 1;
   4337 		}
   4338 	}
   4339 #endif
   4340 	return 0;
   4341 }
   4342 
   4343 /* ------------------------------------------------------------------------ */
   4344 /* Function:    ipf_rule_compare                                            */
   4345 /* Parameters:  fr1(I) - first rule structure to compare                    */
   4346 /*              fr2(I) - second rule structure to compare                   */
   4347 /* Returns:     int    - 0 == rules are the same, else mismatch             */
   4348 /*                                                                          */
   4349 /* Compare two rules and return 0 if they match or a number indicating      */
   4350 /* which of the individual checks failed.                                   */
   4351 /* ------------------------------------------------------------------------ */
   4352 static int
   4353 ipf_rule_compare(frentry_t *fr1, frentry_t *fr2)
   4354 {
   4355 	if (fr1->fr_cksum != fr2->fr_cksum)
   4356 		return 1;
   4357 	if (fr1->fr_size != fr2->fr_size)
   4358 		return 2;
   4359 	if (fr1->fr_dsize != fr2->fr_dsize)
   4360 		return 3;
   4361 	if (memcmp(&fr1->fr_func, &fr2->fr_func,
   4362 		 fr1->fr_size - offsetof(struct frentry, fr_func)) != 0)
   4363 		return 4;
   4364 	if (fr1->fr_data && !fr2->fr_data)
   4365 		return 5;
   4366 	if (!fr1->fr_data && fr2->fr_data)
   4367 		return 6;
   4368 	if (fr1->fr_data) {
   4369 		if (memcmp(fr1->fr_caddr, fr2->fr_caddr, fr1->fr_dsize))
   4370 			return 7;
   4371 	}
   4372 	return 0;
   4373 }
   4374 
   4375 
   4376 /* ------------------------------------------------------------------------ */
   4377 /* Function:    frrequest                                                   */
   4378 /* Returns:     int - 0 == success, > 0 == errno value                      */
   4379 /* Parameters:  unit(I)     - device for which this is for                  */
   4380 /*              req(I)      - ioctl command (SIOC*)                         */
   4381 /*              data(I)     - pointr to ioctl data                          */
   4382 /*              set(I)      - 1 or 0 (filter set)                           */
   4383 /*              makecopy(I) - flag indicating whether data points to a rule */
   4384 /*                            in kernel space & hence doesn't need copying. */
   4385 /*                                                                          */
   4386 /* This function handles all the requests which operate on the list of      */
   4387 /* filter rules.  This includes adding, deleting, insertion.  It is also    */
   4388 /* responsible for creating groups when a "head" rule is loaded.  Interface */
   4389 /* names are resolved here and other sanity checks are made on the content  */
   4390 /* of the rule structure being loaded.  If a rule has user defined timeouts */
   4391 /* then make sure they are created and initialised before exiting.          */
   4392 /* ------------------------------------------------------------------------ */
   4393 int
   4394 frrequest(ipf_main_softc_t *softc, int unit, ioctlcmd_t req, void *data,
   4395     int set, int makecopy)
   4396 {
   4397 	int error = 0, in, family, addrem, need_free = 0;
   4398 	frentry_t frd, *fp, *f, **fprev, **ftail;
   4399 	void *ptr, *uptr;
   4400 	u_int *p, *pp;
   4401 	frgroup_t *fg;
   4402 	char *group;
   4403 
   4404 	ptr = NULL;
   4405 	fg = NULL;
   4406 	fp = &frd;
   4407 	if (makecopy != 0) {
   4408 		bzero(fp, sizeof(frd));
   4409 		error = ipf_inobj(softc, data, NULL, fp, IPFOBJ_FRENTRY);
   4410 		if (error) {
   4411 			return error;
   4412 		}
   4413 		if ((fp->fr_type & FR_T_BUILTIN) != 0) {
   4414 			IPFERROR(6);
   4415 			return EINVAL;
   4416 		}
   4417 		KMALLOCS(f, frentry_t *, fp->fr_size);
   4418 		if (f == NULL) {
   4419 			IPFERROR(131);
   4420 			return ENOMEM;
   4421 		}
   4422 		bzero(f, fp->fr_size);
   4423 		error = ipf_inobjsz(softc, data, f, IPFOBJ_FRENTRY,
   4424 				    fp->fr_size);
   4425 		if (error) {
   4426 			KFREES(f, fp->fr_size);
   4427 			return error;
   4428 		}
   4429 
   4430 		fp = f;
   4431 		f = NULL;
   4432 		fp->fr_next = NULL;
   4433 		fp->fr_dnext = NULL;
   4434 		fp->fr_pnext = NULL;
   4435 		fp->fr_pdnext = NULL;
   4436 		fp->fr_grp = NULL;
   4437 		fp->fr_grphead = NULL;
   4438 		fp->fr_icmpgrp = NULL;
   4439 		fp->fr_isc = (void *)-1;
   4440 		fp->fr_ptr = NULL;
   4441 		fp->fr_ref = 0;
   4442 		fp->fr_flags |= FR_COPIED;
   4443 	} else {
   4444 		fp = (frentry_t *)data;
   4445 		if ((fp->fr_type & FR_T_BUILTIN) == 0) {
   4446 			IPFERROR(7);
   4447 			return EINVAL;
   4448 		}
   4449 		fp->fr_flags &= ~FR_COPIED;
   4450 	}
   4451 
   4452 	if (((fp->fr_dsize == 0) && (fp->fr_data != NULL)) ||
   4453 	    ((fp->fr_dsize != 0) && (fp->fr_data == NULL))) {
   4454 		IPFERROR(8);
   4455 		error = EINVAL;
   4456 		goto donenolock;
   4457 	}
   4458 
   4459 	family = fp->fr_family;
   4460 	uptr = fp->fr_data;
   4461 
   4462 	if (req == (ioctlcmd_t)SIOCINAFR || req == (ioctlcmd_t)SIOCINIFR ||
   4463 	    req == (ioctlcmd_t)SIOCADAFR || req == (ioctlcmd_t)SIOCADIFR)
   4464 		addrem = 0;
   4465 	else if (req == (ioctlcmd_t)SIOCRMAFR || req == (ioctlcmd_t)SIOCRMIFR)
   4466 		addrem = 1;
   4467 	else if (req == (ioctlcmd_t)SIOCZRLST)
   4468 		addrem = 2;
   4469 	else {
   4470 		IPFERROR(9);
   4471 		error = EINVAL;
   4472 		goto donenolock;
   4473 	}
   4474 
   4475 	/*
   4476 	 * Only filter rules for IPv4 or IPv6 are accepted.
   4477 	 */
   4478 	if (family == AF_INET) {
   4479 		/*EMPTY*/;
   4480 #ifdef	USE_INET6
   4481 	} else if (family == AF_INET6) {
   4482 		/*EMPTY*/;
   4483 #endif
   4484 	} else if (family != 0) {
   4485 		IPFERROR(10);
   4486 		error = EINVAL;
   4487 		goto donenolock;
   4488 	}
   4489 
   4490 	/*
   4491 	 * If the rule is being loaded from user space, i.e. we had to copy it
   4492 	 * into kernel space, then do not trust the function pointer in the
   4493 	 * rule.
   4494 	 */
   4495 	if ((makecopy == 1) && (fp->fr_func != NULL)) {
   4496 		if (ipf_findfunc(fp->fr_func) == NULL) {
   4497 			IPFERROR(11);
   4498 			error = ESRCH;
   4499 			goto donenolock;
   4500 		}
   4501 
   4502 		if (addrem == 0) {
   4503 			error = ipf_funcinit(softc, fp);
   4504 			if (error != 0)
   4505 				goto donenolock;
   4506 		}
   4507 	}
   4508 	if ((fp->fr_flags & FR_CALLNOW) &&
   4509 	    ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
   4510 		IPFERROR(142);
   4511 		error = ESRCH;
   4512 		goto donenolock;
   4513 	}
   4514 	if (((fp->fr_flags & FR_CMDMASK) == FR_CALL) &&
   4515 	    ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
   4516 		IPFERROR(143);
   4517 		error = ESRCH;
   4518 		goto donenolock;
   4519 	}
   4520 
   4521 	ptr = NULL;
   4522 
   4523 	if (FR_ISACCOUNT(fp->fr_flags))
   4524 		unit = IPL_LOGCOUNT;
   4525 
   4526 	/*
   4527 	 * Check that each group name in the rule has a start index that
   4528 	 * is valid.
   4529 	 */
   4530 	if (fp->fr_icmphead != -1) {
   4531 		if ((fp->fr_icmphead < 0) ||
   4532 		    (fp->fr_icmphead >= fp->fr_namelen)) {
   4533 			IPFERROR(136);
   4534 			error = EINVAL;
   4535 			goto donenolock;
   4536 		}
   4537 		if (!strcmp(FR_NAME(fp, fr_icmphead), "0"))
   4538 			fp->fr_names[fp->fr_icmphead] = '\0';
   4539 	}
   4540 
   4541 	if (fp->fr_grhead != -1) {
   4542 		if ((fp->fr_grhead < 0) ||
   4543 		    (fp->fr_grhead >= fp->fr_namelen)) {
   4544 			IPFERROR(137);
   4545 			error = EINVAL;
   4546 			goto donenolock;
   4547 		}
   4548 		if (!strcmp(FR_NAME(fp, fr_grhead), "0"))
   4549 			fp->fr_names[fp->fr_grhead] = '\0';
   4550 	}
   4551 
   4552 	if (fp->fr_group != -1) {
   4553 		if ((fp->fr_group < 0) ||
   4554 		    (fp->fr_group >= fp->fr_namelen)) {
   4555 			IPFERROR(138);
   4556 			error = EINVAL;
   4557 			goto donenolock;
   4558 		}
   4559 		if ((req != (int)SIOCZRLST) && (fp->fr_group != -1)) {
   4560 			/*
   4561 			 * Allow loading rules that are in groups to cause
   4562 			 * them to be created if they don't already exit.
   4563 			 */
   4564 			group = FR_NAME(fp, fr_group);
   4565 			if (addrem == 0) {
   4566 				fg = ipf_group_add(softc, group, NULL,
   4567 						   fp->fr_flags, unit, set);
   4568 				if (fg == NULL) {
   4569 					IPFERROR(152);
   4570 					error = ESRCH;
   4571 					goto donenolock;
   4572 				}
   4573 				fp->fr_grp = fg;
   4574 			} else {
   4575 				fg = ipf_findgroup(softc, group, unit,
   4576 						   set, NULL);
   4577 				if (fg == NULL) {
   4578 					IPFERROR(12);
   4579 					error = ESRCH;
   4580 					goto donenolock;
   4581 				}
   4582 			}
   4583 
   4584 			if (fg->fg_flags == 0) {
   4585 				fg->fg_flags = fp->fr_flags & FR_INOUT;
   4586 			} else if (fg->fg_flags != (fp->fr_flags & FR_INOUT)) {
   4587 				IPFERROR(13);
   4588 				error = ESRCH;
   4589 				goto donenolock;
   4590 			}
   4591 		}
   4592 	} else {
   4593 		/*
   4594 		 * If a rule is going to be part of a group then it does
   4595 		 * not matter whether it is an in or out rule, but if it
   4596 		 * isn't in a group, then it does...
   4597 		 */
   4598 		if ((fp->fr_flags & (FR_INQUE|FR_OUTQUE)) == 0) {
   4599 			IPFERROR(14);
   4600 			error = EINVAL;
   4601 			goto donenolock;
   4602 		}
   4603 	}
   4604 	in = (fp->fr_flags & FR_INQUE) ? 0 : 1;
   4605 
   4606 	/*
   4607 	 * Work out which rule list this change is being applied to.
   4608 	 */
   4609 	ftail = NULL;
   4610 	fprev = NULL;
   4611 	if (unit == IPL_LOGAUTH) {
   4612 		if ((fp->fr_tifs[0].fd_ptr != NULL) ||
   4613 		    (fp->fr_tifs[1].fd_ptr != NULL) ||
   4614 		    (fp->fr_dif.fd_ptr != NULL) ||
   4615 		    (fp->fr_flags & FR_FASTROUTE)) {
   4616 			IPFERROR(145);
   4617 			error = EINVAL;
   4618 			goto donenolock;
   4619 		}
   4620 		fprev = ipf_auth_rulehead(softc);
   4621 	} else {
   4622 		if (FR_ISACCOUNT(fp->fr_flags))
   4623 			fprev = &softc->ipf_acct[in][set];
   4624 		else if ((fp->fr_flags & (FR_OUTQUE|FR_INQUE)) != 0)
   4625 			fprev = &softc->ipf_rules[in][set];
   4626 	}
   4627 	if (fprev == NULL) {
   4628 		IPFERROR(15);
   4629 		error = ESRCH;
   4630 		goto donenolock;
   4631 	}
   4632 
   4633 	if (fg != NULL)
   4634 		fprev = &fg->fg_start;
   4635 
   4636 	/*
   4637 	 * Copy in extra data for the rule.
   4638 	 */
   4639 	if (fp->fr_dsize != 0) {
   4640 		if (makecopy != 0) {
   4641 			KMALLOCS(ptr, void *, fp->fr_dsize);
   4642 			if (ptr == NULL) {
   4643 				IPFERROR(16);
   4644 				error = ENOMEM;
   4645 				goto donenolock;
   4646 			}
   4647 
   4648 			/*
   4649 			 * The bcopy case is for when the data is appended
   4650 			 * to the rule by ipf_in_compat().
   4651 			 */
   4652 			if (uptr >= (void *)fp &&
   4653 			    uptr < (void *)((char *)fp + fp->fr_size)) {
   4654 				bcopy(uptr, ptr, fp->fr_dsize);
   4655 				error = 0;
   4656 			} else {
   4657 				error = COPYIN(uptr, ptr, fp->fr_dsize);
   4658 				if (error != 0) {
   4659 					IPFERROR(17);
   4660 					error = EFAULT;
   4661 					goto donenolock;
   4662 				}
   4663 			}
   4664 		} else {
   4665 			ptr = uptr;
   4666 		}
   4667 		fp->fr_data = ptr;
   4668 	} else {
   4669 		fp->fr_data = NULL;
   4670 	}
   4671 
   4672 	/*
   4673 	 * Perform per-rule type sanity checks of their members.
   4674 	 * All code after this needs to be aware that allocated memory
   4675 	 * may need to be free'd before exiting.
   4676 	 */
   4677 	switch (fp->fr_type & ~FR_T_BUILTIN)
   4678 	{
   4679 #if defined(IPFILTER_BPF)
   4680 	case FR_T_BPFOPC :
   4681 		if (fp->fr_dsize == 0) {
   4682 			IPFERROR(19);
   4683 			error = EINVAL;
   4684 			break;
   4685 		}
   4686 		if (!bpf_validate(ptr, fp->fr_dsize/sizeof(struct bpf_insn))) {
   4687 			IPFERROR(20);
   4688 			error = EINVAL;
   4689 			break;
   4690 		}
   4691 		break;
   4692 #endif
   4693 	case FR_T_IPF :
   4694 		/*
   4695 		 * Preparation for error case at the bottom of this function.
   4696 		 */
   4697 		if (fp->fr_datype == FRI_LOOKUP)
   4698 			fp->fr_dstptr = NULL;
   4699 		if (fp->fr_satype == FRI_LOOKUP)
   4700 			fp->fr_srcptr = NULL;
   4701 
   4702 		if (fp->fr_dsize != sizeof(fripf_t)) {
   4703 			IPFERROR(21);
   4704 			error = EINVAL;
   4705 			break;
   4706 		}
   4707 
   4708 		/*
   4709 		 * Allowing a rule with both "keep state" and "with oow" is
   4710 		 * pointless because adding a state entry to the table will
   4711 		 * fail with the out of window (oow) flag set.
   4712 		 */
   4713 		if ((fp->fr_flags & FR_KEEPSTATE) && (fp->fr_flx & FI_OOW)) {
   4714 			IPFERROR(22);
   4715 			error = EINVAL;
   4716 			break;
   4717 		}
   4718 
   4719 		switch (fp->fr_satype)
   4720 		{
   4721 		case FRI_BROADCAST :
   4722 		case FRI_DYNAMIC :
   4723 		case FRI_NETWORK :
   4724 		case FRI_NETMASKED :
   4725 		case FRI_PEERADDR :
   4726 			if (fp->fr_sifpidx < 0) {
   4727 				IPFERROR(23);
   4728 				error = EINVAL;
   4729 			}
   4730 			break;
   4731 		case FRI_LOOKUP :
   4732 			fp->fr_srcptr = ipf_findlookup(softc, unit, fp,
   4733 						       &fp->fr_src6,
   4734 						       &fp->fr_smsk6);
   4735 			if (fp->fr_srcfunc == NULL) {
   4736 				IPFERROR(132);
   4737 				error = ESRCH;
   4738 				break;
   4739 			}
   4740 			break;
   4741 		case FRI_NORMAL :
   4742 			break;
   4743 		default :
   4744 			IPFERROR(133);
   4745 			error = EINVAL;
   4746 			break;
   4747 		}
   4748 		if (error != 0)
   4749 			break;
   4750 
   4751 		switch (fp->fr_datype)
   4752 		{
   4753 		case FRI_BROADCAST :
   4754 		case FRI_DYNAMIC :
   4755 		case FRI_NETWORK :
   4756 		case FRI_NETMASKED :
   4757 		case FRI_PEERADDR :
   4758 			if (fp->fr_difpidx < 0) {
   4759 				IPFERROR(24);
   4760 				error = EINVAL;
   4761 			}
   4762 			break;
   4763 		case FRI_LOOKUP :
   4764 			fp->fr_dstptr = ipf_findlookup(softc, unit, fp,
   4765 						       &fp->fr_dst6,
   4766 						       &fp->fr_dmsk6);
   4767 			if (fp->fr_dstfunc == NULL) {
   4768 				IPFERROR(134);
   4769 				error = ESRCH;
   4770 			}
   4771 			break;
   4772 		case FRI_NORMAL :
   4773 			break;
   4774 		default :
   4775 			IPFERROR(135);
   4776 			error = EINVAL;
   4777 		}
   4778 		break;
   4779 
   4780 	case FR_T_NONE :
   4781 	case FR_T_CALLFUNC :
   4782 	case FR_T_COMPIPF :
   4783 		break;
   4784 
   4785 	case FR_T_IPFEXPR :
   4786 		if (ipf_matcharray_verify(fp->fr_data, fp->fr_dsize) == -1) {
   4787 			IPFERROR(25);
   4788 			error = EINVAL;
   4789 		}
   4790 		break;
   4791 
   4792 	default :
   4793 		IPFERROR(26);
   4794 		error = EINVAL;
   4795 		break;
   4796 	}
   4797 	if (error != 0)
   4798 		goto donenolock;
   4799 
   4800 	if (fp->fr_tif.fd_name != -1) {
   4801 		if ((fp->fr_tif.fd_name < 0) ||
   4802 		    (fp->fr_tif.fd_name >= fp->fr_namelen)) {
   4803 			IPFERROR(139);
   4804 			error = EINVAL;
   4805 			goto donenolock;
   4806 		}
   4807 	}
   4808 
   4809 	if (fp->fr_dif.fd_name != -1) {
   4810 		if ((fp->fr_dif.fd_name < 0) ||
   4811 		    (fp->fr_dif.fd_name >= fp->fr_namelen)) {
   4812 			IPFERROR(140);
   4813 			error = EINVAL;
   4814 			goto donenolock;
   4815 		}
   4816 	}
   4817 
   4818 	if (fp->fr_rif.fd_name != -1) {
   4819 		if ((fp->fr_rif.fd_name < 0) ||
   4820 		    (fp->fr_rif.fd_name >= fp->fr_namelen)) {
   4821 			IPFERROR(141);
   4822 			error = EINVAL;
   4823 			goto donenolock;
   4824 		}
   4825 	}
   4826 
   4827 	/*
   4828 	 * Lookup all the interface names that are part of the rule.
   4829 	 */
   4830 	error = ipf_synclist(softc, fp, NULL);
   4831 	if (error != 0)
   4832 		goto donenolock;
   4833 	fp->fr_statecnt = 0;
   4834 	if (fp->fr_srctrack.ht_max_nodes != 0)
   4835 		ipf_rb_ht_init(&fp->fr_srctrack);
   4836 
   4837 	/*
   4838 	 * Look for an existing matching filter rule, but don't include the
   4839 	 * next or interface pointer in the comparison (fr_next, fr_ifa).
   4840 	 * This elminates rules which are indentical being loaded.  Checksum
   4841 	 * the constant part of the filter rule to make comparisons quicker
   4842 	 * (this meaning no pointers are included).
   4843 	 */
   4844 	for (fp->fr_cksum = 0, p = (u_int *)&fp->fr_func, pp = &fp->fr_cksum;
   4845 	     p < pp; p++)
   4846 		fp->fr_cksum += *p;
   4847 	pp = (u_int *)((char *)fp->fr_caddr + fp->fr_dsize);
   4848 	for (p = (u_int *)fp->fr_data; p < pp; p++)
   4849 		fp->fr_cksum += *p;
   4850 
   4851 	WRITE_ENTER(&softc->ipf_mutex);
   4852 
   4853 	/*
   4854 	 * Now that the filter rule lists are locked, we can walk the
   4855 	 * chain of them without fear.
   4856 	 */
   4857 	ftail = fprev;
   4858 	for (f = *ftail; (f = *ftail) != NULL; ftail = &f->fr_next) {
   4859 		if (fp->fr_collect <= f->fr_collect) {
   4860 			ftail = fprev;
   4861 			f = NULL;
   4862 			break;
   4863 		}
   4864 		fprev = ftail;
   4865 	}
   4866 
   4867 	for (; (f = *ftail) != NULL; ftail = &f->fr_next) {
   4868 		DT2(rule_cmp, frentry_t *, fp, frentry_t *, f);
   4869 		if (ipf_rule_compare(fp, f) == 0)
   4870 			break;
   4871 	}
   4872 
   4873 	/*
   4874 	 * If zero'ing statistics, copy current to caller and zero.
   4875 	 */
   4876 	if (addrem == 2) {
   4877 		if (f == NULL) {
   4878 			IPFERROR(27);
   4879 			error = ESRCH;
   4880 		} else {
   4881 			/*
   4882 			 * Copy and reduce lock because of impending copyout.
   4883 			 * Well we should, but if we do then the atomicity of
   4884 			 * this call and the correctness of fr_hits and
   4885 			 * fr_bytes cannot be guaranteed.  As it is, this code
   4886 			 * only resets them to 0 if they are successfully
   4887 			 * copied out into user space.
   4888 			 */
   4889 			bcopy((char *)f, (char *)fp, f->fr_size);
   4890 			/* MUTEX_DOWNGRADE(&softc->ipf_mutex); */
   4891 
   4892 			/*
   4893 			 * When we copy this rule back out, set the data
   4894 			 * pointer to be what it was in user space.
   4895 			 */
   4896 			fp->fr_data = uptr;
   4897 			error = ipf_outobj(softc, data, fp, IPFOBJ_FRENTRY);
   4898 
   4899 			if (error == 0) {
   4900 				if ((f->fr_dsize != 0) && (uptr != NULL)) {
   4901 					error = COPYOUT(f->fr_data, uptr,
   4902 							f->fr_dsize);
   4903 					if (error != 0) {
   4904 						IPFERROR(28);
   4905 						error = EFAULT;
   4906 					}
   4907 				}
   4908 				if (error == 0) {
   4909 					f->fr_hits = 0;
   4910 					f->fr_bytes = 0;
   4911 				}
   4912 			}
   4913 		}
   4914 
   4915 		if (makecopy != 0) {
   4916 			if (ptr != NULL) {
   4917 				KFREES(ptr, fp->fr_dsize);
   4918 			}
   4919 			KFREES(fp, fp->fr_size);
   4920 		}
   4921 		RWLOCK_EXIT(&softc->ipf_mutex);
   4922 		return error;
   4923 	}
   4924 
   4925   	if (!f) {
   4926 		/*
   4927 		 * At the end of this, ftail must point to the place where the
   4928 		 * new rule is to be saved/inserted/added.
   4929 		 * For SIOCAD*FR, this should be the last rule in the group of
   4930 		 * rules that have equal fr_collect fields.
   4931 		 * For SIOCIN*FR, ...
   4932 		 */
   4933 		if (req == (ioctlcmd_t)SIOCADAFR ||
   4934 		    req == (ioctlcmd_t)SIOCADIFR) {
   4935 
   4936 			for (ftail = fprev; (f = *ftail) != NULL; ) {
   4937 				if (f->fr_collect > fp->fr_collect)
   4938 					break;
   4939 				ftail = &f->fr_next;
   4940 				fprev = ftail;
   4941 			}
   4942 			ftail = fprev;
   4943 			f = NULL;
   4944 			ptr = NULL;
   4945 		} else if (req == (ioctlcmd_t)SIOCINAFR ||
   4946 			   req == (ioctlcmd_t)SIOCINIFR) {
   4947 			while ((f = *fprev) != NULL) {
   4948 				if (f->fr_collect >= fp->fr_collect)
   4949 					break;
   4950 				fprev = &f->fr_next;
   4951 			}
   4952   			ftail = fprev;
   4953   			if (fp->fr_hits != 0) {
   4954 				while (fp->fr_hits && (f = *ftail)) {
   4955 					if (f->fr_collect != fp->fr_collect)
   4956 						break;
   4957 					fprev = ftail;
   4958   					ftail = &f->fr_next;
   4959 					fp->fr_hits--;
   4960 				}
   4961   			}
   4962   			f = NULL;
   4963   			ptr = NULL;
   4964 		}
   4965 	}
   4966 
   4967 	/*
   4968 	 * Request to remove a rule.
   4969 	 */
   4970 	if (addrem == 1) {
   4971 		if (!f) {
   4972 			IPFERROR(29);
   4973 			error = ESRCH;
   4974 		} else {
   4975 			/*
   4976 			 * Do not allow activity from user space to interfere
   4977 			 * with rules not loaded that way.
   4978 			 */
   4979 			if ((makecopy == 1) && !(f->fr_flags & FR_COPIED)) {
   4980 				IPFERROR(30);
   4981 				error = EPERM;
   4982 				goto done;
   4983 			}
   4984 
   4985 			/*
   4986 			 * Return EBUSY if the rule is being reference by
   4987 			 * something else (eg state information.)
   4988 			 */
   4989 			if (f->fr_ref > 1) {
   4990 				IPFERROR(31);
   4991 				error = EBUSY;
   4992 				goto done;
   4993 			}
   4994 #ifdef	IPFILTER_SCAN
   4995 			if (f->fr_isctag != -1 &&
   4996 			    (f->fr_isc != (struct ipscan *)-1))
   4997 				ipf_scan_detachfr(f);
   4998 #endif
   4999 
   5000 			if (unit == IPL_LOGAUTH) {
   5001 				error = ipf_auth_precmd(softc, req, f, ftail);
   5002 				goto done;
   5003 			}
   5004 
   5005 			ipf_rule_delete(softc, f, unit, set);
   5006 
   5007 			need_free = makecopy;
   5008 		}
   5009 	} else {
   5010 		/*
   5011 		 * Not removing, so we must be adding/inserting a rule.
   5012 		 */
   5013 		if (f != NULL) {
   5014 			IPFERROR(32);
   5015 			error = EEXIST;
   5016 			goto done;
   5017 		}
   5018 		if (unit == IPL_LOGAUTH) {
   5019 			error = ipf_auth_precmd(softc, req, fp, ftail);
   5020 			goto done;
   5021 		}
   5022 
   5023 		MUTEX_NUKE(&fp->fr_lock);
   5024 		MUTEX_INIT(&fp->fr_lock, "filter rule lock");
   5025 		if (fp->fr_die != 0)
   5026 			ipf_rule_expire_insert(softc, fp, set);
   5027 
   5028 		fp->fr_hits = 0;
   5029 		if (makecopy != 0)
   5030 			fp->fr_ref = 1;
   5031 		fp->fr_pnext = ftail;
   5032 		fp->fr_next = *ftail;
   5033 		if (fp->fr_next != NULL)
   5034 			fp->fr_next->fr_pnext = &fp->fr_next;
   5035 		*ftail = fp;
   5036 		if (addrem == 0)
   5037 			ipf_fixskip(ftail, fp, 1);
   5038 
   5039 		fp->fr_icmpgrp = NULL;
   5040 		if (fp->fr_icmphead != -1) {
   5041 			group = FR_NAME(fp, fr_icmphead);
   5042 			fg = ipf_group_add(softc, group, fp, 0, unit, set);
   5043 			fp->fr_icmpgrp = fg;
   5044 		}
   5045 
   5046 		fp->fr_grphead = NULL;
   5047 		if (fp->fr_grhead != -1) {
   5048 			group = FR_NAME(fp, fr_grhead);
   5049 			fg = ipf_group_add(softc, group, fp, fp->fr_flags,
   5050 					   unit, set);
   5051 			fp->fr_grphead = fg;
   5052 		}
   5053 	}
   5054 done:
   5055 	RWLOCK_EXIT(&softc->ipf_mutex);
   5056 donenolock:
   5057 	if (need_free || (error != 0)) {
   5058 		if ((fp->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
   5059 			if ((fp->fr_satype == FRI_LOOKUP) &&
   5060 			    (fp->fr_srcptr != NULL))
   5061 				ipf_lookup_deref(softc, fp->fr_srctype,
   5062 						 fp->fr_srcptr);
   5063 			if ((fp->fr_datype == FRI_LOOKUP) &&
   5064 			    (fp->fr_dstptr != NULL))
   5065 				ipf_lookup_deref(softc, fp->fr_dsttype,
   5066 						 fp->fr_dstptr);
   5067 		}
   5068 		if (fp->fr_grp != NULL) {
   5069 			WRITE_ENTER(&softc->ipf_mutex);
   5070 			ipf_group_del(softc, fp->fr_grp, fp);
   5071 			RWLOCK_EXIT(&softc->ipf_mutex);
   5072 		}
   5073 		if ((ptr != NULL) && (makecopy != 0)) {
   5074 			KFREES(ptr, fp->fr_dsize);
   5075 		}
   5076 		KFREES(fp, fp->fr_size);
   5077 	}
   5078 	return (error);
   5079 }
   5080 
   5081 
   5082 /* ------------------------------------------------------------------------ */
   5083 /* Function:   ipf_rule_delete                                              */
   5084 /* Returns:    Nil                                                          */
   5085 /* Parameters: softc(I) - pointer to soft context main structure            */
   5086 /*             f(I)     - pointer to the rule being deleted                 */
   5087 /*             ftail(I) - pointer to the pointer to f                       */
   5088 /*             unit(I)  - device for which this is for                      */
   5089 /*             set(I)   - 1 or 0 (filter set)                               */
   5090 /*                                                                          */
   5091 /* This function attempts to do what it can to delete a filter rule: remove */
   5092 /* it from any linked lists and remove any groups it is responsible for.    */
   5093 /* But in the end, removing a rule can only drop the reference count - we   */
   5094 /* must use that as the guide for whether or not it can be freed.           */
   5095 /* ------------------------------------------------------------------------ */
   5096 static void
   5097 ipf_rule_delete(ipf_main_softc_t *softc, frentry_t *f, int unit, int set)
   5098 {
   5099 
   5100 	/*
   5101 	 * If fr_pdnext is set, then the rule is on the expire list, so
   5102 	 * remove it from there.
   5103 	 */
   5104 	if (f->fr_pdnext != NULL) {
   5105 		*f->fr_pdnext = f->fr_dnext;
   5106 		if (f->fr_dnext != NULL)
   5107 			f->fr_dnext->fr_pdnext = f->fr_pdnext;
   5108 		f->fr_pdnext = NULL;
   5109 		f->fr_dnext = NULL;
   5110 	}
   5111 
   5112 	ipf_fixskip(f->fr_pnext, f, -1);
   5113 	if (f->fr_pnext != NULL)
   5114 		*f->fr_pnext = f->fr_next;
   5115 	if (f->fr_next != NULL)
   5116 		f->fr_next->fr_pnext = f->fr_pnext;
   5117 	f->fr_pnext = NULL;
   5118 	f->fr_next = NULL;
   5119 
   5120 	(void) ipf_derefrule(softc, &f);
   5121 }
   5122 
   5123 /* ------------------------------------------------------------------------ */
   5124 /* Function:   ipf_rule_expire_insert                                       */
   5125 /* Returns:    Nil                                                          */
   5126 /* Parameters: softc(I) - pointer to soft context main structure            */
   5127 /*             f(I)     - pointer to rule to be added to expire list        */
   5128 /*             set(I)   - 1 or 0 (filter set)                               */
   5129 /*                                                                          */
   5130 /* If the new rule has a given expiration time, insert it into the list of  */
   5131 /* expiring rules with the ones to be removed first added to the front of   */
   5132 /* the list. The insertion is O(n) but it is kept sorted for quick scans at */
   5133 /* expiration interval checks.                                              */
   5134 /* ------------------------------------------------------------------------ */
   5135 static void
   5136 ipf_rule_expire_insert(ipf_main_softc_t *softc, frentry_t *f, int set)
   5137 {
   5138 	frentry_t *fr;
   5139 
   5140 	/*
   5141 	 */
   5142 
   5143 	f->fr_die = softc->ipf_ticks + IPF_TTLVAL(f->fr_die);
   5144 	for (fr = softc->ipf_rule_explist[set]; fr != NULL;
   5145 	     fr = fr->fr_dnext) {
   5146 		if (f->fr_die < fr->fr_die)
   5147 			break;
   5148 		if (fr->fr_dnext == NULL) {
   5149 			/*
   5150 			 * We've got to the last rule and everything
   5151 			 * wanted to be expired before this new node,
   5152 			 * so we have to tack it on the end...
   5153 			 */
   5154 			fr->fr_dnext = f;
   5155 			f->fr_pdnext = &fr->fr_dnext;
   5156 			fr = NULL;
   5157 			break;
   5158 		}
   5159 	}
   5160 
   5161 	if (softc->ipf_rule_explist[set] == NULL) {
   5162 		softc->ipf_rule_explist[set] = f;
   5163 		f->fr_pdnext = &softc->ipf_rule_explist[set];
   5164 	} else if (fr != NULL) {
   5165 		f->fr_dnext = fr;
   5166 		f->fr_pdnext = fr->fr_pdnext;
   5167 		fr->fr_pdnext = &f->fr_dnext;
   5168 	}
   5169 }
   5170 
   5171 
   5172 /* ------------------------------------------------------------------------ */
   5173 /* Function:   ipf_findlookup                                               */
   5174 /* Returns:    NULL = failure, else success                                 */
   5175 /* Parameters: softc(I) - pointer to soft context main structure            */
   5176 /*             unit(I)  - ipf device we want to find match for              */
   5177 /*             fp(I)    - rule for which lookup is for                      */
   5178 /*             addrp(I) - pointer to lookup information in address struct   */
   5179 /*             maskp(O) - pointer to lookup information for storage         */
   5180 /*                                                                          */
   5181 /* When using pools and hash tables to store addresses for matching in      */
   5182 /* rules, it is necessary to resolve both the object referred to by the     */
   5183 /* name or address (and return that pointer) and also provide the means by  */
   5184 /* which to determine if an address belongs to that object to make the      */
   5185 /* packet matching quicker.                                                 */
   5186 /* ------------------------------------------------------------------------ */
   5187 static void *
   5188 ipf_findlookup(ipf_main_softc_t *softc, int unit, frentry_t *fr,
   5189     i6addr_t *addrp, i6addr_t *maskp)
   5190 {
   5191 	void *ptr = NULL;
   5192 
   5193 	switch (addrp->iplookupsubtype)
   5194 	{
   5195 	case 0 :
   5196 		ptr = ipf_lookup_res_num(softc, unit, addrp->iplookuptype,
   5197 					 addrp->iplookupnum,
   5198 					 &maskp->iplookupfunc);
   5199 		break;
   5200 	case 1 :
   5201 		if (addrp->iplookupname < 0)
   5202 			break;
   5203 		if (addrp->iplookupname >= fr->fr_namelen)
   5204 			break;
   5205 		ptr = ipf_lookup_res_name(softc, unit, addrp->iplookuptype,
   5206 					  fr->fr_names + addrp->iplookupname,
   5207 					  &maskp->iplookupfunc);
   5208 		break;
   5209 	default :
   5210 		break;
   5211 	}
   5212 
   5213 	return ptr;
   5214 }
   5215 
   5216 
   5217 /* ------------------------------------------------------------------------ */
   5218 /* Function:    ipf_funcinit                                                */
   5219 /* Returns:     int - 0 == success, else ESRCH: cannot resolve rule details */
   5220 /* Parameters:  softc(I) - pointer to soft context main structure           */
   5221 /*              fr(I)    - pointer to filter rule                           */
   5222 /*                                                                          */
   5223 /* If a rule is a call rule, then check if the function it points to needs  */
   5224 /* an init function to be called now the rule has been loaded.              */
   5225 /* ------------------------------------------------------------------------ */
   5226 static int
   5227 ipf_funcinit(ipf_main_softc_t *softc, frentry_t *fr)
   5228 {
   5229 	ipfunc_resolve_t *ft;
   5230 	int err;
   5231 
   5232 	IPFERROR(34);
   5233 	err = ESRCH;
   5234 
   5235 	for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
   5236 		if (ft->ipfu_addr == fr->fr_func) {
   5237 			err = 0;
   5238 			if (ft->ipfu_init != NULL)
   5239 				err = (*ft->ipfu_init)(softc, fr);
   5240 			break;
   5241 		}
   5242 	return err;
   5243 }
   5244 
   5245 
   5246 /* ------------------------------------------------------------------------ */
   5247 /* Function:    ipf_funcfini                                                */
   5248 /* Returns:     Nil                                                         */
   5249 /* Parameters:  softc(I) - pointer to soft context main structure           */
   5250 /*              fr(I)    - pointer to filter rule                           */
   5251 /*                                                                          */
   5252 /* For a given filter rule, call the matching "fini" function if the rule   */
   5253 /* is using a known function that would have resulted in the "init" being   */
   5254 /* called for ealier.                                                       */
   5255 /* ------------------------------------------------------------------------ */
   5256 static void
   5257 ipf_funcfini(ipf_main_softc_t *softc, frentry_t *fr)
   5258 {
   5259 	ipfunc_resolve_t *ft;
   5260 
   5261 	for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
   5262 		if (ft->ipfu_addr == fr->fr_func) {
   5263 			if (ft->ipfu_fini != NULL)
   5264 				(void) (*ft->ipfu_fini)(softc, fr);
   5265 			break;
   5266 		}
   5267 }
   5268 
   5269 
   5270 /* ------------------------------------------------------------------------ */
   5271 /* Function:    ipf_findfunc                                                */
   5272 /* Returns:     ipfunc_t - pointer to function if found, else NULL          */
   5273 /* Parameters:  funcptr(I) - function pointer to lookup                     */
   5274 /*                                                                          */
   5275 /* Look for a function in the table of known functions.                     */
   5276 /* ------------------------------------------------------------------------ */
   5277 static ipfunc_t
   5278 ipf_findfunc(ipfunc_t funcptr)
   5279 {
   5280 	ipfunc_resolve_t *ft;
   5281 
   5282 	for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
   5283 		if (ft->ipfu_addr == funcptr)
   5284 			return funcptr;
   5285 	return NULL;
   5286 }
   5287 
   5288 
   5289 /* ------------------------------------------------------------------------ */
   5290 /* Function:    ipf_resolvefunc                                             */
   5291 /* Returns:     int - 0 == success, else error                              */
   5292 /* Parameters:  data(IO) - ioctl data pointer to ipfunc_resolve_t struct    */
   5293 /*                                                                          */
   5294 /* Copy in a ipfunc_resolve_t structure and then fill in the missing field. */
   5295 /* This will either be the function name (if the pointer is set) or the     */
   5296 /* function pointer if the name is set.  When found, fill in the other one  */
   5297 /* so that the entire, complete, structure can be copied back to user space.*/
   5298 /* ------------------------------------------------------------------------ */
   5299 int
   5300 ipf_resolvefunc(ipf_main_softc_t *softc, void *data)
   5301 {
   5302 	ipfunc_resolve_t res, *ft;
   5303 	int error;
   5304 
   5305 	error = BCOPYIN(data, &res, sizeof(res));
   5306 	if (error != 0) {
   5307 		IPFERROR(123);
   5308 		return EFAULT;
   5309 	}
   5310 
   5311 	if (res.ipfu_addr == NULL && res.ipfu_name[0] != '\0') {
   5312 		for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
   5313 			if (strncmp(res.ipfu_name, ft->ipfu_name,
   5314 				    sizeof(res.ipfu_name)) == 0) {
   5315 				res.ipfu_addr = ft->ipfu_addr;
   5316 				res.ipfu_init = ft->ipfu_init;
   5317 				if (COPYOUT(&res, data, sizeof(res)) != 0) {
   5318 					IPFERROR(35);
   5319 					return EFAULT;
   5320 				}
   5321 				return 0;
   5322 			}
   5323 	}
   5324 	if (res.ipfu_addr != NULL && res.ipfu_name[0] == '\0') {
   5325 		for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
   5326 			if (ft->ipfu_addr == res.ipfu_addr) {
   5327 				(void) strncpy(res.ipfu_name, ft->ipfu_name,
   5328 					       sizeof(res.ipfu_name));
   5329 				res.ipfu_init = ft->ipfu_init;
   5330 				if (COPYOUT(&res, data, sizeof(res)) != 0) {
   5331 					IPFERROR(36);
   5332 					return EFAULT;
   5333 				}
   5334 				return 0;
   5335 			}
   5336 	}
   5337 	IPFERROR(37);
   5338 	return ESRCH;
   5339 }
   5340 
   5341 
   5342 #if !defined(_KERNEL) || (!defined(__NetBSD__) && !defined(__OpenBSD__) && \
   5343      !defined(__FreeBSD__)) || \
   5344     FREEBSD_LT_REV(501000) || NETBSD_LT_REV(105000000) || \
   5345     OPENBSD_LT_REV(200006)
   5346 /*
   5347  * From: NetBSD
   5348  * ppsratecheck(): packets (or events) per second limitation.
   5349  */
   5350 int
   5351 ppsratecheck(lasttime, curpps, maxpps)
   5352 	struct timeval *lasttime;
   5353 	int *curpps;
   5354 	int maxpps;	/* maximum pps allowed */
   5355 {
   5356 	struct timeval tv, delta;
   5357 	int rv;
   5358 
   5359 	GETKTIME(&tv);
   5360 
   5361 	delta.tv_sec = tv.tv_sec - lasttime->tv_sec;
   5362 	delta.tv_usec = tv.tv_usec - lasttime->tv_usec;
   5363 	if (delta.tv_usec < 0) {
   5364 		delta.tv_sec--;
   5365 		delta.tv_usec += 1000000;
   5366 	}
   5367 
   5368 	/*
   5369 	 * check for 0,0 is so that the message will be seen at least once.
   5370 	 * if more than one second have passed since the last update of
   5371 	 * lasttime, reset the counter.
   5372 	 *
   5373 	 * we do increment *curpps even in *curpps < maxpps case, as some may
   5374 	 * try to use *curpps for stat purposes as well.
   5375 	 */
   5376 	if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
   5377 	    delta.tv_sec >= 1) {
   5378 		*lasttime = tv;
   5379 		*curpps = 0;
   5380 		rv = 1;
   5381 	} else if (maxpps < 0)
   5382 		rv = 1;
   5383 	else if (*curpps < maxpps)
   5384 		rv = 1;
   5385 	else
   5386 		rv = 0;
   5387 	*curpps = *curpps + 1;
   5388 
   5389 	return (rv);
   5390 }
   5391 #endif
   5392 
   5393 
   5394 /* ------------------------------------------------------------------------ */
   5395 /* Function:    ipf_derefrule                                               */
   5396 /* Returns:     int   - 0 == rule freed up, else rule not freed             */
   5397 /* Parameters:  fr(I) - pointer to filter rule                              */
   5398 /*                                                                          */
   5399 /* Decrement the reference counter to a rule by one.  If it reaches zero,   */
   5400 /* free it and any associated storage space being used by it.               */
   5401 /* ------------------------------------------------------------------------ */
   5402 int
   5403 ipf_derefrule(ipf_main_softc_t *softc, frentry_t **frp)
   5404 {
   5405 	frentry_t *fr;
   5406 	frdest_t *fdp;
   5407 
   5408 	fr = *frp;
   5409 	*frp = NULL;
   5410 
   5411 	MUTEX_ENTER(&fr->fr_lock);
   5412 	fr->fr_ref--;
   5413 	if (fr->fr_ref == 0) {
   5414 		MUTEX_EXIT(&fr->fr_lock);
   5415 		MUTEX_DESTROY(&fr->fr_lock);
   5416 
   5417 		ipf_funcfini(softc, fr);
   5418 
   5419 		fdp = &fr->fr_tif;
   5420 		if (fdp->fd_type == FRD_DSTLIST)
   5421 			ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
   5422 
   5423 		fdp = &fr->fr_rif;
   5424 		if (fdp->fd_type == FRD_DSTLIST)
   5425 			ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
   5426 
   5427 		fdp = &fr->fr_dif;
   5428 		if (fdp->fd_type == FRD_DSTLIST)
   5429 			ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
   5430 
   5431 		if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
   5432 		    fr->fr_satype == FRI_LOOKUP)
   5433 			ipf_lookup_deref(softc, fr->fr_srctype, fr->fr_srcptr);
   5434 		if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
   5435 		    fr->fr_datype == FRI_LOOKUP)
   5436 			ipf_lookup_deref(softc, fr->fr_dsttype, fr->fr_dstptr);
   5437 
   5438 		if (fr->fr_grp != NULL)
   5439 			ipf_group_del(softc, fr->fr_grp, fr);
   5440 
   5441 		if (fr->fr_grphead != NULL)
   5442 			ipf_group_del(softc, fr->fr_grphead, fr);
   5443 
   5444 		if (fr->fr_icmpgrp != NULL)
   5445 			ipf_group_del(softc, fr->fr_icmpgrp, fr);
   5446 
   5447 		if ((fr->fr_flags & FR_COPIED) != 0) {
   5448 			if (fr->fr_dsize) {
   5449 				KFREES(fr->fr_data, fr->fr_dsize);
   5450 			}
   5451 			KFREES(fr, fr->fr_size);
   5452 			return 0;
   5453 		}
   5454 		return 1;
   5455 	} else {
   5456 		MUTEX_EXIT(&fr->fr_lock);
   5457 	}
   5458 	return -1;
   5459 }
   5460 
   5461 
   5462 /* ------------------------------------------------------------------------ */
   5463 /* Function:    ipf_grpmapinit                                              */
   5464 /* Returns:     int - 0 == success, else ESRCH because table entry not found*/
   5465 /* Parameters:  fr(I) - pointer to rule to find hash table for              */
   5466 /*                                                                          */
   5467 /* Looks for group hash table fr_arg and stores a pointer to it in fr_ptr.  */
   5468 /* fr_ptr is later used by ipf_srcgrpmap and ipf_dstgrpmap.                 */
   5469 /* ------------------------------------------------------------------------ */
   5470 static int
   5471 ipf_grpmapinit(ipf_main_softc_t *softc, frentry_t *fr)
   5472 {
   5473 	char name[FR_GROUPLEN];
   5474 	iphtable_t *iph;
   5475 
   5476 	(void) snprintf(name, sizeof(name), "%d", fr->fr_arg);
   5477 	iph = ipf_lookup_find_htable(softc, IPL_LOGIPF, name);
   5478 	if (iph == NULL) {
   5479 		IPFERROR(38);
   5480 		return ESRCH;
   5481 	}
   5482 	if ((iph->iph_flags & FR_INOUT) != (fr->fr_flags & FR_INOUT)) {
   5483 		IPFERROR(39);
   5484 		return ESRCH;
   5485 	}
   5486 	iph->iph_ref++;
   5487 	fr->fr_ptr = iph;
   5488 	return 0;
   5489 }
   5490 
   5491 
   5492 /* ------------------------------------------------------------------------ */
   5493 /* Function:    ipf_grpmapfini                                              */
   5494 /* Returns:     int - 0 == success, else ESRCH because table entry not found*/
   5495 /* Parameters:  softc(I) - pointer to soft context main structure           */
   5496 /*              fr(I)    - pointer to rule to release hash table for        */
   5497 /*                                                                          */
   5498 /* For rules that have had ipf_grpmapinit called, ipf_lookup_deref needs to */
   5499 /* be called to undo what ipf_grpmapinit caused to be done.                 */
   5500 /* ------------------------------------------------------------------------ */
   5501 static int
   5502 ipf_grpmapfini(ipf_main_softc_t *softc, frentry_t *fr)
   5503 {
   5504 	iphtable_t *iph;
   5505 	iph = fr->fr_ptr;
   5506 	if (iph != NULL)
   5507 		ipf_lookup_deref(softc, IPLT_HASH, iph);
   5508 	return 0;
   5509 }
   5510 
   5511 
   5512 /* ------------------------------------------------------------------------ */
   5513 /* Function:    ipf_srcgrpmap                                               */
   5514 /* Returns:     frentry_t * - pointer to "new last matching" rule or NULL   */
   5515 /* Parameters:  fin(I)    - pointer to packet information                   */
   5516 /*              passp(IO) - pointer to current/new filter decision (unused) */
   5517 /*                                                                          */
   5518 /* Look for a rule group head in a hash table, using the source address as  */
   5519 /* the key, and descend into that group and continue matching rules against */
   5520 /* the packet.                                                              */
   5521 /* ------------------------------------------------------------------------ */
   5522 frentry_t *
   5523 ipf_srcgrpmap(fr_info_t *fin, u_32_t *passp)
   5524 {
   5525 	frgroup_t *fg;
   5526 	void *rval;
   5527 
   5528 	rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
   5529 				 &fin->fin_src);
   5530 	if (rval == NULL)
   5531 		return NULL;
   5532 
   5533 	fg = rval;
   5534 	fin->fin_fr = fg->fg_start;
   5535 	(void) ipf_scanlist(fin, *passp);
   5536 	return fin->fin_fr;
   5537 }
   5538 
   5539 
   5540 /* ------------------------------------------------------------------------ */
   5541 /* Function:    ipf_dstgrpmap                                               */
   5542 /* Returns:     frentry_t * - pointer to "new last matching" rule or NULL   */
   5543 /* Parameters:  fin(I)    - pointer to packet information                   */
   5544 /*              passp(IO) - pointer to current/new filter decision (unused) */
   5545 /*                                                                          */
   5546 /* Look for a rule group head in a hash table, using the destination        */
   5547 /* address as the key, and descend into that group and continue matching    */
   5548 /* rules against  the packet.                                               */
   5549 /* ------------------------------------------------------------------------ */
   5550 frentry_t *
   5551 ipf_dstgrpmap(fr_info_t *fin, u_32_t *passp)
   5552 {
   5553 	frgroup_t *fg;
   5554 	void *rval;
   5555 
   5556 	rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
   5557 				 &fin->fin_dst);
   5558 	if (rval == NULL)
   5559 		return NULL;
   5560 
   5561 	fg = rval;
   5562 	fin->fin_fr = fg->fg_start;
   5563 	(void) ipf_scanlist(fin, *passp);
   5564 	return fin->fin_fr;
   5565 }
   5566 
   5567 /*
   5568  * Queue functions
   5569  * ===============
   5570  * These functions manage objects on queues for efficient timeouts.  There
   5571  * are a number of system defined queues as well as user defined timeouts.
   5572  * It is expected that a lock is held in the domain in which the queue
   5573  * belongs (i.e. either state or NAT) when calling any of these functions
   5574  * that prevents ipf_freetimeoutqueue() from being called at the same time
   5575  * as any other.
   5576  */
   5577 
   5578 
   5579 /* ------------------------------------------------------------------------ */
   5580 /* Function:    ipf_addtimeoutqueue                                         */
   5581 /* Returns:     struct ifqtq * - NULL if malloc fails, else pointer to      */
   5582 /*                               timeout queue with given interval.         */
   5583 /* Parameters:  parent(I)  - pointer to pointer to parent node of this list */
   5584 /*                           of interface queues.                           */
   5585 /*              seconds(I) - timeout value in seconds for this queue.       */
   5586 /*                                                                          */
   5587 /* This routine first looks for a timeout queue that matches the interval   */
   5588 /* being requested.  If it finds one, increments the reference counter and  */
   5589 /* returns a pointer to it.  If none are found, it allocates a new one and  */
   5590 /* inserts it at the top of the list.                                       */
   5591 /*                                                                          */
   5592 /* Locking.                                                                 */
   5593 /* It is assumed that the caller of this function has an appropriate lock   */
   5594 /* held (exclusively) in the domain that encompases 'parent'.               */
   5595 /* ------------------------------------------------------------------------ */
   5596 ipftq_t *
   5597 ipf_addtimeoutqueue(ipf_main_softc_t *softc, ipftq_t **parent, u_int seconds)
   5598 {
   5599 	ipftq_t *ifq;
   5600 	u_int period;
   5601 
   5602 	period = seconds * IPF_HZ_DIVIDE;
   5603 
   5604 	MUTEX_ENTER(&softc->ipf_timeoutlock);
   5605 	for (ifq = *parent; ifq != NULL; ifq = ifq->ifq_next) {
   5606 		if (ifq->ifq_ttl == period) {
   5607 			/*
   5608 			 * Reset the delete flag, if set, so the structure
   5609 			 * gets reused rather than freed and reallocated.
   5610 			 */
   5611 			MUTEX_ENTER(&ifq->ifq_lock);
   5612 			ifq->ifq_flags &= ~IFQF_DELETE;
   5613 			ifq->ifq_ref++;
   5614 			MUTEX_EXIT(&ifq->ifq_lock);
   5615 			MUTEX_EXIT(&softc->ipf_timeoutlock);
   5616 
   5617 			return ifq;
   5618 		}
   5619 	}
   5620 
   5621 	KMALLOC(ifq, ipftq_t *);
   5622 	if (ifq != NULL) {
   5623 		MUTEX_NUKE(&ifq->ifq_lock);
   5624 		IPFTQ_INIT(ifq, period, "ipftq mutex");
   5625 		ifq->ifq_next = *parent;
   5626 		ifq->ifq_pnext = parent;
   5627 		ifq->ifq_flags = IFQF_USER;
   5628 		ifq->ifq_ref++;
   5629 		*parent = ifq;
   5630 		softc->ipf_userifqs++;
   5631 	}
   5632 	MUTEX_EXIT(&softc->ipf_timeoutlock);
   5633 	return ifq;
   5634 }
   5635 
   5636 
   5637 /* ------------------------------------------------------------------------ */
   5638 /* Function:    ipf_deletetimeoutqueue                                      */
   5639 /* Returns:     int    - new reference count value of the timeout queue     */
   5640 /* Parameters:  ifq(I) - timeout queue which is losing a reference.         */
   5641 /* Locks:       ifq->ifq_lock                                               */
   5642 /*                                                                          */
   5643 /* This routine must be called when we're discarding a pointer to a timeout */
   5644 /* queue object, taking care of the reference counter.                      */
   5645 /*                                                                          */
   5646 /* Now that this just sets a DELETE flag, it requires the expire code to    */
   5647 /* check the list of user defined timeout queues and call the free function */
   5648 /* below (currently commented out) to stop memory leaking.  It is done this */
   5649 /* way because the locking may not be sufficient to safely do a free when   */
   5650 /* this function is called.                                                 */
   5651 /* ------------------------------------------------------------------------ */
   5652 int
   5653 ipf_deletetimeoutqueue(ipftq_t *ifq)
   5654 {
   5655 
   5656 	ifq->ifq_ref--;
   5657 	if ((ifq->ifq_ref == 0) && ((ifq->ifq_flags & IFQF_USER) != 0)) {
   5658 		ifq->ifq_flags |= IFQF_DELETE;
   5659 	}
   5660 
   5661 	return ifq->ifq_ref;
   5662 }
   5663 
   5664 
   5665 /* ------------------------------------------------------------------------ */
   5666 /* Function:    ipf_freetimeoutqueue                                        */
   5667 /* Parameters:  ifq(I) - timeout queue which is losing a reference.         */
   5668 /* Returns:     Nil                                                         */
   5669 /*                                                                          */
   5670 /* Locking:                                                                 */
   5671 /* It is assumed that the caller of this function has an appropriate lock   */
   5672 /* held (exclusively) in the domain that encompases the callers "domain".   */
   5673 /* The ifq_lock for this structure should not be held.                      */
   5674 /*                                                                          */
   5675 /* Remove a user defined timeout queue from the list of queues it is in and */
   5676 /* tidy up after this is done.                                              */
   5677 /* ------------------------------------------------------------------------ */
   5678 void
   5679 ipf_freetimeoutqueue(ipf_main_softc_t *softc, ipftq_t *ifq)
   5680 {
   5681 
   5682 	if (((ifq->ifq_flags & IFQF_DELETE) == 0) || (ifq->ifq_ref != 0) ||
   5683 	    ((ifq->ifq_flags & IFQF_USER) == 0)) {
   5684 		printf("ipf_freetimeoutqueue(%lx) flags 0x%x ttl %d ref %d\n",
   5685 		       (u_long)ifq, ifq->ifq_flags, ifq->ifq_ttl,
   5686 		       ifq->ifq_ref);
   5687 		return;
   5688 	}
   5689 
   5690 	/*
   5691 	 * Remove from its position in the list.
   5692 	 */
   5693 	*ifq->ifq_pnext = ifq->ifq_next;
   5694 	if (ifq->ifq_next != NULL)
   5695 		ifq->ifq_next->ifq_pnext = ifq->ifq_pnext;
   5696 	ifq->ifq_next = NULL;
   5697 	ifq->ifq_pnext = NULL;
   5698 
   5699 	MUTEX_DESTROY(&ifq->ifq_lock);
   5700 	ATOMIC_DEC(softc->ipf_userifqs);
   5701 	KFREE(ifq);
   5702 }
   5703 
   5704 
   5705 /* ------------------------------------------------------------------------ */
   5706 /* Function:    ipf_deletequeueentry                                        */
   5707 /* Returns:     Nil                                                         */
   5708 /* Parameters:  tqe(I) - timeout queue entry to delete                      */
   5709 /*                                                                          */
   5710 /* Remove a tail queue entry from its queue and make it an orphan.          */
   5711 /* ipf_deletetimeoutqueue is called to make sure the reference count on the */
   5712 /* queue is correct.  We can't, however, call ipf_freetimeoutqueue because  */
   5713 /* the correct lock(s) may not be held that would make it safe to do so.    */
   5714 /* ------------------------------------------------------------------------ */
   5715 void
   5716 ipf_deletequeueentry(ipftqent_t *tqe)
   5717 {
   5718 	ipftq_t *ifq;
   5719 
   5720 	ifq = tqe->tqe_ifq;
   5721 
   5722 	MUTEX_ENTER(&ifq->ifq_lock);
   5723 
   5724 	if (tqe->tqe_pnext != NULL) {
   5725 		*tqe->tqe_pnext = tqe->tqe_next;
   5726 		if (tqe->tqe_next != NULL)
   5727 			tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
   5728 		else    /* we must be the tail anyway */
   5729 			ifq->ifq_tail = tqe->tqe_pnext;
   5730 
   5731 		tqe->tqe_pnext = NULL;
   5732 		tqe->tqe_ifq = NULL;
   5733 	}
   5734 
   5735 	(void) ipf_deletetimeoutqueue(ifq);
   5736 	ASSERT(ifq->ifq_ref > 0);
   5737 
   5738 	MUTEX_EXIT(&ifq->ifq_lock);
   5739 }
   5740 
   5741 
   5742 /* ------------------------------------------------------------------------ */
   5743 /* Function:    ipf_queuefront                                              */
   5744 /* Returns:     Nil                                                         */
   5745 /* Parameters:  tqe(I) - pointer to timeout queue entry                     */
   5746 /*                                                                          */
   5747 /* Move a queue entry to the front of the queue, if it isn't already there. */
   5748 /* ------------------------------------------------------------------------ */
   5749 void
   5750 ipf_queuefront(ipftqent_t *tqe)
   5751 {
   5752 	ipftq_t *ifq;
   5753 
   5754 	ifq = tqe->tqe_ifq;
   5755 	if (ifq == NULL)
   5756 		return;
   5757 
   5758 	MUTEX_ENTER(&ifq->ifq_lock);
   5759 	if (ifq->ifq_head != tqe) {
   5760 		*tqe->tqe_pnext = tqe->tqe_next;
   5761 		if (tqe->tqe_next)
   5762 			tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
   5763 		else
   5764 			ifq->ifq_tail = tqe->tqe_pnext;
   5765 
   5766 		tqe->tqe_next = ifq->ifq_head;
   5767 		ifq->ifq_head->tqe_pnext = &tqe->tqe_next;
   5768 		ifq->ifq_head = tqe;
   5769 		tqe->tqe_pnext = &ifq->ifq_head;
   5770 	}
   5771 	MUTEX_EXIT(&ifq->ifq_lock);
   5772 }
   5773 
   5774 
   5775 /* ------------------------------------------------------------------------ */
   5776 /* Function:    ipf_queueback                                               */
   5777 /* Returns:     Nil                                                         */
   5778 /* Parameters:  ticks(I) - ipf tick time to use with this call              */
   5779 /*              tqe(I)   - pointer to timeout queue entry                   */
   5780 /*                                                                          */
   5781 /* Move a queue entry to the back of the queue, if it isn't already there.  */
   5782 /* We use use ticks to calculate the expiration and mark for when we last   */
   5783 /* touched the structure.                                                   */
   5784 /* ------------------------------------------------------------------------ */
   5785 void
   5786 ipf_queueback(u_long ticks, ipftqent_t *tqe)
   5787 {
   5788 	ipftq_t *ifq;
   5789 
   5790 	ifq = tqe->tqe_ifq;
   5791 	if (ifq == NULL)
   5792 		return;
   5793 	tqe->tqe_die = ticks + ifq->ifq_ttl;
   5794 	tqe->tqe_touched = ticks;
   5795 
   5796 	MUTEX_ENTER(&ifq->ifq_lock);
   5797 	if (tqe->tqe_next != NULL) {		/* at the end already ? */
   5798 		/*
   5799 		 * Remove from list
   5800 		 */
   5801 		*tqe->tqe_pnext = tqe->tqe_next;
   5802 		tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
   5803 
   5804 		/*
   5805 		 * Make it the last entry.
   5806 		 */
   5807 		tqe->tqe_next = NULL;
   5808 		tqe->tqe_pnext = ifq->ifq_tail;
   5809 		*ifq->ifq_tail = tqe;
   5810 		ifq->ifq_tail = &tqe->tqe_next;
   5811 	}
   5812 	MUTEX_EXIT(&ifq->ifq_lock);
   5813 }
   5814 
   5815 
   5816 /* ------------------------------------------------------------------------ */
   5817 /* Function:    ipf_queueappend                                             */
   5818 /* Returns:     Nil                                                         */
   5819 /* Parameters:  ticks(I)  - ipf tick time to use with this call             */
   5820 /*              tqe(I)    - pointer to timeout queue entry                  */
   5821 /*              ifq(I)    - pointer to timeout queue                        */
   5822 /*              parent(I) - owing object pointer                            */
   5823 /*                                                                          */
   5824 /* Add a new item to this queue and put it on the very end.                 */
   5825 /* We use use ticks to calculate the expiration and mark for when we last   */
   5826 /* touched the structure.                                                   */
   5827 /* ------------------------------------------------------------------------ */
   5828 void
   5829 ipf_queueappend(u_long ticks, ipftqent_t *tqe, ipftq_t *ifq, void *parent)
   5830 {
   5831 
   5832 	MUTEX_ENTER(&ifq->ifq_lock);
   5833 	tqe->tqe_parent = parent;
   5834 	tqe->tqe_pnext = ifq->ifq_tail;
   5835 	*ifq->ifq_tail = tqe;
   5836 	ifq->ifq_tail = &tqe->tqe_next;
   5837 	tqe->tqe_next = NULL;
   5838 	tqe->tqe_ifq = ifq;
   5839 	tqe->tqe_die = ticks + ifq->ifq_ttl;
   5840 	tqe->tqe_touched = ticks;
   5841 	ifq->ifq_ref++;
   5842 	MUTEX_EXIT(&ifq->ifq_lock);
   5843 }
   5844 
   5845 
   5846 /* ------------------------------------------------------------------------ */
   5847 /* Function:    ipf_movequeue                                               */
   5848 /* Returns:     Nil                                                         */
   5849 /* Parameters:  tq(I)   - pointer to timeout queue information              */
   5850 /*              oifp(I) - old timeout queue entry was on                    */
   5851 /*              nifp(I) - new timeout queue to put entry on                 */
   5852 /*                                                                          */
   5853 /* Move a queue entry from one timeout queue to another timeout queue.      */
   5854 /* If it notices that the current entry is already last and does not need   */
   5855 /* to move queue, the return.                                               */
   5856 /* ------------------------------------------------------------------------ */
   5857 void
   5858 ipf_movequeue(u_long ticks, ipftqent_t *tqe, ipftq_t *oifq, ipftq_t *nifq)
   5859 {
   5860 
   5861 	/*
   5862 	 * If the queue hasn't changed and we last touched this entry at the
   5863 	 * same ipf time, then we're not going to achieve anything by either
   5864 	 * changing the ttl or moving it on the queue.
   5865 	 */
   5866 	if (oifq == nifq && tqe->tqe_touched == ticks)
   5867 		return;
   5868 
   5869 	/*
   5870 	 * For any of this to be outside the lock, there is a risk that two
   5871 	 * packets entering simultaneously, with one changing to a different
   5872 	 * queue and one not, could end up with things in a bizarre state.
   5873 	 */
   5874 	MUTEX_ENTER(&oifq->ifq_lock);
   5875 
   5876 	tqe->tqe_touched = ticks;
   5877 	tqe->tqe_die = ticks + nifq->ifq_ttl;
   5878 	/*
   5879 	 * Is the operation here going to be a no-op ?
   5880 	 */
   5881 	if (oifq == nifq) {
   5882 		if ((tqe->tqe_next == NULL) ||
   5883 		    (tqe->tqe_next->tqe_die == tqe->tqe_die)) {
   5884 			MUTEX_EXIT(&oifq->ifq_lock);
   5885 			return;
   5886 		}
   5887 	}
   5888 
   5889 	/*
   5890 	 * Remove from the old queue
   5891 	 */
   5892 	*tqe->tqe_pnext = tqe->tqe_next;
   5893 	if (tqe->tqe_next)
   5894 		tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
   5895 	else
   5896 		oifq->ifq_tail = tqe->tqe_pnext;
   5897 	tqe->tqe_next = NULL;
   5898 
   5899 	/*
   5900 	 * If we're moving from one queue to another, release the
   5901 	 * lock on the old queue and get a lock on the new queue.
   5902 	 * For user defined queues, if we're moving off it, call
   5903 	 * delete in case it can now be freed.
   5904 	 */
   5905 	if (oifq != nifq) {
   5906 		tqe->tqe_ifq = NULL;
   5907 
   5908 		(void) ipf_deletetimeoutqueue(oifq);
   5909 
   5910 		MUTEX_EXIT(&oifq->ifq_lock);
   5911 
   5912 		MUTEX_ENTER(&nifq->ifq_lock);
   5913 
   5914 		tqe->tqe_ifq = nifq;
   5915 		nifq->ifq_ref++;
   5916 	}
   5917 
   5918 	/*
   5919 	 * Add to the bottom of the new queue
   5920 	 */
   5921 	tqe->tqe_pnext = nifq->ifq_tail;
   5922 	*nifq->ifq_tail = tqe;
   5923 	nifq->ifq_tail = &tqe->tqe_next;
   5924 	MUTEX_EXIT(&nifq->ifq_lock);
   5925 }
   5926 
   5927 
   5928 /* ------------------------------------------------------------------------ */
   5929 /* Function:    ipf_updateipid                                              */
   5930 /* Returns:     int - 0 == success, -1 == error (packet should be droppped) */
   5931 /* Parameters:  fin(I) - pointer to packet information                      */
   5932 /*                                                                          */
   5933 /* When we are doing NAT, change the IP of every packet to represent a      */
   5934 /* single sequence of packets coming from the host, hiding any host         */
   5935 /* specific sequencing that might otherwise be revealed.  If the packet is  */
   5936 /* a fragment, then store the 'new' IPid in the fragment cache and look up  */
   5937 /* the fragment cache for non-leading fragments.  If a non-leading fragment */
   5938 /* has no match in the cache, return an error.                              */
   5939 /* ------------------------------------------------------------------------ */
   5940 static int
   5941 ipf_updateipid(fr_info_t *fin)
   5942 {
   5943 	u_short id, ido, sums;
   5944 	u_32_t sumd, sum;
   5945 	ip_t *ip;
   5946 
   5947 	if (fin->fin_off != 0) {
   5948 		sum = ipf_frag_ipidknown(fin);
   5949 		if (sum == 0xffffffff)
   5950 			return -1;
   5951 		sum &= 0xffff;
   5952 		id = (u_short)sum;
   5953 	} else {
   5954 		id = ipf_nextipid(fin);
   5955 		if (fin->fin_off == 0 && (fin->fin_flx & FI_FRAG) != 0)
   5956 			(void) ipf_frag_ipidnew(fin, (u_32_t)id);
   5957 	}
   5958 
   5959 	ip = fin->fin_ip;
   5960 	ido = ntohs(ip->ip_id);
   5961 	if (id == ido)
   5962 		return 0;
   5963 	ip->ip_id = htons(id);
   5964 	CALC_SUMD(ido, id, sumd);	/* DESTRUCTIVE MACRO! id,ido change */
   5965 	sum = (~ntohs(ip->ip_sum)) & 0xffff;
   5966 	sum += sumd;
   5967 	sum = (sum >> 16) + (sum & 0xffff);
   5968 	sum = (sum >> 16) + (sum & 0xffff);
   5969 	sums = ~(u_short)sum;
   5970 	ip->ip_sum = htons(sums);
   5971 	return 0;
   5972 }
   5973 
   5974 
   5975 #ifdef	NEED_FRGETIFNAME
   5976 /* ------------------------------------------------------------------------ */
   5977 /* Function:    ipf_getifname                                               */
   5978 /* Returns:     char *    - pointer to interface name                       */
   5979 /* Parameters:  ifp(I)    - pointer to network interface                    */
   5980 /*              buffer(O) - pointer to where to store interface name        */
   5981 /*                                                                          */
   5982 /* Constructs an interface name in the buffer passed.  The buffer passed is */
   5983 /* expected to be at least LIFNAMSIZ in bytes big.  If buffer is passed in  */
   5984 /* as a NULL pointer then return a pointer to a static array.               */
   5985 /* ------------------------------------------------------------------------ */
   5986 char *
   5987 ipf_getifname(ifp, buffer)
   5988 	struct ifnet *ifp;
   5989 	char *buffer;
   5990 {
   5991 	static char namebuf[LIFNAMSIZ];
   5992 # if defined(MENTAT) || defined(__FreeBSD__) || defined(__osf__) || \
   5993      defined(__sgi) || defined(linux) || defined(_AIX51) || \
   5994      (defined(sun) && !defined(__SVR4) && !defined(__svr4__))
   5995 	int unit, space;
   5996 	char temp[20];
   5997 	char *s;
   5998 # endif
   5999 
   6000 	if (buffer == NULL)
   6001 		buffer = namebuf;
   6002 	(void) strncpy(buffer, ifp->if_name, LIFNAMSIZ);
   6003 	buffer[LIFNAMSIZ - 1] = '\0';
   6004 # if defined(MENTAT) || defined(__FreeBSD__) || defined(__osf__) || \
   6005      defined(__sgi) || defined(_AIX51) || \
   6006      (defined(sun) && !defined(__SVR4) && !defined(__svr4__))
   6007 	for (s = buffer; *s; s++)
   6008 		;
   6009 	unit = ifp->if_unit;
   6010 	space = LIFNAMSIZ - (s - buffer);
   6011 	if ((space > 0) && (unit >= 0)) {
   6012 		snprintf(temp, sizeof(temp), "%d", unit);
   6013 		(void) strncpy(s, temp, space);
   6014 		s[space - 1] = '\0';
   6015 	}
   6016 # endif
   6017 	return buffer;
   6018 }
   6019 #endif
   6020 
   6021 
   6022 /* ------------------------------------------------------------------------ */
   6023 /* Function:    ipf_ioctlswitch                                             */
   6024 /* Returns:     int     - -1 continue processing, else ioctl return value   */
   6025 /* Parameters:  unit(I) - device unit opened                                */
   6026 /*              data(I) - pointer to ioctl data                             */
   6027 /*              cmd(I)  - ioctl command                                     */
   6028 /*              mode(I) - mode value                                        */
   6029 /*              uid(I)  - uid making the ioctl call                         */
   6030 /*              ctx(I)  - pointer to context data                           */
   6031 /*                                                                          */
   6032 /* Based on the value of unit, call the appropriate ioctl handler or return */
   6033 /* EIO if ipfilter is not running.   Also checks if write perms are req'd   */
   6034 /* for the device in order to execute the ioctl.  A special case is made    */
   6035 /* SIOCIPFINTERROR so that the same code isn't required in every handler.   */
   6036 /* The context data pointer is passed through as this is used as the key    */
   6037 /* for locating a matching token for continued access for walking lists,    */
   6038 /* etc.                                                                     */
   6039 /* ------------------------------------------------------------------------ */
   6040 int
   6041 ipf_ioctlswitch(ipf_main_softc_t *softc, int unit, void *data, ioctlcmd_t cmd,
   6042     int mode, int uid, void *ctx)
   6043 {
   6044 	int error = 0;
   6045 
   6046 	switch (cmd)
   6047 	{
   6048 	case SIOCIPFINTERROR :
   6049 		error = BCOPYOUT(&softc->ipf_interror, data,
   6050 				 sizeof(softc->ipf_interror));
   6051 		if (error != 0) {
   6052 			IPFERROR(40);
   6053 			error = EFAULT;
   6054 		}
   6055 		return error;
   6056 	default :
   6057 		break;
   6058 	}
   6059 
   6060 	switch (unit)
   6061 	{
   6062 	case IPL_LOGIPF :
   6063 		error = ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx);
   6064 		break;
   6065 	case IPL_LOGNAT :
   6066 		if (softc->ipf_running > 0) {
   6067 			error = ipf_nat_ioctl(softc, data, cmd, mode,
   6068 					      uid, ctx);
   6069 		} else {
   6070 			IPFERROR(42);
   6071 			error = EIO;
   6072 		}
   6073 		break;
   6074 	case IPL_LOGSTATE :
   6075 		if (softc->ipf_running > 0) {
   6076 			error = ipf_state_ioctl(softc, data, cmd, mode,
   6077 						uid, ctx);
   6078 		} else {
   6079 			IPFERROR(43);
   6080 			error = EIO;
   6081 		}
   6082 		break;
   6083 	case IPL_LOGAUTH :
   6084 		if (softc->ipf_running > 0) {
   6085 			error = ipf_auth_ioctl(softc, data, cmd, mode,
   6086 					       uid, ctx);
   6087 		} else {
   6088 			IPFERROR(44);
   6089 			error = EIO;
   6090 		}
   6091 		break;
   6092 	case IPL_LOGSYNC :
   6093 		if (softc->ipf_running > 0) {
   6094 			error = ipf_sync_ioctl(softc, data, cmd, mode,
   6095 					       uid, ctx);
   6096 		} else {
   6097 			error = EIO;
   6098 			IPFERROR(45);
   6099 		}
   6100 		break;
   6101 	case IPL_LOGSCAN :
   6102 #ifdef IPFILTER_SCAN
   6103 		if (softc->ipf_running > 0)
   6104 			error = ipf_scan_ioctl(softc, data, cmd, mode,
   6105 					       uid, ctx);
   6106 		else
   6107 #endif
   6108 		{
   6109 			error = EIO;
   6110 			IPFERROR(46);
   6111 		}
   6112 		break;
   6113 	case IPL_LOGLOOKUP :
   6114 		if (softc->ipf_running > 0) {
   6115 			error = ipf_lookup_ioctl(softc, data, cmd, mode,
   6116 						 uid, ctx);
   6117 		} else {
   6118 			error = EIO;
   6119 			IPFERROR(47);
   6120 		}
   6121 		break;
   6122 	default :
   6123 		IPFERROR(48);
   6124 		error = EIO;
   6125 		break;
   6126 	}
   6127 
   6128 	return error;
   6129 }
   6130 
   6131 
   6132 /*
   6133  * This array defines the expected size of objects coming into the kernel
   6134  * for the various recognised object types. The first column is flags (see
   6135  * below), 2nd column is current size, 3rd column is the version number of
   6136  * when the current size became current.
   6137  * Flags:
   6138  * 1 = minimum size, not absolute size
   6139  */
   6140 static	int	ipf_objbytes[IPFOBJ_COUNT][3] = {
   6141 	{ 1,	sizeof(struct frentry),		5010000 },	/* 0 */
   6142 	{ 1,	sizeof(struct friostat),	5010000 },
   6143 	{ 0,	sizeof(struct fr_info),		5010000 },
   6144 	{ 0,	sizeof(struct ipf_authstat),	4010100 },
   6145 	{ 0,	sizeof(struct ipfrstat),	5010000 },
   6146 	{ 1,	sizeof(struct ipnat),		5010000 },	/* 5 */
   6147 	{ 0,	sizeof(struct natstat),		5010000 },
   6148 	{ 0,	sizeof(struct ipstate_save),	5010000 },
   6149 	{ 1,	sizeof(struct nat_save),	5010000 },
   6150 	{ 0,	sizeof(struct natlookup),	5010000 },
   6151 	{ 1,	sizeof(struct ipstate),		5010000 },	/* 10 */
   6152 	{ 0,	sizeof(struct ips_stat),	5010000 },
   6153 	{ 0,	sizeof(struct frauth),		5010000 },
   6154 	{ 0,	sizeof(struct ipftune),		4010100 },
   6155 	{ 0,	sizeof(struct nat),		5010000 },
   6156 	{ 0,	sizeof(struct ipfruleiter),	4011400 },	/* 15 */
   6157 	{ 0,	sizeof(struct ipfgeniter),	4011400 },
   6158 	{ 0,	sizeof(struct ipftable),	4011400 },
   6159 	{ 0,	sizeof(struct ipflookupiter),	4011400 },
   6160 	{ 0,	sizeof(struct ipftq) * IPF_TCP_NSTATES },
   6161 	{ 1,	0,				0	}, /* IPFEXPR */
   6162 	{ 0,	0,				0	}, /* PROXYCTL */
   6163 	{ 0,	sizeof (struct fripf),		5010000	}
   6164 };
   6165 
   6166 
   6167 /* ------------------------------------------------------------------------ */
   6168 /* Function:    ipf_inobj                                                   */
   6169 /* Returns:     int     - 0 = success, else failure                         */
   6170 /* Parameters:  softc(I) - soft context pointerto work with                 */
   6171 /*              data(I)  - pointer to ioctl data                            */
   6172 /*              objp(O)  - where to store ipfobj structure                  */
   6173 /*              ptr(I)   - pointer to data to copy out                      */
   6174 /*              type(I)  - type of structure being moved                    */
   6175 /*                                                                          */
   6176 /* Copy in the contents of what the ipfobj_t points to.  In future, we      */
   6177 /* add things to check for version numbers, sizes, etc, to make it backward */
   6178 /* compatible at the ABI for user land.                                     */
   6179 /* If objp is not NULL then we assume that the caller wants to see what is  */
   6180 /* in the ipfobj_t structure being copied in. As an example, this can tell  */
   6181 /* the caller what version of ipfilter the ioctl program was written to.    */
   6182 /* ------------------------------------------------------------------------ */
   6183 int
   6184 ipf_inobj(ipf_main_softc_t *softc, void *data, ipfobj_t *objp, void *ptr,
   6185     int type)
   6186 {
   6187 	ipfobj_t obj;
   6188 	int error;
   6189 	int size;
   6190 
   6191 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
   6192 		IPFERROR(49);
   6193 		return EINVAL;
   6194 	}
   6195 
   6196 	if (objp == NULL)
   6197 		objp = &obj;
   6198 	error = BCOPYIN(data, objp, sizeof(*objp));
   6199 	if (error != 0) {
   6200 		IPFERROR(124);
   6201 		return EFAULT;
   6202 	}
   6203 
   6204 	if (objp->ipfo_type != type) {
   6205 		IPFERROR(50);
   6206 		return EINVAL;
   6207 	}
   6208 
   6209 	if (objp->ipfo_rev >= ipf_objbytes[type][2]) {
   6210 		if ((ipf_objbytes[type][0] & 1) != 0) {
   6211 			if (objp->ipfo_size < ipf_objbytes[type][1]) {
   6212 				IPFERROR(51);
   6213 				return EINVAL;
   6214 			}
   6215 			size =  ipf_objbytes[type][1];
   6216 		} else if (objp->ipfo_size == ipf_objbytes[type][1]) {
   6217 			size =  objp->ipfo_size;
   6218 		} else {
   6219 			IPFERROR(52);
   6220 			return EINVAL;
   6221 		}
   6222 		error = COPYIN(objp->ipfo_ptr, ptr, size);
   6223 		if (error != 0) {
   6224 			IPFERROR(55);
   6225 			error = EFAULT;
   6226 		}
   6227 	} else {
   6228 #ifdef  IPFILTER_COMPAT
   6229 		error = ipf_in_compat(softc, objp, ptr, 0);
   6230 #else
   6231 		IPFERROR(54);
   6232 		error = EINVAL;
   6233 #endif
   6234 	}
   6235 	return error;
   6236 }
   6237 
   6238 
   6239 /* ------------------------------------------------------------------------ */
   6240 /* Function:    ipf_inobjsz                                                 */
   6241 /* Returns:     int     - 0 = success, else failure                         */
   6242 /* Parameters:  softc(I) - soft context pointerto work with                 */
   6243 /*              data(I)  - pointer to ioctl data                            */
   6244 /*              ptr(I)   - pointer to store real data in                    */
   6245 /*              type(I)  - type of structure being moved                    */
   6246 /*              sz(I)    - size of data to copy                             */
   6247 /*                                                                          */
   6248 /* As per ipf_inobj, except the size of the object to copy in is passed in  */
   6249 /* but it must not be smaller than the size defined for the type and the    */
   6250 /* type must allow for varied sized objects.  The extra requirement here is */
   6251 /* that sz must match the size of the object being passed in - this is not  */
   6252 /* not possible nor required in ipf_inobj().                                */
   6253 /* ------------------------------------------------------------------------ */
   6254 int
   6255 ipf_inobjsz(ipf_main_softc_t *softc, void *data, void *ptr, int type, int sz)
   6256 {
   6257 	ipfobj_t obj;
   6258 	int error;
   6259 
   6260 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
   6261 		IPFERROR(56);
   6262 		return EINVAL;
   6263 	}
   6264 
   6265 	error = BCOPYIN(data, &obj, sizeof(obj));
   6266 	if (error != 0) {
   6267 		IPFERROR(125);
   6268 		return EFAULT;
   6269 	}
   6270 
   6271 	if (obj.ipfo_type != type) {
   6272 		IPFERROR(58);
   6273 		return EINVAL;
   6274 	}
   6275 
   6276 	if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
   6277 		if (((ipf_objbytes[type][0] & 1) == 0) ||
   6278 		    (sz < ipf_objbytes[type][1])) {
   6279 			IPFERROR(57);
   6280 			return EINVAL;
   6281 		}
   6282 		error = COPYIN(obj.ipfo_ptr, ptr, sz);
   6283 		if (error != 0) {
   6284 			IPFERROR(61);
   6285 			error = EFAULT;
   6286 		}
   6287 	} else {
   6288 #ifdef	IPFILTER_COMPAT
   6289 		error = ipf_in_compat(softc, &obj, ptr, sz);
   6290 #else
   6291 		IPFERROR(60);
   6292 		error = EINVAL;
   6293 #endif
   6294 	}
   6295 	return error;
   6296 }
   6297 
   6298 
   6299 /* ------------------------------------------------------------------------ */
   6300 /* Function:    ipf_outobjsz                                                */
   6301 /* Returns:     int     - 0 = success, else failure                         */
   6302 /* Parameters:  data(I) - pointer to ioctl data                             */
   6303 /*              ptr(I)  - pointer to store real data in                     */
   6304 /*              type(I) - type of structure being moved                     */
   6305 /*              sz(I)   - size of data to copy                              */
   6306 /*                                                                          */
   6307 /* As per ipf_outobj, except the size of the object to copy out is passed in*/
   6308 /* but it must not be smaller than the size defined for the type and the    */
   6309 /* type must allow for varied sized objects.  The extra requirement here is */
   6310 /* that sz must match the size of the object being passed in - this is not  */
   6311 /* not possible nor required in ipf_outobj().                               */
   6312 /* ------------------------------------------------------------------------ */
   6313 int
   6314 ipf_outobjsz(ipf_main_softc_t *softc, void *data, void *ptr, int type, int sz)
   6315 {
   6316 	ipfobj_t obj;
   6317 	int error;
   6318 
   6319 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
   6320 		IPFERROR(62);
   6321 		return EINVAL;
   6322 	}
   6323 
   6324 	error = BCOPYIN(data, &obj, sizeof(obj));
   6325 	if (error != 0) {
   6326 		IPFERROR(127);
   6327 		return EFAULT;
   6328 	}
   6329 
   6330 	if (obj.ipfo_type != type) {
   6331 		IPFERROR(63);
   6332 		return EINVAL;
   6333 	}
   6334 
   6335 	if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
   6336 		if (((ipf_objbytes[type][0] & 1) == 0) ||
   6337 		    (sz < ipf_objbytes[type][1])) {
   6338 			IPFERROR(146);
   6339 			return EINVAL;
   6340 		}
   6341 		error = COPYOUT(ptr, obj.ipfo_ptr, sz);
   6342 		if (error != 0) {
   6343 			IPFERROR(66);
   6344 			error = EFAULT;
   6345 		}
   6346 	} else {
   6347 #ifdef	IPFILTER_COMPAT
   6348 		error = ipf_out_compat(softc, &obj, ptr);
   6349 #else
   6350 		IPFERROR(65);
   6351 		error = EINVAL;
   6352 #endif
   6353 	}
   6354 	return error;
   6355 }
   6356 
   6357 
   6358 /* ------------------------------------------------------------------------ */
   6359 /* Function:    ipf_outobj                                                  */
   6360 /* Returns:     int     - 0 = success, else failure                         */
   6361 /* Parameters:  data(I) - pointer to ioctl data                             */
   6362 /*              ptr(I)  - pointer to store real data in                     */
   6363 /*              type(I) - type of structure being moved                     */
   6364 /*                                                                          */
   6365 /* Copy out the contents of what ptr is to where ipfobj points to.  In      */
   6366 /* future, we add things to check for version numbers, sizes, etc, to make  */
   6367 /* it backward  compatible at the ABI for user land.                        */
   6368 /* ------------------------------------------------------------------------ */
   6369 int
   6370 ipf_outobj(ipf_main_softc_t *softc, void *data, void *ptr, int type)
   6371 {
   6372 	ipfobj_t obj;
   6373 	int error;
   6374 
   6375 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
   6376 		IPFERROR(67);
   6377 		return EINVAL;
   6378 	}
   6379 
   6380 	error = BCOPYIN(data, &obj, sizeof(obj));
   6381 	if (error != 0) {
   6382 		IPFERROR(126);
   6383 		return EFAULT;
   6384 	}
   6385 
   6386 	if (obj.ipfo_type != type) {
   6387 		IPFERROR(68);
   6388 		return EINVAL;
   6389 	}
   6390 
   6391 	if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
   6392 		if ((ipf_objbytes[type][0] & 1) != 0) {
   6393 			if (obj.ipfo_size < ipf_objbytes[type][1]) {
   6394 				IPFERROR(69);
   6395 				return EINVAL;
   6396 			}
   6397 		} else if (obj.ipfo_size != ipf_objbytes[type][1]) {
   6398 			IPFERROR(70);
   6399 			return EINVAL;
   6400 		}
   6401 
   6402 		error = COPYOUT(ptr, obj.ipfo_ptr, obj.ipfo_size);
   6403 		if (error != 0) {
   6404 			IPFERROR(73);
   6405 			error = EFAULT;
   6406 		}
   6407 	} else {
   6408 #ifdef	IPFILTER_COMPAT
   6409 		error = ipf_out_compat(softc, &obj, ptr);
   6410 #else
   6411 		IPFERROR(72);
   6412 		error = EINVAL;
   6413 #endif
   6414 	}
   6415 	return error;
   6416 }
   6417 
   6418 
   6419 /* ------------------------------------------------------------------------ */
   6420 /* Function:    ipf_outobjk                                                 */
   6421 /* Returns:     int     - 0 = success, else failure                         */
   6422 /* Parameters:  obj(I)  - pointer to data description structure             */
   6423 /*              ptr(I)  - pointer to kernel data to copy out                */
   6424 /*                                                                          */
   6425 /* In the above functions, the ipfobj_t structure is copied into the kernel,*/
   6426 /* telling ipfilter how to copy out data. In this instance, the ipfobj_t is */
   6427 /* already populated with information and now we just need to use it.       */
   6428 /* There is no need for this function to have a "type" parameter as there   */
   6429 /* is no point in validating information that comes from the kernel with    */
   6430 /* itself.                                                                  */
   6431 /* ------------------------------------------------------------------------ */
   6432 int
   6433 ipf_outobjk(ipf_main_softc_t *softc, ipfobj_t *obj, void *ptr)
   6434 {
   6435 	int type = obj->ipfo_type;
   6436 	int error;
   6437 
   6438 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
   6439 		IPFERROR(147);
   6440 		return EINVAL;
   6441 	}
   6442 
   6443 	if (obj->ipfo_rev >= ipf_objbytes[type][2]) {
   6444 		if ((ipf_objbytes[type][0] & 1) != 0) {
   6445 			if (obj->ipfo_size < ipf_objbytes[type][1]) {
   6446 				IPFERROR(148);
   6447 				return EINVAL;
   6448 			}
   6449 
   6450 		} else if (obj->ipfo_size != ipf_objbytes[type][1]) {
   6451 			IPFERROR(149);
   6452 			return EINVAL;
   6453 		}
   6454 
   6455 		error = COPYOUT(ptr, obj->ipfo_ptr, obj->ipfo_size);
   6456 		if (error != 0) {
   6457 			IPFERROR(150);
   6458 			error = EFAULT;
   6459 		}
   6460 	} else {
   6461 #ifdef  IPFILTER_COMPAT
   6462 		error = ipf_out_compat(softc, obj, ptr);
   6463 #else
   6464 		IPFERROR(151);
   6465 		error = EINVAL;
   6466 #endif
   6467 	}
   6468 	return error;
   6469 }
   6470 
   6471 
   6472 /* ------------------------------------------------------------------------ */
   6473 /* Function:    ipf_checkl4sum                                              */
   6474 /* Returns:     int     - 0 = good, -1 = bad, 1 = cannot check              */
   6475 /* Parameters:  fin(I) - pointer to packet information                      */
   6476 /*                                                                          */
   6477 /* If possible, calculate the layer 4 checksum for the packet.  If this is  */
   6478 /* not possible, return without indicating a failure or success but in a    */
   6479 /* way that is ditinguishable. This function should only be called by the   */
   6480 /* ipf_checkv6sum() for each platform.                                      */
   6481 /* ------------------------------------------------------------------------ */
   6482 int
   6483 ipf_checkl4sum(fr_info_t *fin)
   6484 {
   6485 	u_short sum, hdrsum, *csump;
   6486 	udphdr_t *udp;
   6487 	int dosum;
   6488 
   6489 	/*
   6490 	 * If the TCP packet isn't a fragment, isn't too short and otherwise
   6491 	 * isn't already considered "bad", then validate the checksum.  If
   6492 	 * this check fails then considered the packet to be "bad".
   6493 	 */
   6494 	if ((fin->fin_flx & (FI_FRAG|FI_SHORT|FI_BAD)) != 0)
   6495 		return 1;
   6496 
   6497 	csump = NULL;
   6498 	hdrsum = 0;
   6499 	dosum = 0;
   6500 	sum = 0;
   6501 
   6502 	switch (fin->fin_p)
   6503 	{
   6504 	case IPPROTO_TCP :
   6505 		csump = &((tcphdr_t *)fin->fin_dp)->th_sum;
   6506 		dosum = 1;
   6507 		break;
   6508 
   6509 	case IPPROTO_UDP :
   6510 		udp = fin->fin_dp;
   6511 		if (udp->uh_sum != 0) {
   6512 			csump = &udp->uh_sum;
   6513 			dosum = 1;
   6514 		}
   6515 		break;
   6516 
   6517 #ifdef USE_INET6
   6518 	case IPPROTO_ICMPV6 :
   6519 		csump = &((struct icmp6_hdr *)fin->fin_dp)->icmp6_cksum;
   6520 		dosum = 1;
   6521 		break;
   6522 #endif
   6523 
   6524 	case IPPROTO_ICMP :
   6525 		csump = &((struct icmp *)fin->fin_dp)->icmp_cksum;
   6526 		dosum = 1;
   6527 		break;
   6528 
   6529 	default :
   6530 		return 1;
   6531 		/*NOTREACHED*/
   6532 	}
   6533 
   6534 	if (csump != NULL)
   6535 		hdrsum = *csump;
   6536 
   6537 	if (dosum) {
   6538 		sum = fr_cksum(fin, fin->fin_ip, fin->fin_p, fin->fin_dp);
   6539 	}
   6540 #if !defined(_KERNEL)
   6541 	if (sum == hdrsum) {
   6542 		FR_DEBUG(("checkl4sum: %hx == %hx\n", sum, hdrsum));
   6543 	} else {
   6544 		FR_DEBUG(("checkl4sum: %hx != %hx\n", sum, hdrsum));
   6545 	}
   6546 #endif
   6547 	DT2(l4sums, u_short, hdrsum, u_short, sum);
   6548 	if (hdrsum == sum) {
   6549 		fin->fin_cksum = FI_CK_SUMOK;
   6550 		return 0;
   6551 	}
   6552 	fin->fin_cksum = FI_CK_BAD;
   6553 	return -1;
   6554 }
   6555 
   6556 
   6557 /* ------------------------------------------------------------------------ */
   6558 /* Function:    ipf_ifpfillv4addr                                           */
   6559 /* Returns:     int     - 0 = address update, -1 = address not updated      */
   6560 /* Parameters:  atype(I)   - type of network address update to perform      */
   6561 /*              sin(I)     - pointer to source of address information       */
   6562 /*              mask(I)    - pointer to source of netmask information       */
   6563 /*              inp(I)     - pointer to destination address store           */
   6564 /*              inpmask(I) - pointer to destination netmask store           */
   6565 /*                                                                          */
   6566 /* Given a type of network address update (atype) to perform, copy          */
   6567 /* information from sin/mask into inp/inpmask.  If ipnmask is NULL then no  */
   6568 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in  */
   6569 /* which case the operation fails.  For all values of atype other than      */
   6570 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s  */
   6571 /* value.                                                                   */
   6572 /* ------------------------------------------------------------------------ */
   6573 int
   6574 ipf_ifpfillv4addr(int atype, struct sockaddr_in *sin, struct sockaddr_in *mask,
   6575     struct in_addr *inp, struct in_addr *inpmask)
   6576 {
   6577 	if (inpmask != NULL && atype != FRI_NETMASKED)
   6578 		inpmask->s_addr = 0xffffffff;
   6579 
   6580 	if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
   6581 		if (atype == FRI_NETMASKED) {
   6582 			if (inpmask == NULL)
   6583 				return -1;
   6584 			inpmask->s_addr = mask->sin_addr.s_addr;
   6585 		}
   6586 		inp->s_addr = sin->sin_addr.s_addr & mask->sin_addr.s_addr;
   6587 	} else {
   6588 		inp->s_addr = sin->sin_addr.s_addr;
   6589 	}
   6590 	return 0;
   6591 }
   6592 
   6593 
   6594 #ifdef	USE_INET6
   6595 /* ------------------------------------------------------------------------ */
   6596 /* Function:    ipf_ifpfillv6addr                                           */
   6597 /* Returns:     int     - 0 = address update, -1 = address not updated      */
   6598 /* Parameters:  atype(I)   - type of network address update to perform      */
   6599 /*              sin(I)     - pointer to source of address information       */
   6600 /*              mask(I)    - pointer to source of netmask information       */
   6601 /*              inp(I)     - pointer to destination address store           */
   6602 /*              inpmask(I) - pointer to destination netmask store           */
   6603 /*                                                                          */
   6604 /* Given a type of network address update (atype) to perform, copy          */
   6605 /* information from sin/mask into inp/inpmask.  If ipnmask is NULL then no  */
   6606 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in  */
   6607 /* which case the operation fails.  For all values of atype other than      */
   6608 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s  */
   6609 /* value.                                                                   */
   6610 /* ------------------------------------------------------------------------ */
   6611 int
   6612 ipf_ifpfillv6addr(int atype, struct sockaddr_in6 *sin,
   6613     struct sockaddr_in6 *mask, i6addr_t *inp, i6addr_t *inpmask)
   6614 {
   6615 	i6addr_t *src, *and;
   6616 
   6617 	src = (i6addr_t *)&sin->sin6_addr;
   6618 	and = (i6addr_t *)&mask->sin6_addr;
   6619 
   6620 	if (inpmask != NULL && atype != FRI_NETMASKED) {
   6621 		inpmask->i6[0] = 0xffffffff;
   6622 		inpmask->i6[1] = 0xffffffff;
   6623 		inpmask->i6[2] = 0xffffffff;
   6624 		inpmask->i6[3] = 0xffffffff;
   6625 	}
   6626 
   6627 	if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
   6628 		if (atype == FRI_NETMASKED) {
   6629 			if (inpmask == NULL)
   6630 				return -1;
   6631 			inpmask->i6[0] = and->i6[0];
   6632 			inpmask->i6[1] = and->i6[1];
   6633 			inpmask->i6[2] = and->i6[2];
   6634 			inpmask->i6[3] = and->i6[3];
   6635 		}
   6636 
   6637 		inp->i6[0] = src->i6[0] & and->i6[0];
   6638 		inp->i6[1] = src->i6[1] & and->i6[1];
   6639 		inp->i6[2] = src->i6[2] & and->i6[2];
   6640 		inp->i6[3] = src->i6[3] & and->i6[3];
   6641 	} else {
   6642 		inp->i6[0] = src->i6[0];
   6643 		inp->i6[1] = src->i6[1];
   6644 		inp->i6[2] = src->i6[2];
   6645 		inp->i6[3] = src->i6[3];
   6646 	}
   6647 	return 0;
   6648 }
   6649 #endif
   6650 
   6651 
   6652 /* ------------------------------------------------------------------------ */
   6653 /* Function:    ipf_matchtag                                                */
   6654 /* Returns:     0 == mismatch, 1 == match.                                  */
   6655 /* Parameters:  tag1(I) - pointer to first tag to compare                   */
   6656 /*              tag2(I) - pointer to second tag to compare                  */
   6657 /*                                                                          */
   6658 /* Returns true (non-zero) or false(0) if the two tag structures can be     */
   6659 /* considered to be a match or not match, respectively.  The tag is 16      */
   6660 /* bytes long (16 characters) but that is overlayed with 4 32bit ints so    */
   6661 /* compare the ints instead, for speed. tag1 is the master of the           */
   6662 /* comparison.  This function should only be called with both tag1 and tag2 */
   6663 /* as non-NULL pointers.                                                    */
   6664 /* ------------------------------------------------------------------------ */
   6665 int
   6666 ipf_matchtag(ipftag_t *tag1, ipftag_t *tag2)
   6667 {
   6668 	if (tag1 == tag2)
   6669 		return 1;
   6670 
   6671 	if ((tag1->ipt_num[0] == 0) && (tag2->ipt_num[0] == 0))
   6672 		return 1;
   6673 
   6674 	if ((tag1->ipt_num[0] == tag2->ipt_num[0]) &&
   6675 	    (tag1->ipt_num[1] == tag2->ipt_num[1]) &&
   6676 	    (tag1->ipt_num[2] == tag2->ipt_num[2]) &&
   6677 	    (tag1->ipt_num[3] == tag2->ipt_num[3]))
   6678 		return 1;
   6679 	return 0;
   6680 }
   6681 
   6682 
   6683 /* ------------------------------------------------------------------------ */
   6684 /* Function:    ipf_coalesce                                                */
   6685 /* Returns:     1 == success, -1 == failure, 0 == no change                 */
   6686 /* Parameters:  fin(I) - pointer to packet information                      */
   6687 /*                                                                          */
   6688 /* Attempt to get all of the packet data into a single, contiguous buffer.  */
   6689 /* If this call returns a failure then the buffers have also been freed.    */
   6690 /* ------------------------------------------------------------------------ */
   6691 int
   6692 ipf_coalesce(fr_info_t *fin)
   6693 {
   6694 
   6695 	if ((fin->fin_flx & FI_COALESCE) != 0)
   6696 		return 1;
   6697 
   6698 	/*
   6699 	 * If the mbuf pointers indicate that there is no mbuf to work with,
   6700 	 * return but do not indicate success or failure.
   6701 	 */
   6702 	if (fin->fin_m == NULL || fin->fin_mp == NULL)
   6703 		return 0;
   6704 
   6705 #if defined(_KERNEL)
   6706 	if (ipf_pullup(fin->fin_m, fin, fin->fin_plen) == NULL) {
   6707 		ipf_main_softc_t *softc = fin->fin_main_soft;
   6708 
   6709 		DT1(frb_coalesce, fr_info_t *, fin);
   6710 		LBUMP(ipf_stats[fin->fin_out].fr_badcoalesces);
   6711 # ifdef MENTAT
   6712 		FREE_MB_T(*fin->fin_mp);
   6713 # endif
   6714 		fin->fin_reason = FRB_COALESCE;
   6715 		*fin->fin_mp = NULL;
   6716 		fin->fin_m = NULL;
   6717 		return -1;
   6718 	}
   6719 #else
   6720 	fin = fin;	/* LINT */
   6721 #endif
   6722 	return 1;
   6723 }
   6724 
   6725 
   6726 /*
   6727  * The following table lists all of the tunable variables that can be
   6728  * accessed via SIOCIPFGET/SIOCIPFSET/SIOCIPFGETNEXt.  The format of each row
   6729  * in the table below is as follows:
   6730  *
   6731  * pointer to value, name of value, minimum, maximum, size of the value's
   6732  *     container, value attribute flags
   6733  *
   6734  * For convienience, IPFT_RDONLY means the value is read-only, IPFT_WRDISABLED
   6735  * means the value can only be written to when IPFilter is loaded but disabled.
   6736  * The obvious implication is if neither of these are set then the value can be
   6737  * changed at any time without harm.
   6738  */
   6739 
   6740 
   6741 /* ------------------------------------------------------------------------ */
   6742 /* Function:    ipf_tune_findbycookie                                       */
   6743 /* Returns:     NULL = search failed, else pointer to tune struct           */
   6744 /* Parameters:  cookie(I) - cookie value to search for amongst tuneables    */
   6745 /*              next(O)   - pointer to place to store the cookie for the    */
   6746 /*                          "next" tuneable, if it is desired.              */
   6747 /*                                                                          */
   6748 /* This function is used to walk through all of the existing tunables with  */
   6749 /* successive calls.  It searches the known tunables for the one which has  */
   6750 /* a matching value for "cookie" - ie its address.  When returning a match, */
   6751 /* the next one to be found may be returned inside next.                    */
   6752 /* ------------------------------------------------------------------------ */
   6753 static ipftuneable_t *
   6754 ipf_tune_findbycookie(ipftuneable_t **ptop, void *cookie, void **next)
   6755 {
   6756 	ipftuneable_t *ta, **tap;
   6757 
   6758 	for (ta = *ptop; ta->ipft_name != NULL; ta++)
   6759 		if (ta == cookie) {
   6760 			if (next != NULL) {
   6761 				/*
   6762 				 * If the next entry in the array has a name
   6763 				 * present, then return a pointer to it for
   6764 				 * where to go next, else return a pointer to
   6765 				 * the dynaminc list as a key to search there
   6766 				 * next.  This facilitates a weak linking of
   6767 				 * the two "lists" together.
   6768 				 */
   6769 				if ((ta + 1)->ipft_name != NULL)
   6770 					*next = ta + 1;
   6771 				else
   6772 					*next = ptop;
   6773 			}
   6774 			return ta;
   6775 		}
   6776 
   6777 	for (tap = ptop; (ta = *tap) != NULL; tap = &ta->ipft_next)
   6778 		if (tap == cookie) {
   6779 			if (next != NULL)
   6780 				*next = &ta->ipft_next;
   6781 			return ta;
   6782 		}
   6783 
   6784 	if (next != NULL)
   6785 		*next = NULL;
   6786 	return NULL;
   6787 }
   6788 
   6789 
   6790 /* ------------------------------------------------------------------------ */
   6791 /* Function:    ipf_tune_findbyname                                         */
   6792 /* Returns:     NULL = search failed, else pointer to tune struct           */
   6793 /* Parameters:  name(I) - name of the tuneable entry to find.               */
   6794 /*                                                                          */
   6795 /* Search the static array of tuneables and the list of dynamic tuneables   */
   6796 /* for an entry with a matching name.  If we can find one, return a pointer */
   6797 /* to the matching structure.                                               */
   6798 /* ------------------------------------------------------------------------ */
   6799 static ipftuneable_t *
   6800 ipf_tune_findbyname(ipftuneable_t *top, const char *name)
   6801 {
   6802 	ipftuneable_t *ta;
   6803 
   6804 	for (ta = top; ta != NULL; ta = ta->ipft_next)
   6805 		if (!strcmp(ta->ipft_name, name)) {
   6806 			return ta;
   6807 		}
   6808 
   6809 	return NULL;
   6810 }
   6811 
   6812 
   6813 /* ------------------------------------------------------------------------ */
   6814 /* Function:    ipf_tune_add_array                                          */
   6815 /* Returns:     int - 0 == success, else failure                            */
   6816 /* Parameters:  newtune - pointer to new tune array to add to tuneables     */
   6817 /*                                                                          */
   6818 /* Appends tune structures from the array passed in (newtune) to the end of */
   6819 /* the current list of "dynamic" tuneable parameters.                       */
   6820 /* If any entry to be added is already present (by name) then the operation */
   6821 /* is aborted - entries that have been added are removed before returning.  */
   6822 /* An entry with no name (NULL) is used as the indication that the end of   */
   6823 /* the array has been reached.                                              */
   6824 /* ------------------------------------------------------------------------ */
   6825 int
   6826 ipf_tune_add_array(ipf_main_softc_t *softc, ipftuneable_t *newtune)
   6827 {
   6828 	ipftuneable_t *nt, *dt;
   6829 	int error = 0;
   6830 
   6831 	for (nt = newtune; nt->ipft_name != NULL; nt++) {
   6832 		error = ipf_tune_add(softc, nt);
   6833 		if (error != 0) {
   6834 			for (dt = newtune; dt != nt; dt++) {
   6835 				(void) ipf_tune_del(softc, dt);
   6836 			}
   6837 		}
   6838 	}
   6839 
   6840 	return error;
   6841 }
   6842 
   6843 
   6844 /* ------------------------------------------------------------------------ */
   6845 /* Function:    ipf_tune_array_link                                         */
   6846 /* Returns:     0 == success, -1 == failure                                 */
   6847 /* Parameters:  softc(I) - soft context pointerto work with                 */
   6848 /*              array(I) - pointer to an array of tuneables                 */
   6849 /*                                                                          */
   6850 /* Given an array of tunables (array), append them to the current list of   */
   6851 /* tuneables for this context (softc->ipf_tuners.) To properly prepare the  */
   6852 /* the array for being appended to the list, initialise all of the next     */
   6853 /* pointers so we don't need to walk parts of it with ++ and others with    */
   6854 /* next. The array is expected to have an entry with a NULL name as the     */
   6855 /* terminator. Trying to add an array with no non-NULL names will return as */
   6856 /* a failure.                                                               */
   6857 /* ------------------------------------------------------------------------ */
   6858 int
   6859 ipf_tune_array_link(ipf_main_softc_t *softc, ipftuneable_t *array)
   6860 {
   6861 	ipftuneable_t *t, **p;
   6862 
   6863 	t = array;
   6864 	if (t->ipft_name == NULL)
   6865 		return -1;
   6866 
   6867 	for (; t[1].ipft_name != NULL; t++)
   6868 		t[0].ipft_next = &t[1];
   6869 	t->ipft_next = NULL;
   6870 
   6871 	/*
   6872 	 * Since a pointer to the last entry isn't kept, we need to find it
   6873 	 * each time we want to add new variables to the list.
   6874 	 */
   6875 	for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
   6876 		if (t->ipft_name == NULL)
   6877 			break;
   6878 	*p = array;
   6879 
   6880 	return 0;
   6881 }
   6882 
   6883 
   6884 /* ------------------------------------------------------------------------ */
   6885 /* Function:    ipf_tune_array_unlink                                       */
   6886 /* Returns:     0 == success, -1 == failure                                 */
   6887 /* Parameters:  softc(I) - soft context pointerto work with                 */
   6888 /*              array(I) - pointer to an array of tuneables                 */
   6889 /*                                                                          */
   6890 /* ------------------------------------------------------------------------ */
   6891 int
   6892 ipf_tune_array_unlink(ipf_main_softc_t *softc, ipftuneable_t *array)
   6893 {
   6894 	ipftuneable_t *t, **p;
   6895 
   6896 	for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
   6897 		if (t == array)
   6898 			break;
   6899 	if (t == NULL)
   6900 		return -1;
   6901 
   6902 	for (; t[1].ipft_name != NULL; t++)
   6903 		;
   6904 
   6905 	*p = t->ipft_next;
   6906 
   6907 	return 0;
   6908 }
   6909 
   6910 
   6911 /* ------------------------------------------------------------------------ */
   6912 /* Function:   ipf_tune_array_copy                                          */
   6913 /* Returns:    NULL = failure, else pointer to new array                    */
   6914 /* Parameters: base(I)     - pointer to structure base                      */
   6915 /*             size(I)     - size of the array at template                  */
   6916 /*             template(I) - original array to copy                         */
   6917 /*                                                                          */
   6918 /* Allocate memory for a new set of tuneable values and copy everything     */
   6919 /* from template into the new region of memory.  The new region is full of  */
   6920 /* uninitialised pointers (ipft_next) so set them up.  Now, ipftp_offset... */
   6921 /*                                                                          */
   6922 /* NOTE: the following assumes that sizeof(long) == sizeof(void *)          */
   6923 /* In the array template, ipftp_offset is the offset (in bytes) of the      */
   6924 /* location of the tuneable value inside the structure pointed to by base.  */
   6925 /* As ipftp_offset is a union over the pointers to the tuneable values, if  */
   6926 /* we add base to the copy's ipftp_offset, copy ends up with a pointer in   */
   6927 /* ipftp_void that points to the stored value.                              */
   6928 /* ------------------------------------------------------------------------ */
   6929 ipftuneable_t *
   6930 ipf_tune_array_copy(void *base, size_t size, const ipftuneable_t *template)
   6931 {
   6932 	ipftuneable_t *copy;
   6933 	int i;
   6934 
   6935 
   6936 	KMALLOCS(copy, ipftuneable_t *, size);
   6937 	if (copy == NULL) {
   6938 		return NULL;
   6939 	}
   6940 	bcopy(template, copy, size);
   6941 
   6942 	for (i = 0; copy[i].ipft_name; i++) {
   6943 		copy[i].ipft_una.ipftp_offset += (u_long)base;
   6944 		copy[i].ipft_next = copy + i + 1;
   6945 	}
   6946 
   6947 	return copy;
   6948 }
   6949 
   6950 
   6951 /* ------------------------------------------------------------------------ */
   6952 /* Function:    ipf_tune_add                                                */
   6953 /* Returns:     int - 0 == success, else failure                            */
   6954 /* Parameters:  newtune - pointer to new tune entry to add to tuneables     */
   6955 /*                                                                          */
   6956 /* Appends tune structures from the array passed in (newtune) to the end of */
   6957 /* the current list of "dynamic" tuneable parameters.  Once added, the      */
   6958 /* owner of the object is not expected to ever change "ipft_next".          */
   6959 /* ------------------------------------------------------------------------ */
   6960 int
   6961 ipf_tune_add(ipf_main_softc_t *softc, ipftuneable_t *newtune)
   6962 {
   6963 	ipftuneable_t *ta, **tap;
   6964 
   6965 	ta = ipf_tune_findbyname(softc->ipf_tuners, newtune->ipft_name);
   6966 	if (ta != NULL) {
   6967 		IPFERROR(74);
   6968 		return EEXIST;
   6969 	}
   6970 
   6971 	for (tap = &softc->ipf_tuners; *tap != NULL; tap = &(*tap)->ipft_next)
   6972 		;
   6973 
   6974 	newtune->ipft_next = NULL;
   6975 	*tap = newtune;
   6976 	return 0;
   6977 }
   6978 
   6979 
   6980 /* ------------------------------------------------------------------------ */
   6981 /* Function:    ipf_tune_del                                                */
   6982 /* Returns:     int - 0 == success, else failure                            */
   6983 /* Parameters:  oldtune - pointer to tune entry to remove from the list of  */
   6984 /*                        current dynamic tuneables                         */
   6985 /*                                                                          */
   6986 /* Search for the tune structure, by pointer, in the list of those that are */
   6987 /* dynamically added at run time.  If found, adjust the list so that this   */
   6988 /* structure is no longer part of it.                                       */
   6989 /* ------------------------------------------------------------------------ */
   6990 int
   6991 ipf_tune_del(ipf_main_softc_t *softc, ipftuneable_t *oldtune)
   6992 {
   6993 	ipftuneable_t *ta, **tap;
   6994 	int error = 0;
   6995 
   6996 	for (tap = &softc->ipf_tuners; (ta = *tap) != NULL;
   6997 	     tap = &ta->ipft_next) {
   6998 		if (ta == oldtune) {
   6999 			*tap = oldtune->ipft_next;
   7000 			oldtune->ipft_next = NULL;
   7001 			break;
   7002 		}
   7003 	}
   7004 
   7005 	if (ta == NULL) {
   7006 		error = ESRCH;
   7007 		IPFERROR(75);
   7008 	}
   7009 	return error;
   7010 }
   7011 
   7012 
   7013 /* ------------------------------------------------------------------------ */
   7014 /* Function:    ipf_tune_del_array                                          */
   7015 /* Returns:     int - 0 == success, else failure                            */
   7016 /* Parameters:  oldtune - pointer to tuneables array                        */
   7017 /*                                                                          */
   7018 /* Remove each tuneable entry in the array from the list of "dynamic"       */
   7019 /* tunables.  If one entry should fail to be found, an error will be        */
   7020 /* returned and no further ones removed.                                    */
   7021 /* An entry with a NULL name is used as the indicator of the last entry in  */
   7022 /* the array.                                                               */
   7023 /* ------------------------------------------------------------------------ */
   7024 int
   7025 ipf_tune_del_array(ipf_main_softc_t *softc, ipftuneable_t *oldtune)
   7026 {
   7027 	ipftuneable_t *ot;
   7028 	int error = 0;
   7029 
   7030 	for (ot = oldtune; ot->ipft_name != NULL; ot++) {
   7031 		error = ipf_tune_del(softc, ot);
   7032 		if (error != 0)
   7033 			break;
   7034 	}
   7035 
   7036 	return error;
   7037 
   7038 }
   7039 
   7040 
   7041 /* ------------------------------------------------------------------------ */
   7042 /* Function:    ipf_tune                                                    */
   7043 /* Returns:     int - 0 == success, else failure                            */
   7044 /* Parameters:  cmd(I)  - ioctl command number                              */
   7045 /*              data(I) - pointer to ioctl data structure                   */
   7046 /*                                                                          */
   7047 /* Implement handling of SIOCIPFGETNEXT, SIOCIPFGET and SIOCIPFSET.  These  */
   7048 /* three ioctls provide the means to access and control global variables    */
   7049 /* within IPFilter, allowing (for example) timeouts and table sizes to be   */
   7050 /* changed without rebooting, reloading or recompiling.  The initialisation */
   7051 /* and 'destruction' routines of the various components of ipfilter are all */
   7052 /* each responsible for handling their own values being too big.            */
   7053 /* ------------------------------------------------------------------------ */
   7054 int
   7055 ipf_ipftune(ipf_main_softc_t *softc, ioctlcmd_t cmd, void *data)
   7056 {
   7057 	ipftuneable_t *ta;
   7058 	ipftune_t tu;
   7059 	void *cookie;
   7060 	int error;
   7061 
   7062 	error = ipf_inobj(softc, data, NULL, &tu, IPFOBJ_TUNEABLE);
   7063 	if (error != 0)
   7064 		return error;
   7065 
   7066 	tu.ipft_name[sizeof(tu.ipft_name) - 1] = '\0';
   7067 	cookie = tu.ipft_cookie;
   7068 	ta = NULL;
   7069 
   7070 	switch (cmd)
   7071 	{
   7072 	case SIOCIPFGETNEXT :
   7073 		/*
   7074 		 * If cookie is non-NULL, assume it to be a pointer to the last
   7075 		 * entry we looked at, so find it (if possible) and return a
   7076 		 * pointer to the next one after it.  The last entry in the
   7077 		 * the table is a NULL entry, so when we get to it, set cookie
   7078 		 * to NULL and return that, indicating end of list, erstwhile
   7079 		 * if we come in with cookie set to NULL, we are starting anew
   7080 		 * at the front of the list.
   7081 		 */
   7082 		if (cookie != NULL) {
   7083 			ta = ipf_tune_findbycookie(&softc->ipf_tuners,
   7084 						   cookie, &tu.ipft_cookie);
   7085 		} else {
   7086 			ta = softc->ipf_tuners;
   7087 			tu.ipft_cookie = ta + 1;
   7088 		}
   7089 		if (ta != NULL) {
   7090 			/*
   7091 			 * Entry found, but does the data pointed to by that
   7092 			 * row fit in what we can return?
   7093 			 */
   7094 			if (ta->ipft_sz > sizeof(tu.ipft_un)) {
   7095 				IPFERROR(76);
   7096 				return EINVAL;
   7097 			}
   7098 
   7099 			tu.ipft_vlong = 0;
   7100 			if (ta->ipft_sz == sizeof(u_long))
   7101 				tu.ipft_vlong = *ta->ipft_plong;
   7102 			else if (ta->ipft_sz == sizeof(u_int))
   7103 				tu.ipft_vint = *ta->ipft_pint;
   7104 			else if (ta->ipft_sz == sizeof(u_short))
   7105 				tu.ipft_vshort = *ta->ipft_pshort;
   7106 			else if (ta->ipft_sz == sizeof(u_char))
   7107 				tu.ipft_vchar = *ta->ipft_pchar;
   7108 
   7109 			tu.ipft_sz = ta->ipft_sz;
   7110 			tu.ipft_min = ta->ipft_min;
   7111 			tu.ipft_max = ta->ipft_max;
   7112 			tu.ipft_flags = ta->ipft_flags;
   7113 			bcopy(ta->ipft_name, tu.ipft_name,
   7114 			      MIN(sizeof(tu.ipft_name),
   7115 				  strlen(ta->ipft_name) + 1));
   7116 		}
   7117 		error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
   7118 		break;
   7119 
   7120 	case SIOCIPFGET :
   7121 	case SIOCIPFSET :
   7122 		/*
   7123 		 * Search by name or by cookie value for a particular entry
   7124 		 * in the tuning paramter table.
   7125 		 */
   7126 		IPFERROR(77);
   7127 		error = ESRCH;
   7128 		if (cookie != NULL) {
   7129 			ta = ipf_tune_findbycookie(&softc->ipf_tuners,
   7130 						   cookie, NULL);
   7131 			if (ta != NULL)
   7132 				error = 0;
   7133 		} else if (tu.ipft_name[0] != '\0') {
   7134 			ta = ipf_tune_findbyname(softc->ipf_tuners,
   7135 						 tu.ipft_name);
   7136 			if (ta != NULL)
   7137 				error = 0;
   7138 		}
   7139 		if (error != 0)
   7140 			break;
   7141 
   7142 		if (cmd == (ioctlcmd_t)SIOCIPFGET) {
   7143 			/*
   7144 			 * Fetch the tuning parameters for a particular value
   7145 			 */
   7146 			tu.ipft_vlong = 0;
   7147 			if (ta->ipft_sz == sizeof(u_long))
   7148 				tu.ipft_vlong = *ta->ipft_plong;
   7149 			else if (ta->ipft_sz == sizeof(u_int))
   7150 				tu.ipft_vint = *ta->ipft_pint;
   7151 			else if (ta->ipft_sz == sizeof(u_short))
   7152 				tu.ipft_vshort = *ta->ipft_pshort;
   7153 			else if (ta->ipft_sz == sizeof(u_char))
   7154 				tu.ipft_vchar = *ta->ipft_pchar;
   7155 			tu.ipft_cookie = ta;
   7156 			tu.ipft_sz = ta->ipft_sz;
   7157 			tu.ipft_min = ta->ipft_min;
   7158 			tu.ipft_max = ta->ipft_max;
   7159 			tu.ipft_flags = ta->ipft_flags;
   7160 			error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
   7161 
   7162 		} else if (cmd == (ioctlcmd_t)SIOCIPFSET) {
   7163 			/*
   7164 			 * Set an internal parameter.  The hard part here is
   7165 			 * getting the new value safely and correctly out of
   7166 			 * the kernel (given we only know its size, not type.)
   7167 			 */
   7168 			u_long in;
   7169 
   7170 			if (((ta->ipft_flags & IPFT_WRDISABLED) != 0) &&
   7171 			    (softc->ipf_running > 0)) {
   7172 				IPFERROR(78);
   7173 				error = EBUSY;
   7174 				break;
   7175 			}
   7176 
   7177 			in = tu.ipft_vlong;
   7178 			if (in < ta->ipft_min || in > ta->ipft_max) {
   7179 				IPFERROR(79);
   7180 				error = EINVAL;
   7181 				break;
   7182 			}
   7183 
   7184 			if (ta->ipft_func != NULL) {
   7185 				SPL_INT(s);
   7186 
   7187 				SPL_NET(s);
   7188 				error = (*ta->ipft_func)(softc, ta,
   7189 							 &tu.ipft_un);
   7190 				SPL_X(s);
   7191 
   7192 			} else if (ta->ipft_sz == sizeof(u_long)) {
   7193 				tu.ipft_vlong = *ta->ipft_plong;
   7194 				*ta->ipft_plong = in;
   7195 
   7196 			} else if (ta->ipft_sz == sizeof(u_int)) {
   7197 				tu.ipft_vint = *ta->ipft_pint;
   7198 				*ta->ipft_pint = (u_int)(in & 0xffffffff);
   7199 
   7200 			} else if (ta->ipft_sz == sizeof(u_short)) {
   7201 				tu.ipft_vshort = *ta->ipft_pshort;
   7202 				*ta->ipft_pshort = (u_short)(in & 0xffff);
   7203 
   7204 			} else if (ta->ipft_sz == sizeof(u_char)) {
   7205 				tu.ipft_vchar = *ta->ipft_pchar;
   7206 				*ta->ipft_pchar = (u_char)(in & 0xff);
   7207 			}
   7208 			error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
   7209 		}
   7210 		break;
   7211 
   7212 	default :
   7213 		IPFERROR(80);
   7214 		error = EINVAL;
   7215 		break;
   7216 	}
   7217 
   7218 	return error;
   7219 }
   7220 
   7221 
   7222 /* ------------------------------------------------------------------------ */
   7223 /* Function:    ipf_zerostats                                               */
   7224 /* Returns:     int - 0 = success, else failure                             */
   7225 /* Parameters:  data(O) - pointer to pointer for copying data back to       */
   7226 /*                                                                          */
   7227 /* Copies the current statistics out to userspace and then zero's the       */
   7228 /* current ones in the kernel. The lock is only held across the bzero() as  */
   7229 /* the copyout may result in paging (ie network activity.)                  */
   7230 /* ------------------------------------------------------------------------ */
   7231 int
   7232 ipf_zerostats(ipf_main_softc_t *softc, void *data)
   7233 {
   7234 	friostat_t fio;
   7235 	ipfobj_t obj;
   7236 	int error;
   7237 
   7238 	error = ipf_inobj(softc, data, &obj, &fio, IPFOBJ_IPFSTAT);
   7239 	if (error != 0)
   7240 		return error;
   7241 	ipf_getstat(softc, &fio, obj.ipfo_rev);
   7242 	error = ipf_outobj(softc, data, &fio, IPFOBJ_IPFSTAT);
   7243 	if (error != 0)
   7244 		return error;
   7245 
   7246 	WRITE_ENTER(&softc->ipf_mutex);
   7247 	bzero(&softc->ipf_stats, sizeof(softc->ipf_stats));
   7248 	RWLOCK_EXIT(&softc->ipf_mutex);
   7249 
   7250 	return 0;
   7251 }
   7252 
   7253 
   7254 /* ------------------------------------------------------------------------ */
   7255 /* Function:    ipf_resolvedest                                             */
   7256 /* Returns:     Nil                                                         */
   7257 /* Parameters:  softc(I) - pointer to soft context main structure           */
   7258 /*              base(I)  - where strings are stored                         */
   7259 /*              fdp(IO)  - pointer to destination information to resolve    */
   7260 /*              v(I)     - IP protocol version to match                     */
   7261 /*                                                                          */
   7262 /* Looks up an interface name in the frdest structure pointed to by fdp and */
   7263 /* if a matching name can be found for the particular IP protocol version   */
   7264 /* then store the interface pointer in the frdest struct.  If no match is   */
   7265 /* found, then set the interface pointer to be -1 as NULL is considered to  */
   7266 /* indicate there is no information at all in the structure.                */
   7267 /* ------------------------------------------------------------------------ */
   7268 int
   7269 ipf_resolvedest(ipf_main_softc_t *softc, char *base, frdest_t *fdp, int v)
   7270 {
   7271 	int errval = 0;
   7272 	void *ifp;
   7273 
   7274 	ifp = NULL;
   7275 
   7276 	if (fdp->fd_name != -1) {
   7277 		if (fdp->fd_type == FRD_DSTLIST) {
   7278 			ifp = ipf_lookup_res_name(softc, IPL_LOGIPF,
   7279 						  IPLT_DSTLIST,
   7280 						  base + fdp->fd_name,
   7281 						  NULL);
   7282 			if (ifp == NULL) {
   7283 				IPFERROR(144);
   7284 				errval = ESRCH;
   7285 			}
   7286 		} else {
   7287 			ifp = GETIFP(base + fdp->fd_name, v);
   7288 			if (ifp == NULL)
   7289 				ifp = (void *)-1;
   7290 			if ((ifp != NULL) && (ifp != (void *)-1))
   7291 				fdp->fd_local = ipf_deliverlocal(softc, v, ifp,
   7292 								 &fdp->fd_ip6);
   7293 		}
   7294 	}
   7295 	fdp->fd_ptr = ifp;
   7296 
   7297 	return errval;
   7298 }
   7299 
   7300 
   7301 /* ------------------------------------------------------------------------ */
   7302 /* Function:    ipf_resolvenic                                              */
   7303 /* Returns:     void* - NULL = wildcard name, -1 = failed to find NIC, else */
   7304 /*                      pointer to interface structure for NIC              */
   7305 /* Parameters:  softc(I)- pointer to soft context main structure            */
   7306 /*              name(I) - complete interface name                           */
   7307 /*              v(I)    - IP protocol version                               */
   7308 /*                                                                          */
   7309 /* Look for a network interface structure that firstly has a matching name  */
   7310 /* to that passed in and that is also being used for that IP protocol       */
   7311 /* version (necessary on some platforms where there are separate listings   */
   7312 /* for both IPv4 and IPv6 on the same physical NIC.                         */
   7313 /*                                                                          */
   7314 /* ------------------------------------------------------------------------ */
   7315 void *
   7316 ipf_resolvenic(ipf_main_softc_t *softc, char *name, int v)
   7317 {
   7318 	void *nic;
   7319 
   7320 	softc = softc;	/* gcc -Wextra */
   7321 	if (name[0] == '\0')
   7322 		return NULL;
   7323 
   7324 	if ((name[1] == '\0') && ((name[0] == '-') || (name[0] == '*'))) {
   7325 		return NULL;
   7326 	}
   7327 
   7328 	nic = GETIFP(name, v);
   7329 	if (nic == NULL)
   7330 		nic = (void *)-1;
   7331 	return nic;
   7332 }
   7333 
   7334 
   7335 /* ------------------------------------------------------------------------ */
   7336 /* Function:    ipf_token_expire                                            */
   7337 /* Returns:     None.                                                       */
   7338 /* Parameters:  softc(I) - pointer to soft context main structure           */
   7339 /*                                                                          */
   7340 /* This function is run every ipf tick to see if there are any tokens that  */
   7341 /* have been held for too long and need to be freed up.                     */
   7342 /* ------------------------------------------------------------------------ */
   7343 void
   7344 ipf_token_expire(ipf_main_softc_t *softc)
   7345 {
   7346 	ipftoken_t *it;
   7347 
   7348 	WRITE_ENTER(&softc->ipf_tokens);
   7349 	while ((it = softc->ipf_token_head) != NULL) {
   7350 		if (it->ipt_die > softc->ipf_ticks)
   7351 			break;
   7352 
   7353 		ipf_token_deref(softc, it);
   7354 	}
   7355 	RWLOCK_EXIT(&softc->ipf_tokens);
   7356 }
   7357 
   7358 
   7359 /* ------------------------------------------------------------------------ */
   7360 /* Function:    ipf_token_flush                                             */
   7361 /* Returns:     None.                                                       */
   7362 /* Parameters:  softc(I) - pointer to soft context main structure           */
   7363 /*                                                                          */
   7364 /* Loop through all of the existing tokens and call deref to see if they    */
   7365 /* can be freed. Normally a function like this might just loop on           */
   7366 /* ipf_token_head but there is a chance that a token might have a ref count */
   7367 /* of greater than one and in that case the the reference would drop twice  */
   7368 /* by code that is only entitled to drop it once.                           */
   7369 /* ------------------------------------------------------------------------ */
   7370 static void
   7371 ipf_token_flush(ipf_main_softc_t *softc)
   7372 {
   7373 	ipftoken_t *it, *next;
   7374 
   7375 	WRITE_ENTER(&softc->ipf_tokens);
   7376 	for (it = softc->ipf_token_head; it != NULL; it = next) {
   7377 		next = it->ipt_next;
   7378 		(void) ipf_token_deref(softc, it);
   7379 	}
   7380 	RWLOCK_EXIT(&softc->ipf_tokens);
   7381 }
   7382 
   7383 
   7384 /* ------------------------------------------------------------------------ */
   7385 /* Function:    ipf_token_del                                               */
   7386 /* Returns:     int     - 0 = success, else error                           */
   7387 /* Parameters:  softc(I)- pointer to soft context main structure            */
   7388 /*              type(I) - the token type to match                           */
   7389 /*              uid(I)  - uid owning the token                              */
   7390 /*              ptr(I)  - context pointer for the token                     */
   7391 /*                                                                          */
   7392 /* This function looks for a a token in the current list that matches up    */
   7393 /* the fields (type, uid, ptr).  If none is found, ESRCH is returned, else  */
   7394 /* call ipf_token_dewref() to remove it from the list. In the event that    */
   7395 /* the token has a reference held elsewhere, setting ipt_complete to 2      */
   7396 /* enables debugging to distinguish between the two paths that ultimately   */
   7397 /* lead to a token to be deleted.                                           */
   7398 /* ------------------------------------------------------------------------ */
   7399 int
   7400 ipf_token_del(ipf_main_softc_t *softc, int type, int uid, void *ptr)
   7401 {
   7402 	ipftoken_t *it;
   7403 	int error;
   7404 
   7405 	IPFERROR(82);
   7406 	error = ESRCH;
   7407 
   7408 	WRITE_ENTER(&softc->ipf_tokens);
   7409 	for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
   7410 		if (ptr == it->ipt_ctx && type == it->ipt_type &&
   7411 		    uid == it->ipt_uid) {
   7412 			it->ipt_complete = 2;
   7413 			ipf_token_deref(softc, it);
   7414 			error = 0;
   7415 			break;
   7416 		}
   7417 	}
   7418 	RWLOCK_EXIT(&softc->ipf_tokens);
   7419 
   7420 	return error;
   7421 }
   7422 
   7423 
   7424 /* ------------------------------------------------------------------------ */
   7425 /* Function:    ipf_token_mark_complete                                     */
   7426 /* Returns:     None.                                                       */
   7427 /* Parameters:  token(I) - pointer to token structure                       */
   7428 /*                                                                          */
   7429 /* Mark a token as being ineligable for being found with ipf_token_find.    */
   7430 /* ------------------------------------------------------------------------ */
   7431 void
   7432 ipf_token_mark_complete(ipftoken_t *token)
   7433 {
   7434 	if (token->ipt_complete == 0)
   7435 		token->ipt_complete = 1;
   7436 }
   7437 
   7438 
   7439 /* ------------------------------------------------------------------------ */
   7440 /* Function:    ipf_token_find                                               */
   7441 /* Returns:     ipftoken_t * - NULL if no memory, else pointer to token     */
   7442 /* Parameters:  softc(I)- pointer to soft context main structure            */
   7443 /*              type(I) - the token type to match                           */
   7444 /*              uid(I)  - uid owning the token                              */
   7445 /*              ptr(I)  - context pointer for the token                     */
   7446 /*                                                                          */
   7447 /* This function looks for a live token in the list of current tokens that  */
   7448 /* matches the tuple (type, uid, ptr).  If one cannot be found then one is  */
   7449 /* allocated.  If one is found then it is moved to the top of the list of   */
   7450 /* currently active tokens.                                                 */
   7451 /* ------------------------------------------------------------------------ */
   7452 ipftoken_t *
   7453 ipf_token_find(ipf_main_softc_t *softc, int type, int uid, void *ptr)
   7454 {
   7455 	ipftoken_t *it, *new;
   7456 
   7457 	KMALLOC(new, ipftoken_t *);
   7458 	if (new != NULL)
   7459 		bzero((char *)new, sizeof(*new));
   7460 
   7461 	WRITE_ENTER(&softc->ipf_tokens);
   7462 	for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
   7463 		if ((ptr == it->ipt_ctx) && (type == it->ipt_type) &&
   7464 		    (uid == it->ipt_uid) && (it->ipt_complete < 2))
   7465 			break;
   7466 	}
   7467 
   7468 	if (it == NULL) {
   7469 		it = new;
   7470 		new = NULL;
   7471 		if (it == NULL) {
   7472 			RWLOCK_EXIT(&softc->ipf_tokens);
   7473 			return NULL;
   7474 		}
   7475 		it->ipt_ctx = ptr;
   7476 		it->ipt_uid = uid;
   7477 		it->ipt_type = type;
   7478 		it->ipt_ref = 1;
   7479 	} else {
   7480 		if (new != NULL) {
   7481 			KFREE(new);
   7482 			new = NULL;
   7483 		}
   7484 
   7485 		if (it->ipt_complete > 0)
   7486 			it = NULL;
   7487 		else
   7488 			ipf_token_unlink(softc, it);
   7489 	}
   7490 
   7491 	if (it != NULL) {
   7492 		it->ipt_pnext = softc->ipf_token_tail;
   7493 		*softc->ipf_token_tail = it;
   7494 		softc->ipf_token_tail = &it->ipt_next;
   7495 		it->ipt_next = NULL;
   7496 		it->ipt_ref++;
   7497 
   7498 		it->ipt_die = softc->ipf_ticks + 20;
   7499 	}
   7500 
   7501 	RWLOCK_EXIT(&softc->ipf_tokens);
   7502 
   7503 	return it;
   7504 }
   7505 
   7506 
   7507 /* ------------------------------------------------------------------------ */
   7508 /* Function:    ipf_token_unlink                                            */
   7509 /* Returns:     None.                                                       */
   7510 /* Parameters:  softc(I) - pointer to soft context main structure           */
   7511 /*              token(I) - pointer to token structure                       */
   7512 /* Write Locks: ipf_tokens                                                  */
   7513 /*                                                                          */
   7514 /* This function unlinks a token structure from the linked list of tokens   */
   7515 /* that "own" it.  The head pointer never needs to be explicitly adjusted   */
   7516 /* but the tail does due to the linked list implementation.                 */
   7517 /* ------------------------------------------------------------------------ */
   7518 static void
   7519 ipf_token_unlink(ipf_main_softc_t *softc, ipftoken_t *token)
   7520 {
   7521 
   7522 	if (softc->ipf_token_tail == &token->ipt_next)
   7523 		softc->ipf_token_tail = token->ipt_pnext;
   7524 
   7525 	*token->ipt_pnext = token->ipt_next;
   7526 	if (token->ipt_next != NULL)
   7527 		token->ipt_next->ipt_pnext = token->ipt_pnext;
   7528 	token->ipt_next = NULL;
   7529 	token->ipt_pnext = NULL;
   7530 }
   7531 
   7532 
   7533 /* ------------------------------------------------------------------------ */
   7534 /* Function:    ipf_token_deref                                             */
   7535 /* Returns:     int      - 0 == token freed, else reference count           */
   7536 /* Parameters:  softc(I) - pointer to soft context main structure           */
   7537 /*              token(I) - pointer to token structure                       */
   7538 /* Write Locks: ipf_tokens                                                  */
   7539 /*                                                                          */
   7540 /* Drop the reference count on the token structure and if it drops to zero, */
   7541 /* call the dereference function for the token type because it is then      */
   7542 /* possible to free the token data structure.                               */
   7543 /* ------------------------------------------------------------------------ */
   7544 int
   7545 ipf_token_deref(ipf_main_softc_t *softc, ipftoken_t *token)
   7546 {
   7547 	void *data, **datap;
   7548 
   7549 	ASSERT(token->ipt_ref > 0);
   7550 	token->ipt_ref--;
   7551 	if (token->ipt_ref > 0)
   7552 		return token->ipt_ref;
   7553 
   7554 	data = token->ipt_data;
   7555 	datap = &data;
   7556 
   7557 	if ((data != NULL) && (data != (void *)-1)) {
   7558 		switch (token->ipt_type)
   7559 		{
   7560 		case IPFGENITER_IPF :
   7561 			(void) ipf_derefrule(softc, (frentry_t **)datap);
   7562 			break;
   7563 		case IPFGENITER_IPNAT :
   7564 			WRITE_ENTER(&softc->ipf_nat);
   7565 			ipf_nat_rule_deref(softc, (ipnat_t **)datap);
   7566 			RWLOCK_EXIT(&softc->ipf_nat);
   7567 			break;
   7568 		case IPFGENITER_NAT :
   7569 			ipf_nat_deref(softc, (nat_t **)datap);
   7570 			break;
   7571 		case IPFGENITER_STATE :
   7572 			ipf_state_deref(softc, (ipstate_t **)datap);
   7573 			break;
   7574 		case IPFGENITER_FRAG :
   7575 			ipf_frag_pkt_deref(softc, (ipfr_t **)datap);
   7576 			break;
   7577 		case IPFGENITER_NATFRAG :
   7578 			ipf_frag_nat_deref(softc, (ipfr_t **)datap);
   7579 			break;
   7580 		case IPFGENITER_HOSTMAP :
   7581 			WRITE_ENTER(&softc->ipf_nat);
   7582 			ipf_nat_hostmapdel(softc, (hostmap_t **)datap);
   7583 			RWLOCK_EXIT(&softc->ipf_nat);
   7584 			break;
   7585 		default :
   7586 			ipf_lookup_iterderef(softc, token->ipt_type, data);
   7587 			break;
   7588 		}
   7589 	}
   7590 
   7591 	ipf_token_unlink(softc, token);
   7592 	KFREE(token);
   7593 	return 0;
   7594 }
   7595 
   7596 
   7597 /* ------------------------------------------------------------------------ */
   7598 /* Function:    ipf_nextrule                                                */
   7599 /* Returns:     frentry_t * - NULL == no more rules, else pointer to next   */
   7600 /* Parameters:  softc(I)    - pointer to soft context main structure        */
   7601 /*              fr(I)       - pointer to filter rule                        */
   7602 /*              out(I)      - 1 == out rules, 0 == input rules              */
   7603 /*                                                                          */
   7604 /* Starting with "fr", find the next rule to visit. This includes visiting  */
   7605 /* the list of rule groups if either fr is NULL (empty list) or it is the   */
   7606 /* last rule in the list. When walking rule lists, it is either input or    */
   7607 /* output rules that are returned, never both.                              */
   7608 /* ------------------------------------------------------------------------ */
   7609 static frentry_t *
   7610 ipf_nextrule(ipf_main_softc_t *softc, int active, int unit,
   7611     frentry_t *fr, int out)
   7612 {
   7613 	frentry_t *next;
   7614 	frgroup_t *fg;
   7615 
   7616 	if (fr != NULL && fr->fr_group != -1) {
   7617 		fg = ipf_findgroup(softc, fr->fr_names + fr->fr_group,
   7618 				   unit, active, NULL);
   7619 		if (fg != NULL)
   7620 			fg = fg->fg_next;
   7621 	} else {
   7622 		fg = softc->ipf_groups[unit][active];
   7623 	}
   7624 
   7625 	while (fg != NULL) {
   7626 		next = fg->fg_start;
   7627 		while (next != NULL) {
   7628 			if (out) {
   7629 				if (next->fr_flags & FR_OUTQUE)
   7630 					return next;
   7631 			} else if (next->fr_flags & FR_INQUE) {
   7632 				return next;
   7633 			}
   7634 			next = next->fr_next;
   7635 		}
   7636 		if (next == NULL)
   7637 			fg = fg->fg_next;
   7638 	}
   7639 
   7640 	return NULL;
   7641 }
   7642 
   7643 /* ------------------------------------------------------------------------ */
   7644 /* Function:    ipf_getnextrule                                             */
   7645 /* Returns:     int - 0 = success, else error                               */
   7646 /* Parameters:  softc(I)- pointer to soft context main structure            */
   7647 /*              t(I)   - pointer to destination information to resolve      */
   7648 /*              ptr(I) - pointer to ipfobj_t to copyin from user space      */
   7649 /*                                                                          */
   7650 /* This function's first job is to bring in the ipfruleiter_t structure via */
   7651 /* the ipfobj_t structure to determine what should be the next rule to      */
   7652 /* return. Once the ipfruleiter_t has been brought in, it then tries to     */
   7653 /* find the 'next rule'.  This may include searching rule group lists or    */
   7654 /* just be as simple as looking at the 'next' field in the rule structure.  */
   7655 /* When we have found the rule to return, increase its reference count and  */
   7656 /* if we used an existing rule to get here, decrease its reference count.   */
   7657 /* ------------------------------------------------------------------------ */
   7658 int
   7659 ipf_getnextrule(ipf_main_softc_t *softc, ipftoken_t *t, void *ptr)
   7660 {
   7661 	frentry_t *fr, *next, zero;
   7662 	ipfruleiter_t it;
   7663 	int error, out;
   7664 	frgroup_t *fg;
   7665 	ipfobj_t obj;
   7666 	int predict;
   7667 	char *dst;
   7668 	int unit;
   7669 
   7670 	if (t == NULL || ptr == NULL) {
   7671 		IPFERROR(84);
   7672 		return EFAULT;
   7673 	}
   7674 
   7675 	error = ipf_inobj(softc, ptr, &obj, &it, IPFOBJ_IPFITER);
   7676 	if (error != 0)
   7677 		return error;
   7678 
   7679 	if ((it.iri_inout < 0) || (it.iri_inout > 3)) {
   7680 		IPFERROR(85);
   7681 		return EINVAL;
   7682 	}
   7683 	if ((it.iri_active != 0) && (it.iri_active != 1)) {
   7684 		IPFERROR(86);
   7685 		return EINVAL;
   7686 	}
   7687 	if (it.iri_nrules == 0) {
   7688 		IPFERROR(87);
   7689 		return ENOSPC;
   7690 	}
   7691 	if (it.iri_rule == NULL) {
   7692 		IPFERROR(88);
   7693 		return EFAULT;
   7694 	}
   7695 
   7696 	fg = NULL;
   7697 	fr = t->ipt_data;
   7698 	if ((it.iri_inout & F_OUT) != 0)
   7699 		out = 1;
   7700 	else
   7701 		out = 0;
   7702 	if ((it.iri_inout & F_ACIN) != 0)
   7703 		unit = IPL_LOGCOUNT;
   7704 	else
   7705 		unit = IPL_LOGIPF;
   7706 
   7707 	READ_ENTER(&softc->ipf_mutex);
   7708 	if (fr == NULL) {
   7709 		if (*it.iri_group == '\0') {
   7710 			if (unit == IPL_LOGCOUNT) {
   7711 				next = softc->ipf_acct[out][it.iri_active];
   7712 			} else {
   7713 				next = softc->ipf_rules[out][it.iri_active];
   7714 			}
   7715 			if (next == NULL)
   7716 				next = ipf_nextrule(softc, it.iri_active,
   7717 						    unit, NULL, out);
   7718 		} else {
   7719 			fg = ipf_findgroup(softc, it.iri_group, unit,
   7720 					   it.iri_active, NULL);
   7721 			if (fg != NULL)
   7722 				next = fg->fg_start;
   7723 			else
   7724 				next = NULL;
   7725 		}
   7726 	} else {
   7727 		next = fr->fr_next;
   7728 		if (next == NULL)
   7729 			next = ipf_nextrule(softc, it.iri_active, unit,
   7730 					    fr, out);
   7731 	}
   7732 
   7733 	if (next != NULL && next->fr_next != NULL)
   7734 		predict = 1;
   7735 	else if (ipf_nextrule(softc, it.iri_active, unit, next, out) != NULL)
   7736 		predict = 1;
   7737 	else
   7738 		predict = 0;
   7739 
   7740 	if (fr != NULL)
   7741 		(void) ipf_derefrule(softc, &fr);
   7742 
   7743 	obj.ipfo_type = IPFOBJ_FRENTRY;
   7744 	dst = (char *)it.iri_rule;
   7745 
   7746 	if (next != NULL) {
   7747 		obj.ipfo_size = next->fr_size;
   7748 		MUTEX_ENTER(&next->fr_lock);
   7749 		next->fr_ref++;
   7750 		MUTEX_EXIT(&next->fr_lock);
   7751 		t->ipt_data = next;
   7752 	} else {
   7753 		obj.ipfo_size = sizeof(frentry_t);
   7754 		bzero(&zero, sizeof(zero));
   7755 		next = &zero;
   7756 		t->ipt_data = NULL;
   7757 	}
   7758 	it.iri_rule = predict ? next : NULL;
   7759 	if (predict == 0)
   7760 		ipf_token_mark_complete(t);
   7761 
   7762 	RWLOCK_EXIT(&softc->ipf_mutex);
   7763 
   7764 	obj.ipfo_ptr = dst;
   7765 	error = ipf_outobjk(softc, &obj, next);
   7766 	if (error == 0 && t->ipt_data != NULL) {
   7767 		dst += obj.ipfo_size;
   7768 		if (next->fr_data != NULL) {
   7769 			ipfobj_t dobj;
   7770 
   7771 			if (next->fr_type == FR_T_IPFEXPR)
   7772 				dobj.ipfo_type = IPFOBJ_IPFEXPR;
   7773 			else
   7774 				dobj.ipfo_type = IPFOBJ_FRIPF;
   7775 			dobj.ipfo_size = next->fr_dsize;
   7776 			dobj.ipfo_rev = obj.ipfo_rev;
   7777 			dobj.ipfo_ptr = dst;
   7778 			error = ipf_outobjk(softc, &dobj, next->fr_data);
   7779 		}
   7780 	}
   7781 
   7782 	if ((fr != NULL) && (next == &zero))
   7783 		(void) ipf_derefrule(softc, &fr);
   7784 
   7785 	return error;
   7786 }
   7787 
   7788 
   7789 /* ------------------------------------------------------------------------ */
   7790 /* Function:    ipf_frruleiter                                              */
   7791 /* Returns:     int - 0 = success, else error                               */
   7792 /* Parameters:  softc(I)- pointer to soft context main structure            */
   7793 /*              data(I) - the token type to match                           */
   7794 /*              uid(I)  - uid owning the token                              */
   7795 /*              ptr(I)  - context pointer for the token                     */
   7796 /*                                                                          */
   7797 /* This function serves as a stepping stone between ipf_ipf_ioctl and       */
   7798 /* ipf_getnextrule.  It's role is to find the right token in the kernel for */
   7799 /* the process doing the ioctl and use that to ask for the next rule.       */
   7800 /* ------------------------------------------------------------------------ */
   7801 static int
   7802 ipf_frruleiter(ipf_main_softc_t *softc, void *data, int uid, void *ctx)
   7803 {
   7804 	ipftoken_t *token;
   7805 	ipfruleiter_t it;
   7806 	ipfobj_t obj;
   7807 	int error;
   7808 
   7809 	token = ipf_token_find(softc, IPFGENITER_IPF, uid, ctx);
   7810 	if (token != NULL) {
   7811 		error = ipf_getnextrule(softc, token, data);
   7812 		WRITE_ENTER(&softc->ipf_tokens);
   7813 		ipf_token_deref(softc, token);
   7814 		RWLOCK_EXIT(&softc->ipf_tokens);
   7815 	} else {
   7816 		error = ipf_inobj(softc, data, &obj, &it, IPFOBJ_IPFITER);
   7817 		if (error != 0)
   7818 			return error;
   7819 		it.iri_rule = NULL;
   7820 		error = ipf_outobj(softc, data, &it, IPFOBJ_IPFITER);
   7821 	}
   7822 
   7823 	return error;
   7824 }
   7825 
   7826 
   7827 /* ------------------------------------------------------------------------ */
   7828 /* Function:    ipf_geniter                                                 */
   7829 /* Returns:     int - 0 = success, else error                               */
   7830 /* Parameters:  softc(I) - pointer to soft context main structure           */
   7831 /*              token(I) - pointer to ipftoken_t structure                  */
   7832 /*              itp(I)   - pointer to iterator data                         */
   7833 /*                                                                          */
   7834 /* Decide which iterator function to call using information passed through  */
   7835 /* the ipfgeniter_t structure at itp.                                       */
   7836 /* ------------------------------------------------------------------------ */
   7837 static int
   7838 ipf_geniter(ipf_main_softc_t *softc, ipftoken_t *token, ipfgeniter_t *itp)
   7839 {
   7840 	int error;
   7841 
   7842 	switch (itp->igi_type)
   7843 	{
   7844 	case IPFGENITER_FRAG :
   7845 		error = ipf_frag_pkt_next(softc, token, itp);
   7846 		break;
   7847 	default :
   7848 		IPFERROR(92);
   7849 		error = EINVAL;
   7850 		break;
   7851 	}
   7852 
   7853 	return error;
   7854 }
   7855 
   7856 
   7857 /* ------------------------------------------------------------------------ */
   7858 /* Function:    ipf_genericiter                                             */
   7859 /* Returns:     int - 0 = success, else error                               */
   7860 /* Parameters:  softc(I)- pointer to soft context main structure            */
   7861 /*              data(I) - the token type to match                           */
   7862 /*              uid(I)  - uid owning the token                              */
   7863 /*              ptr(I)  - context pointer for the token                     */
   7864 /*                                                                          */
   7865 /* Handle the SIOCGENITER ioctl for the ipfilter device. The primary role   */
   7866 /* ------------------------------------------------------------------------ */
   7867 int
   7868 ipf_genericiter(ipf_main_softc_t *softc, void *data, int uid, void *ctx)
   7869 {
   7870 	ipftoken_t *token;
   7871 	ipfgeniter_t iter;
   7872 	int error;
   7873 
   7874 	error = ipf_inobj(softc, data, NULL, &iter, IPFOBJ_GENITER);
   7875 	if (error != 0)
   7876 		return error;
   7877 
   7878 	token = ipf_token_find(softc, iter.igi_type, uid, ctx);
   7879 	if (token != NULL) {
   7880 		token->ipt_subtype = iter.igi_type;
   7881 		error = ipf_geniter(softc, token, &iter);
   7882 		WRITE_ENTER(&softc->ipf_tokens);
   7883 		ipf_token_deref(softc, token);
   7884 		RWLOCK_EXIT(&softc->ipf_tokens);
   7885 	} else {
   7886 		IPFERROR(93);
   7887 		error = 0;
   7888 	}
   7889 
   7890 	return error;
   7891 }
   7892 
   7893 
   7894 /* ------------------------------------------------------------------------ */
   7895 /* Function:    ipf_ipf_ioctl                                               */
   7896 /* Returns:     int - 0 = success, else error                               */
   7897 /* Parameters:  softc(I)- pointer to soft context main structure           */
   7898 /*              data(I) - the token type to match                           */
   7899 /*              cmd(I)  - the ioctl command number                          */
   7900 /*              mode(I) - mode flags for the ioctl                          */
   7901 /*              uid(I)  - uid owning the token                              */
   7902 /*              ptr(I)  - context pointer for the token                     */
   7903 /*                                                                          */
   7904 /* This function handles all of the ioctl command that are actually isssued */
   7905 /* to the /dev/ipl device.                                                  */
   7906 /* ------------------------------------------------------------------------ */
   7907 int
   7908 ipf_ipf_ioctl(ipf_main_softc_t *softc, void *data, ioctlcmd_t cmd, int mode,
   7909     int uid, void *ctx)
   7910 {
   7911 	friostat_t fio;
   7912 	int error, tmp;
   7913 	ipfobj_t obj;
   7914 	SPL_INT(s);
   7915 
   7916 	switch (cmd)
   7917 	{
   7918 	case SIOCFRENB :
   7919 		if (!(mode & FWRITE)) {
   7920 			IPFERROR(94);
   7921 			error = EPERM;
   7922 		} else {
   7923 			error = BCOPYIN(data, &tmp, sizeof(tmp));
   7924 			if (error != 0) {
   7925 				IPFERROR(95);
   7926 				error = EFAULT;
   7927 				break;
   7928 			}
   7929 
   7930 			WRITE_ENTER(&softc->ipf_global);
   7931 			if (tmp) {
   7932 				if (softc->ipf_running > 0)
   7933 					error = 0;
   7934 				else
   7935 					error = ipfattach(softc);
   7936 				if (error == 0)
   7937 					softc->ipf_running = 1;
   7938 				else
   7939 					(void) ipfdetach(softc);
   7940 			} else {
   7941 				if (softc->ipf_running == 1)
   7942 					error = ipfdetach(softc);
   7943 				else
   7944 					error = 0;
   7945 				if (error == 0)
   7946 					softc->ipf_running = -1;
   7947 			}
   7948 			RWLOCK_EXIT(&softc->ipf_global);
   7949 		}
   7950 		break;
   7951 
   7952 	case SIOCIPFSET :
   7953 		if (!(mode & FWRITE)) {
   7954 			IPFERROR(96);
   7955 			error = EPERM;
   7956 			break;
   7957 		}
   7958 		/* FALLTHRU */
   7959 	case SIOCIPFGETNEXT :
   7960 	case SIOCIPFGET :
   7961 		error = ipf_ipftune(softc, cmd, (void *)data);
   7962 		break;
   7963 
   7964 	case SIOCSETFF :
   7965 		if (!(mode & FWRITE)) {
   7966 			IPFERROR(97);
   7967 			error = EPERM;
   7968 		} else {
   7969 			error = BCOPYIN(data, &softc->ipf_flags,
   7970 					sizeof(softc->ipf_flags));
   7971 			if (error != 0) {
   7972 				IPFERROR(98);
   7973 				error = EFAULT;
   7974 			}
   7975 		}
   7976 		break;
   7977 
   7978 	case SIOCGETFF :
   7979 		error = BCOPYOUT(&softc->ipf_flags, data,
   7980 				 sizeof(softc->ipf_flags));
   7981 		if (error != 0) {
   7982 			IPFERROR(99);
   7983 			error = EFAULT;
   7984 		}
   7985 		break;
   7986 
   7987 	case SIOCFUNCL :
   7988 		error = ipf_resolvefunc(softc, (void *)data);
   7989 		break;
   7990 
   7991 	case SIOCINAFR :
   7992 	case SIOCRMAFR :
   7993 	case SIOCADAFR :
   7994 	case SIOCZRLST :
   7995 		if (!(mode & FWRITE)) {
   7996 			IPFERROR(100);
   7997 			error = EPERM;
   7998 		} else {
   7999 			error = frrequest(softc, IPL_LOGIPF, cmd, data,
   8000 					  softc->ipf_active, 1);
   8001 		}
   8002 		break;
   8003 
   8004 	case SIOCINIFR :
   8005 	case SIOCRMIFR :
   8006 	case SIOCADIFR :
   8007 		if (!(mode & FWRITE)) {
   8008 			IPFERROR(101);
   8009 			error = EPERM;
   8010 		} else {
   8011 			error = frrequest(softc, IPL_LOGIPF, cmd, data,
   8012 					  1 - softc->ipf_active, 1);
   8013 		}
   8014 		break;
   8015 
   8016 	case SIOCSWAPA :
   8017 		if (!(mode & FWRITE)) {
   8018 			IPFERROR(102);
   8019 			error = EPERM;
   8020 		} else {
   8021 			WRITE_ENTER(&softc->ipf_mutex);
   8022 			error = BCOPYOUT(&softc->ipf_active, data,
   8023 					 sizeof(softc->ipf_active));
   8024 			if (error != 0) {
   8025 				IPFERROR(103);
   8026 				error = EFAULT;
   8027 			} else {
   8028 				softc->ipf_active = 1 - softc->ipf_active;
   8029 			}
   8030 			RWLOCK_EXIT(&softc->ipf_mutex);
   8031 		}
   8032 		break;
   8033 
   8034 	case SIOCGETFS :
   8035 		error = ipf_inobj(softc, (void *)data, &obj, &fio,
   8036 				  IPFOBJ_IPFSTAT);
   8037 		if (error != 0)
   8038 			break;
   8039 		ipf_getstat(softc, &fio, obj.ipfo_rev);
   8040 		error = ipf_outobj(softc, (void *)data, &fio, IPFOBJ_IPFSTAT);
   8041 		break;
   8042 
   8043 	case SIOCFRZST :
   8044 		if (!(mode & FWRITE)) {
   8045 			IPFERROR(104);
   8046 			error = EPERM;
   8047 		} else
   8048 			error = ipf_zerostats(softc, data);
   8049 		break;
   8050 
   8051 	case SIOCIPFFL :
   8052 		if (!(mode & FWRITE)) {
   8053 			IPFERROR(105);
   8054 			error = EPERM;
   8055 		} else {
   8056 			error = BCOPYIN(data, &tmp, sizeof(tmp));
   8057 			if (!error) {
   8058 				tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
   8059 				error = BCOPYOUT(&tmp, data, sizeof(tmp));
   8060 				if (error != 0) {
   8061 					IPFERROR(106);
   8062 					error = EFAULT;
   8063 				}
   8064 			} else {
   8065 				IPFERROR(107);
   8066 				error = EFAULT;
   8067 			}
   8068 		}
   8069 		break;
   8070 
   8071 #ifdef USE_INET6
   8072 	case SIOCIPFL6 :
   8073 		if (!(mode & FWRITE)) {
   8074 			IPFERROR(108);
   8075 			error = EPERM;
   8076 		} else {
   8077 			error = BCOPYIN(data, &tmp, sizeof(tmp));
   8078 			if (!error) {
   8079 				tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
   8080 				error = BCOPYOUT(&tmp, data, sizeof(tmp));
   8081 				if (error != 0) {
   8082 					IPFERROR(109);
   8083 					error = EFAULT;
   8084 				}
   8085 			} else {
   8086 				IPFERROR(110);
   8087 				error = EFAULT;
   8088 			}
   8089 		}
   8090 		break;
   8091 #endif
   8092 
   8093 	case SIOCSTLCK :
   8094 		if (!(mode & FWRITE)) {
   8095 			IPFERROR(122);
   8096 			error = EPERM;
   8097 		} else {
   8098 			error = BCOPYIN(data, &tmp, sizeof(tmp));
   8099 			if (error == 0) {
   8100 				ipf_state_setlock(softc->ipf_state_soft, tmp);
   8101 				ipf_nat_setlock(softc->ipf_nat_soft, tmp);
   8102 				ipf_frag_setlock(softc->ipf_frag_soft, tmp);
   8103 				ipf_auth_setlock(softc->ipf_auth_soft, tmp);
   8104 			} else {
   8105 				IPFERROR(111);
   8106 				error = EFAULT;
   8107 			}
   8108 		}
   8109 		break;
   8110 
   8111 #ifdef	IPFILTER_LOG
   8112 	case SIOCIPFFB :
   8113 		if (!(mode & FWRITE)) {
   8114 			IPFERROR(112);
   8115 			error = EPERM;
   8116 		} else {
   8117 			tmp = ipf_log_clear(softc, IPL_LOGIPF);
   8118 			error = BCOPYOUT(&tmp, data, sizeof(tmp));
   8119 			if (error) {
   8120 				IPFERROR(113);
   8121 				error = EFAULT;
   8122 			}
   8123 		}
   8124 		break;
   8125 #endif /* IPFILTER_LOG */
   8126 
   8127 	case SIOCFRSYN :
   8128 		if (!(mode & FWRITE)) {
   8129 			IPFERROR(114);
   8130 			error = EPERM;
   8131 		} else {
   8132 			WRITE_ENTER(&softc->ipf_global);
   8133 #if (defined(MENTAT) && defined(_KERNEL)) && !defined(INSTANCES)
   8134 			error = ipfsync();
   8135 #else
   8136 			ipf_sync(softc, NULL);
   8137 			error = 0;
   8138 #endif
   8139 			RWLOCK_EXIT(&softc->ipf_global);
   8140 
   8141 		}
   8142 		break;
   8143 
   8144 	case SIOCGFRST :
   8145 		error = ipf_outobj(softc, (void *)data,
   8146 				   ipf_frag_stats(softc->ipf_frag_soft),
   8147 				   IPFOBJ_FRAGSTAT);
   8148 		break;
   8149 
   8150 #ifdef	IPFILTER_LOG
   8151 	case FIONREAD :
   8152 		tmp = ipf_log_bytesused(softc, IPL_LOGIPF);
   8153 		error = BCOPYOUT(&tmp, data, sizeof(tmp));
   8154 		break;
   8155 #endif
   8156 
   8157 	case SIOCIPFITER :
   8158 		SPL_SCHED(s);
   8159 		error = ipf_frruleiter(softc, data, uid, ctx);
   8160 		SPL_X(s);
   8161 		break;
   8162 
   8163 	case SIOCGENITER :
   8164 		SPL_SCHED(s);
   8165 		error = ipf_genericiter(softc, data, uid, ctx);
   8166 		SPL_X(s);
   8167 		break;
   8168 
   8169 	case SIOCIPFDELTOK :
   8170 		error = BCOPYIN(data, &tmp, sizeof(tmp));
   8171 		if (error == 0) {
   8172 			SPL_SCHED(s);
   8173 			error = ipf_token_del(softc, tmp, uid, ctx);
   8174 			SPL_X(s);
   8175 		}
   8176 		break;
   8177 
   8178 	default :
   8179 		IPFERROR(115);
   8180 		error = EINVAL;
   8181 		break;
   8182 	}
   8183 
   8184 	return error;
   8185 }
   8186 
   8187 
   8188 /* ------------------------------------------------------------------------ */
   8189 /* Function:    ipf_decaps                                                  */
   8190 /* Returns:     int        - -1 == decapsulation failed, else bit mask of   */
   8191 /*                           flags indicating packet filtering decision.    */
   8192 /* Parameters:  fin(I)     - pointer to packet information                  */
   8193 /*              pass(I)    - IP protocol version to match                   */
   8194 /*              l5proto(I) - layer 5 protocol to decode UDP data as.        */
   8195 /*                                                                          */
   8196 /* This function is called for packets that are wrapt up in other packets,  */
   8197 /* for example, an IP packet that is the entire data segment for another IP */
   8198 /* packet.  If the basic constraints for this are satisfied, change the     */
   8199 /* buffer to point to the start of the inner packet and start processing    */
   8200 /* rules belonging to the head group this rule specifies.                   */
   8201 /* ------------------------------------------------------------------------ */
   8202 u_32_t
   8203 ipf_decaps(fr_info_t *fin, u_32_t pass, int l5proto)
   8204 {
   8205 	fr_info_t fin2, *fino = NULL;
   8206 	int elen, hlen, nh;
   8207 	grehdr_t gre;
   8208 	ip_t *ip;
   8209 	mb_t *m;
   8210 
   8211 	if ((fin->fin_flx & FI_COALESCE) == 0)
   8212 		if (ipf_coalesce(fin) == -1)
   8213 			goto cantdecaps;
   8214 
   8215 	m = fin->fin_m;
   8216 	hlen = fin->fin_hlen;
   8217 
   8218 	switch (fin->fin_p)
   8219 	{
   8220 	case IPPROTO_UDP :
   8221 		/*
   8222 		 * In this case, the specific protocol being decapsulated
   8223 		 * inside UDP frames comes from the rule.
   8224 		 */
   8225 		nh = fin->fin_fr->fr_icode;
   8226 		break;
   8227 
   8228 	case IPPROTO_GRE :	/* 47 */
   8229 		bcopy(fin->fin_dp, (char *)&gre, sizeof(gre));
   8230 		hlen += sizeof(grehdr_t);
   8231 		if (gre.gr_R|gre.gr_s)
   8232 			goto cantdecaps;
   8233 		if (gre.gr_C)
   8234 			hlen += 4;
   8235 		if (gre.gr_K)
   8236 			hlen += 4;
   8237 		if (gre.gr_S)
   8238 			hlen += 4;
   8239 
   8240 		nh = IPPROTO_IP;
   8241 
   8242 		/*
   8243 		 * If the routing options flag is set, validate that it is
   8244 		 * there and bounce over it.
   8245 		 */
   8246 #if 0
   8247 		/* This is really heavy weight and lots of room for error, */
   8248 		/* so for now, put it off and get the simple stuff right.  */
   8249 		if (gre.gr_R) {
   8250 			u_char off, len, *s;
   8251 			u_short af;
   8252 			int end;
   8253 
   8254 			end = 0;
   8255 			s = fin->fin_dp;
   8256 			s += hlen;
   8257 			aplen = fin->fin_plen - hlen;
   8258 			while (aplen > 3) {
   8259 				af = (s[0] << 8) | s[1];
   8260 				off = s[2];
   8261 				len = s[3];
   8262 				aplen -= 4;
   8263 				s += 4;
   8264 				if (af == 0 && len == 0) {
   8265 					end = 1;
   8266 					break;
   8267 				}
   8268 				if (aplen < len)
   8269 					break;
   8270 				s += len;
   8271 				aplen -= len;
   8272 			}
   8273 			if (end != 1)
   8274 				goto cantdecaps;
   8275 			hlen = s - (u_char *)fin->fin_dp;
   8276 		}
   8277 #endif
   8278 		break;
   8279 
   8280 #ifdef IPPROTO_IPIP
   8281 	case IPPROTO_IPIP :	/* 4 */
   8282 #endif
   8283 		nh = IPPROTO_IP;
   8284 		break;
   8285 
   8286 	default :	/* Includes ESP, AH is special for IPv4 */
   8287 		goto cantdecaps;
   8288 	}
   8289 
   8290 	switch (nh)
   8291 	{
   8292 	case IPPROTO_IP :
   8293 	case IPPROTO_IPV6 :
   8294 		break;
   8295 	default :
   8296 		goto cantdecaps;
   8297 	}
   8298 
   8299 	bcopy((char *)fin, (char *)&fin2, sizeof(fin2));
   8300 	fino = fin;
   8301 	fin = &fin2;
   8302 	elen = hlen;
   8303 #if defined(MENTAT) && defined(_KERNEL)
   8304 	m->b_rptr += elen;
   8305 #else
   8306 	m->m_data += elen;
   8307 	m->m_len -= elen;
   8308 #endif
   8309 	fin->fin_plen -= elen;
   8310 
   8311 	ip = (ip_t *)((char *)fin->fin_ip + elen);
   8312 
   8313 	/*
   8314 	 * Make sure we have at least enough data for the network layer
   8315 	 * header.
   8316 	 */
   8317 	if (IP_V(ip) == 4)
   8318 		hlen = IP_HL(ip) << 2;
   8319 #ifdef USE_INET6
   8320 	else if (IP_V(ip) == 6)
   8321 		hlen = sizeof(ip6_t);
   8322 #endif
   8323 	else
   8324 		goto cantdecaps2;
   8325 
   8326 	if (fin->fin_plen < hlen)
   8327 		goto cantdecaps2;
   8328 
   8329 	fin->fin_dp = (char *)ip + hlen;
   8330 
   8331 	if (IP_V(ip) == 4) {
   8332 		/*
   8333 		 * Perform IPv4 header checksum validation.
   8334 		 */
   8335 		if (ipf_cksum((u_short *)ip, hlen))
   8336 			goto cantdecaps2;
   8337 	}
   8338 
   8339 	if (ipf_makefrip(hlen, ip, fin) == -1) {
   8340 cantdecaps2:
   8341 		if (m != NULL) {
   8342 #if defined(MENTAT) && defined(_KERNEL)
   8343 			m->b_rptr -= elen;
   8344 #else
   8345 			m->m_data -= elen;
   8346 			m->m_len += elen;
   8347 #endif
   8348 		}
   8349 cantdecaps:
   8350 		DT1(frb_decapfrip, fr_info_t *, fin);
   8351 		pass &= ~FR_CMDMASK;
   8352 		pass |= FR_BLOCK|FR_QUICK;
   8353 		fin->fin_reason = FRB_DECAPFRIP;
   8354 		return -1;
   8355 	}
   8356 
   8357 	pass = ipf_scanlist(fin, pass);
   8358 
   8359 	/*
   8360 	 * Copy the packet filter "result" fields out of the fr_info_t struct
   8361 	 * that is local to the decapsulation processing and back into the
   8362 	 * one we were called with.
   8363 	 */
   8364 	fino->fin_flx = fin->fin_flx;
   8365 	fino->fin_rev = fin->fin_rev;
   8366 	fino->fin_icode = fin->fin_icode;
   8367 	fino->fin_rule = fin->fin_rule;
   8368 	(void) strncpy(fino->fin_group, fin->fin_group, FR_GROUPLEN);
   8369 	fino->fin_fr = fin->fin_fr;
   8370 	fino->fin_error = fin->fin_error;
   8371 	fino->fin_mp = fin->fin_mp;
   8372 	fino->fin_m = fin->fin_m;
   8373 	m = fin->fin_m;
   8374 	if (m != NULL) {
   8375 #if defined(MENTAT) && defined(_KERNEL)
   8376 		m->b_rptr -= elen;
   8377 #else
   8378 		m->m_data -= elen;
   8379 		m->m_len += elen;
   8380 #endif
   8381 	}
   8382 	return pass;
   8383 }
   8384 
   8385 
   8386 /* ------------------------------------------------------------------------ */
   8387 /* Function:    ipf_matcharray_load                                         */
   8388 /* Returns:     int         - 0 = success, else error                       */
   8389 /* Parameters:  softc(I)    - pointer to soft context main structure        */
   8390 /*              data(I)     - pointer to ioctl data                         */
   8391 /*              objp(I)     - ipfobj_t structure to load data into          */
   8392 /*              arrayptr(I) - pointer to location to store array pointer    */
   8393 /*                                                                          */
   8394 /* This function loads in a mathing array through the ipfobj_t struct that  */
   8395 /* describes it.  Sanity checking and array size limitations are enforced   */
   8396 /* in this function to prevent userspace from trying to load in something   */
   8397 /* that is insanely big.  Once the size of the array is known, the memory   */
   8398 /* required is malloc'd and returned through changing *arrayptr.  The       */
   8399 /* contents of the array are verified before returning.  Only in the event  */
   8400 /* of a successful call is the caller required to free up the malloc area.  */
   8401 /* ------------------------------------------------------------------------ */
   8402 int
   8403 ipf_matcharray_load(ipf_main_softc_t *softc, void *data, ipfobj_t *objp,
   8404     int **arrayptr)
   8405 {
   8406 	int arraysize, *array, error;
   8407 
   8408 	*arrayptr = NULL;
   8409 
   8410 	error = BCOPYIN(data, objp, sizeof(*objp));
   8411 	if (error != 0) {
   8412 		IPFERROR(116);
   8413 		return EFAULT;
   8414 	}
   8415 
   8416 	if (objp->ipfo_type != IPFOBJ_IPFEXPR) {
   8417 		IPFERROR(117);
   8418 		return EINVAL;
   8419 	}
   8420 
   8421 	if (((objp->ipfo_size & 3) != 0) || (objp->ipfo_size == 0) ||
   8422 	    (objp->ipfo_size > 1024)) {
   8423 		IPFERROR(118);
   8424 		return EINVAL;
   8425 	}
   8426 
   8427 	arraysize = objp->ipfo_size * sizeof(*array);
   8428 	KMALLOCS(array, int *, arraysize);
   8429 	if (array == NULL) {
   8430 		IPFERROR(119);
   8431 		return ENOMEM;
   8432 	}
   8433 
   8434 	error = COPYIN(objp->ipfo_ptr, array, arraysize);
   8435 	if (error != 0) {
   8436 		KFREES(array, arraysize);
   8437 		IPFERROR(120);
   8438 		return EFAULT;
   8439 	}
   8440 
   8441 	if (ipf_matcharray_verify(array, arraysize) != 0) {
   8442 		KFREES(array, arraysize);
   8443 		IPFERROR(121);
   8444 		return EINVAL;
   8445 	}
   8446 
   8447 	*arrayptr = array;
   8448 	return 0;
   8449 }
   8450 
   8451 
   8452 /* ------------------------------------------------------------------------ */
   8453 /* Function:    ipf_matcharray_verify                                       */
   8454 /* Returns:     Nil                                                         */
   8455 /* Parameters:  array(I)     - pointer to matching array                    */
   8456 /*              arraysize(I) - number of elements in the array              */
   8457 /*                                                                          */
   8458 /* Verify the contents of a matching array by stepping through each element */
   8459 /* in it.  The actual commands in the array are not verified for            */
   8460 /* correctness, only that all of the sizes are correctly within limits.     */
   8461 /* ------------------------------------------------------------------------ */
   8462 int
   8463 ipf_matcharray_verify(int *array, int arraysize)
   8464 {
   8465 	int i, nelem, maxidx;
   8466 	ipfexp_t *e;
   8467 
   8468 	nelem = arraysize / sizeof(*array);
   8469 
   8470 	/*
   8471 	 * Currently, it makes no sense to have an array less than 6
   8472 	 * elements long - the initial size at the from, a single operation
   8473 	 * (minimum 4 in length) and a trailer, for a total of 6.
   8474 	 */
   8475 	if ((array[0] < 6) || (arraysize < 24) || (arraysize > 4096)) {
   8476 		return -1;
   8477 	}
   8478 
   8479 	/*
   8480 	 * Verify the size of data pointed to by array with how long
   8481 	 * the array claims to be itself.
   8482 	 */
   8483 	if (array[0] * sizeof(*array) != arraysize) {
   8484 		return -1;
   8485 	}
   8486 
   8487 	maxidx = nelem - 1;
   8488 	/*
   8489 	 * The last opcode in this array should be an IPF_EXP_END.
   8490 	 */
   8491 	if (array[maxidx] != IPF_EXP_END) {
   8492 		return -1;
   8493 	}
   8494 
   8495 	for (i = 1; i < maxidx; ) {
   8496 		e = (ipfexp_t *)(array + i);
   8497 
   8498 		/*
   8499 		 * The length of the bits to check must be at least 1
   8500 		 * (or else there is nothing to comapre with!) and it
   8501 		 * cannot exceed the length of the data present.
   8502 		 */
   8503 		if ((e->ipfe_size < 1 ) ||
   8504 		    (e->ipfe_size + i > maxidx)) {
   8505 			return -1;
   8506 		}
   8507 		i += e->ipfe_size;
   8508 	}
   8509 	return 0;
   8510 }
   8511 
   8512 
   8513 /* ------------------------------------------------------------------------ */
   8514 /* Function:    ipf_fr_matcharray                                           */
   8515 /* Returns:     int      - 0 = match failed, else positive match            */
   8516 /* Parameters:  fin(I)   - pointer to packet information                    */
   8517 /*              array(I) - pointer to matching array                        */
   8518 /*                                                                          */
   8519 /* This function is used to apply a matching array against a packet and     */
   8520 /* return an indication of whether or not the packet successfully matches   */
   8521 /* all of the commands in it.                                               */
   8522 /* ------------------------------------------------------------------------ */
   8523 static int
   8524 ipf_fr_matcharray(fr_info_t *fin, int *array)
   8525 {
   8526 	int i, n, *x, rv, p;
   8527 	ipfexp_t *e;
   8528 
   8529 	rv = 0;
   8530 	n = array[0];
   8531 	x = array + 1;
   8532 
   8533 	for (; n > 0; x += 3 + x[3], rv = 0) {
   8534 		e = (ipfexp_t *)x;
   8535 		if (e->ipfe_cmd == IPF_EXP_END)
   8536 			break;
   8537 		n -= e->ipfe_size;
   8538 
   8539 		/*
   8540 		 * The upper 16 bits currently store the protocol value.
   8541 		 * This is currently used with TCP and UDP port compares and
   8542 		 * allows "tcp.port = 80" without requiring an explicit
   8543 		 " "ip.pr = tcp" first.
   8544 		 */
   8545 		p = e->ipfe_cmd >> 16;
   8546 		if ((p != 0) && (p != fin->fin_p))
   8547 			break;
   8548 
   8549 		switch (e->ipfe_cmd)
   8550 		{
   8551 		case IPF_EXP_IP_PR :
   8552 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
   8553 				rv |= (fin->fin_p == e->ipfe_arg0[i]);
   8554 			}
   8555 			break;
   8556 
   8557 		case IPF_EXP_IP_SRCADDR :
   8558 			if (fin->fin_v != 4)
   8559 				break;
   8560 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
   8561 				rv |= ((fin->fin_saddr &
   8562 					e->ipfe_arg0[i * 2 + 1]) ==
   8563 				       e->ipfe_arg0[i * 2]);
   8564 			}
   8565 			break;
   8566 
   8567 		case IPF_EXP_IP_DSTADDR :
   8568 			if (fin->fin_v != 4)
   8569 				break;
   8570 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
   8571 				rv |= ((fin->fin_daddr &
   8572 					e->ipfe_arg0[i * 2 + 1]) ==
   8573 				       e->ipfe_arg0[i * 2]);
   8574 			}
   8575 			break;
   8576 
   8577 		case IPF_EXP_IP_ADDR :
   8578 			if (fin->fin_v != 4)
   8579 				break;
   8580 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
   8581 				rv |= ((fin->fin_saddr &
   8582 					e->ipfe_arg0[i * 2 + 1]) ==
   8583 				       e->ipfe_arg0[i * 2]) ||
   8584 				      ((fin->fin_daddr &
   8585 					e->ipfe_arg0[i * 2 + 1]) ==
   8586 				       e->ipfe_arg0[i * 2]);
   8587 			}
   8588 			break;
   8589 
   8590 #ifdef USE_INET6
   8591 		case IPF_EXP_IP6_SRCADDR :
   8592 			if (fin->fin_v != 6)
   8593 				break;
   8594 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
   8595 				rv |= IP6_MASKEQ(&fin->fin_src6,
   8596 						 &e->ipfe_arg0[i * 8 + 4],
   8597 						 &e->ipfe_arg0[i * 8]);
   8598 			}
   8599 			break;
   8600 
   8601 		case IPF_EXP_IP6_DSTADDR :
   8602 			if (fin->fin_v != 6)
   8603 				break;
   8604 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
   8605 				rv |= IP6_MASKEQ(&fin->fin_dst6,
   8606 						 &e->ipfe_arg0[i * 8 + 4],
   8607 						 &e->ipfe_arg0[i * 8]);
   8608 			}
   8609 			break;
   8610 
   8611 		case IPF_EXP_IP6_ADDR :
   8612 			if (fin->fin_v != 6)
   8613 				break;
   8614 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
   8615 				rv |= IP6_MASKEQ(&fin->fin_src6,
   8616 						 &e->ipfe_arg0[i * 8 + 4],
   8617 						 &e->ipfe_arg0[i * 8]) ||
   8618 				      IP6_MASKEQ(&fin->fin_dst6,
   8619 						 &e->ipfe_arg0[i * 8 + 4],
   8620 						 &e->ipfe_arg0[i * 8]);
   8621 			}
   8622 			break;
   8623 #endif
   8624 
   8625 		case IPF_EXP_UDP_PORT :
   8626 		case IPF_EXP_TCP_PORT :
   8627 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
   8628 				rv |= (fin->fin_sport == e->ipfe_arg0[i]) ||
   8629 				      (fin->fin_dport == e->ipfe_arg0[i]);
   8630 			}
   8631 			break;
   8632 
   8633 		case IPF_EXP_UDP_SPORT :
   8634 		case IPF_EXP_TCP_SPORT :
   8635 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
   8636 				rv |= (fin->fin_sport == e->ipfe_arg0[i]);
   8637 			}
   8638 			break;
   8639 
   8640 		case IPF_EXP_UDP_DPORT :
   8641 		case IPF_EXP_TCP_DPORT :
   8642 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
   8643 				rv |= (fin->fin_dport == e->ipfe_arg0[i]);
   8644 			}
   8645 			break;
   8646 
   8647 		case IPF_EXP_TCP_FLAGS :
   8648 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
   8649 				rv |= ((fin->fin_tcpf &
   8650 					e->ipfe_arg0[i * 2 + 1]) ==
   8651 				       e->ipfe_arg0[i * 2]);
   8652 			}
   8653 			break;
   8654 		}
   8655 		rv ^= e->ipfe_not;
   8656 
   8657 		if (rv == 0)
   8658 			break;
   8659 	}
   8660 
   8661 	return rv;
   8662 }
   8663 
   8664 
   8665 /* ------------------------------------------------------------------------ */
   8666 /* Function:    ipf_queueflush                                              */
   8667 /* Returns:     int - number of entries flushed (0 = none)                  */
   8668 /* Parameters:  softc(I)    - pointer to soft context main structure        */
   8669 /*              deletefn(I) - function to call to delete entry              */
   8670 /*              ipfqs(I)    - top of the list of ipf internal queues        */
   8671 /*              userqs(I)   - top of the list of user defined timeouts      */
   8672 /*                                                                          */
   8673 /* This fucntion gets called when the state/NAT hash tables fill up and we  */
   8674 /* need to try a bit harder to free up some space.  The algorithm used here */
   8675 /* split into two parts but both halves have the same goal: to reduce the   */
   8676 /* number of connections considered to be "active" to the low watermark.    */
   8677 /* There are two steps in doing this:                                       */
   8678 /* 1) Remove any TCP connections that are already considered to be "closed" */
   8679 /*    but have not yet been removed from the state table.  The two states   */
   8680 /*    TCPS_TIME_WAIT and TCPS_CLOSED are considered to be the perfect       */
   8681 /*    candidates for this style of removal.  If freeing up entries in       */
   8682 /*    CLOSED or both CLOSED and TIME_WAIT brings us to the low watermark,   */
   8683 /*    we do not go on to step 2.                                            */
   8684 /*                                                                          */
   8685 /* 2) Look for the oldest entries on each timeout queue and free them if    */
   8686 /*    they are within the given window we are considering.  Where the       */
   8687 /*    window starts and the steps taken to increase its size depend upon    */
   8688 /*    how long ipf has been running (ipf_ticks.)  Anything modified in the  */
   8689 /*    last 30 seconds is not touched.                                       */
   8690 /*                                              touched                     */
   8691 /*         die     ipf_ticks  30*1.5    1800*1.5   |  43200*1.5             */
   8692 /*           |          |        |           |     |     |                  */
   8693 /* future <--+----------+--------+-----------+-----+-----+-----------> past */
   8694 /*                     now        \_int=30s_/ \_int=1hr_/ \_int=12hr        */
   8695 /*                                                                          */
   8696 /* Points to note:                                                          */
   8697 /* - tqe_die is the time, in the future, when entries die.                  */
   8698 /* - tqe_die - ipf_ticks is how long left the connection has to live in ipf */
   8699 /*   ticks.                                                                 */
   8700 /* - tqe_touched is when the entry was last used by NAT/state               */
   8701 /* - the closer tqe_touched is to ipf_ticks, the further tqe_die will be    */
   8702 /*   ipf_ticks any given timeout queue and vice versa.                      */
   8703 /* - both tqe_die and tqe_touched increase over time                        */
   8704 /* - timeout queues are sorted with the highest value of tqe_die at the     */
   8705 /*   bottom and therefore the smallest values of each are at the top        */
   8706 /* - the pointer passed in as ipfqs should point to an array of timeout     */
   8707 /*   queues representing each of the TCP states                             */
   8708 /*                                                                          */
   8709 /* We start by setting up a maximum range to scan for things to move of     */
   8710 /* iend (newest) to istart (oldest) in chunks of "interval".  If nothing is */
   8711 /* found in that range, "interval" is adjusted (so long as it isn't 30) and */
   8712 /* we start again with a new value for "iend" and "istart".  This is        */
   8713 /* continued until we either finish the scan of 30 second intervals or the  */
   8714 /* low water mark is reached.                                               */
   8715 /* ------------------------------------------------------------------------ */
   8716 int
   8717 ipf_queueflush(ipf_main_softc_t *softc, ipftq_delete_fn_t deletefn,
   8718     ipftq_t *ipfqs, ipftq_t *userqs, u_int *activep, int size, int low)
   8719 {
   8720 	u_long interval, istart, iend;
   8721 	ipftq_t *ifq, *ifqnext;
   8722 	ipftqent_t *tqe, *tqn;
   8723 	int removed = 0;
   8724 
   8725 	for (tqn = ipfqs[IPF_TCPS_CLOSED].ifq_head; ((tqe = tqn) != NULL); ) {
   8726 		tqn = tqe->tqe_next;
   8727 		if ((*deletefn)(softc, tqe->tqe_parent) == 0)
   8728 			removed++;
   8729 	}
   8730 	if ((*activep * 100 / size) > low) {
   8731 		for (tqn = ipfqs[IPF_TCPS_TIME_WAIT].ifq_head;
   8732 		     ((tqe = tqn) != NULL); ) {
   8733 			tqn = tqe->tqe_next;
   8734 			if ((*deletefn)(softc, tqe->tqe_parent) == 0)
   8735 				removed++;
   8736 		}
   8737 	}
   8738 
   8739 	if ((*activep * 100 / size) <= low) {
   8740 		return removed;
   8741 	}
   8742 
   8743 	/*
   8744 	 * NOTE: Use of "* 15 / 10" is required here because if "* 1.5" is
   8745 	 *       used then the operations are upgraded to floating point
   8746 	 *       and kernels don't like floating point...
   8747 	 */
   8748 	if (softc->ipf_ticks > IPF_TTLVAL(43200 * 15 / 10)) {
   8749 		istart = IPF_TTLVAL(86400 * 4);
   8750 		interval = IPF_TTLVAL(43200);
   8751 	} else if (softc->ipf_ticks > IPF_TTLVAL(1800 * 15 / 10)) {
   8752 		istart = IPF_TTLVAL(43200);
   8753 		interval = IPF_TTLVAL(1800);
   8754 	} else if (softc->ipf_ticks > IPF_TTLVAL(30 * 15 / 10)) {
   8755 		istart = IPF_TTLVAL(1800);
   8756 		interval = IPF_TTLVAL(30);
   8757 	} else {
   8758 		return 0;
   8759 	}
   8760 	if (istart > softc->ipf_ticks) {
   8761 		if (softc->ipf_ticks - interval < interval)
   8762 			istart = interval;
   8763 		else
   8764 			istart = (softc->ipf_ticks / interval) * interval;
   8765 	}
   8766 
   8767 	iend = softc->ipf_ticks - interval;
   8768 
   8769 	while ((*activep * 100 / size) > low) {
   8770 		u_long try;
   8771 
   8772 		try = softc->ipf_ticks - istart;
   8773 
   8774 		for (ifq = ipfqs; ifq != NULL; ifq = ifq->ifq_next) {
   8775 			for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
   8776 				if (try < tqe->tqe_touched)
   8777 					break;
   8778 				tqn = tqe->tqe_next;
   8779 				if ((*deletefn)(softc, tqe->tqe_parent) == 0)
   8780 					removed++;
   8781 			}
   8782 		}
   8783 
   8784 		for (ifq = userqs; ifq != NULL; ifq = ifqnext) {
   8785 			ifqnext = ifq->ifq_next;
   8786 
   8787 			for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
   8788 				if (try < tqe->tqe_touched)
   8789 					break;
   8790 				tqn = tqe->tqe_next;
   8791 				if ((*deletefn)(softc, tqe->tqe_parent) == 0)
   8792 					removed++;
   8793 			}
   8794 		}
   8795 
   8796 		if (try >= iend) {
   8797 			if (interval == IPF_TTLVAL(43200)) {
   8798 				interval = IPF_TTLVAL(1800);
   8799 			} else if (interval == IPF_TTLVAL(1800)) {
   8800 				interval = IPF_TTLVAL(30);
   8801 			} else {
   8802 				break;
   8803 			}
   8804 			if (interval >= softc->ipf_ticks)
   8805 				break;
   8806 
   8807 			iend = softc->ipf_ticks - interval;
   8808 		}
   8809 		istart -= interval;
   8810 	}
   8811 
   8812 	return removed;
   8813 }
   8814 
   8815 
   8816 /* ------------------------------------------------------------------------ */
   8817 /* Function:    ipf_deliverlocal                                            */
   8818 /* Returns:     int - 1 = local address, 0 = non-local address              */
   8819 /* Parameters:  softc(I)     - pointer to soft context main structure       */
   8820 /*              ipversion(I) - IP protocol version (4 or 6)                 */
   8821 /*              ifp(I)       - network interface pointer                    */
   8822 /*              ipaddr(I)    - IPv4/6 destination address                   */
   8823 /*                                                                          */
   8824 /* This fucntion is used to determine in the address "ipaddr" belongs to    */
   8825 /* the network interface represented by ifp.                                */
   8826 /* ------------------------------------------------------------------------ */
   8827 int
   8828 ipf_deliverlocal(ipf_main_softc_t *softc, int ipversion, void *ifp,
   8829     i6addr_t *ipaddr)
   8830 {
   8831 	i6addr_t addr;
   8832 	int islocal = 0;
   8833 
   8834 	if (ipversion == 4) {
   8835 		if (ipf_ifpaddr(softc, 4, FRI_NORMAL, ifp, &addr, NULL) == 0) {
   8836 			if (addr.in4.s_addr == ipaddr->in4.s_addr)
   8837 				islocal = 1;
   8838 		}
   8839 
   8840 #ifdef USE_INET6
   8841 	} else if (ipversion == 6) {
   8842 		if (ipf_ifpaddr(softc, 6, FRI_NORMAL, ifp, &addr, NULL) == 0) {
   8843 			if (IP6_EQ(&addr, ipaddr))
   8844 				islocal = 1;
   8845 		}
   8846 #endif
   8847 	}
   8848 
   8849 	return islocal;
   8850 }
   8851 
   8852 
   8853 /* ------------------------------------------------------------------------ */
   8854 /* Function:    ipf_settimeout                                              */
   8855 /* Returns:     int - 0 = success, -1 = failure                             */
   8856 /* Parameters:  softc(I) - pointer to soft context main structure           */
   8857 /*              t(I)     - pointer to tuneable array entry                  */
   8858 /*              p(I)     - pointer to values passed in to apply             */
   8859 /*                                                                          */
   8860 /* This function is called to set the timeout values for each distinct      */
   8861 /* queue timeout that is available.  When called, it calls into both the    */
   8862 /* state and NAT code, telling them to update their timeout queues.         */
   8863 /* ------------------------------------------------------------------------ */
   8864 static int
   8865 ipf_settimeout(struct ipf_main_softc_s *softc, ipftuneable_t *t,
   8866     ipftuneval_t *p)
   8867 {
   8868 
   8869 	/*
   8870 	 * ipf_interror should be set by the functions called here, not
   8871 	 * by this function - it's just a middle man.
   8872 	 */
   8873 	if (ipf_state_settimeout(softc, t, p) == -1)
   8874 		return -1;
   8875 	if (ipf_nat_settimeout(softc, t, p) == -1)
   8876 		return -1;
   8877 	return 0;
   8878 }
   8879 
   8880 
   8881 /* ------------------------------------------------------------------------ */
   8882 /* Function:    ipf_apply_timeout                                           */
   8883 /* Returns:     int - 0 = success, -1 = failure                             */
   8884 /* Parameters:  head(I)    - pointer to tuneable array entry                */
   8885 /*              seconds(I) - pointer to values passed in to apply           */
   8886 /*                                                                          */
   8887 /* This function applies a timeout of "seconds" to the timeout queue that   */
   8888 /* is pointed to by "head".  All entries on this list have an expiration    */
   8889 /* set to be the current tick value of ipf plus the ttl.  Given that this   */
   8890 /* function should only be called when the delta is non-zero, the task is   */
   8891 /* to walk the entire list and apply the change.  The sort order will not   */
   8892 /* change.  The only catch is that this is O(n) across the list, so if the  */
   8893 /* queue has lots of entries (10s of thousands or 100s of thousands), it    */
   8894 /* could take a relatively long time to work through them all.              */
   8895 /* ------------------------------------------------------------------------ */
   8896 void
   8897 ipf_apply_timeout(ipftq_t *head, u_int seconds)
   8898 {
   8899 	u_int oldtimeout, newtimeout;
   8900 	ipftqent_t *tqe;
   8901 	int delta;
   8902 
   8903 	MUTEX_ENTER(&head->ifq_lock);
   8904 	oldtimeout = head->ifq_ttl;
   8905 	newtimeout = IPF_TTLVAL(seconds);
   8906 	delta = oldtimeout - newtimeout;
   8907 
   8908 	head->ifq_ttl = newtimeout;
   8909 
   8910 	for (tqe = head->ifq_head; tqe != NULL; tqe = tqe->tqe_next) {
   8911 		tqe->tqe_die += delta;
   8912 	}
   8913 	MUTEX_EXIT(&head->ifq_lock);
   8914 }
   8915 
   8916 
   8917 /* ------------------------------------------------------------------------ */
   8918 /* Function:   ipf_settimeout_tcp                                           */
   8919 /* Returns:    int - 0 = successfully applied, -1 = failed                  */
   8920 /* Parameters: t(I)   - pointer to tuneable to change                       */
   8921 /*             p(I)   - pointer to new timeout information                  */
   8922 /*             tab(I) - pointer to table of TCP queues                      */
   8923 /*                                                                          */
   8924 /* This function applies the new timeout (p) to the TCP tunable (t) and     */
   8925 /* updates all of the entries on the relevant timeout queue by calling      */
   8926 /* ipf_apply_timeout().                                                     */
   8927 /* ------------------------------------------------------------------------ */
   8928 int
   8929 ipf_settimeout_tcp(ipftuneable_t *t, ipftuneval_t *p, ipftq_t *tab)
   8930 {
   8931 	if (!strcmp(t->ipft_name, "tcp_idle_timeout") ||
   8932 	    !strcmp(t->ipft_name, "tcp_established")) {
   8933 		ipf_apply_timeout(&tab[IPF_TCPS_ESTABLISHED], p->ipftu_int);
   8934 	} else if (!strcmp(t->ipft_name, "tcp_close_wait")) {
   8935 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSE_WAIT], p->ipftu_int);
   8936 	} else if (!strcmp(t->ipft_name, "tcp_last_ack")) {
   8937 		ipf_apply_timeout(&tab[IPF_TCPS_LAST_ACK], p->ipftu_int);
   8938 	} else if (!strcmp(t->ipft_name, "tcp_timeout")) {
   8939 		ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
   8940 		ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
   8941 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
   8942 	} else if (!strcmp(t->ipft_name, "tcp_listen")) {
   8943 		ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
   8944 	} else if (!strcmp(t->ipft_name, "tcp_half_established")) {
   8945 		ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
   8946 	} else if (!strcmp(t->ipft_name, "tcp_closing")) {
   8947 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
   8948 	} else if (!strcmp(t->ipft_name, "tcp_syn_received")) {
   8949 		ipf_apply_timeout(&tab[IPF_TCPS_SYN_RECEIVED], p->ipftu_int);
   8950 	} else if (!strcmp(t->ipft_name, "tcp_syn_sent")) {
   8951 		ipf_apply_timeout(&tab[IPF_TCPS_SYN_SENT], p->ipftu_int);
   8952 	} else if (!strcmp(t->ipft_name, "tcp_closed")) {
   8953 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
   8954 	} else if (!strcmp(t->ipft_name, "tcp_half_closed")) {
   8955 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
   8956 	} else if (!strcmp(t->ipft_name, "tcp_time_wait")) {
   8957 		ipf_apply_timeout(&tab[IPF_TCPS_TIME_WAIT], p->ipftu_int);
   8958 	} else {
   8959 		/*
   8960 		 * ipf_interror isn't set here because it should be set
   8961 		 * by whatever called this function.
   8962 		 */
   8963 		return -1;
   8964 	}
   8965 	return 0;
   8966 }
   8967 
   8968 
   8969 /* ------------------------------------------------------------------------ */
   8970 /* Function:   ipf_main_soft_create                                         */
   8971 /* Returns:    NULL = failure, else success                                 */
   8972 /* Parameters: arg(I) - pointer to soft context structure if already allocd */
   8973 /*                                                                          */
   8974 /* Create the foundation soft context structure. In circumstances where it  */
   8975 /* is not required to dynamically allocate the context, a pointer can be    */
   8976 /* passed in (rather than NULL) to a structure to be initialised.           */
   8977 /* The main thing of interest is that a number of locks are initialised     */
   8978 /* here instead of in the where might be expected - in the relevant create  */
   8979 /* function elsewhere.  This is done because the current locking design has */
   8980 /* some areas where these locks are used outside of their module.           */
   8981 /* Possibly the most important exercise that is done here is setting of all */
   8982 /* the timeout values, allowing them to be changed before init().           */
   8983 /* ------------------------------------------------------------------------ */
   8984 void *
   8985 ipf_main_soft_create(void *arg)
   8986 {
   8987 	ipf_main_softc_t *softc;
   8988 
   8989 	if (arg == NULL) {
   8990 		KMALLOC(softc, ipf_main_softc_t *);
   8991 		if (softc == NULL)
   8992 			return NULL;
   8993 	} else {
   8994 		softc = arg;
   8995 	}
   8996 
   8997 	bzero((char *)softc, sizeof(*softc));
   8998 
   8999 	/*
   9000 	 * This serves as a flag as to whether or not the softc should be
   9001 	 * free'd when _destroy is called.
   9002 	 */
   9003 	softc->ipf_dynamic_softc = (arg == NULL) ? 1 : 0;
   9004 
   9005 	softc->ipf_tuners = ipf_tune_array_copy(softc,
   9006 						sizeof(ipf_main_tuneables),
   9007 						ipf_main_tuneables);
   9008 	if (softc->ipf_tuners == NULL) {
   9009 		ipf_main_soft_destroy(softc);
   9010 		return NULL;
   9011 	}
   9012 
   9013 	MUTEX_INIT(&softc->ipf_rw, "ipf rw mutex");
   9014 	MUTEX_INIT(&softc->ipf_timeoutlock, "ipf timeout lock");
   9015 	RWLOCK_INIT(&softc->ipf_global, "ipf filter load/unload mutex");
   9016 	RWLOCK_INIT(&softc->ipf_mutex, "ipf filter rwlock");
   9017 	RWLOCK_INIT(&softc->ipf_tokens, "ipf token rwlock");
   9018 	RWLOCK_INIT(&softc->ipf_state, "ipf state rwlock");
   9019 	RWLOCK_INIT(&softc->ipf_nat, "ipf IP NAT rwlock");
   9020 	RWLOCK_INIT(&softc->ipf_poolrw, "ipf pool rwlock");
   9021 	RWLOCK_INIT(&softc->ipf_frag, "ipf frag rwlock");
   9022 
   9023 	softc->ipf_token_head = NULL;
   9024 	softc->ipf_token_tail = &softc->ipf_token_head;
   9025 
   9026 	softc->ipf_tcpidletimeout = FIVE_DAYS;
   9027 	softc->ipf_tcpclosewait = IPF_TTLVAL(2 * TCP_MSL);
   9028 	softc->ipf_tcplastack = IPF_TTLVAL(30);
   9029 	softc->ipf_tcptimewait = IPF_TTLVAL(2 * TCP_MSL);
   9030 	softc->ipf_tcptimeout = IPF_TTLVAL(2 * TCP_MSL);
   9031 	softc->ipf_tcpsynsent = IPF_TTLVAL(2 * TCP_MSL);
   9032 	softc->ipf_tcpsynrecv = IPF_TTLVAL(2 * TCP_MSL);
   9033 	softc->ipf_tcpclosed = IPF_TTLVAL(30);
   9034 	softc->ipf_tcphalfclosed = IPF_TTLVAL(2 * 3600);
   9035 	softc->ipf_udptimeout = IPF_TTLVAL(120);
   9036 	softc->ipf_udpacktimeout = IPF_TTLVAL(12);
   9037 	softc->ipf_icmptimeout = IPF_TTLVAL(60);
   9038 	softc->ipf_icmpacktimeout = IPF_TTLVAL(6);
   9039 	softc->ipf_iptimeout = IPF_TTLVAL(60);
   9040 
   9041 #if defined(IPFILTER_DEFAULT_BLOCK)
   9042 	softc->ipf_pass = FR_BLOCK|FR_NOMATCH;
   9043 #else
   9044 	softc->ipf_pass = (IPF_DEFAULT_PASS)|FR_NOMATCH;
   9045 #endif
   9046 	softc->ipf_minttl = 4;
   9047 	softc->ipf_icmpminfragmtu = 68;
   9048 	softc->ipf_flags = IPF_LOGGING;
   9049 
   9050 	return softc;
   9051 }
   9052 
   9053 /* ------------------------------------------------------------------------ */
   9054 /* Function:   ipf_main_soft_init                                           */
   9055 /* Returns:    0 = success, -1 = failure                                    */
   9056 /* Parameters: softc(I) - pointer to soft context main structure            */
   9057 /*                                                                          */
   9058 /* A null-op function that exists as a placeholder so that the flow in      */
   9059 /* other functions is obvious.                                              */
   9060 /* ------------------------------------------------------------------------ */
   9061 /*ARGSUSED*/
   9062 int
   9063 ipf_main_soft_init(ipf_main_softc_t *softc)
   9064 {
   9065 	return 0;
   9066 }
   9067 
   9068 
   9069 /* ------------------------------------------------------------------------ */
   9070 /* Function:   ipf_main_soft_destroy                                        */
   9071 /* Returns:    void                                                         */
   9072 /* Parameters: softc(I) - pointer to soft context main structure            */
   9073 /*                                                                          */
   9074 /* Undo everything that we did in ipf_main_soft_create.                     */
   9075 /*                                                                          */
   9076 /* The most important check that needs to be made here is whether or not    */
   9077 /* the structure was allocated by ipf_main_soft_create() by checking what   */
   9078 /* value is stored in ipf_dynamic_main.                                     */
   9079 /* ------------------------------------------------------------------------ */
   9080 /*ARGSUSED*/
   9081 void
   9082 ipf_main_soft_destroy(ipf_main_softc_t *softc)
   9083 {
   9084 
   9085 	RW_DESTROY(&softc->ipf_frag);
   9086 	RW_DESTROY(&softc->ipf_poolrw);
   9087 	RW_DESTROY(&softc->ipf_nat);
   9088 	RW_DESTROY(&softc->ipf_state);
   9089 	RW_DESTROY(&softc->ipf_tokens);
   9090 	RW_DESTROY(&softc->ipf_mutex);
   9091 	RW_DESTROY(&softc->ipf_global);
   9092 	MUTEX_DESTROY(&softc->ipf_timeoutlock);
   9093 	MUTEX_DESTROY(&softc->ipf_rw);
   9094 
   9095 	if (softc->ipf_tuners != NULL) {
   9096 		KFREES(softc->ipf_tuners, sizeof(ipf_main_tuneables));
   9097 	}
   9098 	if (softc->ipf_dynamic_softc == 1) {
   9099 		KFREE(softc);
   9100 	}
   9101 }
   9102 
   9103 
   9104 /* ------------------------------------------------------------------------ */
   9105 /* Function:   ipf_main_soft_fini                                           */
   9106 /* Returns:    0 = success, -1 = failure                                    */
   9107 /* Parameters: softc(I) - pointer to soft context main structure            */
   9108 /*                                                                          */
   9109 /* Clean out the rules which have been added since _init was last called,   */
   9110 /* the only dynamic part of the mainline.                                   */
   9111 /* ------------------------------------------------------------------------ */
   9112 int
   9113 ipf_main_soft_fini(ipf_main_softc_t *softc)
   9114 {
   9115 	(void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
   9116 	(void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE);
   9117 	(void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
   9118 	(void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE);
   9119 
   9120 	return 0;
   9121 }
   9122 
   9123 
   9124 /* ------------------------------------------------------------------------ */
   9125 /* Function:   ipf_main_load                                                */
   9126 /* Returns:    0 = success, -1 = failure                                    */
   9127 /* Parameters: none                                                         */
   9128 /*                                                                          */
   9129 /* Handle global initialisation that needs to be done for the base part of  */
   9130 /* IPFilter. At present this just amounts to initialising some ICMP lookup  */
   9131 /* arrays that get used by the state/NAT code.                              */
   9132 /* ------------------------------------------------------------------------ */
   9133 int
   9134 ipf_main_load(void)
   9135 {
   9136 	int i;
   9137 
   9138 	/* fill icmp reply type table */
   9139 	for (i = 0; i <= ICMP_MAXTYPE; i++)
   9140 		icmpreplytype4[i] = -1;
   9141 	icmpreplytype4[ICMP_ECHO] = ICMP_ECHOREPLY;
   9142 	icmpreplytype4[ICMP_TSTAMP] = ICMP_TSTAMPREPLY;
   9143 	icmpreplytype4[ICMP_IREQ] = ICMP_IREQREPLY;
   9144 	icmpreplytype4[ICMP_MASKREQ] = ICMP_MASKREPLY;
   9145 
   9146 #ifdef  USE_INET6
   9147 	/* fill icmp reply type table */
   9148 	for (i = 0; i <= ICMP6_MAXTYPE; i++)
   9149 		icmpreplytype6[i] = -1;
   9150 	icmpreplytype6[ICMP6_ECHO_REQUEST] = ICMP6_ECHO_REPLY;
   9151 	icmpreplytype6[ICMP6_MEMBERSHIP_QUERY] = ICMP6_MEMBERSHIP_REPORT;
   9152 	icmpreplytype6[ICMP6_NI_QUERY] = ICMP6_NI_REPLY;
   9153 	icmpreplytype6[ND_ROUTER_SOLICIT] = ND_ROUTER_ADVERT;
   9154 	icmpreplytype6[ND_NEIGHBOR_SOLICIT] = ND_NEIGHBOR_ADVERT;
   9155 #endif
   9156 
   9157 	return 0;
   9158 }
   9159 
   9160 
   9161 /* ------------------------------------------------------------------------ */
   9162 /* Function:   ipf_main_unload                                              */
   9163 /* Returns:    0 = success, -1 = failure                                    */
   9164 /* Parameters: none                                                         */
   9165 /*                                                                          */
   9166 /* A null-op function that exists as a placeholder so that the flow in      */
   9167 /* other functions is obvious.                                              */
   9168 /* ------------------------------------------------------------------------ */
   9169 int
   9170 ipf_main_unload(void)
   9171 {
   9172 	return 0;
   9173 }
   9174 
   9175 
   9176 /* ------------------------------------------------------------------------ */
   9177 /* Function:   ipf_load_all                                                 */
   9178 /* Returns:    0 = success, -1 = failure                                    */
   9179 /* Parameters: none                                                         */
   9180 /*                                                                          */
   9181 /* Work through all of the subsystems inside IPFilter and call the load     */
   9182 /* function for each in an order that won't lead to a crash :)              */
   9183 /* ------------------------------------------------------------------------ */
   9184 int
   9185 ipf_load_all(void)
   9186 {
   9187 	if (ipf_main_load() == -1)
   9188 		return -1;
   9189 
   9190 	if (ipf_state_main_load() == -1)
   9191 		return -1;
   9192 
   9193 	if (ipf_nat_main_load() == -1)
   9194 		return -1;
   9195 
   9196 	if (ipf_frag_main_load() == -1)
   9197 		return -1;
   9198 
   9199 	if (ipf_auth_main_load() == -1)
   9200 		return -1;
   9201 
   9202 	if (ipf_proxy_main_load() == -1)
   9203 		return -1;
   9204 
   9205 	return 0;
   9206 }
   9207 
   9208 
   9209 /* ------------------------------------------------------------------------ */
   9210 /* Function:   ipf_unload_all                                               */
   9211 /* Returns:    0 = success, -1 = failure                                    */
   9212 /* Parameters: none                                                         */
   9213 /*                                                                          */
   9214 /* Work through all of the subsystems inside IPFilter and call the unload   */
   9215 /* function for each in an order that won't lead to a crash :)              */
   9216 /* ------------------------------------------------------------------------ */
   9217 int
   9218 ipf_unload_all(void)
   9219 {
   9220 	if (ipf_proxy_main_unload() == -1)
   9221 		return -1;
   9222 
   9223 	if (ipf_auth_main_unload() == -1)
   9224 		return -1;
   9225 
   9226 	if (ipf_frag_main_unload() == -1)
   9227 		return -1;
   9228 
   9229 	if (ipf_nat_main_unload() == -1)
   9230 		return -1;
   9231 
   9232 	if (ipf_state_main_unload() == -1)
   9233 		return -1;
   9234 
   9235 	if (ipf_main_unload() == -1)
   9236 		return -1;
   9237 
   9238 	return 0;
   9239 }
   9240 
   9241 
   9242 /* ------------------------------------------------------------------------ */
   9243 /* Function:   ipf_create_all                                               */
   9244 /* Returns:    NULL = failure, else success                                 */
   9245 /* Parameters: arg(I) - pointer to soft context main structure              */
   9246 /*                                                                          */
   9247 /* Work through all of the subsystems inside IPFilter and call the create   */
   9248 /* function for each in an order that won't lead to a crash :)              */
   9249 /* ------------------------------------------------------------------------ */
   9250 ipf_main_softc_t *
   9251 ipf_create_all(void *arg)
   9252 {
   9253 	ipf_main_softc_t *softc;
   9254 
   9255 	softc = ipf_main_soft_create(arg);
   9256 	if (softc == NULL)
   9257 		return NULL;
   9258 
   9259 #ifdef IPFILTER_LOG
   9260 	softc->ipf_log_soft = ipf_log_soft_create(softc);
   9261 	if (softc->ipf_log_soft == NULL) {
   9262 		ipf_destroy_all(softc);
   9263 		return NULL;
   9264 	}
   9265 #endif
   9266 
   9267 	softc->ipf_lookup_soft = ipf_lookup_soft_create(softc);
   9268 	if (softc->ipf_lookup_soft == NULL) {
   9269 		ipf_destroy_all(softc);
   9270 		return NULL;
   9271 	}
   9272 
   9273 	softc->ipf_sync_soft = ipf_sync_soft_create(softc);
   9274 	if (softc->ipf_sync_soft == NULL) {
   9275 		ipf_destroy_all(softc);
   9276 		return NULL;
   9277 	}
   9278 
   9279 	softc->ipf_state_soft = ipf_state_soft_create(softc);
   9280 	if (softc->ipf_state_soft == NULL) {
   9281 		ipf_destroy_all(softc);
   9282 		return NULL;
   9283 	}
   9284 
   9285 	softc->ipf_nat_soft = ipf_nat_soft_create(softc);
   9286 	if (softc->ipf_nat_soft == NULL) {
   9287 		ipf_destroy_all(softc);
   9288 		return NULL;
   9289 	}
   9290 
   9291 	softc->ipf_frag_soft = ipf_frag_soft_create(softc);
   9292 	if (softc->ipf_frag_soft == NULL) {
   9293 		ipf_destroy_all(softc);
   9294 		return NULL;
   9295 	}
   9296 
   9297 	softc->ipf_auth_soft = ipf_auth_soft_create(softc);
   9298 	if (softc->ipf_auth_soft == NULL) {
   9299 		ipf_destroy_all(softc);
   9300 		return NULL;
   9301 	}
   9302 
   9303 	softc->ipf_proxy_soft = ipf_proxy_soft_create(softc);
   9304 	if (softc->ipf_proxy_soft == NULL) {
   9305 		ipf_destroy_all(softc);
   9306 		return NULL;
   9307 	}
   9308 
   9309 	return softc;
   9310 }
   9311 
   9312 
   9313 /* ------------------------------------------------------------------------ */
   9314 /* Function:   ipf_destroy_all                                              */
   9315 /* Returns:    void                                                         */
   9316 /* Parameters: softc(I) - pointer to soft context main structure            */
   9317 /*                                                                          */
   9318 /* Work through all of the subsystems inside IPFilter and call the destroy  */
   9319 /* function for each in an order that won't lead to a crash :)              */
   9320 /*                                                                          */
   9321 /* Every one of these functions is expected to succeed, so there is no      */
   9322 /* checking of return values.                                               */
   9323 /* ------------------------------------------------------------------------ */
   9324 void
   9325 ipf_destroy_all(ipf_main_softc_t *softc)
   9326 {
   9327 
   9328 	if (softc->ipf_state_soft != NULL) {
   9329 		ipf_state_soft_destroy(softc, softc->ipf_state_soft);
   9330 		softc->ipf_state_soft = NULL;
   9331 	}
   9332 
   9333 	if (softc->ipf_nat_soft != NULL) {
   9334 		ipf_nat_soft_destroy(softc, softc->ipf_nat_soft);
   9335 		softc->ipf_nat_soft = NULL;
   9336 	}
   9337 
   9338 	if (softc->ipf_frag_soft != NULL) {
   9339 		ipf_frag_soft_destroy(softc, softc->ipf_frag_soft);
   9340 		softc->ipf_frag_soft = NULL;
   9341 	}
   9342 
   9343 	if (softc->ipf_auth_soft != NULL) {
   9344 		ipf_auth_soft_destroy(softc, softc->ipf_auth_soft);
   9345 		softc->ipf_auth_soft = NULL;
   9346 	}
   9347 
   9348 	if (softc->ipf_proxy_soft != NULL) {
   9349 		ipf_proxy_soft_destroy(softc, softc->ipf_proxy_soft);
   9350 		softc->ipf_proxy_soft = NULL;
   9351 	}
   9352 
   9353 	if (softc->ipf_sync_soft != NULL) {
   9354 		ipf_sync_soft_destroy(softc, softc->ipf_sync_soft);
   9355 		softc->ipf_sync_soft = NULL;
   9356 	}
   9357 
   9358 	if (softc->ipf_lookup_soft != NULL) {
   9359 		ipf_lookup_soft_destroy(softc, softc->ipf_lookup_soft);
   9360 		softc->ipf_lookup_soft = NULL;
   9361 	}
   9362 
   9363 #ifdef IPFILTER_LOG
   9364 	if (softc->ipf_log_soft != NULL) {
   9365 		ipf_log_soft_destroy(softc, softc->ipf_log_soft);
   9366 		softc->ipf_log_soft = NULL;
   9367 	}
   9368 #endif
   9369 
   9370 	ipf_main_soft_destroy(softc);
   9371 }
   9372 
   9373 
   9374 /* ------------------------------------------------------------------------ */
   9375 /* Function:   ipf_init_all                                                 */
   9376 /* Returns:    0 = success, -1 = failure                                    */
   9377 /* Parameters: softc(I) - pointer to soft context main structure            */
   9378 /*                                                                          */
   9379 /* Work through all of the subsystems inside IPFilter and call the init     */
   9380 /* function for each in an order that won't lead to a crash :)              */
   9381 /* ------------------------------------------------------------------------ */
   9382 int
   9383 ipf_init_all(ipf_main_softc_t *softc)
   9384 {
   9385 
   9386 	if (ipf_main_soft_init(softc) == -1)
   9387 		return -1;
   9388 
   9389 #ifdef IPFILTER_LOG
   9390 	if (ipf_log_soft_init(softc, softc->ipf_log_soft) == -1)
   9391 		return -1;
   9392 #endif
   9393 
   9394 	if (ipf_lookup_soft_init(softc, softc->ipf_lookup_soft) == -1)
   9395 		return -1;
   9396 
   9397 	if (ipf_sync_soft_init(softc, softc->ipf_sync_soft) == -1)
   9398 		return -1;
   9399 
   9400 	if (ipf_state_soft_init(softc, softc->ipf_state_soft) == -1)
   9401 		return -1;
   9402 
   9403 	if (ipf_nat_soft_init(softc, softc->ipf_nat_soft) == -1)
   9404 		return -1;
   9405 
   9406 	if (ipf_frag_soft_init(softc, softc->ipf_frag_soft) == -1)
   9407 		return -1;
   9408 
   9409 	if (ipf_auth_soft_init(softc, softc->ipf_auth_soft) == -1)
   9410 		return -1;
   9411 
   9412 	if (ipf_proxy_soft_init(softc, softc->ipf_proxy_soft) == -1)
   9413 		return -1;
   9414 
   9415 	return 0;
   9416 }
   9417 
   9418 
   9419 /* ------------------------------------------------------------------------ */
   9420 /* Function:   ipf_fini_all                                                 */
   9421 /* Returns:    0 = success, -1 = failure                                    */
   9422 /* Parameters: softc(I) - pointer to soft context main structure            */
   9423 /*                                                                          */
   9424 /* Work through all of the subsystems inside IPFilter and call the fini     */
   9425 /* function for each in an order that won't lead to a crash :)              */
   9426 /* ------------------------------------------------------------------------ */
   9427 int
   9428 ipf_fini_all(ipf_main_softc_t *softc)
   9429 {
   9430 
   9431 	ipf_token_flush(softc);
   9432 
   9433 	if (ipf_proxy_soft_fini(softc, softc->ipf_proxy_soft) == -1)
   9434 		return -1;
   9435 
   9436 	if (ipf_auth_soft_fini(softc, softc->ipf_auth_soft) == -1)
   9437 		return -1;
   9438 
   9439 	if (ipf_frag_soft_fini(softc, softc->ipf_frag_soft) == -1)
   9440 		return -1;
   9441 
   9442 	if (ipf_nat_soft_fini(softc, softc->ipf_nat_soft) == -1)
   9443 		return -1;
   9444 
   9445 	if (ipf_state_soft_fini(softc, softc->ipf_state_soft) == -1)
   9446 		return -1;
   9447 
   9448 	if (ipf_sync_soft_fini(softc, softc->ipf_sync_soft) == -1)
   9449 		return -1;
   9450 
   9451 	if (ipf_lookup_soft_fini(softc, softc->ipf_lookup_soft) == -1)
   9452 		return -1;
   9453 
   9454 #ifdef IPFILTER_LOG
   9455 	if (ipf_log_soft_fini(softc, softc->ipf_log_soft) == -1)
   9456 		return -1;
   9457 #endif
   9458 
   9459 	if (ipf_main_soft_fini(softc) == -1)
   9460 		return -1;
   9461 
   9462 	return 0;
   9463 }
   9464 
   9465 
   9466 /* ------------------------------------------------------------------------ */
   9467 /* Function:    ipf_rule_expire                                             */
   9468 /* Returns:     Nil                                                         */
   9469 /* Parameters:  softc(I) - pointer to soft context main structure           */
   9470 /*                                                                          */
   9471 /* At present this function exists just to support temporary addition of    */
   9472 /* firewall rules. Both inactive and active lists are scanned for items to  */
   9473 /* purge, as by rights, the expiration is computed as soon as the rule is   */
   9474 /* loaded in.                                                               */
   9475 /* ------------------------------------------------------------------------ */
   9476 void
   9477 ipf_rule_expire(ipf_main_softc_t *softc)
   9478 {
   9479 	frentry_t *fr;
   9480 
   9481 	if ((softc->ipf_rule_explist[0] == NULL) &&
   9482 	    (softc->ipf_rule_explist[1] == NULL))
   9483 		return;
   9484 
   9485 	WRITE_ENTER(&softc->ipf_mutex);
   9486 
   9487 	while ((fr = softc->ipf_rule_explist[0]) != NULL) {
   9488 		/*
   9489 		 * Because the list is kept sorted on insertion, the fist
   9490 		 * one that dies in the future means no more work to do.
   9491 		 */
   9492 		if (fr->fr_die > softc->ipf_ticks)
   9493 			break;
   9494 		ipf_rule_delete(softc, fr, IPL_LOGIPF, 0);
   9495 	}
   9496 
   9497 	while ((fr = softc->ipf_rule_explist[1]) != NULL) {
   9498 		/*
   9499 		 * Because the list is kept sorted on insertion, the fist
   9500 		 * one that dies in the future means no more work to do.
   9501 		 */
   9502 		if (fr->fr_die > softc->ipf_ticks)
   9503 			break;
   9504 		ipf_rule_delete(softc, fr, IPL_LOGIPF, 1);
   9505 	}
   9506 
   9507 	RWLOCK_EXIT(&softc->ipf_mutex);
   9508 }
   9509 
   9510 
   9511 static int ipf_ht_node_cmp(const struct host_node_s *, const struct host_node_s *);
   9512 static void ipf_ht_node_make_key(host_track_t *, host_node_t *, int,
   9513 				 i6addr_t *);
   9514 
   9515 RBI_CODE(ipf_rb, host_node_t, hn_entry, ipf_ht_node_cmp)
   9516 
   9517 
   9518 /* ------------------------------------------------------------------------ */
   9519 /* Function:    ipf_ht_node_cmp                                             */
   9520 /* Returns:     int   - 0 == nodes are the same, ..                         */
   9521 /* Parameters:  k1(I) - pointer to first key to compare                     */
   9522 /*              k2(I) - pointer to second key to compare                    */
   9523 /*                                                                          */
   9524 /* The "key" for the node is a combination of two fields: the address       */
   9525 /* family and the address itself.                                           */
   9526 /*                                                                          */
   9527 /* Because we're not actually interpreting the address data, it isn't       */
   9528 /* necessary to convert them to/from network/host byte order. The mask is   */
   9529 /* just used to remove bits that aren't significant - it doesn't matter     */
   9530 /* where they are, as long as they're always in the same place.             */
   9531 /*                                                                          */
   9532 /* As with IP6_EQ, comparing IPv6 addresses starts at the bottom because    */
   9533 /* this is where individual ones will differ the most - but not true for    */
   9534 /* for /48's, etc.                                                          */
   9535 /* ------------------------------------------------------------------------ */
   9536 static int
   9537 ipf_ht_node_cmp(const struct host_node_s *k1, const struct host_node_s *k2)
   9538 {
   9539 	int i;
   9540 
   9541 	i = (k2->hn_addr.adf_family - k1->hn_addr.adf_family);
   9542 	if (i != 0)
   9543 		return i;
   9544 
   9545 	if (k1->hn_addr.adf_family == AF_INET)
   9546 		return (k2->hn_addr.adf_addr.in4.s_addr -
   9547 			k1->hn_addr.adf_addr.in4.s_addr);
   9548 
   9549 	i = k2->hn_addr.adf_addr.i6[3] - k1->hn_addr.adf_addr.i6[3];
   9550 	if (i != 0)
   9551 		return i;
   9552 	i = k2->hn_addr.adf_addr.i6[2] - k1->hn_addr.adf_addr.i6[2];
   9553 	if (i != 0)
   9554 		return i;
   9555 	i = k2->hn_addr.adf_addr.i6[1] - k1->hn_addr.adf_addr.i6[1];
   9556 	if (i != 0)
   9557 		return i;
   9558 	i = k2->hn_addr.adf_addr.i6[0] - k1->hn_addr.adf_addr.i6[0];
   9559 	return i;
   9560 }
   9561 
   9562 
   9563 /* ------------------------------------------------------------------------ */
   9564 /* Function:    ipf_ht_node_make_key                                        */
   9565 /* Returns:     Nil                                                         */
   9566 /* parameters:  htp(I)    - pointer to address tracking structure           */
   9567 /*              key(I)    - where to store masked address for lookup        */
   9568 /*              family(I) - protocol family of address                      */
   9569 /*              addr(I)   - pointer to network address                      */
   9570 /*                                                                          */
   9571 /* Using the "netmask" (number of bits) stored parent host tracking struct, */
   9572 /* copy the address passed in into the key structure whilst masking out the */
   9573 /* bits that we don't want.                                                 */
   9574 /*                                                                          */
   9575 /* Because the parser will set ht_netmask to 128 if there is no protocol    */
   9576 /* specified (the parser doesn't know if it should be a v4 or v6 rule), we  */
   9577 /* have to be wary of that and not allow 32-128 to happen.                  */
   9578 /* ------------------------------------------------------------------------ */
   9579 static void
   9580 ipf_ht_node_make_key(host_track_t *htp, host_node_t *key, int family,
   9581     i6addr_t *addr)
   9582 {
   9583 	key->hn_addr.adf_family = family;
   9584 	if (family == AF_INET) {
   9585 		u_32_t mask;
   9586 		int bits;
   9587 
   9588 		key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in4);
   9589 		bits = htp->ht_netmask;
   9590 		if (bits >= 32) {
   9591 			mask = 0xffffffff;
   9592 		} else {
   9593 			mask = htonl(0xffffffff << (32 - bits));
   9594 		}
   9595 		key->hn_addr.adf_addr.in4.s_addr = addr->in4.s_addr & mask;
   9596 #ifdef USE_INET6
   9597 	} else {
   9598 		int bits = htp->ht_netmask;
   9599 
   9600 		key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in6);
   9601 		if (bits > 96) {
   9602 			key->hn_addr.adf_addr.i6[3] = addr->i6[3] &
   9603 					     htonl(0xffffffff << (128 - bits));
   9604 			key->hn_addr.adf_addr.i6[2] = addr->i6[2];
   9605 			key->hn_addr.adf_addr.i6[1] = addr->i6[2];
   9606 			key->hn_addr.adf_addr.i6[0] = addr->i6[2];
   9607 		} else if (bits > 64) {
   9608 			key->hn_addr.adf_addr.i6[3] = 0;
   9609 			key->hn_addr.adf_addr.i6[2] = addr->i6[2] &
   9610 					     htonl(0xffffffff << (96 - bits));
   9611 			key->hn_addr.adf_addr.i6[1] = addr->i6[1];
   9612 			key->hn_addr.adf_addr.i6[0] = addr->i6[0];
   9613 		} else if (bits > 32) {
   9614 			key->hn_addr.adf_addr.i6[3] = 0;
   9615 			key->hn_addr.adf_addr.i6[2] = 0;
   9616 			key->hn_addr.adf_addr.i6[1] = addr->i6[1] &
   9617 					     htonl(0xffffffff << (64 - bits));
   9618 			key->hn_addr.adf_addr.i6[0] = addr->i6[0];
   9619 		} else {
   9620 			key->hn_addr.adf_addr.i6[3] = 0;
   9621 			key->hn_addr.adf_addr.i6[2] = 0;
   9622 			key->hn_addr.adf_addr.i6[1] = 0;
   9623 			key->hn_addr.adf_addr.i6[0] = addr->i6[0] &
   9624 					     htonl(0xffffffff << (32 - bits));
   9625 		}
   9626 #endif
   9627 	}
   9628 }
   9629 
   9630 
   9631 /* ------------------------------------------------------------------------ */
   9632 /* Function:    ipf_ht_node_add                                             */
   9633 /* Returns:     int       - 0 == success,  -1 == failure                    */
   9634 /* Parameters:  softc(I)  - pointer to soft context main structure          */
   9635 /*              htp(I)    - pointer to address tracking structure           */
   9636 /*              family(I) - protocol family of address                      */
   9637 /*              addr(I)   - pointer to network address                      */
   9638 /*                                                                          */
   9639 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS  */
   9640 /*       ipf_ht_node_del FROM RUNNING CONCURRENTLY ON THE SAME htp.         */
   9641 /*                                                                          */
   9642 /* After preparing the key with the address information to find, look in    */
   9643 /* the red-black tree to see if the address is known. A successful call to  */
   9644 /* this function can mean one of two things: a new node was added to the    */
   9645 /* tree or a matching node exists and we're able to bump up its activity.   */
   9646 /* ------------------------------------------------------------------------ */
   9647 int
   9648 ipf_ht_node_add(ipf_main_softc_t *softc, host_track_t *htp, int family,
   9649     i6addr_t *addr)
   9650 {
   9651 	host_node_t *h;
   9652 	host_node_t k;
   9653 
   9654 	ipf_ht_node_make_key(htp, &k, family, addr);
   9655 
   9656 	h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
   9657 	if (h == NULL) {
   9658 		if (htp->ht_cur_nodes >= htp->ht_max_nodes)
   9659 			return -1;
   9660 		KMALLOC(h, host_node_t *);
   9661 		if (h == NULL) {
   9662 			DT(ipf_rb_no_mem);
   9663 			LBUMP(ipf_rb_no_mem);
   9664 			return -1;
   9665 		}
   9666 
   9667 		/*
   9668 		 * If there was a macro to initialise the RB node then that
   9669 		 * would get used here, but there isn't...
   9670 		 */
   9671 		bzero((char *)h, sizeof(*h));
   9672 		h->hn_addr = k.hn_addr;
   9673 		h->hn_addr.adf_family = k.hn_addr.adf_family;
   9674 		RBI_INSERT(ipf_rb, &htp->ht_root, h);
   9675 		htp->ht_cur_nodes++;
   9676 	} else {
   9677 		if ((htp->ht_max_per_node != 0) &&
   9678 		    (h->hn_active >= htp->ht_max_per_node)) {
   9679 			DT(ipf_rb_node_max);
   9680 			LBUMP(ipf_rb_node_max);
   9681 			return -1;
   9682 		}
   9683 	}
   9684 
   9685 	h->hn_active++;
   9686 
   9687 	return 0;
   9688 }
   9689 
   9690 
   9691 /* ------------------------------------------------------------------------ */
   9692 /* Function:    ipf_ht_node_del                                             */
   9693 /* Returns:     int       - 0 == success,  -1 == failure                    */
   9694 /* parameters:  htp(I)    - pointer to address tracking structure           */
   9695 /*              family(I) - protocol family of address                      */
   9696 /*              addr(I)   - pointer to network address                      */
   9697 /*                                                                          */
   9698 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS  */
   9699 /*       ipf_ht_node_add FROM RUNNING CONCURRENTLY ON THE SAME htp.         */
   9700 /*                                                                          */
   9701 /* Try and find the address passed in amongst the leaves on this tree to    */
   9702 /* be friend. If found then drop the active account for that node drops by  */
   9703 /* one. If that count reaches 0, it is time to free it all up.              */
   9704 /* ------------------------------------------------------------------------ */
   9705 int
   9706 ipf_ht_node_del(host_track_t *htp, int family, i6addr_t *addr)
   9707 {
   9708 	host_node_t *h;
   9709 	host_node_t k;
   9710 
   9711 	ipf_ht_node_make_key(htp, &k, family, addr);
   9712 
   9713 	h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
   9714 	if (h == NULL) {
   9715 		return -1;
   9716 	} else {
   9717 		h->hn_active--;
   9718 		if (h->hn_active == 0) {
   9719 			(void) RBI_DELETE(ipf_rb, &htp->ht_root, h);
   9720 			htp->ht_cur_nodes--;
   9721 			KFREE(h);
   9722 		}
   9723 	}
   9724 
   9725 	return 0;
   9726 }
   9727 
   9728 
   9729 /* ------------------------------------------------------------------------ */
   9730 /* Function:    ipf_rb_ht_init                                              */
   9731 /* Returns:     Nil                                                         */
   9732 /* Parameters:  head(I) - pointer to host tracking structure                */
   9733 /*                                                                          */
   9734 /* Initialise the host tracking structure to be ready for use above.        */
   9735 /* ------------------------------------------------------------------------ */
   9736 void
   9737 ipf_rb_ht_init(host_track_t *head)
   9738 {
   9739 	memset(head, 0, sizeof(*head));
   9740 	RBI_INIT(ipf_rb, &head->ht_root);
   9741 }
   9742 
   9743 
   9744 /* ------------------------------------------------------------------------ */
   9745 /* Function:    ipf_rb_ht_freenode                                          */
   9746 /* Returns:     Nil                                                         */
   9747 /* Parameters:  head(I) - pointer to host tracking structure                */
   9748 /*              arg(I)  - additional argument from walk caller              */
   9749 /*                                                                          */
   9750 /* Free an actual host_node_t structure.                                    */
   9751 /* ------------------------------------------------------------------------ */
   9752 void
   9753 ipf_rb_ht_freenode(host_node_t *node, void *arg)
   9754 {
   9755 	KFREE(node);
   9756 }
   9757 
   9758 
   9759 /* ------------------------------------------------------------------------ */
   9760 /* Function:    ipf_rb_ht_flush                                             */
   9761 /* Returns:     Nil                                                         */
   9762 /* Parameters:  head(I) - pointer to host tracking structure                */
   9763 /*                                                                          */
   9764 /* Remove all of the nodes in the tree tracking hosts by calling a walker   */
   9765 /* and free'ing each one.                                                   */
   9766 /* ------------------------------------------------------------------------ */
   9767 void
   9768 ipf_rb_ht_flush(host_track_t *head)
   9769 {
   9770 	/* XXX - May use node members after freeing the node. */
   9771 	RBI_WALK(ipf_rb, &head->ht_root, ipf_rb_ht_freenode, NULL);
   9772 }
   9773 
   9774 
   9775 /* ------------------------------------------------------------------------ */
   9776 /* Function:    ipf_slowtimer                                               */
   9777 /* Returns:     Nil                                                         */
   9778 /* Parameters:  ptr(I) - pointer to main ipf soft context structure         */
   9779 /*                                                                          */
   9780 /* Slowly expire held state for fragments.  Timeouts are set * in           */
   9781 /* expectation of this being called twice per second.                       */
   9782 /* ------------------------------------------------------------------------ */
   9783 void
   9784 ipf_slowtimer(ipf_main_softc_t *softc)
   9785 {
   9786 
   9787 	ipf_token_expire(softc);
   9788 	ipf_frag_expire(softc);
   9789 	ipf_state_expire(softc);
   9790 	ipf_nat_expire(softc);
   9791 	ipf_auth_expire(softc);
   9792 	ipf_lookup_expire(softc);
   9793 	ipf_rule_expire(softc);
   9794 	ipf_sync_expire(softc);
   9795 	softc->ipf_ticks++;
   9796 #   if defined(__OpenBSD__)
   9797 	timeout_add(&ipf_slowtimer_ch, hz/2);
   9798 #   endif
   9799 }
   9800 
   9801 
   9802 /* ------------------------------------------------------------------------ */
   9803 /* Function:    ipf_inet_mask_add                                           */
   9804 /* Returns:     Nil                                                         */
   9805 /* Parameters:  bits(I) - pointer to nat context information                */
   9806 /*              mtab(I) - pointer to mask hash table structure              */
   9807 /*                                                                          */
   9808 /* When called, bits represents the mask of a new NAT rule that has just    */
   9809 /* been added. This function inserts a bitmask into the array of masks to   */
   9810 /* search when searching for a matching NAT rule for a packet.              */
   9811 /* Prevention of duplicate masks is achieved by checking the use count for  */
   9812 /* a given netmask.                                                         */
   9813 /* ------------------------------------------------------------------------ */
   9814 void
   9815 ipf_inet_mask_add(int bits, ipf_v4_masktab_t *mtab)
   9816 {
   9817 	u_32_t mask;
   9818 	int i, j;
   9819 
   9820 	mtab->imt4_masks[bits]++;
   9821 	if (mtab->imt4_masks[bits] > 1)
   9822 		return;
   9823 
   9824 	if (bits == 0)
   9825 		mask = 0;
   9826 	else
   9827 		mask = 0xffffffff << (32 - bits);
   9828 
   9829 	for (i = 0; i < 33; i++) {
   9830 		if (ntohl(mtab->imt4_active[i]) < mask) {
   9831 			for (j = 32; j > i; j--)
   9832 				mtab->imt4_active[j] = mtab->imt4_active[j - 1];
   9833 			mtab->imt4_active[i] = htonl(mask);
   9834 			break;
   9835 		}
   9836 	}
   9837 	mtab->imt4_max++;
   9838 }
   9839 
   9840 
   9841 /* ------------------------------------------------------------------------ */
   9842 /* Function:    ipf_inet_mask_del                                           */
   9843 /* Returns:     Nil                                                         */
   9844 /* Parameters:  bits(I) - number of bits set in the netmask                 */
   9845 /*              mtab(I) - pointer to mask hash table structure              */
   9846 /*                                                                          */
   9847 /* Remove the 32bit bitmask represented by "bits" from the collection of    */
   9848 /* netmasks stored inside of mtab.                                          */
   9849 /* ------------------------------------------------------------------------ */
   9850 void
   9851 ipf_inet_mask_del(int bits, ipf_v4_masktab_t *mtab)
   9852 {
   9853 	u_32_t mask;
   9854 	int i, j;
   9855 
   9856 	mtab->imt4_masks[bits]--;
   9857 	if (mtab->imt4_masks[bits] > 0)
   9858 		return;
   9859 
   9860 	mask = htonl(0xffffffff << (32 - bits));
   9861 	for (i = 0; i < 33; i++) {
   9862 		if (mtab->imt4_active[i] == mask) {
   9863 			for (j = i + 1; j < 33; j++)
   9864 				mtab->imt4_active[j - 1] = mtab->imt4_active[j];
   9865 			break;
   9866 		}
   9867 	}
   9868 	mtab->imt4_max--;
   9869 	ASSERT(mtab->imt4_max >= 0);
   9870 }
   9871 
   9872 
   9873 #ifdef USE_INET6
   9874 /* ------------------------------------------------------------------------ */
   9875 /* Function:    ipf_inet6_mask_add                                          */
   9876 /* Returns:     Nil                                                         */
   9877 /* Parameters:  bits(I) - number of bits set in mask                        */
   9878 /*              mask(I) - pointer to mask to add                            */
   9879 /*              mtab(I) - pointer to mask hash table structure              */
   9880 /*                                                                          */
   9881 /* When called, bitcount represents the mask of a IPv6 NAT map rule that    */
   9882 /* has just been added. This function inserts a bitmask into the array of   */
   9883 /* masks to search when searching for a matching NAT rule for a packet.     */
   9884 /* Prevention of duplicate masks is achieved by checking the use count for  */
   9885 /* a given netmask.                                                         */
   9886 /* ------------------------------------------------------------------------ */
   9887 void
   9888 ipf_inet6_mask_add(int bits, i6addr_t *mask, ipf_v6_masktab_t *mtab)
   9889 {
   9890 	i6addr_t zero;
   9891 	int i, j;
   9892 
   9893 	mtab->imt6_masks[bits]++;
   9894 	if (mtab->imt6_masks[bits] > 1)
   9895 		return;
   9896 
   9897 	if (bits == 0) {
   9898 		mask = &zero;
   9899 		zero.i6[0] = 0;
   9900 		zero.i6[1] = 0;
   9901 		zero.i6[2] = 0;
   9902 		zero.i6[3] = 0;
   9903 	}
   9904 
   9905 	for (i = 0; i < 129; i++) {
   9906 		if (IP6_LT(&mtab->imt6_active[i], mask)) {
   9907 			for (j = 128; j > i; j--)
   9908 				mtab->imt6_active[j] = mtab->imt6_active[j - 1];
   9909 			mtab->imt6_active[i] = *mask;
   9910 			break;
   9911 		}
   9912 	}
   9913 	mtab->imt6_max++;
   9914 }
   9915 
   9916 
   9917 /* ------------------------------------------------------------------------ */
   9918 /* Function:    ipf_inet6_mask_del                                          */
   9919 /* Returns:     Nil                                                         */
   9920 /* Parameters:  bits(I) - number of bits set in mask                        */
   9921 /*              mask(I) - pointer to mask to remove                         */
   9922 /*              mtab(I) - pointer to mask hash table structure              */
   9923 /*                                                                          */
   9924 /* Remove the 128bit bitmask represented by "bits" from the collection of   */
   9925 /* netmasks stored inside of mtab.                                          */
   9926 /* ------------------------------------------------------------------------ */
   9927 void
   9928 ipf_inet6_mask_del(int bits, i6addr_t *mask, ipf_v6_masktab_t *mtab)
   9929 {
   9930 	i6addr_t zero;
   9931 	int i, j;
   9932 
   9933 	mtab->imt6_masks[bits]--;
   9934 	if (mtab->imt6_masks[bits] > 0)
   9935 		return;
   9936 
   9937 	if (bits == 0)
   9938 		mask = &zero;
   9939 	zero.i6[0] = 0;
   9940 	zero.i6[1] = 0;
   9941 	zero.i6[2] = 0;
   9942 	zero.i6[3] = 0;
   9943 
   9944 	for (i = 0; i < 129; i++) {
   9945 		if (IP6_EQ(&mtab->imt6_active[i], mask)) {
   9946 			for (j = i + 1; j < 129; j++) {
   9947 				mtab->imt6_active[j - 1] = mtab->imt6_active[j];
   9948 				if (IP6_EQ(&mtab->imt6_active[j - 1], &zero))
   9949 					break;
   9950 			}
   9951 			break;
   9952 		}
   9953 	}
   9954 	mtab->imt6_max--;
   9955 	ASSERT(mtab->imt6_max >= 0);
   9956 }
   9957 #endif
   9958