Home | History | Annotate | Line # | Download | only in netinet
fil.c revision 1.30
      1 /*	$NetBSD: fil.c,v 1.30 2019/08/08 14:38:53 christos Exp $	*/
      2 
      3 /*
      4  * Copyright (C) 2012 by Darren Reed.
      5  *
      6  * See the IPFILTER.LICENCE file for details on licencing.
      7  *
      8  * Id: fil.c,v 1.1.1.2 2012/07/22 13:45:07 darrenr Exp $
      9  *
     10  */
     11 #if defined(KERNEL) || defined(_KERNEL)
     12 # undef KERNEL
     13 # undef _KERNEL
     14 # define        KERNEL	1
     15 # define        _KERNEL	1
     16 #endif
     17 #include <sys/errno.h>
     18 #include <sys/types.h>
     19 #include <sys/param.h>
     20 #include <sys/time.h>
     21 #if defined(_KERNEL) && defined(__FreeBSD_version) && \
     22     (__FreeBSD_version >= 220000)
     23 # if (__FreeBSD_version >= 400000)
     24 #  if !defined(IPFILTER_LKM)
     25 #   include "opt_inet6.h"
     26 #  endif
     27 #  if (__FreeBSD_version == 400019)
     28 #   define CSUM_DELAY_DATA
     29 #  endif
     30 # endif
     31 # include <sys/filio.h>
     32 #else
     33 # include <sys/ioctl.h>
     34 #endif
     35 #if (defined(__SVR4) || defined(__svr4__)) && defined(sun)
     36 # include <sys/filio.h>
     37 #endif
     38 #if !defined(_AIX51)
     39 # include <sys/fcntl.h>
     40 #endif
     41 #if defined(_KERNEL)
     42 # include <sys/systm.h>
     43 # include <sys/file.h>
     44 #else
     45 # include <stdio.h>
     46 # include <string.h>
     47 # include <stdlib.h>
     48 # include <stddef.h>
     49 # include <sys/file.h>
     50 # define _KERNEL
     51 # ifdef __OpenBSD__
     52 struct file;
     53 # endif
     54 # include <sys/uio.h>
     55 # undef _KERNEL
     56 #endif
     57 #if !defined(__SVR4) && !defined(__svr4__) && !defined(__hpux) && \
     58     !defined(linux)
     59 # include <sys/mbuf.h>
     60 #else
     61 # if !defined(linux)
     62 #  include <sys/byteorder.h>
     63 # endif
     64 # if (SOLARIS2 < 5) && defined(sun)
     65 #  include <sys/dditypes.h>
     66 # endif
     67 #endif
     68 #ifdef __hpux
     69 # define _NET_ROUTE_INCLUDED
     70 #endif
     71 #if !defined(linux)
     72 # include <sys/protosw.h>
     73 #endif
     74 #include <sys/socket.h>
     75 #include <net/if.h>
     76 #ifdef sun
     77 # include <net/af.h>
     78 #endif
     79 #include <netinet/in.h>
     80 #include <netinet/in_systm.h>
     81 #include <netinet/ip.h>
     82 #if defined(__sgi) && defined(IFF_DRVRLOCK) /* IRIX 6 */
     83 # include <sys/hashing.h>
     84 # include <netinet/in_var.h>
     85 #endif
     86 #include <netinet/tcp.h>
     87 #if (!defined(__sgi) && !defined(AIX)) || defined(_KERNEL)
     88 # include <netinet/udp.h>
     89 # include <netinet/ip_icmp.h>
     90 #endif
     91 #ifdef __hpux
     92 # undef _NET_ROUTE_INCLUDED
     93 #endif
     94 #ifdef __osf__
     95 # undef _RADIX_H_
     96 #endif
     97 #include "netinet/ip_compat.h"
     98 #ifdef	USE_INET6
     99 # include <netinet/icmp6.h>
    100 # if !SOLARIS && defined(_KERNEL) && !defined(__osf__) && !defined(__hpux)
    101 #  include <netinet6/in6_var.h>
    102 # endif
    103 #endif
    104 #include "netinet/ip_fil.h"
    105 #include "netinet/ip_nat.h"
    106 #include "netinet/ip_frag.h"
    107 #include "netinet/ip_state.h"
    108 #include "netinet/ip_proxy.h"
    109 #include "netinet/ip_auth.h"
    110 #ifdef IPFILTER_SCAN
    111 # include "netinet/ip_scan.h"
    112 #endif
    113 #include "netinet/ip_sync.h"
    114 #include "netinet/ip_lookup.h"
    115 #include "netinet/ip_pool.h"
    116 #include "netinet/ip_htable.h"
    117 #ifdef IPFILTER_COMPILED
    118 # include "netinet/ip_rules.h"
    119 #endif
    120 #if defined(IPFILTER_BPF) && defined(_KERNEL)
    121 # include <net/bpf.h>
    122 #endif
    123 #if defined(__FreeBSD_version) && (__FreeBSD_version >= 300000)
    124 # include <sys/malloc.h>
    125 #endif
    126 #include "netinet/ipl.h"
    127 
    128 #if defined(__NetBSD__) && (__NetBSD_Version__ >= 104230000)
    129 # include <sys/callout.h>
    130 extern struct callout ipf_slowtimer_ch;
    131 #endif
    132 #if defined(__OpenBSD__)
    133 # include <sys/timeout.h>
    134 extern struct timeout ipf_slowtimer_ch;
    135 #endif
    136 #if defined(__NetBSD__)
    137 #include <netinet/in_offload.h>
    138 #endif
    139 /* END OF INCLUDES */
    140 
    141 #if !defined(lint)
    142 #if defined(__NetBSD__)
    143 #include <sys/cdefs.h>
    144 __KERNEL_RCSID(0, "$NetBSD: fil.c,v 1.30 2019/08/08 14:38:53 christos Exp $");
    145 #else
    146 static const char sccsid[] = "@(#)fil.c	1.36 6/5/96 (C) 1993-2000 Darren Reed";
    147 static const char rcsid[] = "@(#)Id: fil.c,v 1.1.1.2 2012/07/22 13:45:07 darrenr Exp $";
    148 #endif
    149 #endif
    150 
    151 #ifndef	_KERNEL
    152 # include "ipf.h"
    153 # include "ipt.h"
    154 extern	int	opts;
    155 extern	int	blockreason;
    156 #endif /* _KERNEL */
    157 
    158 #define	LBUMP(x)	softc->x++
    159 #define	LBUMPD(x, y)	do { softc->x.y++; DT(y); } while (0)
    160 
    161 static	INLINE int	ipf_check_ipf(fr_info_t *, frentry_t *, int);
    162 static	u_32_t		ipf_checkcipso(fr_info_t *, u_char *, int);
    163 static	u_32_t		ipf_checkripso(u_char *);
    164 static	u_32_t		ipf_decaps(fr_info_t *, u_32_t, int);
    165 #ifdef	IPFILTER_LOG
    166 static	frentry_t	*ipf_dolog(fr_info_t *, u_32_t *);
    167 #endif
    168 static	int		ipf_flushlist(ipf_main_softc_t *, int *, frentry_t **);
    169 static	int		ipf_flush_groups(ipf_main_softc_t *, frgroup_t **, int);
    170 static	ipfunc_t	ipf_findfunc(ipfunc_t);
    171 static	void		*ipf_findlookup(ipf_main_softc_t *, int, frentry_t *,
    172 					i6addr_t *, i6addr_t *);
    173 static	frentry_t	*ipf_firewall(fr_info_t *, u_32_t *);
    174 static	int		ipf_fr_matcharray(fr_info_t *, int *);
    175 static	int		ipf_frruleiter(ipf_main_softc_t *, void *, int, void *);
    176 static	void		ipf_funcfini(ipf_main_softc_t *, frentry_t *);;
    177 static	int		ipf_funcinit(ipf_main_softc_t *, frentry_t *);
    178 static	int		ipf_geniter(ipf_main_softc_t *, ipftoken_t *,
    179 				    ipfgeniter_t *);
    180 static	void		ipf_getstat(ipf_main_softc_t *,
    181 				    struct friostat *, int);
    182 static	int		ipf_group_flush(ipf_main_softc_t *, frgroup_t *);
    183 static	void		ipf_group_free(frgroup_t *);
    184 static	int		ipf_grpmapfini(struct ipf_main_softc_s *, frentry_t *);
    185 static	int		ipf_grpmapinit(struct ipf_main_softc_s *, frentry_t *);
    186 static	frentry_t	*ipf_nextrule(ipf_main_softc_t *, int, int,
    187 					frentry_t *, int);
    188 static	int		ipf_portcheck(frpcmp_t *, u_32_t);
    189 static	INLINE int	ipf_pr_ah(fr_info_t *);
    190 static	INLINE void	ipf_pr_esp(fr_info_t *);
    191 static	INLINE void	ipf_pr_gre(fr_info_t *);
    192 static	INLINE void	ipf_pr_udp(fr_info_t *);
    193 static	INLINE void	ipf_pr_tcp(fr_info_t *);
    194 static	INLINE void	ipf_pr_icmp(fr_info_t *);
    195 static	INLINE void	ipf_pr_ipv4hdr(fr_info_t *);
    196 static	INLINE void	ipf_pr_short(fr_info_t *, int);
    197 static	INLINE int	ipf_pr_tcpcommon(fr_info_t *);
    198 static	INLINE int	ipf_pr_udpcommon(fr_info_t *);
    199 static	void		ipf_rule_delete(ipf_main_softc_t *, frentry_t *f,
    200 					int, int);
    201 static	void		ipf_rule_expire_insert(ipf_main_softc_t *,
    202 					       frentry_t *, int);
    203 static	int		ipf_synclist(ipf_main_softc_t *, frentry_t *, void *);
    204 static	void		ipf_token_flush(ipf_main_softc_t *);
    205 static	void		ipf_token_unlink(ipf_main_softc_t *, ipftoken_t *);
    206 static	ipftuneable_t	*ipf_tune_findbyname(ipftuneable_t *, const char *);
    207 static	ipftuneable_t	*ipf_tune_findbycookie(ipftuneable_t **, void *,
    208 					       void **);
    209 static	int		ipf_updateipid(fr_info_t *);
    210 static	int		ipf_settimeout(struct ipf_main_softc_s *,
    211 				       struct ipftuneable *, ipftuneval_t *);
    212 
    213 
    214 /*
    215  * bit values for identifying presence of individual IP options
    216  * All of these tables should be ordered by increasing key value on the left
    217  * hand side to allow for binary searching of the array and include a trailer
    218  * with a 0 for the bitmask for linear searches to easily find the end with.
    219  */
    220 static const	struct	optlist	ipopts[20] = {
    221 	{ IPOPT_NOP,	0x000001 },
    222 	{ IPOPT_RR,	0x000002 },
    223 	{ IPOPT_ZSU,	0x000004 },
    224 	{ IPOPT_MTUP,	0x000008 },
    225 	{ IPOPT_MTUR,	0x000010 },
    226 	{ IPOPT_ENCODE,	0x000020 },
    227 	{ IPOPT_TS,	0x000040 },
    228 	{ IPOPT_TR,	0x000080 },
    229 	{ IPOPT_SECURITY, 0x000100 },
    230 	{ IPOPT_LSRR,	0x000200 },
    231 	{ IPOPT_E_SEC,	0x000400 },
    232 	{ IPOPT_CIPSO,	0x000800 },
    233 	{ IPOPT_SATID,	0x001000 },
    234 	{ IPOPT_SSRR,	0x002000 },
    235 	{ IPOPT_ADDEXT,	0x004000 },
    236 	{ IPOPT_VISA,	0x008000 },
    237 	{ IPOPT_IMITD,	0x010000 },
    238 	{ IPOPT_EIP,	0x020000 },
    239 	{ IPOPT_FINN,	0x040000 },
    240 	{ 0,		0x000000 }
    241 };
    242 
    243 #ifdef USE_INET6
    244 static const struct optlist ip6exthdr[] = {
    245 	{ IPPROTO_HOPOPTS,		0x000001 },
    246 	{ IPPROTO_IPV6,			0x000002 },
    247 	{ IPPROTO_ROUTING,		0x000004 },
    248 	{ IPPROTO_FRAGMENT,		0x000008 },
    249 	{ IPPROTO_ESP,			0x000010 },
    250 	{ IPPROTO_AH,			0x000020 },
    251 	{ IPPROTO_NONE,			0x000040 },
    252 	{ IPPROTO_DSTOPTS,		0x000080 },
    253 	{ IPPROTO_MOBILITY,		0x000100 },
    254 	{ 0,				0 }
    255 };
    256 #endif
    257 
    258 /*
    259  * bit values for identifying presence of individual IP security options
    260  */
    261 static const	struct	optlist	secopt[8] = {
    262 	{ IPSO_CLASS_RES4,	0x01 },
    263 	{ IPSO_CLASS_TOPS,	0x02 },
    264 	{ IPSO_CLASS_SECR,	0x04 },
    265 	{ IPSO_CLASS_RES3,	0x08 },
    266 	{ IPSO_CLASS_CONF,	0x10 },
    267 	{ IPSO_CLASS_UNCL,	0x20 },
    268 	{ IPSO_CLASS_RES2,	0x40 },
    269 	{ IPSO_CLASS_RES1,	0x80 }
    270 };
    271 
    272 char	ipfilter_version[] = IPL_VERSION;
    273 
    274 int	ipf_features = 0
    275 #ifdef	IPFILTER_LKM
    276 		| IPF_FEAT_LKM
    277 #endif
    278 #ifdef	IPFILTER_LOG
    279 		| IPF_FEAT_LOG
    280 #endif
    281 		| IPF_FEAT_LOOKUP
    282 #ifdef	IPFILTER_BPF
    283 		| IPF_FEAT_BPF
    284 #endif
    285 #ifdef	IPFILTER_COMPILED
    286 		| IPF_FEAT_COMPILED
    287 #endif
    288 #ifdef	IPFILTER_CKSUM
    289 		| IPF_FEAT_CKSUM
    290 #endif
    291 		| IPF_FEAT_SYNC
    292 #ifdef	IPFILTER_SCAN
    293 		| IPF_FEAT_SCAN
    294 #endif
    295 #ifdef	USE_INET6
    296 		| IPF_FEAT_IPV6
    297 #endif
    298 	;
    299 
    300 
    301 /*
    302  * Table of functions available for use with call rules.
    303  */
    304 static ipfunc_resolve_t ipf_availfuncs[] = {
    305 	{ "srcgrpmap", ipf_srcgrpmap, ipf_grpmapinit, ipf_grpmapfini },
    306 	{ "dstgrpmap", ipf_dstgrpmap, ipf_grpmapinit, ipf_grpmapfini },
    307 	{ "",	       NULL,	      NULL,	      NULL }
    308 };
    309 
    310 static const ipftuneable_t ipf_main_tuneables[] = {
    311 	{ { (void *)offsetof(struct ipf_main_softc_s, ipf_flags) },
    312 		"ipf_flags",		0,	0xffffffff,
    313 		stsizeof(ipf_main_softc_t, ipf_flags),
    314 		0,			NULL,	NULL },
    315 	{ { (void *)offsetof(struct ipf_main_softc_s, ipf_active) },
    316 		"active",		0,	0,
    317 		stsizeof(ipf_main_softc_t, ipf_active),
    318 		IPFT_RDONLY,		NULL,	NULL },
    319 	{ { (void *)offsetof(ipf_main_softc_t, ipf_control_forwarding) },
    320 		"control_forwarding",	0, 1,
    321 		stsizeof(ipf_main_softc_t, ipf_control_forwarding),
    322 		0,			NULL,	NULL },
    323 	{ { (void *)offsetof(ipf_main_softc_t, ipf_update_ipid) },
    324 		"update_ipid",		0,	1,
    325 		stsizeof(ipf_main_softc_t, ipf_update_ipid),
    326 		0,			NULL,	NULL },
    327 	{ { (void *)offsetof(ipf_main_softc_t, ipf_chksrc) },
    328 		"chksrc",		0,	1,
    329 		stsizeof(ipf_main_softc_t, ipf_chksrc),
    330 		0,			NULL,	NULL },
    331 	{ { (void *)offsetof(ipf_main_softc_t, ipf_minttl) },
    332 		"min_ttl",		0,	1,
    333 		stsizeof(ipf_main_softc_t, ipf_minttl),
    334 		0,			NULL,	NULL },
    335 	{ { (void *)offsetof(ipf_main_softc_t, ipf_icmpminfragmtu) },
    336 		"icmp_minfragmtu",	0,	1,
    337 		stsizeof(ipf_main_softc_t, ipf_icmpminfragmtu),
    338 		0,			NULL,	NULL },
    339 	{ { (void *)offsetof(ipf_main_softc_t, ipf_pass) },
    340 		"default_pass",		0,	0xffffffff,
    341 		stsizeof(ipf_main_softc_t, ipf_pass),
    342 		0,			NULL,	NULL },
    343 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpidletimeout) },
    344 		"tcp_idle_timeout",	1,	0x7fffffff,
    345 		stsizeof(ipf_main_softc_t, ipf_tcpidletimeout),
    346 		0,			NULL,	ipf_settimeout },
    347 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosewait) },
    348 		"tcp_close_wait",	1,	0x7fffffff,
    349 		stsizeof(ipf_main_softc_t, ipf_tcpclosewait),
    350 		0,			NULL,	ipf_settimeout },
    351 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcplastack) },
    352 		"tcp_last_ack",		1,	0x7fffffff,
    353 		stsizeof(ipf_main_softc_t, ipf_tcplastack),
    354 		0,			NULL,	ipf_settimeout },
    355 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcptimeout) },
    356 		"tcp_timeout",		1,	0x7fffffff,
    357 		stsizeof(ipf_main_softc_t, ipf_tcptimeout),
    358 		0,			NULL,	ipf_settimeout },
    359 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynsent) },
    360 		"tcp_syn_sent",		1,	0x7fffffff,
    361 		stsizeof(ipf_main_softc_t, ipf_tcpsynsent),
    362 		0,			NULL,	ipf_settimeout },
    363 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynrecv) },
    364 		"tcp_syn_received",	1,	0x7fffffff,
    365 		stsizeof(ipf_main_softc_t, ipf_tcpsynrecv),
    366 		0,			NULL,	ipf_settimeout },
    367 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosed) },
    368 		"tcp_closed",		1,	0x7fffffff,
    369 		stsizeof(ipf_main_softc_t, ipf_tcpclosed),
    370 		0,			NULL,	ipf_settimeout },
    371 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcphalfclosed) },
    372 		"tcp_half_closed",	1,	0x7fffffff,
    373 		stsizeof(ipf_main_softc_t, ipf_tcphalfclosed),
    374 		0,			NULL,	ipf_settimeout },
    375 	{ { (void *)offsetof(ipf_main_softc_t, ipf_tcptimewait) },
    376 		"tcp_time_wait",	1,	0x7fffffff,
    377 		stsizeof(ipf_main_softc_t, ipf_tcptimewait),
    378 		0,			NULL,	ipf_settimeout },
    379 	{ { (void *)offsetof(ipf_main_softc_t, ipf_udptimeout) },
    380 		"udp_timeout",		1,	0x7fffffff,
    381 		stsizeof(ipf_main_softc_t, ipf_udptimeout),
    382 		0,			NULL,	ipf_settimeout },
    383 	{ { (void *)offsetof(ipf_main_softc_t, ipf_udpacktimeout) },
    384 		"udp_ack_timeout",	1,	0x7fffffff,
    385 		stsizeof(ipf_main_softc_t, ipf_udpacktimeout),
    386 		0,			NULL,	ipf_settimeout },
    387 	{ { (void *)offsetof(ipf_main_softc_t, ipf_icmptimeout) },
    388 		"icmp_timeout",		1,	0x7fffffff,
    389 		stsizeof(ipf_main_softc_t, ipf_icmptimeout),
    390 		0,			NULL,	ipf_settimeout },
    391 	{ { (void *)offsetof(ipf_main_softc_t, ipf_icmpacktimeout) },
    392 		"icmp_ack_timeout",	1,	0x7fffffff,
    393 		stsizeof(ipf_main_softc_t, ipf_icmpacktimeout),
    394 		0,			NULL,	ipf_settimeout },
    395 	{ { (void *)offsetof(ipf_main_softc_t, ipf_iptimeout) },
    396 		"ip_timeout",		1,	0x7fffffff,
    397 		stsizeof(ipf_main_softc_t, ipf_iptimeout),
    398 		0,			NULL,	ipf_settimeout },
    399 #if defined(INSTANCES) && defined(_KERNEL)
    400 	{ { (void *)offsetof(ipf_main_softc_t, ipf_get_loopback) },
    401 		"intercept_loopback",	0,	1,
    402 		stsizeof(ipf_main_softc_t, ipf_get_loopback),
    403 		0,			NULL,	ipf_set_loopback },
    404 #endif
    405 	{ { 0 },
    406 		NULL,			0,	0,
    407 		0,
    408 		0,			NULL,	NULL }
    409 };
    410 
    411 
    412 /*
    413  * The next section of code is a a collection of small routines that set
    414  * fields in the fr_info_t structure passed based on properties of the
    415  * current packet.  There are different routines for the same protocol
    416  * for each of IPv4 and IPv6.  Adding a new protocol, for which there
    417  * will "special" inspection for setup, is now more easily done by adding
    418  * a new routine and expanding the ipf_pr_ipinit*() function rather than by
    419  * adding more code to a growing switch statement.
    420  */
    421 #ifdef USE_INET6
    422 static	INLINE int	ipf_pr_ah6(fr_info_t *);
    423 static	INLINE void	ipf_pr_esp6(fr_info_t *);
    424 static	INLINE void	ipf_pr_gre6(fr_info_t *);
    425 static	INLINE void	ipf_pr_udp6(fr_info_t *);
    426 static	INLINE void	ipf_pr_tcp6(fr_info_t *);
    427 static	INLINE void	ipf_pr_icmp6(fr_info_t *);
    428 static	INLINE void	ipf_pr_ipv6hdr(fr_info_t *);
    429 static	INLINE void	ipf_pr_short6(fr_info_t *, int);
    430 static	INLINE int	ipf_pr_hopopts6(fr_info_t *);
    431 static	INLINE int	ipf_pr_mobility6(fr_info_t *);
    432 static	INLINE int	ipf_pr_routing6(fr_info_t *);
    433 static	INLINE int	ipf_pr_dstopts6(fr_info_t *);
    434 static	INLINE int	ipf_pr_fragment6(fr_info_t *);
    435 static	INLINE struct ip6_ext *ipf_pr_ipv6exthdr(fr_info_t *, int, int);
    436 
    437 
    438 /* ------------------------------------------------------------------------ */
    439 /* Function:    ipf_pr_short6                                               */
    440 /* Returns:     void                                                        */
    441 /* Parameters:  fin(I)  - pointer to packet information                     */
    442 /*              xmin(I) - minimum header size                               */
    443 /*                                                                          */
    444 /* IPv6 Only                                                                */
    445 /* This is function enforces the 'is a packet too short to be legit' rule   */
    446 /* for IPv6 and marks the packet with FI_SHORT if so.  See function comment */
    447 /* for ipf_pr_short() for more details.                                     */
    448 /* ------------------------------------------------------------------------ */
    449 static INLINE void
    450 ipf_pr_short6(fr_info_t *fin, int xmin)
    451 {
    452 
    453 	if (fin->fin_dlen < xmin)
    454 		fin->fin_flx |= FI_SHORT;
    455 }
    456 
    457 
    458 /* ------------------------------------------------------------------------ */
    459 /* Function:    ipf_pr_ipv6hdr                                              */
    460 /* Returns:     void                                                        */
    461 /* Parameters:  fin(I) - pointer to packet information                      */
    462 /*                                                                          */
    463 /* IPv6 Only                                                                */
    464 /* Copy values from the IPv6 header into the fr_info_t struct and call the  */
    465 /* per-protocol analyzer if it exists.  In validating the packet, a protocol*/
    466 /* analyzer may pullup or free the packet itself so we need to be vigiliant */
    467 /* of that possibility arising.                                             */
    468 /* ------------------------------------------------------------------------ */
    469 static INLINE void
    470 ipf_pr_ipv6hdr(fr_info_t *fin)
    471 {
    472 	ip6_t *ip6 = (ip6_t *)fin->fin_ip;
    473 	int p, go = 1, i, hdrcount;
    474 	fr_ip_t *fi = &fin->fin_fi;
    475 
    476 	fin->fin_off = 0;
    477 
    478 	fi->fi_tos = 0;
    479 	fi->fi_optmsk = 0;
    480 	fi->fi_secmsk = 0;
    481 	fi->fi_auth = 0;
    482 
    483 	p = ip6->ip6_nxt;
    484 	fin->fin_crc = p;
    485 	fi->fi_ttl = ip6->ip6_hlim;
    486 	fi->fi_src.in6 = ip6->ip6_src;
    487 	fin->fin_crc += fi->fi_src.i6[0];
    488 	fin->fin_crc += fi->fi_src.i6[1];
    489 	fin->fin_crc += fi->fi_src.i6[2];
    490 	fin->fin_crc += fi->fi_src.i6[3];
    491 	fi->fi_dst.in6 = ip6->ip6_dst;
    492 	fin->fin_crc += fi->fi_dst.i6[0];
    493 	fin->fin_crc += fi->fi_dst.i6[1];
    494 	fin->fin_crc += fi->fi_dst.i6[2];
    495 	fin->fin_crc += fi->fi_dst.i6[3];
    496 	fin->fin_id = 0;
    497 	if (IN6_IS_ADDR_MULTICAST(&fi->fi_dst.in6))
    498 		fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
    499 
    500 	hdrcount = 0;
    501 	while (go && !(fin->fin_flx & FI_SHORT)) {
    502 		switch (p)
    503 		{
    504 		case IPPROTO_UDP :
    505 			ipf_pr_udp6(fin);
    506 			go = 0;
    507 			break;
    508 
    509 		case IPPROTO_TCP :
    510 			ipf_pr_tcp6(fin);
    511 			go = 0;
    512 			break;
    513 
    514 		case IPPROTO_ICMPV6 :
    515 			ipf_pr_icmp6(fin);
    516 			go = 0;
    517 			break;
    518 
    519 		case IPPROTO_GRE :
    520 			ipf_pr_gre6(fin);
    521 			go = 0;
    522 			break;
    523 
    524 		case IPPROTO_HOPOPTS :
    525 			p = ipf_pr_hopopts6(fin);
    526 			break;
    527 
    528 		case IPPROTO_MOBILITY :
    529 			p = ipf_pr_mobility6(fin);
    530 			break;
    531 
    532 		case IPPROTO_DSTOPTS :
    533 			p = ipf_pr_dstopts6(fin);
    534 			break;
    535 
    536 		case IPPROTO_ROUTING :
    537 			p = ipf_pr_routing6(fin);
    538 			break;
    539 
    540 		case IPPROTO_AH :
    541 			p = ipf_pr_ah6(fin);
    542 			break;
    543 
    544 		case IPPROTO_ESP :
    545 			ipf_pr_esp6(fin);
    546 			go = 0;
    547 			break;
    548 
    549 		case IPPROTO_IPV6 :
    550 			for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
    551 				if (ip6exthdr[i].ol_val == p) {
    552 					fin->fin_flx |= ip6exthdr[i].ol_bit;
    553 					break;
    554 				}
    555 			go = 0;
    556 			break;
    557 
    558 		case IPPROTO_NONE :
    559 			go = 0;
    560 			break;
    561 
    562 		case IPPROTO_FRAGMENT :
    563 			p = ipf_pr_fragment6(fin);
    564 			/*
    565 			 * Given that the only fragments we want to let through
    566 			 * (where fin_off != 0) are those where the non-first
    567 			 * fragments only have data, we can safely stop looking
    568 			 * at headers if this is a non-leading fragment.
    569 			 */
    570 			if (fin->fin_off != 0)
    571 				go = 0;
    572 			break;
    573 
    574 		default :
    575 			go = 0;
    576 			break;
    577 		}
    578 		hdrcount++;
    579 
    580 		/*
    581 		 * It is important to note that at this point, for the
    582 		 * extension headers (go != 0), the entire header may not have
    583 		 * been pulled up when the code gets to this point.  This is
    584 		 * only done for "go != 0" because the other header handlers
    585 		 * will all pullup their complete header.  The other indicator
    586 		 * of an incomplete packet is that this was just an extension
    587 		 * header.
    588 		 */
    589 		if ((go != 0) && (p != IPPROTO_NONE) &&
    590 		    (ipf_pr_pullup(fin, 0) == -1)) {
    591 			p = IPPROTO_NONE;
    592 			break;
    593 		}
    594 	}
    595 
    596 	/*
    597 	 * Some of the above functions, like ipf_pr_esp6(), can call ipf_pullup
    598 	 * and destroy whatever packet was here.  The caller of this function
    599 	 * expects us to return if there is a problem with ipf_pullup.
    600 	 */
    601 	if (fin->fin_m == NULL) {
    602 		ipf_main_softc_t *softc = fin->fin_main_soft;
    603 
    604 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_bad);
    605 		return;
    606 	}
    607 
    608 	fi->fi_p = p;
    609 
    610 	/*
    611 	 * IPv6 fragment case 1 - see comment for ipf_pr_fragment6().
    612 	 * "go != 0" imples the above loop hasn't arrived at a layer 4 header.
    613 	 */
    614 	if ((go != 0) && (fin->fin_flx & FI_FRAG) && (fin->fin_off == 0)) {
    615 		ipf_main_softc_t *softc = fin->fin_main_soft;
    616 
    617 		fin->fin_flx |= FI_BAD;
    618 		DT2(ipf_fi_bad_ipv6_frag_1, fr_info_t *, fin, int, go);
    619 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_badfrag);
    620 		LBUMP(ipf_stats[fin->fin_out].fr_v6_bad);
    621 	}
    622 }
    623 
    624 
    625 /* ------------------------------------------------------------------------ */
    626 /* Function:    ipf_pr_ipv6exthdr                                           */
    627 /* Returns:     struct ip6_ext * - pointer to the start of the next header  */
    628 /*                                 or NULL if there is a prolblem.          */
    629 /* Parameters:  fin(I)      - pointer to packet information                 */
    630 /*              multiple(I) - flag indicating yes/no if multiple occurances */
    631 /*                            of this extension header are allowed.         */
    632 /*              proto(I)    - protocol number for this extension header     */
    633 /*                                                                          */
    634 /* IPv6 Only                                                                */
    635 /* This function embodies a number of common checks that all IPv6 extension */
    636 /* headers must be subjected to.  For example, making sure the packet is    */
    637 /* big enough for it to be in, checking if it is repeated and setting a     */
    638 /* flag to indicate its presence.                                           */
    639 /* ------------------------------------------------------------------------ */
    640 static INLINE struct ip6_ext *
    641 ipf_pr_ipv6exthdr(fr_info_t *fin, int multiple, int proto)
    642 {
    643 	ipf_main_softc_t *softc = fin->fin_main_soft;
    644 	struct ip6_ext *hdr;
    645 	u_short shift;
    646 	int i;
    647 
    648 	fin->fin_flx |= FI_V6EXTHDR;
    649 
    650 				/* 8 is default length of extension hdr */
    651 	if ((fin->fin_dlen - 8) < 0) {
    652 		fin->fin_flx |= FI_SHORT;
    653 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_short);
    654 		return NULL;
    655 	}
    656 
    657 	if (ipf_pr_pullup(fin, 8) == -1) {
    658 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_pullup);
    659 		return NULL;
    660 	}
    661 
    662 	hdr = fin->fin_dp;
    663 	switch (proto)
    664 	{
    665 	case IPPROTO_FRAGMENT :
    666 		shift = 8;
    667 		break;
    668 	default :
    669 		shift = 8 + (hdr->ip6e_len << 3);
    670 		break;
    671 	}
    672 
    673 	if (shift > fin->fin_dlen) {	/* Nasty extension header length? */
    674 		fin->fin_flx |= FI_BAD;
    675 		DT3(ipf_fi_bad_pr_ipv6exthdr_len, fr_info_t *, fin, u_short, shift, u_short, fin->fin_dlen);
    676 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_hlen);
    677 		return NULL;
    678 	}
    679 
    680 	fin->fin_dp = (char *)fin->fin_dp + shift;
    681 	fin->fin_dlen -= shift;
    682 
    683 	/*
    684 	 * If we have seen a fragment header, do not set any flags to indicate
    685 	 * the presence of this extension header as it has no impact on the
    686 	 * end result until after it has been defragmented.
    687 	 */
    688 	if (fin->fin_flx & FI_FRAG)
    689 		return hdr;
    690 
    691 	for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
    692 		if (ip6exthdr[i].ol_val == proto) {
    693 			/*
    694 			 * Most IPv6 extension headers are only allowed once.
    695 			 */
    696 			if ((multiple == 0) &&
    697 			    ((fin->fin_optmsk & ip6exthdr[i].ol_bit) != 0)) {
    698 				fin->fin_flx |= FI_BAD;
    699 				DT2(ipf_fi_bad_ipv6exthdr_once, fr_info_t *, fin, u_int, (fin->fin_optmsk & ip6exthdr[i].ol_bit));
    700 			} else
    701 				fin->fin_optmsk |= ip6exthdr[i].ol_bit;
    702 			break;
    703 		}
    704 
    705 	return hdr;
    706 }
    707 
    708 
    709 /* ------------------------------------------------------------------------ */
    710 /* Function:    ipf_pr_hopopts6                                             */
    711 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
    712 /* Parameters:  fin(I) - pointer to packet information                      */
    713 /*                                                                          */
    714 /* IPv6 Only                                                                */
    715 /* This is function checks pending hop by hop options extension header      */
    716 /* ------------------------------------------------------------------------ */
    717 static INLINE int
    718 ipf_pr_hopopts6(fr_info_t *fin)
    719 {
    720 	struct ip6_ext *hdr;
    721 
    722 	hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
    723 	if (hdr == NULL)
    724 		return IPPROTO_NONE;
    725 	return hdr->ip6e_nxt;
    726 }
    727 
    728 
    729 /* ------------------------------------------------------------------------ */
    730 /* Function:    ipf_pr_mobility6                                            */
    731 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
    732 /* Parameters:  fin(I) - pointer to packet information                      */
    733 /*                                                                          */
    734 /* IPv6 Only                                                                */
    735 /* This is function checks the IPv6 mobility extension header               */
    736 /* ------------------------------------------------------------------------ */
    737 static INLINE int
    738 ipf_pr_mobility6(fr_info_t *fin)
    739 {
    740 	struct ip6_ext *hdr;
    741 
    742 	hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_MOBILITY);
    743 	if (hdr == NULL)
    744 		return IPPROTO_NONE;
    745 	return hdr->ip6e_nxt;
    746 }
    747 
    748 
    749 /* ------------------------------------------------------------------------ */
    750 /* Function:    ipf_pr_routing6                                             */
    751 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
    752 /* Parameters:  fin(I) - pointer to packet information                      */
    753 /*                                                                          */
    754 /* IPv6 Only                                                                */
    755 /* This is function checks pending routing extension header                 */
    756 /* ------------------------------------------------------------------------ */
    757 static INLINE int
    758 ipf_pr_routing6(fr_info_t *fin)
    759 {
    760 	struct ip6_routing *hdr;
    761 
    762 	hdr = (struct ip6_routing *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_ROUTING);
    763 	if (hdr == NULL)
    764 		return IPPROTO_NONE;
    765 
    766 	switch (hdr->ip6r_type)
    767 	{
    768 	case 0 :
    769 		/*
    770 		 * Nasty extension header length?
    771 		 */
    772 		if (((hdr->ip6r_len >> 1) < hdr->ip6r_segleft) ||
    773 		    (hdr->ip6r_segleft && (hdr->ip6r_len & 1))) {
    774 			ipf_main_softc_t *softc = fin->fin_main_soft;
    775 
    776 			fin->fin_flx |= FI_BAD;
    777 			DT1(ipf_fi_bad_routing6, fr_info_t *, fin);
    778 			LBUMPD(ipf_stats[fin->fin_out], fr_v6_rh_bad);
    779 			return IPPROTO_NONE;
    780 		}
    781 		break;
    782 
    783 	default :
    784 		break;
    785 	}
    786 
    787 	return hdr->ip6r_nxt;
    788 }
    789 
    790 
    791 /* ------------------------------------------------------------------------ */
    792 /* Function:    ipf_pr_fragment6                                            */
    793 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
    794 /* Parameters:  fin(I) - pointer to packet information                      */
    795 /*                                                                          */
    796 /* IPv6 Only                                                                */
    797 /* Examine the IPv6 fragment header and extract fragment offset information.*/
    798 /*                                                                          */
    799 /* Fragments in IPv6 are extraordinarily difficult to deal with - much more */
    800 /* so than in IPv4.  There are 5 cases of fragments with IPv6 that all      */
    801 /* packets with a fragment header can fit into.  They are as follows:       */
    802 /*                                                                          */
    803 /* 1.  [IPv6][0-n EH][FH][0-n EH] (no L4HDR present)                        */
    804 /* 2.  [IPV6][0-n EH][FH][0-n EH][L4HDR part] (short)                       */
    805 /* 3.  [IPV6][0-n EH][FH][L4HDR part][0-n data] (short)                     */
    806 /* 4.  [IPV6][0-n EH][FH][0-n EH][L4HDR][0-n data]                          */
    807 /* 5.  [IPV6][0-n EH][FH][data]                                             */
    808 /*                                                                          */
    809 /* IPV6 = IPv6 header, FH = Fragment Header,                                */
    810 /* 0-n EH = 0 or more extension headers, 0-n data = 0 or more bytes of data */
    811 /*                                                                          */
    812 /* Packets that match 1, 2, 3 will be dropped as the only reasonable        */
    813 /* scenario in which they happen is in extreme circumstances that are most  */
    814 /* likely to be an indication of an attack rather than normal traffic.      */
    815 /* A type 3 packet may be sent by an attacked after a type 4 packet.  There */
    816 /* are two rules that can be used to guard against type 3 packets: L4       */
    817 /* headers must always be in a packet that has the offset field set to 0    */
    818 /* and no packet is allowed to overlay that where offset = 0.               */
    819 /* ------------------------------------------------------------------------ */
    820 static INLINE int
    821 ipf_pr_fragment6(fr_info_t *fin)
    822 {
    823 	ipf_main_softc_t *softc = fin->fin_main_soft;
    824 	struct ip6_frag *frag;
    825 
    826 	fin->fin_flx |= FI_FRAG;
    827 
    828 	frag = (struct ip6_frag *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_FRAGMENT);
    829 	if (frag == NULL) {
    830 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_frag_bad);
    831 		return IPPROTO_NONE;
    832 	}
    833 
    834 	if ((frag->ip6f_offlg & IP6F_MORE_FRAG) != 0) {
    835 		/*
    836 		 * Any fragment that isn't the last fragment must have its
    837 		 * length as a multiple of 8.
    838 		 */
    839 		if ((fin->fin_plen & 7) != 0) {
    840 			fin->fin_flx |= FI_BAD;
    841 			DT2(ipf_fi_bad_frag_not_8, fr_info_t *, fin, u_int, (fin->fin_plen & 7));
    842 		}
    843 	}
    844 
    845 	fin->fin_fraghdr = frag;
    846 	fin->fin_id = frag->ip6f_ident;
    847 	fin->fin_off = ntohs(frag->ip6f_offlg & IP6F_OFF_MASK);
    848 	if (fin->fin_off != 0)
    849 		fin->fin_flx |= FI_FRAGBODY;
    850 
    851 	/*
    852 	 * Jumbograms aren't handled, so the max. length is 64k
    853 	 */
    854 	if ((fin->fin_off << 3) + fin->fin_dlen > 65535) {
    855 		  fin->fin_flx |= FI_BAD;
    856 		  DT2(ipf_fi_bad_jumbogram, fr_info_t *, fin, u_int, ((fin->fin_off << 3) + fin->fin_dlen));
    857 	}
    858 
    859 	/*
    860 	 * We don't know where the transport layer header (or whatever is next
    861 	 * is), as it could be behind destination options (amongst others) so
    862 	 * return the fragment header as the type of packet this is.  Note that
    863 	 * this effectively disables the fragment cache for > 1 protocol at a
    864 	 * time.
    865 	 */
    866 	return frag->ip6f_nxt;
    867 }
    868 
    869 
    870 /* ------------------------------------------------------------------------ */
    871 /* Function:    ipf_pr_dstopts6                                             */
    872 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
    873 /* Parameters:  fin(I) - pointer to packet information                      */
    874 /*                                                                          */
    875 /* IPv6 Only                                                                */
    876 /* This is function checks pending destination options extension header     */
    877 /* ------------------------------------------------------------------------ */
    878 static INLINE int
    879 ipf_pr_dstopts6(fr_info_t *fin)
    880 {
    881 	ipf_main_softc_t *softc = fin->fin_main_soft;
    882 	struct ip6_ext *hdr;
    883 
    884 	hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_DSTOPTS);
    885 	if (hdr == NULL) {
    886 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_dst_bad);
    887 		return IPPROTO_NONE;
    888 	}
    889 	return hdr->ip6e_nxt;
    890 }
    891 
    892 
    893 /* ------------------------------------------------------------------------ */
    894 /* Function:    ipf_pr_icmp6                                                */
    895 /* Returns:     void                                                        */
    896 /* Parameters:  fin(I) - pointer to packet information                      */
    897 /*                                                                          */
    898 /* IPv6 Only                                                                */
    899 /* This routine is mainly concerned with determining the minimum valid size */
    900 /* for an ICMPv6 packet.                                                    */
    901 /* ------------------------------------------------------------------------ */
    902 static INLINE void
    903 ipf_pr_icmp6(fr_info_t *fin)
    904 {
    905 	int minicmpsz = sizeof(struct icmp6_hdr);
    906 	struct icmp6_hdr *icmp6;
    907 
    908 	if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN - sizeof(ip6_t)) == -1) {
    909 		ipf_main_softc_t *softc = fin->fin_main_soft;
    910 
    911 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_icmp6_pullup);
    912 		return;
    913 	}
    914 
    915 	if (fin->fin_dlen > 1) {
    916 		ip6_t *ip6;
    917 
    918 		icmp6 = fin->fin_dp;
    919 
    920 		fin->fin_data[0] = *(u_short *)icmp6;
    921 
    922 		if ((icmp6->icmp6_type & ICMP6_INFOMSG_MASK) != 0)
    923 			fin->fin_flx |= FI_ICMPQUERY;
    924 
    925 		switch (icmp6->icmp6_type)
    926 		{
    927 		case ICMP6_ECHO_REPLY :
    928 		case ICMP6_ECHO_REQUEST :
    929 			if (fin->fin_dlen >= 6)
    930 				fin->fin_data[1] = icmp6->icmp6_id;
    931 			minicmpsz = ICMP6ERR_MINPKTLEN - sizeof(ip6_t);
    932 			break;
    933 
    934 		case ICMP6_DST_UNREACH :
    935 		case ICMP6_PACKET_TOO_BIG :
    936 		case ICMP6_TIME_EXCEEDED :
    937 		case ICMP6_PARAM_PROB :
    938 			fin->fin_flx |= FI_ICMPERR;
    939 			minicmpsz = ICMP6ERR_IPICMPHLEN - sizeof(ip6_t);
    940 			if (fin->fin_plen < ICMP6ERR_IPICMPHLEN)
    941 				break;
    942 
    943 			if (M_LEN(fin->fin_m) < fin->fin_plen) {
    944 				if (ipf_coalesce(fin) != 1)
    945 					return;
    946 			}
    947 
    948 			if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN) == -1)
    949 				return;
    950 
    951 			/*
    952 			 * If the destination of this packet doesn't match the
    953 			 * source of the original packet then this packet is
    954 			 * not correct.
    955 			 */
    956 			icmp6 = fin->fin_dp;
    957 			ip6 = (ip6_t *)((char *)icmp6 + ICMPERR_ICMPHLEN);
    958 			if (IP6_NEQ(&fin->fin_fi.fi_dst,
    959 				    &ip6->ip6_src)) {
    960 				fin->fin_flx |= FI_BAD;
    961 				DT1(ipf_fi_bad_icmp6, fr_info_t *, fin);
    962 			}
    963 			break;
    964 		default :
    965 			break;
    966 		}
    967 	}
    968 
    969 	ipf_pr_short6(fin, minicmpsz);
    970 	if ((fin->fin_flx & (FI_SHORT|FI_BAD)) == 0) {
    971 		u_char p = fin->fin_p;
    972 
    973 		fin->fin_p = IPPROTO_ICMPV6;
    974 		ipf_checkv6sum(fin);
    975 		fin->fin_p = p;
    976 	}
    977 }
    978 
    979 
    980 /* ------------------------------------------------------------------------ */
    981 /* Function:    ipf_pr_udp6                                                 */
    982 /* Returns:     void                                                        */
    983 /* Parameters:  fin(I) - pointer to packet information                      */
    984 /*                                                                          */
    985 /* IPv6 Only                                                                */
    986 /* Analyse the packet for IPv6/UDP properties.                              */
    987 /* Is not expected to be called for fragmented packets.                     */
    988 /* ------------------------------------------------------------------------ */
    989 static INLINE void
    990 ipf_pr_udp6(fr_info_t *fin)
    991 {
    992 
    993 	if (ipf_pr_udpcommon(fin) == 0) {
    994 		u_char p = fin->fin_p;
    995 
    996 		fin->fin_p = IPPROTO_UDP;
    997 		ipf_checkv6sum(fin);
    998 		fin->fin_p = p;
    999 	}
   1000 }
   1001 
   1002 
   1003 /* ------------------------------------------------------------------------ */
   1004 /* Function:    ipf_pr_tcp6                                                 */
   1005 /* Returns:     void                                                        */
   1006 /* Parameters:  fin(I) - pointer to packet information                      */
   1007 /*                                                                          */
   1008 /* IPv6 Only                                                                */
   1009 /* Analyse the packet for IPv6/TCP properties.                              */
   1010 /* Is not expected to be called for fragmented packets.                     */
   1011 /* ------------------------------------------------------------------------ */
   1012 static INLINE void
   1013 ipf_pr_tcp6(fr_info_t *fin)
   1014 {
   1015 
   1016 	if (ipf_pr_tcpcommon(fin) == 0) {
   1017 		u_char p = fin->fin_p;
   1018 
   1019 		fin->fin_p = IPPROTO_TCP;
   1020 		ipf_checkv6sum(fin);
   1021 		fin->fin_p = p;
   1022 	}
   1023 }
   1024 
   1025 
   1026 /* ------------------------------------------------------------------------ */
   1027 /* Function:    ipf_pr_esp6                                                 */
   1028 /* Returns:     void                                                        */
   1029 /* Parameters:  fin(I) - pointer to packet information                      */
   1030 /*                                                                          */
   1031 /* IPv6 Only                                                                */
   1032 /* Analyse the packet for ESP properties.                                   */
   1033 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits)  */
   1034 /* even though the newer ESP packets must also have a sequence number that  */
   1035 /* is 32bits as well, it is not possible(?) to determine the version from a */
   1036 /* simple packet header.                                                    */
   1037 /* ------------------------------------------------------------------------ */
   1038 static INLINE void
   1039 ipf_pr_esp6(fr_info_t *fin)
   1040 {
   1041 
   1042 	if ((fin->fin_off == 0) && (ipf_pr_pullup(fin, 8) == -1)) {
   1043 		ipf_main_softc_t *softc = fin->fin_main_soft;
   1044 
   1045 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_esp_pullup);
   1046 		return;
   1047 	}
   1048 }
   1049 
   1050 
   1051 /* ------------------------------------------------------------------------ */
   1052 /* Function:    ipf_pr_ah6                                                  */
   1053 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
   1054 /* Parameters:  fin(I) - pointer to packet information                      */
   1055 /*                                                                          */
   1056 /* IPv6 Only                                                                */
   1057 /* Analyse the packet for AH properties.                                    */
   1058 /* The minimum length is taken to be the combination of all fields in the   */
   1059 /* header being present and no authentication data (null algorithm used.)   */
   1060 /* ------------------------------------------------------------------------ */
   1061 static INLINE int
   1062 ipf_pr_ah6(fr_info_t *fin)
   1063 {
   1064 	authhdr_t *ah;
   1065 
   1066 	fin->fin_flx |= FI_AH;
   1067 
   1068 	ah = (authhdr_t *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
   1069 	if (ah == NULL) {
   1070 		ipf_main_softc_t *softc = fin->fin_main_soft;
   1071 
   1072 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_ah_bad);
   1073 		return IPPROTO_NONE;
   1074 	}
   1075 
   1076 	ipf_pr_short6(fin, sizeof(*ah));
   1077 
   1078 	/*
   1079 	 * No need for another pullup, ipf_pr_ipv6exthdr() will pullup
   1080 	 * enough data to satisfy ah_next (the very first one.)
   1081 	 */
   1082 	return ah->ah_next;
   1083 }
   1084 
   1085 
   1086 /* ------------------------------------------------------------------------ */
   1087 /* Function:    ipf_pr_gre6                                                 */
   1088 /* Returns:     void                                                        */
   1089 /* Parameters:  fin(I) - pointer to packet information                      */
   1090 /*                                                                          */
   1091 /* Analyse the packet for GRE properties.                                   */
   1092 /* ------------------------------------------------------------------------ */
   1093 static INLINE void
   1094 ipf_pr_gre6(fr_info_t *fin)
   1095 {
   1096 	grehdr_t *gre;
   1097 
   1098 	if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
   1099 		ipf_main_softc_t *softc = fin->fin_main_soft;
   1100 
   1101 		LBUMPD(ipf_stats[fin->fin_out], fr_v6_gre_pullup);
   1102 		return;
   1103 	}
   1104 
   1105 	gre = fin->fin_dp;
   1106 	if (GRE_REV(gre->gr_flags) == 1)
   1107 		fin->fin_data[0] = gre->gr_call;
   1108 }
   1109 #endif	/* USE_INET6 */
   1110 
   1111 
   1112 /* ------------------------------------------------------------------------ */
   1113 /* Function:    ipf_pr_pullup                                               */
   1114 /* Returns:     int     - 0 == pullup succeeded, -1 == failure              */
   1115 /* Parameters:  fin(I)  - pointer to packet information                     */
   1116 /*              plen(I) - length (excluding L3 header) to pullup            */
   1117 /*                                                                          */
   1118 /* Short inline function to cut down on code duplication to perform a call  */
   1119 /* to ipf_pullup to ensure there is the required amount of data,            */
   1120 /* consecutively in the packet buffer.                                      */
   1121 /*                                                                          */
   1122 /* This function pulls up 'extra' data at the location of fin_dp.  fin_dp   */
   1123 /* points to the first byte after the complete layer 3 header, which will   */
   1124 /* include all of the known extension headers for IPv6 or options for IPv4. */
   1125 /*                                                                          */
   1126 /* Since fr_pullup() expects the total length of bytes to be pulled up, it  */
   1127 /* is necessary to add those we can already assume to be pulled up (fin_dp  */
   1128 /* - fin_ip) to what is passed through.                                     */
   1129 /* ------------------------------------------------------------------------ */
   1130 int
   1131 ipf_pr_pullup(fr_info_t *fin, int plen)
   1132 {
   1133 	ipf_main_softc_t *softc = fin->fin_main_soft;
   1134 
   1135 	if (fin->fin_m != NULL) {
   1136 		if (fin->fin_dp != NULL)
   1137 			plen += (char *)fin->fin_dp -
   1138 				((char *)fin->fin_ip + fin->fin_hlen);
   1139 		plen += fin->fin_hlen;
   1140 		if (M_LEN(fin->fin_m) < plen + fin->fin_ipoff) {
   1141 #if defined(_KERNEL)
   1142 			if (ipf_pullup(fin->fin_m, fin, plen) == NULL) {
   1143 				DT(ipf_pullup_fail);
   1144 				LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
   1145 				return -1;
   1146 			}
   1147 			LBUMP(ipf_stats[fin->fin_out].fr_pull[0]);
   1148 #else
   1149 			LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
   1150 			/*
   1151 			 * Fake ipf_pullup failing
   1152 			 */
   1153 			fin->fin_reason = FRB_PULLUP;
   1154 			*fin->fin_mp = NULL;
   1155 			fin->fin_m = NULL;
   1156 			fin->fin_ip = NULL;
   1157 			return -1;
   1158 #endif
   1159 		}
   1160 	}
   1161 	return 0;
   1162 }
   1163 
   1164 
   1165 /* ------------------------------------------------------------------------ */
   1166 /* Function:    ipf_pr_short                                                */
   1167 /* Returns:     void                                                        */
   1168 /* Parameters:  fin(I)  - pointer to packet information                     */
   1169 /*              xmin(I) - minimum header size                               */
   1170 /*                                                                          */
   1171 /* Check if a packet is "short" as defined by xmin.  The rule we are        */
   1172 /* applying here is that the packet must not be fragmented within the layer */
   1173 /* 4 header.  That is, it must not be a fragment that has its offset set to */
   1174 /* start within the layer 4 header (hdrmin) or if it is at offset 0, the    */
   1175 /* entire layer 4 header must be present (min).                             */
   1176 /* ------------------------------------------------------------------------ */
   1177 static INLINE void
   1178 ipf_pr_short(fr_info_t *fin, int xmin)
   1179 {
   1180 
   1181 	if (fin->fin_off == 0) {
   1182 		if (fin->fin_dlen < xmin)
   1183 			fin->fin_flx |= FI_SHORT;
   1184 	} else if (fin->fin_off < xmin) {
   1185 		fin->fin_flx |= FI_SHORT;
   1186 	}
   1187 }
   1188 
   1189 
   1190 /* ------------------------------------------------------------------------ */
   1191 /* Function:    ipf_pr_icmp                                                 */
   1192 /* Returns:     void                                                        */
   1193 /* Parameters:  fin(I) - pointer to packet information                      */
   1194 /*                                                                          */
   1195 /* IPv4 Only                                                                */
   1196 /* Do a sanity check on the packet for ICMP (v4).  In nearly all cases,     */
   1197 /* except extrememly bad packets, both type and code will be present.       */
   1198 /* The expected minimum size of an ICMP packet is very much dependent on    */
   1199 /* the type of it.                                                          */
   1200 /*                                                                          */
   1201 /* XXX - other ICMP sanity checks?                                          */
   1202 /* ------------------------------------------------------------------------ */
   1203 static INLINE void
   1204 ipf_pr_icmp(fr_info_t *fin)
   1205 {
   1206 	ipf_main_softc_t *softc = fin->fin_main_soft;
   1207 	int minicmpsz = sizeof(struct icmp);
   1208 	icmphdr_t *icmp;
   1209 	ip_t *oip;
   1210 
   1211 	ipf_pr_short(fin, ICMPERR_ICMPHLEN);
   1212 
   1213 	if (fin->fin_off != 0) {
   1214 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_frag);
   1215 		return;
   1216 	}
   1217 
   1218 	if (ipf_pr_pullup(fin, ICMPERR_ICMPHLEN) == -1) {
   1219 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_pullup);
   1220 		return;
   1221 	}
   1222 
   1223 	icmp = fin->fin_dp;
   1224 
   1225 	fin->fin_data[0] = *(u_short *)icmp;
   1226 	fin->fin_data[1] = icmp->icmp_id;
   1227 
   1228 	switch (icmp->icmp_type)
   1229 	{
   1230 	case ICMP_ECHOREPLY :
   1231 	case ICMP_ECHO :
   1232 	/* Router discovery messaes - RFC 1256 */
   1233 	case ICMP_ROUTERADVERT :
   1234 	case ICMP_ROUTERSOLICIT :
   1235 		fin->fin_flx |= FI_ICMPQUERY;
   1236 		minicmpsz = ICMP_MINLEN;
   1237 		break;
   1238 	/*
   1239 	 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
   1240 	 * 3 * timestamp(3 * 4)
   1241 	 */
   1242 	case ICMP_TSTAMP :
   1243 	case ICMP_TSTAMPREPLY :
   1244 		fin->fin_flx |= FI_ICMPQUERY;
   1245 		minicmpsz = 20;
   1246 		break;
   1247 	/*
   1248 	 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
   1249 	 * mask(4)
   1250 	 */
   1251 	case ICMP_IREQ :
   1252 	case ICMP_IREQREPLY :
   1253 	case ICMP_MASKREQ :
   1254 	case ICMP_MASKREPLY :
   1255 		fin->fin_flx |= FI_ICMPQUERY;
   1256 		minicmpsz = 12;
   1257 		break;
   1258 	/*
   1259 	 * type(1) + code(1) + cksum(2) + id(2) seq(2) + ip(20+)
   1260 	 */
   1261 	case ICMP_UNREACH :
   1262 #ifdef icmp_nextmtu
   1263 		if (icmp->icmp_code == ICMP_UNREACH_NEEDFRAG) {
   1264 			if (icmp->icmp_nextmtu < softc->ipf_icmpminfragmtu) {
   1265 				fin->fin_flx |= FI_BAD;
   1266 				DT3(ipf_fi_bad_icmp_nextmtu, fr_info_t *, fin, u_int, icmp->icmp_nextmtu, u_int, softc->ipf_icmpminfragmtu);
   1267 			}
   1268 		}
   1269 #endif
   1270 		/* FALLTHROUGH */
   1271 	case ICMP_SOURCEQUENCH :
   1272 	case ICMP_REDIRECT :
   1273 	case ICMP_TIMXCEED :
   1274 	case ICMP_PARAMPROB :
   1275 		fin->fin_flx |= FI_ICMPERR;
   1276 		if (ipf_coalesce(fin) != 1) {
   1277 			LBUMPD(ipf_stats[fin->fin_out], fr_icmp_coalesce);
   1278 			return;
   1279 		}
   1280 
   1281 		/*
   1282 		 * ICMP error packets should not be generated for IP
   1283 		 * packets that are a fragment that isn't the first
   1284 		 * fragment.
   1285 		 */
   1286 		oip = (ip_t *)((char *)fin->fin_dp + ICMPERR_ICMPHLEN);
   1287 		if ((ntohs(oip->ip_off) & IP_OFFMASK) != 0) {
   1288 			fin->fin_flx |= FI_BAD;
   1289 			DT2(ipf_fi_bad_icmp_err, fr_info_t, fin, u_int, (ntohs(oip->ip_off) & IP_OFFMASK));
   1290 		}
   1291 
   1292 		/*
   1293 		 * If the destination of this packet doesn't match the
   1294 		 * source of the original packet then this packet is
   1295 		 * not correct.
   1296 		 */
   1297 		if (oip->ip_src.s_addr != fin->fin_daddr) {
   1298 			fin->fin_flx |= FI_BAD;
   1299 			DT1(ipf_fi_bad_src_ne_dst, fr_info_t *, fin);
   1300 		}
   1301 		break;
   1302 	default :
   1303 		break;
   1304 	}
   1305 
   1306 	ipf_pr_short(fin, minicmpsz);
   1307 
   1308 	ipf_checkv4sum(fin);
   1309 }
   1310 
   1311 
   1312 /* ------------------------------------------------------------------------ */
   1313 /* Function:    ipf_pr_tcpcommon                                            */
   1314 /* Returns:     int    - 0 = header ok, 1 = bad packet, -1 = buffer error   */
   1315 /* Parameters:  fin(I) - pointer to packet information                      */
   1316 /*                                                                          */
   1317 /* TCP header sanity checking.  Look for bad combinations of TCP flags,     */
   1318 /* and make some checks with how they interact with other fields.           */
   1319 /* If compiled with IPFILTER_CKSUM, check to see if the TCP checksum is     */
   1320 /* valid and mark the packet as bad if not.                                 */
   1321 /* ------------------------------------------------------------------------ */
   1322 static INLINE int
   1323 ipf_pr_tcpcommon(fr_info_t *fin)
   1324 {
   1325 	ipf_main_softc_t *softc = fin->fin_main_soft;
   1326 	int flags, tlen;
   1327 	tcphdr_t *tcp;
   1328 
   1329 	fin->fin_flx |= FI_TCPUDP;
   1330 	if (fin->fin_off != 0) {
   1331 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_frag);
   1332 		return 0;
   1333 	}
   1334 
   1335 	if (ipf_pr_pullup(fin, sizeof(*tcp)) == -1) {
   1336 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
   1337 		return -1;
   1338 	}
   1339 
   1340 	tcp = fin->fin_dp;
   1341 	if (fin->fin_dlen > 3) {
   1342 		fin->fin_sport = ntohs(tcp->th_sport);
   1343 		fin->fin_dport = ntohs(tcp->th_dport);
   1344 	}
   1345 
   1346 	if ((fin->fin_flx & FI_SHORT) != 0) {
   1347 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_short);
   1348 		return 1;
   1349 	}
   1350 
   1351 	/*
   1352 	 * Use of the TCP data offset *must* result in a value that is at
   1353 	 * least the same size as the TCP header.
   1354 	 */
   1355 	tlen = TCP_OFF(tcp) << 2;
   1356 	if (tlen < sizeof(tcphdr_t)) {
   1357 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_small);
   1358 		fin->fin_flx |= FI_BAD;
   1359 		DT3(ipf_fi_bad_tlen, fr_info_t, fin, u_int, tlen, u_int, sizeof(tcphdr_t));
   1360 		return 1;
   1361 	}
   1362 
   1363 	flags = tcp->th_flags;
   1364 	fin->fin_tcpf = tcp->th_flags;
   1365 
   1366 	/*
   1367 	 * If the urgent flag is set, then the urgent pointer must
   1368 	 * also be set and vice versa.  Good TCP packets do not have
   1369 	 * just one of these set.
   1370 	 */
   1371 	if ((flags & TH_URG) != 0 && (tcp->th_urp == 0)) {
   1372 		fin->fin_flx |= FI_BAD;
   1373 		DT3(ipf_fi_bad_th_urg, fr_info_t*, fin, u_int, (flags & TH_URG), u_int, tcp->th_urp);
   1374 #if 0
   1375 	} else if ((flags & TH_URG) == 0 && (tcp->th_urp != 0)) {
   1376 		/*
   1377 		 * Ignore this case (#if 0) as it shows up in "real"
   1378 		 * traffic with bogus values in the urgent pointer field.
   1379 		 */
   1380 		fin->fin_flx |= FI_BAD;
   1381 		DT3(ipf_fi_bad_th_urg0, fr_info_t *, fin, u_int, (flags & TH_URG), u_int, tcp->th_urp);
   1382 #endif
   1383 	} else if (((flags & (TH_SYN|TH_FIN)) != 0) &&
   1384 		   ((flags & (TH_RST|TH_ACK)) == TH_RST)) {
   1385 		/* TH_FIN|TH_RST|TH_ACK seems to appear "naturally" */
   1386 		fin->fin_flx |= FI_BAD;
   1387 		DT1(ipf_fi_bad_th_fin_rst_ack, fr_info_t, fin);
   1388 #if 1
   1389 	} else if (((flags & TH_SYN) != 0) &&
   1390 		   ((flags & (TH_URG|TH_PUSH)) != 0)) {
   1391 		/*
   1392 		 * SYN with URG and PUSH set is not for normal TCP but it is
   1393 		 * possible(?) with T/TCP...but who uses T/TCP?
   1394 		 */
   1395 		fin->fin_flx |= FI_BAD;
   1396 		DT1(ipf_fi_bad_th_syn_urg_psh, fr_info_t *, fin);
   1397 #endif
   1398 	} else if (!(flags & TH_ACK)) {
   1399 		/*
   1400 		 * If the ack bit isn't set, then either the SYN or
   1401 		 * RST bit must be set.  If the SYN bit is set, then
   1402 		 * we expect the ACK field to be 0.  If the ACK is
   1403 		 * not set and if URG, PSH or FIN are set, consdier
   1404 		 * that to indicate a bad TCP packet.
   1405 		 */
   1406 		if ((flags == TH_SYN) && (tcp->th_ack != 0)) {
   1407 			/*
   1408 			 * Cisco PIX sets the ACK field to a random value.
   1409 			 * In light of this, do not set FI_BAD until a patch
   1410 			 * is available from Cisco to ensure that
   1411 			 * interoperability between existing systems is
   1412 			 * achieved.
   1413 			 */
   1414 			/*fin->fin_flx |= FI_BAD*/;
   1415 			/*DT1(ipf_fi_bad_th_syn_ack, fr_info_t *, fin);*/
   1416 		} else if (!(flags & (TH_RST|TH_SYN))) {
   1417 			fin->fin_flx |= FI_BAD;
   1418 			DT1(ipf_fi_bad_th_rst_syn, fr_info_t *, fin);
   1419 		} else if ((flags & (TH_URG|TH_PUSH|TH_FIN)) != 0) {
   1420 			fin->fin_flx |= FI_BAD;
   1421 			DT1(ipf_fi_bad_th_urg_push_fin, fr_info_t *, fin);
   1422 		}
   1423 	}
   1424 	if (fin->fin_flx & FI_BAD) {
   1425 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_bad_flags);
   1426 		return 1;
   1427 	}
   1428 
   1429 	/*
   1430 	 * At this point, it's not exactly clear what is to be gained by
   1431 	 * marking up which TCP options are and are not present.  The one we
   1432 	 * are most interested in is the TCP window scale.  This is only in
   1433 	 * a SYN packet [RFC1323] so we don't need this here...?
   1434 	 * Now if we were to analyse the header for passive fingerprinting,
   1435 	 * then that might add some weight to adding this...
   1436 	 */
   1437 	if (tlen == sizeof(tcphdr_t)) {
   1438 		return 0;
   1439 	}
   1440 
   1441 	if (ipf_pr_pullup(fin, tlen) == -1) {
   1442 		LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
   1443 		return -1;
   1444 	}
   1445 
   1446 #if 0
   1447 	tcp = fin->fin_dp;
   1448 	ip = fin->fin_ip;
   1449 	s = (u_char *)(tcp + 1);
   1450 	off = IP_HL(ip) << 2;
   1451 # ifdef _KERNEL
   1452 	if (fin->fin_mp != NULL) {
   1453 		mb_t *m = *fin->fin_mp;
   1454 
   1455 		if (off + tlen > M_LEN(m))
   1456 			return;
   1457 	}
   1458 # endif
   1459 	for (tlen -= (int)sizeof(*tcp); tlen > 0; ) {
   1460 		opt = *s;
   1461 		if (opt == '\0')
   1462 			break;
   1463 		else if (opt == TCPOPT_NOP)
   1464 			ol = 1;
   1465 		else {
   1466 			if (tlen < 2)
   1467 				break;
   1468 			ol = (int)*(s + 1);
   1469 			if (ol < 2 || ol > tlen)
   1470 				break;
   1471 		}
   1472 
   1473 		for (i = 9, mv = 4; mv >= 0; ) {
   1474 			op = ipopts + i;
   1475 			if (opt == (u_char)op->ol_val) {
   1476 				optmsk |= op->ol_bit;
   1477 				break;
   1478 			}
   1479 		}
   1480 		tlen -= ol;
   1481 		s += ol;
   1482 	}
   1483 #endif /* 0 */
   1484 
   1485 	return 0;
   1486 }
   1487 
   1488 
   1489 
   1490 /* ------------------------------------------------------------------------ */
   1491 /* Function:    ipf_pr_udpcommon                                            */
   1492 /* Returns:     int    - 0 = header ok, 1 = bad packet                      */
   1493 /* Parameters:  fin(I) - pointer to packet information                      */
   1494 /*                                                                          */
   1495 /* Extract the UDP source and destination ports, if present.  If compiled   */
   1496 /* with IPFILTER_CKSUM, check to see if the UDP checksum is valid.          */
   1497 /* ------------------------------------------------------------------------ */
   1498 static INLINE int
   1499 ipf_pr_udpcommon(fr_info_t *fin)
   1500 {
   1501 	udphdr_t *udp;
   1502 
   1503 	fin->fin_flx |= FI_TCPUDP;
   1504 
   1505 	if (!fin->fin_off && (fin->fin_dlen > 3)) {
   1506 		if (ipf_pr_pullup(fin, sizeof(*udp)) == -1) {
   1507 			ipf_main_softc_t *softc = fin->fin_main_soft;
   1508 
   1509 			fin->fin_flx |= FI_SHORT;
   1510 			LBUMPD(ipf_stats[fin->fin_out], fr_udp_pullup);
   1511 			return 1;
   1512 		}
   1513 
   1514 		udp = fin->fin_dp;
   1515 
   1516 		fin->fin_sport = ntohs(udp->uh_sport);
   1517 		fin->fin_dport = ntohs(udp->uh_dport);
   1518 	}
   1519 
   1520 	return 0;
   1521 }
   1522 
   1523 
   1524 /* ------------------------------------------------------------------------ */
   1525 /* Function:    ipf_pr_tcp                                                  */
   1526 /* Returns:     void                                                        */
   1527 /* Parameters:  fin(I) - pointer to packet information                      */
   1528 /*                                                                          */
   1529 /* IPv4 Only                                                                */
   1530 /* Analyse the packet for IPv4/TCP properties.                              */
   1531 /* ------------------------------------------------------------------------ */
   1532 static INLINE void
   1533 ipf_pr_tcp(fr_info_t *fin)
   1534 {
   1535 
   1536 	ipf_pr_short(fin, sizeof(tcphdr_t));
   1537 
   1538 	if (ipf_pr_tcpcommon(fin) == 0)
   1539 		ipf_checkv4sum(fin);
   1540 }
   1541 
   1542 
   1543 /* ------------------------------------------------------------------------ */
   1544 /* Function:    ipf_pr_udp                                                  */
   1545 /* Returns:     void                                                        */
   1546 /* Parameters:  fin(I) - pointer to packet information                      */
   1547 /*                                                                          */
   1548 /* IPv4 Only                                                                */
   1549 /* Analyse the packet for IPv4/UDP properties.                              */
   1550 /* ------------------------------------------------------------------------ */
   1551 static INLINE void
   1552 ipf_pr_udp(fr_info_t *fin)
   1553 {
   1554 
   1555 	ipf_pr_short(fin, sizeof(udphdr_t));
   1556 
   1557 	if (ipf_pr_udpcommon(fin) == 0)
   1558 		ipf_checkv4sum(fin);
   1559 }
   1560 
   1561 
   1562 /* ------------------------------------------------------------------------ */
   1563 /* Function:    ipf_pr_esp                                                  */
   1564 /* Returns:     void                                                        */
   1565 /* Parameters:  fin(I) - pointer to packet information                      */
   1566 /*                                                                          */
   1567 /* Analyse the packet for ESP properties.                                   */
   1568 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits)  */
   1569 /* even though the newer ESP packets must also have a sequence number that  */
   1570 /* is 32bits as well, it is not possible(?) to determine the version from a */
   1571 /* simple packet header.                                                    */
   1572 /* ------------------------------------------------------------------------ */
   1573 static INLINE void
   1574 ipf_pr_esp(fr_info_t *fin)
   1575 {
   1576 
   1577 	if (fin->fin_off == 0) {
   1578 		ipf_pr_short(fin, 8);
   1579 		if (ipf_pr_pullup(fin, 8) == -1) {
   1580 			ipf_main_softc_t *softc = fin->fin_main_soft;
   1581 
   1582 			LBUMPD(ipf_stats[fin->fin_out], fr_v4_esp_pullup);
   1583 		}
   1584 	}
   1585 }
   1586 
   1587 
   1588 /* ------------------------------------------------------------------------ */
   1589 /* Function:    ipf_pr_ah                                                   */
   1590 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
   1591 /* Parameters:  fin(I) - pointer to packet information                      */
   1592 /*                                                                          */
   1593 /* Analyse the packet for AH properties.                                    */
   1594 /* The minimum length is taken to be the combination of all fields in the   */
   1595 /* header being present and no authentication data (null algorithm used.)   */
   1596 /* ------------------------------------------------------------------------ */
   1597 static INLINE int
   1598 ipf_pr_ah(fr_info_t *fin)
   1599 {
   1600 	ipf_main_softc_t *softc = fin->fin_main_soft;
   1601 	authhdr_t *ah;
   1602 	int len;
   1603 
   1604 	fin->fin_flx |= FI_AH;
   1605 	ipf_pr_short(fin, sizeof(*ah));
   1606 
   1607 	if (((fin->fin_flx & FI_SHORT) != 0) || (fin->fin_off != 0)) {
   1608 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_ah_bad);
   1609 		return IPPROTO_NONE;
   1610 	}
   1611 
   1612 	if (ipf_pr_pullup(fin, sizeof(*ah)) == -1) {
   1613 		DT(fr_v4_ah_pullup_1);
   1614 		LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
   1615 		return IPPROTO_NONE;
   1616 	}
   1617 
   1618 	ah = (authhdr_t *)fin->fin_dp;
   1619 
   1620 	len = (ah->ah_plen + 2) << 2;
   1621 	ipf_pr_short(fin, len);
   1622 	if (ipf_pr_pullup(fin, len) == -1) {
   1623 		DT(fr_v4_ah_pullup_2);
   1624 		LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
   1625 		return IPPROTO_NONE;
   1626 	}
   1627 
   1628 	/*
   1629 	 * Adjust fin_dp and fin_dlen for skipping over the authentication
   1630 	 * header.
   1631 	 */
   1632 	fin->fin_dp = (char *)fin->fin_dp + len;
   1633 	fin->fin_dlen -= len;
   1634 	return ah->ah_next;
   1635 }
   1636 
   1637 
   1638 /* ------------------------------------------------------------------------ */
   1639 /* Function:    ipf_pr_gre                                                  */
   1640 /* Returns:     void                                                        */
   1641 /* Parameters:  fin(I) - pointer to packet information                      */
   1642 /*                                                                          */
   1643 /* Analyse the packet for GRE properties.                                   */
   1644 /* ------------------------------------------------------------------------ */
   1645 static INLINE void
   1646 ipf_pr_gre(fr_info_t *fin)
   1647 {
   1648 	ipf_main_softc_t *softc = fin->fin_main_soft;
   1649 	grehdr_t *gre;
   1650 
   1651 	ipf_pr_short(fin, sizeof(grehdr_t));
   1652 
   1653 	if (fin->fin_off != 0) {
   1654 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_frag);
   1655 		return;
   1656 	}
   1657 
   1658 	if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
   1659 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_pullup);
   1660 		return;
   1661 	}
   1662 
   1663 	gre = fin->fin_dp;
   1664 	if (GRE_REV(gre->gr_flags) == 1)
   1665 		fin->fin_data[0] = gre->gr_call;
   1666 }
   1667 
   1668 
   1669 /* ------------------------------------------------------------------------ */
   1670 /* Function:    ipf_pr_ipv4hdr                                              */
   1671 /* Returns:     void                                                        */
   1672 /* Parameters:  fin(I) - pointer to packet information                      */
   1673 /*                                                                          */
   1674 /* IPv4 Only                                                                */
   1675 /* Analyze the IPv4 header and set fields in the fr_info_t structure.       */
   1676 /* Check all options present and flag their presence if any exist.          */
   1677 /* ------------------------------------------------------------------------ */
   1678 static INLINE void
   1679 ipf_pr_ipv4hdr(fr_info_t *fin)
   1680 {
   1681 	u_short optmsk = 0, secmsk = 0, auth = 0;
   1682 	int hlen, ol, mv, p, i;
   1683 	const struct optlist *op;
   1684 	u_char *s, opt;
   1685 	u_short off;
   1686 	fr_ip_t *fi;
   1687 	ip_t *ip;
   1688 
   1689 	fi = &fin->fin_fi;
   1690 	hlen = fin->fin_hlen;
   1691 
   1692 	ip = fin->fin_ip;
   1693 	p = ip->ip_p;
   1694 	fi->fi_p = p;
   1695 	fin->fin_crc = p;
   1696 	fi->fi_tos = ip->ip_tos;
   1697 	fin->fin_id = ip->ip_id;
   1698 	off = ntohs(ip->ip_off);
   1699 
   1700 	/* Get both TTL and protocol */
   1701 	fi->fi_p = ip->ip_p;
   1702 	fi->fi_ttl = ip->ip_ttl;
   1703 
   1704 	/* Zero out bits not used in IPv6 address */
   1705 	fi->fi_src.i6[1] = 0;
   1706 	fi->fi_src.i6[2] = 0;
   1707 	fi->fi_src.i6[3] = 0;
   1708 	fi->fi_dst.i6[1] = 0;
   1709 	fi->fi_dst.i6[2] = 0;
   1710 	fi->fi_dst.i6[3] = 0;
   1711 
   1712 	fi->fi_saddr = ip->ip_src.s_addr;
   1713 	fin->fin_crc += fi->fi_saddr;
   1714 	fi->fi_daddr = ip->ip_dst.s_addr;
   1715 	fin->fin_crc += fi->fi_daddr;
   1716 	if (IN_CLASSD(fi->fi_daddr))
   1717 		fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
   1718 
   1719 	/*
   1720 	 * set packet attribute flags based on the offset and
   1721 	 * calculate the byte offset that it represents.
   1722 	 */
   1723 	off &= IP_MF|IP_OFFMASK;
   1724 	if (off != 0) {
   1725 		fi->fi_flx |= FI_FRAG;
   1726 		off &= IP_OFFMASK;
   1727 		if (off != 0) {
   1728 			int morefrag = off & IP_MF;
   1729 
   1730 			if (off == 1 && p == IPPROTO_TCP) {
   1731 				fin->fin_flx |= FI_SHORT;       /* RFC 3128 */
   1732 				DT1(ipf_fi_tcp_frag_off_1, fr_info_t *, fin);
   1733 			}
   1734 
   1735 			fin->fin_flx |= FI_FRAGBODY;
   1736 			off <<= 3;
   1737 			if ((off + fin->fin_dlen > 65535) ||
   1738 			    (fin->fin_dlen == 0) ||
   1739 			    ((morefrag != 0) && ((fin->fin_dlen & 7) != 0))) {
   1740 				/*
   1741 				 * The length of the packet, starting at its
   1742 				 * offset cannot exceed 65535 (0xffff) as the
   1743 				 * length of an IP packet is only 16 bits.
   1744 				 *
   1745 				 * Any fragment that isn't the last fragment
   1746 				 * must have a length greater than 0 and it
   1747 				 * must be an even multiple of 8.
   1748 				 */
   1749 				fi->fi_flx |= FI_BAD;
   1750 				DT1(ipf_fi_bad_fragbody_gt_65535, fr_info_t *, fin);
   1751 			}
   1752 		}
   1753 	}
   1754 	fin->fin_off = off;
   1755 
   1756 	/*
   1757 	 * Call per-protocol setup and checking
   1758 	 */
   1759 	if (p == IPPROTO_AH) {
   1760 		/*
   1761 		 * Treat AH differently because we expect there to be another
   1762 		 * layer 4 header after it.
   1763 		 */
   1764 		p = ipf_pr_ah(fin);
   1765 	}
   1766 
   1767 	switch (p)
   1768 	{
   1769 	case IPPROTO_UDP :
   1770 		ipf_pr_udp(fin);
   1771 		break;
   1772 	case IPPROTO_TCP :
   1773 		ipf_pr_tcp(fin);
   1774 		break;
   1775 	case IPPROTO_ICMP :
   1776 		ipf_pr_icmp(fin);
   1777 		break;
   1778 	case IPPROTO_ESP :
   1779 		ipf_pr_esp(fin);
   1780 		break;
   1781 	case IPPROTO_GRE :
   1782 		ipf_pr_gre(fin);
   1783 		break;
   1784 	}
   1785 
   1786 	ip = fin->fin_ip;
   1787 	if (ip == NULL)
   1788 		return;
   1789 
   1790 	/*
   1791 	 * If it is a standard IP header (no options), set the flag fields
   1792 	 * which relate to options to 0.
   1793 	 */
   1794 	if (hlen == sizeof(*ip)) {
   1795 		fi->fi_optmsk = 0;
   1796 		fi->fi_secmsk = 0;
   1797 		fi->fi_auth = 0;
   1798 		return;
   1799 	}
   1800 
   1801 	/*
   1802 	 * So the IP header has some IP options attached.  Walk the entire
   1803 	 * list of options present with this packet and set flags to indicate
   1804 	 * which ones are here and which ones are not.  For the somewhat out
   1805 	 * of date and obscure security classification options, set a flag to
   1806 	 * represent which classification is present.
   1807 	 */
   1808 	fi->fi_flx |= FI_OPTIONS;
   1809 
   1810 	for (s = (u_char *)(ip + 1), hlen -= (int)sizeof(*ip); hlen > 0; ) {
   1811 		opt = *s;
   1812 		if (opt == '\0')
   1813 			break;
   1814 		else if (opt == IPOPT_NOP)
   1815 			ol = 1;
   1816 		else {
   1817 			if (hlen < 2)
   1818 				break;
   1819 			ol = (int)*(s + 1);
   1820 			if (ol < 2 || ol > hlen)
   1821 				break;
   1822 		}
   1823 		for (i = 9, mv = 4; mv >= 0; ) {
   1824 			op = ipopts + i;
   1825 
   1826 			if ((opt == (u_char)op->ol_val) && (ol > 4)) {
   1827 				u_32_t doi;
   1828 
   1829 				switch (opt)
   1830 				{
   1831 				case IPOPT_SECURITY :
   1832 					if (optmsk & op->ol_bit) {
   1833 						fin->fin_flx |= FI_BAD;
   1834 						DT2(ipf_fi_bad_ipopt_security, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
   1835 					} else {
   1836 						doi = ipf_checkripso(s);
   1837 						secmsk = doi >> 16;
   1838 						auth = doi & 0xffff;
   1839 					}
   1840 					break;
   1841 
   1842 				case IPOPT_CIPSO :
   1843 
   1844 					if (optmsk & op->ol_bit) {
   1845 						fin->fin_flx |= FI_BAD;
   1846 						DT2(ipf_fi_bad_ipopt_cipso, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
   1847 					} else {
   1848 						doi = ipf_checkcipso(fin,
   1849 								     s, ol);
   1850 						secmsk = doi >> 16;
   1851 						auth = doi & 0xffff;
   1852 					}
   1853 					break;
   1854 				}
   1855 				optmsk |= op->ol_bit;
   1856 			}
   1857 
   1858 			if (opt < op->ol_val)
   1859 				i -= mv;
   1860 			else
   1861 				i += mv;
   1862 			mv--;
   1863 		}
   1864 		hlen -= ol;
   1865 		s += ol;
   1866 	}
   1867 
   1868 	/*
   1869 	 *
   1870 	 */
   1871 	if (auth && !(auth & 0x0100))
   1872 		auth &= 0xff00;
   1873 	fi->fi_optmsk = optmsk;
   1874 	fi->fi_secmsk = secmsk;
   1875 	fi->fi_auth = auth;
   1876 }
   1877 
   1878 
   1879 /* ------------------------------------------------------------------------ */
   1880 /* Function:    ipf_checkripso                                              */
   1881 /* Returns:     void                                                        */
   1882 /* Parameters:  s(I)   - pointer to start of RIPSO option                   */
   1883 /*                                                                          */
   1884 /* ------------------------------------------------------------------------ */
   1885 static u_32_t
   1886 ipf_checkripso(u_char *s)
   1887 {
   1888 	const struct optlist *sp;
   1889 	u_short secmsk = 0, auth = 0;
   1890 	u_char sec;
   1891 	int j, m;
   1892 
   1893 	sec = *(s + 2);	/* classification */
   1894 	for (j = 3, m = 2; m >= 0; ) {
   1895 		sp = secopt + j;
   1896 		if (sec == sp->ol_val) {
   1897 			secmsk |= sp->ol_bit;
   1898 			auth = *(s + 3);
   1899 			auth *= 256;
   1900 			auth += *(s + 4);
   1901 			break;
   1902 		}
   1903 		if (sec < sp->ol_val)
   1904 			j -= m;
   1905 		else
   1906 			j += m;
   1907 		m--;
   1908 	}
   1909 
   1910 	return (secmsk << 16) | auth;
   1911 }
   1912 
   1913 
   1914 /* ------------------------------------------------------------------------ */
   1915 /* Function:    ipf_checkcipso                                              */
   1916 /* Returns:     u_32_t  - 0 = failure, else the doi from the header         */
   1917 /* Parameters:  fin(IO) - pointer to packet information                     */
   1918 /*              s(I)    - pointer to start of CIPSO option                  */
   1919 /*              ol(I)   - length of CIPSO option field                      */
   1920 /*                                                                          */
   1921 /* This function returns the domain of integrity (DOI) field from the CIPSO */
   1922 /* header and returns that whilst also storing the highest sensitivity      */
   1923 /* value found in the fr_info_t structure.                                  */
   1924 /*                                                                          */
   1925 /* No attempt is made to extract the category bitmaps as these are defined  */
   1926 /* by the user (rather than the protocol) and can be rather numerous on the */
   1927 /* end nodes.                                                               */
   1928 /* ------------------------------------------------------------------------ */
   1929 static u_32_t
   1930 ipf_checkcipso(fr_info_t *fin, u_char *s, int ol)
   1931 {
   1932 	ipf_main_softc_t *softc = fin->fin_main_soft;
   1933 	fr_ip_t *fi;
   1934 	u_32_t doi;
   1935 	u_char *t, tag, tlen, sensitivity;
   1936 	int len;
   1937 
   1938 	if (ol < 6 || ol > 40) {
   1939 		LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_bad);
   1940 		fin->fin_flx |= FI_BAD;
   1941 		DT2(ipf_fi_bad_checkcipso_ol, fr_info_t *, fin, u_int, ol);
   1942 		return 0;
   1943 	}
   1944 
   1945 	fi = &fin->fin_fi;
   1946 	fi->fi_sensitivity = 0;
   1947 	/*
   1948 	 * The DOI field MUST be there.
   1949 	 */
   1950 	bcopy(s + 2, &doi, sizeof(doi));
   1951 
   1952 	t = (u_char *)s + 6;
   1953 	for (len = ol - 6; len >= 2; len -= tlen, t+= tlen) {
   1954 		tag = *t;
   1955 		tlen = *(t + 1);
   1956 		if (tlen > len || tlen < 4 || tlen > 34) {
   1957 			LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_tlen);
   1958 			fin->fin_flx |= FI_BAD;
   1959 			DT2(ipf_fi_bad_checkcipso_tlen, fr_info_t *, fin, u_int, tlen);
   1960 			return 0;
   1961 		}
   1962 
   1963 		sensitivity = 0;
   1964 		/*
   1965 		 * Tag numbers 0, 1, 2, 5 are laid out in the CIPSO Internet
   1966 		 * draft (16 July 1992) that has expired.
   1967 		 */
   1968 		if (tag == 0) {
   1969 			fin->fin_flx |= FI_BAD;
   1970 			DT2(ipf_fi_bad_checkcipso_tag, fr_info_t *, fin, u_int, tag);
   1971 			continue;
   1972 		} else if (tag == 1) {
   1973 			if (*(t + 2) != 0) {
   1974 				fin->fin_flx |= FI_BAD;
   1975 				DT2(ipf_fi_bad_checkcipso_tag1_t2, fr_info_t *, fin, u_int, (*t + 2));
   1976 				continue;
   1977 			}
   1978 			sensitivity = *(t + 3);
   1979 			/* Category bitmap for categories 0-239 */
   1980 
   1981 		} else if (tag == 4) {
   1982 			if (*(t + 2) != 0) {
   1983 				fin->fin_flx |= FI_BAD;
   1984 				DT2(ipf_fi_bad_checkcipso_tag4_t2, fr_info_t *, fin, u_int, (*t + 2));
   1985 				continue;
   1986 			}
   1987 			sensitivity = *(t + 3);
   1988 			/* Enumerated categories, 16bits each, upto 15 */
   1989 
   1990 		} else if (tag == 5) {
   1991 			if (*(t + 2) != 0) {
   1992 				fin->fin_flx |= FI_BAD;
   1993 				DT2(ipf_fi_bad_checkcipso_tag5_t2, fr_info_t *, fin, u_int, (*t + 2));
   1994 				continue;
   1995 			}
   1996 			sensitivity = *(t + 3);
   1997 			/* Range of categories (2*16bits), up to 7 pairs */
   1998 
   1999 		} else if (tag > 127) {
   2000 			/* Custom defined DOI */
   2001 			;
   2002 		} else {
   2003 			DT2(ipf_fi_bad_checkcipso_tag127, fr_info_t *, fin, u_int, tag);
   2004 			fin->fin_flx |= FI_BAD;
   2005 			continue;
   2006 		}
   2007 
   2008 		if (sensitivity > fi->fi_sensitivity)
   2009 			fi->fi_sensitivity = sensitivity;
   2010 	}
   2011 
   2012 	return doi;
   2013 }
   2014 
   2015 
   2016 /* ------------------------------------------------------------------------ */
   2017 /* Function:    ipf_makefrip                                                */
   2018 /* Returns:     int     - 0 == packet ok, -1 == packet freed                */
   2019 /* Parameters:  hlen(I) - length of IP packet header                        */
   2020 /*              ip(I)   - pointer to the IP header                          */
   2021 /*              fin(IO) - pointer to packet information                     */
   2022 /*                                                                          */
   2023 /* Compact the IP header into a structure which contains just the info.     */
   2024 /* which is useful for comparing IP headers with and store this information */
   2025 /* in the fr_info_t structure pointer to by fin.  At present, it is assumed */
   2026 /* this function will be called with either an IPv4 or IPv6 packet.         */
   2027 /* ------------------------------------------------------------------------ */
   2028 int
   2029 ipf_makefrip(int hlen, ip_t *ip, fr_info_t *fin)
   2030 {
   2031 	ipf_main_softc_t *softc = fin->fin_main_soft;
   2032 	int v;
   2033 
   2034 	fin->fin_depth = 0;
   2035 	fin->fin_hlen = (u_short)hlen;
   2036 	fin->fin_ip = ip;
   2037 	fin->fin_rule = 0xffffffff;
   2038 	fin->fin_group[0] = -1;
   2039 	fin->fin_group[1] = '\0';
   2040 	fin->fin_dp = (char *)ip + hlen;
   2041 
   2042 	v = fin->fin_v;
   2043 	if (v == 4) {
   2044 		fin->fin_plen = ntohs(ip->ip_len);
   2045 		fin->fin_dlen = fin->fin_plen - hlen;
   2046 		ipf_pr_ipv4hdr(fin);
   2047 #ifdef	USE_INET6
   2048 	} else if (v == 6) {
   2049 		fin->fin_plen = ntohs(((ip6_t *)ip)->ip6_plen);
   2050 		fin->fin_dlen = fin->fin_plen;
   2051 		fin->fin_plen += hlen;
   2052 
   2053 		ipf_pr_ipv6hdr(fin);
   2054 #endif
   2055 	}
   2056 	if (fin->fin_ip == NULL) {
   2057 		LBUMP(ipf_stats[fin->fin_out].fr_ip_freed);
   2058 		return -1;
   2059 	}
   2060 	return 0;
   2061 }
   2062 
   2063 
   2064 /* ------------------------------------------------------------------------ */
   2065 /* Function:    ipf_portcheck                                               */
   2066 /* Returns:     int - 1 == port matched, 0 == port match failed             */
   2067 /* Parameters:  frp(I) - pointer to port check `expression'                 */
   2068 /*              pop(I) - port number to evaluate                            */
   2069 /*                                                                          */
   2070 /* Perform a comparison of a port number against some other(s), using a     */
   2071 /* structure with compare information stored in it.                         */
   2072 /* ------------------------------------------------------------------------ */
   2073 static INLINE int
   2074 ipf_portcheck(frpcmp_t *frp, u_32_t pop)
   2075 {
   2076 	int err = 1;
   2077 	u_32_t po;
   2078 
   2079 	po = frp->frp_port;
   2080 
   2081 	/*
   2082 	 * Do opposite test to that required and continue if that succeeds.
   2083 	 */
   2084 	switch (frp->frp_cmp)
   2085 	{
   2086 	case FR_EQUAL :
   2087 		if (pop != po) /* EQUAL */
   2088 			err = 0;
   2089 		break;
   2090 	case FR_NEQUAL :
   2091 		if (pop == po) /* NOTEQUAL */
   2092 			err = 0;
   2093 		break;
   2094 	case FR_LESST :
   2095 		if (pop >= po) /* LESSTHAN */
   2096 			err = 0;
   2097 		break;
   2098 	case FR_GREATERT :
   2099 		if (pop <= po) /* GREATERTHAN */
   2100 			err = 0;
   2101 		break;
   2102 	case FR_LESSTE :
   2103 		if (pop > po) /* LT or EQ */
   2104 			err = 0;
   2105 		break;
   2106 	case FR_GREATERTE :
   2107 		if (pop < po) /* GT or EQ */
   2108 			err = 0;
   2109 		break;
   2110 	case FR_OUTRANGE :
   2111 		if (pop >= po && pop <= frp->frp_top) /* Out of range */
   2112 			err = 0;
   2113 		break;
   2114 	case FR_INRANGE :
   2115 		if (pop <= po || pop >= frp->frp_top) /* In range */
   2116 			err = 0;
   2117 		break;
   2118 	case FR_INCRANGE :
   2119 		if (pop < po || pop > frp->frp_top) /* Inclusive range */
   2120 			err = 0;
   2121 		break;
   2122 	default :
   2123 		break;
   2124 	}
   2125 	return err;
   2126 }
   2127 
   2128 
   2129 /* ------------------------------------------------------------------------ */
   2130 /* Function:    ipf_tcpudpchk                                               */
   2131 /* Returns:     int - 1 == protocol matched, 0 == check failed              */
   2132 /* Parameters:  fda(I) - pointer to packet information                      */
   2133 /*              ft(I)  - pointer to structure with comparison data          */
   2134 /*                                                                          */
   2135 /* Compares the current pcket (assuming it is TCP/UDP) information with a   */
   2136 /* structure containing information that we want to match against.          */
   2137 /* ------------------------------------------------------------------------ */
   2138 int
   2139 ipf_tcpudpchk(fr_ip_t *fi, frtuc_t *ft)
   2140 {
   2141 	int err = 1;
   2142 
   2143 	/*
   2144 	 * Both ports should *always* be in the first fragment.
   2145 	 * So far, I cannot find any cases where they can not be.
   2146 	 *
   2147 	 * compare destination ports
   2148 	 */
   2149 	if (ft->ftu_dcmp)
   2150 		err = ipf_portcheck(&ft->ftu_dst, fi->fi_ports[1]);
   2151 
   2152 	/*
   2153 	 * compare source ports
   2154 	 */
   2155 	if (err && ft->ftu_scmp)
   2156 		err = ipf_portcheck(&ft->ftu_src, fi->fi_ports[0]);
   2157 
   2158 	/*
   2159 	 * If we don't have all the TCP/UDP header, then how can we
   2160 	 * expect to do any sort of match on it ?  If we were looking for
   2161 	 * TCP flags, then NO match.  If not, then match (which should
   2162 	 * satisfy the "short" class too).
   2163 	 */
   2164 	if (err && (fi->fi_p == IPPROTO_TCP)) {
   2165 		if (fi->fi_flx & FI_SHORT)
   2166 			return !(ft->ftu_tcpf | ft->ftu_tcpfm);
   2167 		/*
   2168 		 * Match the flags ?  If not, abort this match.
   2169 		 */
   2170 		if (ft->ftu_tcpfm &&
   2171 		    ft->ftu_tcpf != (fi->fi_tcpf & ft->ftu_tcpfm)) {
   2172 			FR_DEBUG(("f. %#x & %#x != %#x\n", fi->fi_tcpf,
   2173 				 ft->ftu_tcpfm, ft->ftu_tcpf));
   2174 			err = 0;
   2175 		}
   2176 	}
   2177 	return err;
   2178 }
   2179 
   2180 
   2181 /* ------------------------------------------------------------------------ */
   2182 /* Function:    ipf_check_ipf                                               */
   2183 /* Returns:     int - 0 == match, else no match                             */
   2184 /* Parameters:  fin(I)     - pointer to packet information                  */
   2185 /*              fr(I)      - pointer to filter rule                         */
   2186 /*              portcmp(I) - flag indicating whether to attempt matching on */
   2187 /*                           TCP/UDP port data.                             */
   2188 /*                                                                          */
   2189 /* Check to see if a packet matches an IPFilter rule.  Checks of addresses, */
   2190 /* port numbers, etc, for "standard" IPFilter rules are all orchestrated in */
   2191 /* this function.                                                           */
   2192 /* ------------------------------------------------------------------------ */
   2193 static INLINE int
   2194 ipf_check_ipf(fr_info_t *fin, frentry_t *fr, int portcmp)
   2195 {
   2196 	u_32_t	*ld, *lm, *lip;
   2197 	fripf_t *fri;
   2198 	fr_ip_t *fi;
   2199 	int i;
   2200 
   2201 	fi = &fin->fin_fi;
   2202 	fri = fr->fr_ipf;
   2203 	lip = (u_32_t *)fi;
   2204 	lm = (u_32_t *)&fri->fri_mip;
   2205 	ld = (u_32_t *)&fri->fri_ip;
   2206 
   2207 	/*
   2208 	 * first 32 bits to check coversion:
   2209 	 * IP version, TOS, TTL, protocol
   2210 	 */
   2211 	i = ((*lip & *lm) != *ld);
   2212 	FR_DEBUG(("0. %#08x & %#08x != %#08x\n",
   2213 		   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
   2214 	if (i)
   2215 		return 1;
   2216 
   2217 	/*
   2218 	 * Next 32 bits is a constructed bitmask indicating which IP options
   2219 	 * are present (if any) in this packet.
   2220 	 */
   2221 	lip++, lm++, ld++;
   2222 	i = ((*lip & *lm) != *ld);
   2223 	FR_DEBUG(("1. %#08x & %#08x != %#08x\n",
   2224 		   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
   2225 	if (i != 0)
   2226 		return 1;
   2227 
   2228 	lip++, lm++, ld++;
   2229 	/*
   2230 	 * Unrolled loops (4 each, for 32 bits) for address checks.
   2231 	 */
   2232 	/*
   2233 	 * Check the source address.
   2234 	 */
   2235 	if (fr->fr_satype == FRI_LOOKUP) {
   2236 		i = (*fr->fr_srcfunc)(fin->fin_main_soft, fr->fr_srcptr,
   2237 				      fi->fi_v, lip, fin->fin_plen);
   2238 		if (i == -1)
   2239 			return 1;
   2240 		lip += 3;
   2241 		lm += 3;
   2242 		ld += 3;
   2243 	} else {
   2244 		i = ((*lip & *lm) != *ld);
   2245 		FR_DEBUG(("2a. %#08x & %#08x != %#08x\n",
   2246 			   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
   2247 		if (fi->fi_v == 6) {
   2248 			lip++, lm++, ld++;
   2249 			i |= ((*lip & *lm) != *ld);
   2250 			FR_DEBUG(("2b. %#08x & %#08x != %#08x\n",
   2251 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
   2252 			lip++, lm++, ld++;
   2253 			i |= ((*lip & *lm) != *ld);
   2254 			FR_DEBUG(("2c. %#08x & %#08x != %#08x\n",
   2255 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
   2256 			lip++, lm++, ld++;
   2257 			i |= ((*lip & *lm) != *ld);
   2258 			FR_DEBUG(("2d. %#08x & %#08x != %#08x\n",
   2259 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
   2260 		} else {
   2261 			lip += 3;
   2262 			lm += 3;
   2263 			ld += 3;
   2264 		}
   2265 	}
   2266 	i ^= (fr->fr_flags & FR_NOTSRCIP) >> 6;
   2267 	if (i != 0)
   2268 		return 1;
   2269 
   2270 	/*
   2271 	 * Check the destination address.
   2272 	 */
   2273 	lip++, lm++, ld++;
   2274 	if (fr->fr_datype == FRI_LOOKUP) {
   2275 		i = (*fr->fr_dstfunc)(fin->fin_main_soft, fr->fr_dstptr,
   2276 				      fi->fi_v, lip, fin->fin_plen);
   2277 		if (i == -1)
   2278 			return 1;
   2279 		lip += 3;
   2280 		lm += 3;
   2281 		ld += 3;
   2282 	} else {
   2283 		i = ((*lip & *lm) != *ld);
   2284 		FR_DEBUG(("3a. %#08x & %#08x != %#08x\n",
   2285 			   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
   2286 		if (fi->fi_v == 6) {
   2287 			lip++, lm++, ld++;
   2288 			i |= ((*lip & *lm) != *ld);
   2289 			FR_DEBUG(("3b. %#08x & %#08x != %#08x\n",
   2290 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
   2291 			lip++, lm++, ld++;
   2292 			i |= ((*lip & *lm) != *ld);
   2293 			FR_DEBUG(("3c. %#08x & %#08x != %#08x\n",
   2294 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
   2295 			lip++, lm++, ld++;
   2296 			i |= ((*lip & *lm) != *ld);
   2297 			FR_DEBUG(("3d. %#08x & %#08x != %#08x\n",
   2298 				   ntohl(*lip), ntohl(*lm), ntohl(*ld)));
   2299 		} else {
   2300 			lip += 3;
   2301 			lm += 3;
   2302 			ld += 3;
   2303 		}
   2304 	}
   2305 	i ^= (fr->fr_flags & FR_NOTDSTIP) >> 7;
   2306 	if (i != 0)
   2307 		return 1;
   2308 	/*
   2309 	 * IP addresses matched.  The next 32bits contains:
   2310 	 * mast of old IP header security & authentication bits.
   2311 	 */
   2312 	lip++, lm++, ld++;
   2313 	i = (*ld - (*lip & *lm));
   2314 	FR_DEBUG(("4. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
   2315 
   2316 	/*
   2317 	 * Next we have 32 bits of packet flags.
   2318 	 */
   2319 	lip++, lm++, ld++;
   2320 	i |= (*ld - (*lip & *lm));
   2321 	FR_DEBUG(("5. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
   2322 
   2323 	if (i == 0) {
   2324 		/*
   2325 		 * If a fragment, then only the first has what we're
   2326 		 * looking for here...
   2327 		 */
   2328 		if (portcmp) {
   2329 			if (!ipf_tcpudpchk(&fin->fin_fi, &fr->fr_tuc))
   2330 				i = 1;
   2331 		} else {
   2332 			if (fr->fr_dcmp || fr->fr_scmp ||
   2333 			    fr->fr_tcpf || fr->fr_tcpfm)
   2334 				i = 1;
   2335 			if (fr->fr_icmpm || fr->fr_icmp) {
   2336 				if (((fi->fi_p != IPPROTO_ICMP) &&
   2337 				     (fi->fi_p != IPPROTO_ICMPV6)) ||
   2338 				    fin->fin_off || (fin->fin_dlen < 2))
   2339 					i = 1;
   2340 				else if ((fin->fin_data[0] & fr->fr_icmpm) !=
   2341 					 fr->fr_icmp) {
   2342 					FR_DEBUG(("i. %#x & %#x != %#x\n",
   2343 						 fin->fin_data[0],
   2344 						 fr->fr_icmpm, fr->fr_icmp));
   2345 					i = 1;
   2346 				}
   2347 			}
   2348 		}
   2349 	}
   2350 	return i;
   2351 }
   2352 
   2353 
   2354 /* ------------------------------------------------------------------------ */
   2355 /* Function:    ipf_scanlist                                                */
   2356 /* Returns:     int - result flags of scanning filter list                  */
   2357 /* Parameters:  fin(I) - pointer to packet information                      */
   2358 /*              pass(I) - default result to return for filtering            */
   2359 /*                                                                          */
   2360 /* Check the input/output list of rules for a match to the current packet.  */
   2361 /* If a match is found, the value of fr_flags from the rule becomes the     */
   2362 /* return value and fin->fin_fr points to the matched rule.                 */
   2363 /*                                                                          */
   2364 /* This function may be called recusively upto 16 times (limit inbuilt.)    */
   2365 /* When unwinding, it should finish up with fin_depth as 0.                 */
   2366 /*                                                                          */
   2367 /* Could be per interface, but this gets real nasty when you don't have,    */
   2368 /* or can't easily change, the kernel source code to .                      */
   2369 /* ------------------------------------------------------------------------ */
   2370 int
   2371 ipf_scanlist(fr_info_t *fin, u_32_t pass)
   2372 {
   2373 	ipf_main_softc_t *softc = fin->fin_main_soft;
   2374 	int rulen, portcmp, off, skip;
   2375 	struct frentry *fr, *fnext;
   2376 	u_32_t passt, passo;
   2377 
   2378 	/*
   2379 	 * Do not allow nesting deeper than 16 levels.
   2380 	 */
   2381 	if (fin->fin_depth >= 16)
   2382 		return pass;
   2383 
   2384 	fr = fin->fin_fr;
   2385 
   2386 	/*
   2387 	 * If there are no rules in this list, return now.
   2388 	 */
   2389 	if (fr == NULL)
   2390 		return pass;
   2391 
   2392 	skip = 0;
   2393 	portcmp = 0;
   2394 	fin->fin_depth++;
   2395 	fin->fin_fr = NULL;
   2396 	off = fin->fin_off;
   2397 
   2398 	if ((fin->fin_flx & FI_TCPUDP) && (fin->fin_dlen > 3) && !off)
   2399 		portcmp = 1;
   2400 
   2401 	for (rulen = 0; fr; fr = fnext, rulen++) {
   2402 		fnext = fr->fr_next;
   2403 		if (skip != 0) {
   2404 			FR_VERBOSE(("SKIP %d (%#x)\n", skip, fr->fr_flags));
   2405 			skip--;
   2406 			continue;
   2407 		}
   2408 
   2409 		/*
   2410 		 * In all checks below, a null (zero) value in the
   2411 		 * filter struture is taken to mean a wildcard.
   2412 		 *
   2413 		 * check that we are working for the right interface
   2414 		 */
   2415 #ifdef	_KERNEL
   2416 		if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
   2417 			continue;
   2418 #else
   2419 		if (opts & (OPT_VERBOSE|OPT_DEBUG))
   2420 			printf("\n");
   2421 		FR_VERBOSE(("%c", FR_ISSKIP(pass) ? 's' :
   2422 				  FR_ISPASS(pass) ? 'p' :
   2423 				  FR_ISACCOUNT(pass) ? 'A' :
   2424 				  FR_ISAUTH(pass) ? 'a' :
   2425 				  (pass & FR_NOMATCH) ? 'n' :'b'));
   2426 		if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
   2427 			continue;
   2428 		FR_VERBOSE((":i"));
   2429 #endif
   2430 
   2431 		switch (fr->fr_type)
   2432 		{
   2433 		case FR_T_IPF :
   2434 		case FR_T_IPF_BUILTIN :
   2435 			if (ipf_check_ipf(fin, fr, portcmp))
   2436 				continue;
   2437 			break;
   2438 #if defined(IPFILTER_BPF)
   2439 		case FR_T_BPFOPC :
   2440 		case FR_T_BPFOPC_BUILTIN :
   2441 		    {
   2442 			u_char *mc;
   2443 			int wlen;
   2444 
   2445 			if (*fin->fin_mp == NULL)
   2446 				continue;
   2447 			if (fin->fin_family != fr->fr_family)
   2448 				continue;
   2449 			mc = (u_char *)fin->fin_m;
   2450 			wlen = fin->fin_dlen + fin->fin_hlen;
   2451 			if (!bpf_filter(fr->fr_data, mc, wlen, 0))
   2452 				continue;
   2453 			break;
   2454 		    }
   2455 #endif
   2456 		case FR_T_CALLFUNC_BUILTIN :
   2457 		    {
   2458 			frentry_t *f;
   2459 
   2460 			f = (*fr->fr_func)(fin, &pass);
   2461 			if (f != NULL)
   2462 				fr = f;
   2463 			else
   2464 				continue;
   2465 			break;
   2466 		    }
   2467 
   2468 		case FR_T_IPFEXPR :
   2469 		case FR_T_IPFEXPR_BUILTIN :
   2470 			if (fin->fin_family != fr->fr_family)
   2471 				continue;
   2472 			if (ipf_fr_matcharray(fin, fr->fr_data) == 0)
   2473 				continue;
   2474 			break;
   2475 
   2476 		default :
   2477 			break;
   2478 		}
   2479 
   2480 		if ((fin->fin_out == 0) && (fr->fr_nattag.ipt_num[0] != 0)) {
   2481 			if (fin->fin_nattag == NULL)
   2482 				continue;
   2483 			if (ipf_matchtag(&fr->fr_nattag, fin->fin_nattag) == 0)
   2484 				continue;
   2485 		}
   2486 		FR_VERBOSE(("=%d/%d.%d *", fr->fr_grhead, fr->fr_group, rulen));
   2487 
   2488 		passt = fr->fr_flags;
   2489 
   2490 		/*
   2491 		 * If the rule is a "call now" rule, then call the function
   2492 		 * in the rule, if it exists and use the results from that.
   2493 		 * If the function pointer is bad, just make like we ignore
   2494 		 * it, except for increasing the hit counter.
   2495 		 */
   2496 		if ((passt & FR_CALLNOW) != 0) {
   2497 			frentry_t *frs;
   2498 
   2499 			ATOMIC_INC64(fr->fr_hits);
   2500 			if ((fr->fr_func == NULL) ||
   2501 			    (fr->fr_func == (ipfunc_t)-1))
   2502 				continue;
   2503 
   2504 			frs = fin->fin_fr;
   2505 			fin->fin_fr = fr;
   2506 			fr = (*fr->fr_func)(fin, &passt);
   2507 			if (fr == NULL) {
   2508 				fin->fin_fr = frs;
   2509 				continue;
   2510 			}
   2511 			passt = fr->fr_flags;
   2512 		}
   2513 		fin->fin_fr = fr;
   2514 
   2515 #ifdef  IPFILTER_LOG
   2516 		/*
   2517 		 * Just log this packet...
   2518 		 */
   2519 		if ((passt & FR_LOGMASK) == FR_LOG) {
   2520 			if (ipf_log_pkt(fin, passt) == -1) {
   2521 				if (passt & FR_LOGORBLOCK) {
   2522 					DT(frb_logfail);
   2523 					passt &= ~FR_CMDMASK;
   2524 					passt |= FR_BLOCK|FR_QUICK;
   2525 					fin->fin_reason = FRB_LOGFAIL;
   2526 				}
   2527 			}
   2528 		}
   2529 #endif /* IPFILTER_LOG */
   2530 
   2531 		MUTEX_ENTER(&fr->fr_lock);
   2532 		fr->fr_bytes += (U_QUAD_T)fin->fin_plen;
   2533 		fr->fr_hits++;
   2534 		MUTEX_EXIT(&fr->fr_lock);
   2535 		fin->fin_rule = rulen;
   2536 
   2537 		passo = pass;
   2538 		if (FR_ISSKIP(passt)) {
   2539 			skip = fr->fr_arg;
   2540 			continue;
   2541 		} else if (((passt & FR_LOGMASK) != FR_LOG) &&
   2542 			   ((passt & FR_LOGMASK) != FR_DECAPSULATE)) {
   2543 			pass = passt;
   2544 		}
   2545 
   2546 		if (passt & (FR_RETICMP|FR_FAKEICMP))
   2547 			fin->fin_icode = fr->fr_icode;
   2548 
   2549 		if (fr->fr_group != -1) {
   2550 			(void) strncpy(fin->fin_group,
   2551 				       FR_NAME(fr, fr_group),
   2552 				       strlen(FR_NAME(fr, fr_group)));
   2553 		} else {
   2554 			fin->fin_group[0] = '\0';
   2555 		}
   2556 
   2557 		FR_DEBUG(("pass %#x/%#x/%x\n", passo, pass, passt));
   2558 
   2559 		if (fr->fr_grphead != NULL) {
   2560 			fin->fin_fr = fr->fr_grphead->fg_start;
   2561 			FR_VERBOSE(("group %s\n", FR_NAME(fr, fr_grhead)));
   2562 
   2563 			if (FR_ISDECAPS(passt))
   2564 				passt = ipf_decaps(fin, pass, fr->fr_icode);
   2565 			else
   2566 				passt = ipf_scanlist(fin, pass);
   2567 
   2568 			if (fin->fin_fr == NULL) {
   2569 				fin->fin_rule = rulen;
   2570 				if (fr->fr_group != -1)
   2571 					(void) strncpy(fin->fin_group,
   2572 						       fr->fr_names +
   2573 						       fr->fr_group,
   2574 						       strlen(fr->fr_names +
   2575 							      fr->fr_group));
   2576 				fin->fin_fr = fr;
   2577 				passt = pass;
   2578 			}
   2579 			pass = passt;
   2580 		}
   2581 
   2582 		if (pass & FR_QUICK) {
   2583 			/*
   2584 			 * Finally, if we've asked to track state for this
   2585 			 * packet, set it up.  Add state for "quick" rules
   2586 			 * here so that if the action fails we can consider
   2587 			 * the rule to "not match" and keep on processing
   2588 			 * filter rules.
   2589 			 */
   2590 			if ((pass & FR_KEEPSTATE) && !FR_ISAUTH(pass) &&
   2591 			    !(fin->fin_flx & FI_STATE)) {
   2592 				int out = fin->fin_out;
   2593 
   2594 				fin->fin_fr = fr;
   2595 				if (ipf_state_add(softc, fin, NULL, 0) == 0) {
   2596 					LBUMPD(ipf_stats[out], fr_ads);
   2597 				} else {
   2598 					LBUMPD(ipf_stats[out], fr_bads);
   2599 					pass = passo;
   2600 					continue;
   2601 				}
   2602 			}
   2603 			break;
   2604 		}
   2605 	}
   2606 	fin->fin_depth--;
   2607 	return pass;
   2608 }
   2609 
   2610 
   2611 /* ------------------------------------------------------------------------ */
   2612 /* Function:    ipf_acctpkt                                                 */
   2613 /* Returns:     frentry_t* - always returns NULL                            */
   2614 /* Parameters:  fin(I) - pointer to packet information                      */
   2615 /*              passp(IO) - pointer to current/new filter decision (unused) */
   2616 /*                                                                          */
   2617 /* Checks a packet against accounting rules, if there are any for the given */
   2618 /* IP protocol version.                                                     */
   2619 /*                                                                          */
   2620 /* N.B.: this function returns NULL to match the prototype used by other    */
   2621 /* functions called from the IPFilter "mainline" in ipf_check().            */
   2622 /* ------------------------------------------------------------------------ */
   2623 frentry_t *
   2624 ipf_acctpkt(fr_info_t *fin, u_32_t *passp)
   2625 {
   2626 	ipf_main_softc_t *softc = fin->fin_main_soft;
   2627 	char group[FR_GROUPLEN];
   2628 	frentry_t *fr, *frsave;
   2629 	u_32_t pass, rulen;
   2630 
   2631 	passp = passp;
   2632 	fr = softc->ipf_acct[fin->fin_out][softc->ipf_active];
   2633 
   2634 	if (fr != NULL) {
   2635 		frsave = fin->fin_fr;
   2636 		bcopy(fin->fin_group, group, FR_GROUPLEN);
   2637 		rulen = fin->fin_rule;
   2638 		fin->fin_fr = fr;
   2639 		pass = ipf_scanlist(fin, FR_NOMATCH);
   2640 		if (FR_ISACCOUNT(pass)) {
   2641 			LBUMPD(ipf_stats[0], fr_acct);
   2642 		}
   2643 		fin->fin_fr = frsave;
   2644 		bcopy(group, fin->fin_group, FR_GROUPLEN);
   2645 		fin->fin_rule = rulen;
   2646 	}
   2647 	return NULL;
   2648 }
   2649 
   2650 
   2651 /* ------------------------------------------------------------------------ */
   2652 /* Function:    ipf_firewall                                                */
   2653 /* Returns:     frentry_t* - returns pointer to matched rule, if no matches */
   2654 /*                           were found, returns NULL.                      */
   2655 /* Parameters:  fin(I) - pointer to packet information                      */
   2656 /*              passp(IO) - pointer to current/new filter decision (unused) */
   2657 /*                                                                          */
   2658 /* Applies an appropriate set of firewall rules to the packet, to see if    */
   2659 /* there are any matches.  The first check is to see if a match can be seen */
   2660 /* in the cache.  If not, then search an appropriate list of rules.  Once a */
   2661 /* matching rule is found, take any appropriate actions as defined by the   */
   2662 /* rule - except logging.                                                   */
   2663 /* ------------------------------------------------------------------------ */
   2664 static frentry_t *
   2665 ipf_firewall(fr_info_t *fin, u_32_t *passp)
   2666 {
   2667 	ipf_main_softc_t *softc = fin->fin_main_soft;
   2668 	frentry_t *fr;
   2669 	u_32_t pass;
   2670 	int out;
   2671 
   2672 	out = fin->fin_out;
   2673 	pass = *passp;
   2674 
   2675 	/*
   2676 	 * This rule cache will only affect packets that are not being
   2677 	 * statefully filtered.
   2678 	 */
   2679 	fin->fin_fr = softc->ipf_rules[out][softc->ipf_active];
   2680 	if (fin->fin_fr != NULL)
   2681 		pass = ipf_scanlist(fin, softc->ipf_pass);
   2682 
   2683 	if ((pass & FR_NOMATCH)) {
   2684 		LBUMPD(ipf_stats[out], fr_nom);
   2685 	}
   2686 	fr = fin->fin_fr;
   2687 
   2688 	/*
   2689 	 * Apply packets per second rate-limiting to a rule as required.
   2690 	 */
   2691 	if ((fr != NULL) && (fr->fr_pps != 0) &&
   2692 	    !ppsratecheck(&fr->fr_lastpkt, &fr->fr_curpps, fr->fr_pps)) {
   2693 		DT2(frb_ppsrate, fr_info_t *, fin, frentry_t *, fr);
   2694 		pass &= ~(FR_CMDMASK|FR_RETICMP|FR_RETRST);
   2695 		pass |= FR_BLOCK;
   2696 		LBUMPD(ipf_stats[out], fr_ppshit);
   2697 		fin->fin_reason = FRB_PPSRATE;
   2698 	}
   2699 
   2700 	/*
   2701 	 * If we fail to add a packet to the authorization queue, then we
   2702 	 * drop the packet later.  However, if it was added then pretend
   2703 	 * we've dropped it already.
   2704 	 */
   2705 	if (FR_ISAUTH(pass)) {
   2706 		if (ipf_auth_new(fin->fin_m, fin) != 0) {
   2707 			DT1(frb_authnew, fr_info_t *, fin);
   2708 			fin->fin_m = *fin->fin_mp = NULL;
   2709 			fin->fin_reason = FRB_AUTHNEW;
   2710 			fin->fin_error = 0;
   2711 		} else {
   2712 			IPFERROR(1);
   2713 			fin->fin_error = ENOSPC;
   2714 		}
   2715 	}
   2716 
   2717 	if ((fr != NULL) && (fr->fr_func != NULL) &&
   2718 	    (fr->fr_func != (ipfunc_t)-1) && !(pass & FR_CALLNOW))
   2719 		(void) (*fr->fr_func)(fin, &pass);
   2720 
   2721 	/*
   2722 	 * If a rule is a pre-auth rule, check again in the list of rules
   2723 	 * loaded for authenticated use.  It does not particulary matter
   2724 	 * if this search fails because a "preauth" result, from a rule,
   2725 	 * is treated as "not a pass", hence the packet is blocked.
   2726 	 */
   2727 	if (FR_ISPREAUTH(pass)) {
   2728 		pass = ipf_auth_pre_scanlist(softc, fin, pass);
   2729 	}
   2730 
   2731 	/*
   2732 	 * If the rule has "keep frag" and the packet is actually a fragment,
   2733 	 * then create a fragment state entry.
   2734 	 */
   2735 	if (pass & FR_KEEPFRAG) {
   2736 		if (fin->fin_flx & FI_FRAG) {
   2737 			if (ipf_frag_new(softc, fin, pass) == -1) {
   2738 				LBUMP(ipf_stats[out].fr_bnfr);
   2739 			} else {
   2740 				LBUMP(ipf_stats[out].fr_nfr);
   2741 			}
   2742 		} else {
   2743 			LBUMP(ipf_stats[out].fr_cfr);
   2744 		}
   2745 	}
   2746 
   2747 	fr = fin->fin_fr;
   2748 	*passp = pass;
   2749 
   2750 	return fr;
   2751 }
   2752 
   2753 
   2754 /* ------------------------------------------------------------------------ */
   2755 /* Function:    ipf_check                                                   */
   2756 /* Returns:     int -  0 == packet allowed through,                         */
   2757 /*              User space:                                                 */
   2758 /*                    -1 == packet blocked                                  */
   2759 /*                     1 == packet not matched                              */
   2760 /*                    -2 == requires authentication                         */
   2761 /*              Kernel:                                                     */
   2762 /*                   > 0 == filter error # for packet                       */
   2763 /* Parameters: ip(I)   - pointer to start of IPv4/6 packet                  */
   2764 /*             hlen(I) - length of header                                   */
   2765 /*             ifp(I)  - pointer to interface this packet is on             */
   2766 /*             out(I)  - 0 == packet going in, 1 == packet going out        */
   2767 /*             mp(IO)  - pointer to caller's buffer pointer that holds this */
   2768 /*                       IP packet.                                         */
   2769 /* Solaris & HP-UX ONLY :                                                   */
   2770 /*             qpi(I)  - pointer to STREAMS queue information for this      */
   2771 /*                       interface & direction.                             */
   2772 /*                                                                          */
   2773 /* ipf_check() is the master function for all IPFilter packet processing.   */
   2774 /* It orchestrates: Network Address Translation (NAT), checking for packet  */
   2775 /* authorisation (or pre-authorisation), presence of related state info.,   */
   2776 /* generating log entries, IP packet accounting, routing of packets as      */
   2777 /* directed by firewall rules and of course whether or not to allow the     */
   2778 /* packet to be further processed by the kernel.                            */
   2779 /*                                                                          */
   2780 /* For packets blocked, the contents of "mp" will be NULL'd and the buffer  */
   2781 /* freed.  Packets passed may be returned with the pointer pointed to by    */
   2782 /* by "mp" changed to a new buffer.                                         */
   2783 /* ------------------------------------------------------------------------ */
   2784 int
   2785 ipf_check(void *ctx, ip_t *ip, int hlen, void *ifp, int out,
   2786 #if defined(_KERNEL) && defined(MENTAT)
   2787     void *qif,
   2788 #endif
   2789     mb_t **mp)
   2790 {
   2791 	/*
   2792 	 * The above really sucks, but short of writing a diff
   2793 	 */
   2794 	ipf_main_softc_t *softc = ctx;
   2795 	fr_info_t frinfo;
   2796 	fr_info_t *fin = &frinfo;
   2797 	u_32_t pass = softc->ipf_pass;
   2798 	frentry_t *fr = NULL;
   2799 	int v = IP_V(ip);
   2800 	mb_t *mc = NULL;
   2801 	mb_t *m;
   2802 	/*
   2803 	 * The first part of ipf_check() deals with making sure that what goes
   2804 	 * into the filtering engine makes some sense.  Information about the
   2805 	 * the packet is distilled, collected into a fr_info_t structure and
   2806 	 * the an attempt to ensure the buffer the packet is in is big enough
   2807 	 * to hold all the required packet headers.
   2808 	 */
   2809 #ifdef	_KERNEL
   2810 # ifdef MENTAT
   2811 	qpktinfo_t *qpi = qif;
   2812 
   2813 #  ifdef __sparc
   2814 	if ((u_int)ip & 0x3)
   2815 		return 2;
   2816 #  endif
   2817 # else
   2818 	SPL_INT(s);
   2819 # endif
   2820 
   2821 	if (softc->ipf_running <= 0) {
   2822 		return 0;
   2823 	}
   2824 
   2825 	bzero((char *)fin, sizeof(*fin));
   2826 
   2827 # ifdef MENTAT
   2828 	if (qpi->qpi_flags & QF_BROADCAST)
   2829 		fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
   2830 	if (qpi->qpi_flags & QF_MULTICAST)
   2831 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
   2832 	m = qpi->qpi_m;
   2833 	fin->fin_qfm = m;
   2834 	fin->fin_qpi = qpi;
   2835 # else /* MENTAT */
   2836 
   2837 	m = *mp;
   2838 
   2839 #  if defined(M_MCAST)
   2840 	if ((m->m_flags & M_MCAST) != 0)
   2841 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
   2842 #  endif
   2843 #  if defined(M_MLOOP)
   2844 	if ((m->m_flags & M_MLOOP) != 0)
   2845 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
   2846 #  endif
   2847 #  if defined(M_BCAST)
   2848 	if ((m->m_flags & M_BCAST) != 0)
   2849 		fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
   2850 #  endif
   2851 #  ifdef M_CANFASTFWD
   2852 	/*
   2853 	 * XXX For now, IP Filter and fast-forwarding of cached flows
   2854 	 * XXX are mutually exclusive.  Eventually, IP Filter should
   2855 	 * XXX get a "can-fast-forward" filter rule.
   2856 	 */
   2857 	m->m_flags &= ~M_CANFASTFWD;
   2858 #  endif /* M_CANFASTFWD */
   2859 #  if defined(CSUM_DELAY_DATA) && (!defined(__FreeBSD_version) || \
   2860 				   (__FreeBSD_version < 501108))
   2861 	/*
   2862 	 * disable delayed checksums.
   2863 	 */
   2864 	if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
   2865 		in_undefer_cksum_tcpudp(m);
   2866 		m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
   2867 	}
   2868 #  endif /* CSUM_DELAY_DATA */
   2869 # endif /* MENTAT */
   2870 #else
   2871 	bzero((char *)fin, sizeof(*fin));
   2872 	m = *mp;
   2873 # if defined(M_MCAST)
   2874 	if ((m->m_flags & M_MCAST) != 0)
   2875 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
   2876 # endif
   2877 # if defined(M_MLOOP)
   2878 	if ((m->m_flags & M_MLOOP) != 0)
   2879 		fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
   2880 # endif
   2881 # if defined(M_BCAST)
   2882 	if ((m->m_flags & M_BCAST) != 0)
   2883 		fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
   2884 # endif
   2885 #endif /* _KERNEL */
   2886 
   2887 	fin->fin_v = v;
   2888 	fin->fin_m = m;
   2889 	fin->fin_ip = ip;
   2890 	fin->fin_mp = mp;
   2891 	fin->fin_out = out;
   2892 	fin->fin_ifp = ifp;
   2893 	fin->fin_error = ENETUNREACH;
   2894 	fin->fin_hlen = (u_short)hlen;
   2895 	fin->fin_dp = (char *)ip + hlen;
   2896 	fin->fin_main_soft = softc;
   2897 
   2898 	fin->fin_ipoff = (char *)ip - MTOD(m, char *);
   2899 
   2900 	SPL_NET(s);
   2901 
   2902 #ifdef	USE_INET6
   2903 	if (v == 6) {
   2904 		LBUMP(ipf_stats[out].fr_ipv6);
   2905 		/*
   2906 		 * Jumbo grams are quite likely too big for internal buffer
   2907 		 * structures to handle comfortably, for now, so just drop
   2908 		 * them.
   2909 		 */
   2910 		if (((ip6_t *)ip)->ip6_plen == 0) {
   2911 			DT1(frb_jumbo, ip6_t *, (ip6_t *)ip);
   2912 			pass = FR_BLOCK|FR_NOMATCH;
   2913 			fin->fin_reason = FRB_JUMBO;
   2914 			goto finished;
   2915 		}
   2916 		fin->fin_family = AF_INET6;
   2917 	} else
   2918 #endif
   2919 	{
   2920 		fin->fin_family = AF_INET;
   2921 	}
   2922 
   2923 	if (ipf_makefrip(hlen, ip, fin) == -1) {
   2924 		DT1(frb_makefrip, fr_info_t *, fin);
   2925 		pass = FR_BLOCK|FR_NOMATCH;
   2926 		fin->fin_reason = FRB_MAKEFRIP;
   2927 		goto finished;
   2928 	}
   2929 
   2930 	/*
   2931 	 * For at least IPv6 packets, if a m_pullup() fails then this pointer
   2932 	 * becomes NULL and so we have no packet to free.
   2933 	 */
   2934 	if (*fin->fin_mp == NULL)
   2935 		goto finished;
   2936 
   2937 	if (!out) {
   2938 		if (v == 4) {
   2939 			if (softc->ipf_chksrc && !ipf_verifysrc(fin)) {
   2940 				LBUMPD(ipf_stats[0], fr_v4_badsrc);
   2941 				fin->fin_flx |= FI_BADSRC;
   2942 			}
   2943 			if (fin->fin_ip->ip_ttl < softc->ipf_minttl) {
   2944 				LBUMPD(ipf_stats[0], fr_v4_badttl);
   2945 				fin->fin_flx |= FI_LOWTTL;
   2946 			}
   2947 		}
   2948 #ifdef USE_INET6
   2949 		else  if (v == 6) {
   2950 			if (((ip6_t *)ip)->ip6_hlim < softc->ipf_minttl) {
   2951 				LBUMPD(ipf_stats[0], fr_v6_badttl);
   2952 				fin->fin_flx |= FI_LOWTTL;
   2953 			}
   2954 		}
   2955 #endif
   2956 	}
   2957 
   2958 	if (fin->fin_flx & FI_SHORT) {
   2959 		LBUMPD(ipf_stats[out], fr_short);
   2960 	}
   2961 
   2962 	READ_ENTER(&softc->ipf_mutex);
   2963 
   2964 	if (!out) {
   2965 		switch (fin->fin_v)
   2966 		{
   2967 		case 4 :
   2968 			if (ipf_nat_checkin(fin, &pass) == -1) {
   2969 				goto filterdone;
   2970 			}
   2971 			break;
   2972 #ifdef USE_INET6
   2973 		case 6 :
   2974 			if (ipf_nat6_checkin(fin, &pass) == -1) {
   2975 				goto filterdone;
   2976 			}
   2977 			break;
   2978 #endif
   2979 		default :
   2980 			break;
   2981 		}
   2982 	}
   2983 	/*
   2984 	 * Check auth now.
   2985 	 * If a packet is found in the auth table, then skip checking
   2986 	 * the access lists for permission but we do need to consider
   2987 	 * the result as if it were from the ACL's.  In addition, being
   2988 	 * found in the auth table means it has been seen before, so do
   2989 	 * not pass it through accounting (again), lest it be counted twice.
   2990 	 */
   2991 	fr = ipf_auth_check(fin, &pass);
   2992 	if (!out && (fr == NULL))
   2993 		(void) ipf_acctpkt(fin, NULL);
   2994 
   2995 	if (fr == NULL) {
   2996 		if ((fin->fin_flx & FI_FRAG) != 0)
   2997 			fr = ipf_frag_known(fin, &pass);
   2998 
   2999 		if (fr == NULL)
   3000 			fr = ipf_state_check(fin, &pass);
   3001 	}
   3002 
   3003 	if ((pass & FR_NOMATCH) || (fr == NULL))
   3004 		fr = ipf_firewall(fin, &pass);
   3005 
   3006 	/*
   3007 	 * If we've asked to track state for this packet, set it up.
   3008 	 * Here rather than ipf_firewall because ipf_checkauth may decide
   3009 	 * to return a packet for "keep state"
   3010 	 */
   3011 	if ((pass & FR_KEEPSTATE) && (fin->fin_m != NULL) &&
   3012 	    !(fin->fin_flx & FI_STATE)) {
   3013 		if (ipf_state_add(softc, fin, NULL, 0) == 0) {
   3014 			LBUMP(ipf_stats[out].fr_ads);
   3015 		} else {
   3016 			LBUMP(ipf_stats[out].fr_bads);
   3017 			if (FR_ISPASS(pass)) {
   3018 				DT(frb_stateadd);
   3019 				pass &= ~FR_CMDMASK;
   3020 				pass |= FR_BLOCK;
   3021 				fin->fin_reason = FRB_STATEADD;
   3022 			}
   3023 		}
   3024 	}
   3025 
   3026 	fin->fin_fr = fr;
   3027 	if ((fr != NULL) && !(fin->fin_flx & FI_STATE)) {
   3028 		fin->fin_dif = &fr->fr_dif;
   3029 		fin->fin_tif = &fr->fr_tifs[fin->fin_rev];
   3030 	}
   3031 
   3032 	/*
   3033 	 * Only count/translate packets which will be passed on, out the
   3034 	 * interface.
   3035 	 */
   3036 	if (out && FR_ISPASS(pass)) {
   3037 		(void) ipf_acctpkt(fin, NULL);
   3038 
   3039 		switch (fin->fin_v)
   3040 		{
   3041 		case 4 :
   3042 			if (ipf_nat_checkout(fin, &pass) == -1) {
   3043 				;
   3044 			} else if ((softc->ipf_update_ipid != 0) && (v == 4)) {
   3045 				if (ipf_updateipid(fin) == -1) {
   3046 					DT(frb_updateipid);
   3047 					LBUMP(ipf_stats[1].fr_ipud);
   3048 					pass &= ~FR_CMDMASK;
   3049 					pass |= FR_BLOCK;
   3050 					fin->fin_reason = FRB_UPDATEIPID;
   3051 				} else {
   3052 					LBUMP(ipf_stats[0].fr_ipud);
   3053 				}
   3054 			}
   3055 			break;
   3056 #ifdef USE_INET6
   3057 		case 6 :
   3058 			(void) ipf_nat6_checkout(fin, &pass);
   3059 			break;
   3060 #endif
   3061 		default :
   3062 			break;
   3063 		}
   3064 	}
   3065 
   3066 filterdone:
   3067 #ifdef	IPFILTER_LOG
   3068 	if ((softc->ipf_flags & FF_LOGGING) || (pass & FR_LOGMASK)) {
   3069 		(void) ipf_dolog(fin, &pass);
   3070 	}
   3071 #endif
   3072 
   3073 	/*
   3074 	 * The FI_STATE flag is cleared here so that calling ipf_state_check
   3075 	 * will work when called from inside of fr_fastroute.  Although
   3076 	 * there is a similar flag, FI_NATED, for NAT, it does have the same
   3077 	 * impact on code execution.
   3078 	 */
   3079 	fin->fin_flx &= ~FI_STATE;
   3080 
   3081 #if defined(FASTROUTE_RECURSION)
   3082 	/*
   3083 	 * Up the reference on fr_lock and exit ipf_mutex. The generation of
   3084 	 * a packet below can sometimes cause a recursive call into IPFilter.
   3085 	 * On those platforms where that does happen, we need to hang onto
   3086 	 * the filter rule just in case someone decides to remove or flush it
   3087 	 * in the meantime.
   3088 	 */
   3089 	if (fr != NULL) {
   3090 		MUTEX_ENTER(&fr->fr_lock);
   3091 		fr->fr_ref++;
   3092 		MUTEX_EXIT(&fr->fr_lock);
   3093 	}
   3094 
   3095 	RWLOCK_EXIT(&softc->ipf_mutex);
   3096 #endif
   3097 
   3098 	if ((pass & FR_RETMASK) != 0) {
   3099 		/*
   3100 		 * Should we return an ICMP packet to indicate error
   3101 		 * status passing through the packet filter ?
   3102 		 * WARNING: ICMP error packets AND TCP RST packets should
   3103 		 * ONLY be sent in repsonse to incoming packets.  Sending
   3104 		 * them in response to outbound packets can result in a
   3105 		 * panic on some operating systems.
   3106 		 */
   3107 		if (!out) {
   3108 			if (pass & FR_RETICMP) {
   3109 				int dst;
   3110 
   3111 				if ((pass & FR_RETMASK) == FR_FAKEICMP)
   3112 					dst = 1;
   3113 				else
   3114 					dst = 0;
   3115 				(void) ipf_send_icmp_err(ICMP_UNREACH, fin,
   3116 							 dst);
   3117 				LBUMP(ipf_stats[0].fr_ret);
   3118 			} else if (((pass & FR_RETMASK) == FR_RETRST) &&
   3119 				   !(fin->fin_flx & FI_SHORT)) {
   3120 				if (((fin->fin_flx & FI_OOW) != 0) ||
   3121 				    (ipf_send_reset(fin) == 0)) {
   3122 					LBUMP(ipf_stats[1].fr_ret);
   3123 				}
   3124 			}
   3125 
   3126 			/*
   3127 			 * When using return-* with auth rules, the auth code
   3128 			 * takes over disposing of this packet.
   3129 			 */
   3130 			if (FR_ISAUTH(pass) && (fin->fin_m != NULL)) {
   3131 				DT1(frb_authcapture, fr_info_t *, fin);
   3132 				fin->fin_m = *fin->fin_mp = NULL;
   3133 				fin->fin_reason = FRB_AUTHCAPTURE;
   3134 				m = NULL;
   3135 			}
   3136 		} else {
   3137 			if (pass & FR_RETRST) {
   3138 				fin->fin_error = ECONNRESET;
   3139 			}
   3140 		}
   3141 	}
   3142 
   3143 	/*
   3144 	 * After the above so that ICMP unreachables and TCP RSTs get
   3145 	 * created properly.
   3146 	 */
   3147 	if (FR_ISBLOCK(pass) && (fin->fin_flx & FI_NEWNAT))
   3148 		ipf_nat_uncreate(fin);
   3149 
   3150 	/*
   3151 	 * If we didn't drop off the bottom of the list of rules (and thus
   3152 	 * the 'current' rule fr is not NULL), then we may have some extra
   3153 	 * instructions about what to do with a packet.
   3154 	 * Once we're finished return to our caller, freeing the packet if
   3155 	 * we are dropping it.
   3156 	 */
   3157 	if (fr != NULL) {
   3158 		frdest_t *fdp;
   3159 
   3160 		/*
   3161 		 * Generate a duplicated packet first because ipf_fastroute
   3162 		 * can lead to fin_m being free'd... not good.
   3163 		 */
   3164 		fdp = fin->fin_dif;
   3165 		if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
   3166 		    (fdp->fd_ptr != (void *)-1) && (fin->fin_m != NULL)) {
   3167 			mc = M_COPY(fin->fin_m);
   3168 			if (mc != NULL)
   3169 				ipf_fastroute(mc, &mc, fin, fdp);
   3170 		}
   3171 
   3172 		fdp = fin->fin_tif;
   3173 		if (!out && (pass & FR_FASTROUTE)) {
   3174 			/*
   3175 			 * For fastroute rule, no destination interface defined
   3176 			 * so pass NULL as the frdest_t parameter
   3177 			 */
   3178 			(void) ipf_fastroute(fin->fin_m, mp, fin, NULL);
   3179 			m = *mp = NULL;
   3180 		} else if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
   3181 			   (fdp->fd_ptr != (struct ifnet *)-1)) {
   3182 			/* this is for to rules: */
   3183 			ipf_fastroute(fin->fin_m, mp, fin, fdp);
   3184 			m = *mp = NULL;
   3185 		}
   3186 
   3187 #if defined(FASTROUTE_RECURSION)
   3188 		(void) ipf_derefrule(softc, &fr);
   3189 #endif
   3190 	}
   3191 #if !defined(FASTROUTE_RECURSION)
   3192 	RWLOCK_EXIT(&softc->ipf_mutex);
   3193 #endif
   3194 
   3195 finished:
   3196 	if (!FR_ISPASS(pass)) {
   3197 		LBUMP(ipf_stats[out].fr_block);
   3198 		if (*mp != NULL) {
   3199 #ifdef _KERNEL
   3200 			FREE_MB_T(*mp);
   3201 #endif
   3202 			m = *mp = NULL;
   3203 		}
   3204 	} else {
   3205 		LBUMP(ipf_stats[out].fr_pass);
   3206 #if defined(_KERNEL) && defined(__sgi)
   3207 		if ((fin->fin_hbuf != NULL) &&
   3208 		    (mtod(fin->fin_m, struct ip *) != fin->fin_ip)) {
   3209 			COPYBACK(fin->fin_m, 0, fin->fin_plen, fin->fin_hbuf);
   3210 		}
   3211 #endif
   3212 	}
   3213 
   3214 	SPL_X(s);
   3215 
   3216 #ifdef _KERNEL
   3217 	if (FR_ISPASS(pass))
   3218 		return 0;
   3219 	LBUMP(ipf_stats[out].fr_blocked[fin->fin_reason]);
   3220 	return fin->fin_error;
   3221 #else /* _KERNEL */
   3222 	if (*mp != NULL)
   3223 		(*mp)->mb_ifp = fin->fin_ifp;
   3224 	blockreason = fin->fin_reason;
   3225 	FR_VERBOSE(("fin_flx %#x pass %#x ", fin->fin_flx, pass));
   3226 	/*if ((pass & FR_CMDMASK) == (softc->ipf_pass & FR_CMDMASK))*/
   3227 		if ((pass & FR_NOMATCH) != 0)
   3228 			return 1;
   3229 
   3230 	if ((pass & FR_RETMASK) != 0)
   3231 		switch (pass & FR_RETMASK)
   3232 		{
   3233 		case FR_RETRST :
   3234 			return 3;
   3235 		case FR_RETICMP :
   3236 			return 4;
   3237 		case FR_FAKEICMP :
   3238 			return 5;
   3239 		}
   3240 
   3241 	switch (pass & FR_CMDMASK)
   3242 	{
   3243 	case FR_PASS :
   3244 		return 0;
   3245 	case FR_BLOCK :
   3246 		return -1;
   3247 	case FR_AUTH :
   3248 		return -2;
   3249 	case FR_ACCOUNT :
   3250 		return -3;
   3251 	case FR_PREAUTH :
   3252 		return -4;
   3253 	}
   3254 	return 2;
   3255 #endif /* _KERNEL */
   3256 }
   3257 
   3258 
   3259 #ifdef	IPFILTER_LOG
   3260 /* ------------------------------------------------------------------------ */
   3261 /* Function:    ipf_dolog                                                   */
   3262 /* Returns:     frentry_t* - returns contents of fin_fr (no change made)    */
   3263 /* Parameters:  fin(I) - pointer to packet information                      */
   3264 /*              passp(IO) - pointer to current/new filter decision (unused) */
   3265 /*                                                                          */
   3266 /* Checks flags set to see how a packet should be logged, if it is to be    */
   3267 /* logged.  Adjust statistics based on its success or not.                  */
   3268 /* ------------------------------------------------------------------------ */
   3269 frentry_t *
   3270 ipf_dolog(fr_info_t *fin, u_32_t *passp)
   3271 {
   3272 	ipf_main_softc_t *softc = fin->fin_main_soft;
   3273 	u_32_t pass;
   3274 	int out;
   3275 
   3276 	out = fin->fin_out;
   3277 	pass = *passp;
   3278 
   3279 	if ((softc->ipf_flags & FF_LOGNOMATCH) && (pass & FR_NOMATCH)) {
   3280 		pass |= FF_LOGNOMATCH;
   3281 		LBUMPD(ipf_stats[out], fr_npkl);
   3282 		goto logit;
   3283 
   3284 	} else if (((pass & FR_LOGMASK) == FR_LOGP) ||
   3285 	    (FR_ISPASS(pass) && (softc->ipf_flags & FF_LOGPASS))) {
   3286 		if ((pass & FR_LOGMASK) != FR_LOGP)
   3287 			pass |= FF_LOGPASS;
   3288 		LBUMPD(ipf_stats[out], fr_ppkl);
   3289 		goto logit;
   3290 
   3291 	} else if (((pass & FR_LOGMASK) == FR_LOGB) ||
   3292 		   (FR_ISBLOCK(pass) && (softc->ipf_flags & FF_LOGBLOCK))) {
   3293 		if ((pass & FR_LOGMASK) != FR_LOGB)
   3294 			pass |= FF_LOGBLOCK;
   3295 		LBUMPD(ipf_stats[out], fr_bpkl);
   3296 
   3297 logit:
   3298 		if (ipf_log_pkt(fin, pass) == -1) {
   3299 			/*
   3300 			 * If the "or-block" option has been used then
   3301 			 * block the packet if we failed to log it.
   3302 			 */
   3303 			if ((pass & FR_LOGORBLOCK) && FR_ISPASS(pass)) {
   3304 				DT1(frb_logfail2, u_int, pass);
   3305 				pass &= ~FR_CMDMASK;
   3306 				pass |= FR_BLOCK;
   3307 				fin->fin_reason = FRB_LOGFAIL2;
   3308 			}
   3309 		}
   3310 		*passp = pass;
   3311 	}
   3312 
   3313 	return fin->fin_fr;
   3314 }
   3315 #endif /* IPFILTER_LOG */
   3316 
   3317 
   3318 /* ------------------------------------------------------------------------ */
   3319 /* Function:    ipf_cksum                                                   */
   3320 /* Returns:     u_short - IP header checksum                                */
   3321 /* Parameters:  addr(I) - pointer to start of buffer to checksum            */
   3322 /*              len(I)  - length of buffer in bytes                         */
   3323 /*                                                                          */
   3324 /* Calculate the two's complement 16 bit checksum of the buffer passed.     */
   3325 /*                                                                          */
   3326 /* N.B.: addr should be 16bit aligned.                                      */
   3327 /* ------------------------------------------------------------------------ */
   3328 u_short
   3329 ipf_cksum(u_short *addr, int len)
   3330 {
   3331 	u_32_t sum = 0;
   3332 
   3333 	for (sum = 0; len > 1; len -= 2)
   3334 		sum += *addr++;
   3335 
   3336 	/* mop up an odd byte, if necessary */
   3337 	if (len == 1)
   3338 		sum += *(u_char *)addr;
   3339 
   3340 	/*
   3341 	 * add back carry outs from top 16 bits to low 16 bits
   3342 	 */
   3343 	sum = (sum >> 16) + (sum & 0xffff);	/* add hi 16 to low 16 */
   3344 	sum += (sum >> 16);			/* add carry */
   3345 	return (u_short)(~sum);
   3346 }
   3347 
   3348 
   3349 /* ------------------------------------------------------------------------ */
   3350 /* Function:    fr_cksum                                                    */
   3351 /* Returns:     u_short - layer 4 checksum                                  */
   3352 /* Parameters:  fin(I)     - pointer to packet information                  */
   3353 /*              ip(I)      - pointer to IP header                           */
   3354 /*              l4proto(I) - protocol to caclulate checksum for             */
   3355 /*              l4hdr(I)   - pointer to layer 4 header                      */
   3356 /*                                                                          */
   3357 /* Calculates the TCP checksum for the packet held in "m", using the data   */
   3358 /* in the IP header "ip" to seed it.                                        */
   3359 /*                                                                          */
   3360 /* NB: This function assumes we've pullup'd enough for all of the IP header */
   3361 /* and the TCP header.  We also assume that data blocks aren't allocated in */
   3362 /* odd sizes.                                                               */
   3363 /*                                                                          */
   3364 /* Expects ip_len and ip_off to be in network byte order when called.       */
   3365 /* ------------------------------------------------------------------------ */
   3366 u_short
   3367 fr_cksum(fr_info_t *fin, ip_t *ip, int l4proto, void *l4hdr)
   3368 {
   3369 	u_short *sp, slen, sumsave, *csump;
   3370 	u_int sum, sum2;
   3371 	int hlen;
   3372 	int off;
   3373 #ifdef	USE_INET6
   3374 	ip6_t *ip6;
   3375 #endif
   3376 
   3377 	csump = NULL;
   3378 	sumsave = 0;
   3379 	sp = NULL;
   3380 	slen = 0;
   3381 	hlen = 0;
   3382 	sum = 0;
   3383 
   3384 	sum = htons((u_short)l4proto);
   3385 	/*
   3386 	 * Add up IP Header portion
   3387 	 */
   3388 #ifdef	USE_INET6
   3389 	if (IP_V(ip) == 4) {
   3390 #endif
   3391 		hlen = IP_HL(ip) << 2;
   3392 		off = hlen;
   3393 		sp = (u_short *)&ip->ip_src;
   3394 		sum += *sp++;	/* ip_src */
   3395 		sum += *sp++;
   3396 		sum += *sp++;	/* ip_dst */
   3397 		sum += *sp++;
   3398 #ifdef	USE_INET6
   3399 	} else if (IP_V(ip) == 6) {
   3400 		ip6 = (ip6_t *)ip;
   3401 		hlen = sizeof(*ip6);
   3402 		off = ((char *)fin->fin_dp - (char *)fin->fin_ip);
   3403 		sp = (u_short *)&ip6->ip6_src;
   3404 		sum += *sp++;	/* ip6_src */
   3405 		sum += *sp++;
   3406 		sum += *sp++;
   3407 		sum += *sp++;
   3408 		sum += *sp++;
   3409 		sum += *sp++;
   3410 		sum += *sp++;
   3411 		sum += *sp++;
   3412 		/* This needs to be routing header aware. */
   3413 		sum += *sp++;	/* ip6_dst */
   3414 		sum += *sp++;
   3415 		sum += *sp++;
   3416 		sum += *sp++;
   3417 		sum += *sp++;
   3418 		sum += *sp++;
   3419 		sum += *sp++;
   3420 		sum += *sp++;
   3421 	} else {
   3422 		return 0xffff;
   3423 	}
   3424 #endif
   3425 	slen = fin->fin_plen - off;
   3426 	sum += htons(slen);
   3427 
   3428 	switch (l4proto)
   3429 	{
   3430 	case IPPROTO_UDP :
   3431 		csump = &((udphdr_t *)l4hdr)->uh_sum;
   3432 		break;
   3433 
   3434 	case IPPROTO_TCP :
   3435 		csump = &((tcphdr_t *)l4hdr)->th_sum;
   3436 		break;
   3437 	case IPPROTO_ICMP :
   3438 		csump = &((icmphdr_t *)l4hdr)->icmp_cksum;
   3439 		sum = 0;	/* Pseudo-checksum is not included */
   3440 		break;
   3441 #ifdef USE_INET6
   3442 	case IPPROTO_ICMPV6 :
   3443 		csump = &((struct icmp6_hdr *)l4hdr)->icmp6_cksum;
   3444 		break;
   3445 #endif
   3446 	default :
   3447 		break;
   3448 	}
   3449 
   3450 	if (csump != NULL) {
   3451 		sumsave = *csump;
   3452 		*csump = 0;
   3453 	}
   3454 
   3455 	sum2 = ipf_pcksum(fin, off, sum);
   3456 	if (csump != NULL)
   3457 		*csump = sumsave;
   3458 	return sum2;
   3459 }
   3460 
   3461 
   3462 /* ------------------------------------------------------------------------ */
   3463 /* Function:    ipf_findgroup                                               */
   3464 /* Returns:     frgroup_t * - NULL = group not found, else pointer to group */
   3465 /* Parameters:  softc(I) - pointer to soft context main structure           */
   3466 /*              group(I) - group name to search for                         */
   3467 /*              unit(I)  - device to which this group belongs               */
   3468 /*              set(I)   - which set of rules (inactive/inactive) this is   */
   3469 /*              fgpp(O)  - pointer to place to store pointer to the pointer */
   3470 /*                         to where to add the next (last) group or where   */
   3471 /*                         to delete group from.                            */
   3472 /*                                                                          */
   3473 /* Search amongst the defined groups for a particular group number.         */
   3474 /* ------------------------------------------------------------------------ */
   3475 frgroup_t *
   3476 ipf_findgroup(ipf_main_softc_t *softc, char *group, minor_t unit, int set,
   3477     frgroup_t ***fgpp)
   3478 {
   3479 	frgroup_t *fg, **fgp;
   3480 
   3481 	/*
   3482 	 * Which list of groups to search in is dependent on which list of
   3483 	 * rules are being operated on.
   3484 	 */
   3485 	fgp = &softc->ipf_groups[unit][set];
   3486 
   3487 	while ((fg = *fgp) != NULL) {
   3488 		if (strncmp(group, fg->fg_name, FR_GROUPLEN) == 0)
   3489 			break;
   3490 		else
   3491 			fgp = &fg->fg_next;
   3492 	}
   3493 	if (fgpp != NULL)
   3494 		*fgpp = fgp;
   3495 	return fg;
   3496 }
   3497 
   3498 
   3499 /* ------------------------------------------------------------------------ */
   3500 /* Function:    ipf_group_add                                               */
   3501 /* Returns:     frgroup_t * - NULL == did not create group,                 */
   3502 /*                            != NULL == pointer to the group               */
   3503 /* Parameters:  softc(I) - pointer to soft context main structure           */
   3504 /*              num(I)   - group number to add                              */
   3505 /*              head(I)  - rule pointer that is using this as the head      */
   3506 /*              flags(I) - rule flags which describe the type of rule it is */
   3507 /*              unit(I)  - device to which this group will belong to        */
   3508 /*              set(I)   - which set of rules (inactive/inactive) this is   */
   3509 /* Write Locks: ipf_mutex                                                   */
   3510 /*                                                                          */
   3511 /* Add a new group head, or if it already exists, increase the reference    */
   3512 /* count to it.                                                             */
   3513 /* ------------------------------------------------------------------------ */
   3514 frgroup_t *
   3515 ipf_group_add(ipf_main_softc_t *softc, char *group, void *head, u_32_t flags,
   3516     minor_t unit, int set)
   3517 {
   3518 	frgroup_t *fg, **fgp;
   3519 	u_32_t gflags;
   3520 
   3521 	if (group == NULL)
   3522 		return NULL;
   3523 
   3524 	if (unit == IPL_LOGIPF && *group == '\0')
   3525 		return NULL;
   3526 
   3527 	fgp = NULL;
   3528 	gflags = flags & FR_INOUT;
   3529 
   3530 	fg = ipf_findgroup(softc, group, unit, set, &fgp);
   3531 	if (fg != NULL) {
   3532 		if (fg->fg_head == NULL && head != NULL)
   3533 			fg->fg_head = head;
   3534 		if (fg->fg_flags == 0)
   3535 			fg->fg_flags = gflags;
   3536 		else if (gflags != fg->fg_flags)
   3537 			return NULL;
   3538 		fg->fg_ref++;
   3539 		return fg;
   3540 	}
   3541 
   3542 	KMALLOC(fg, frgroup_t *);
   3543 	if (fg != NULL) {
   3544 		fg->fg_head = head;
   3545 		fg->fg_start = NULL;
   3546 		fg->fg_next = *fgp;
   3547 		bcopy(group, fg->fg_name, strlen(group) + 1);
   3548 		fg->fg_flags = gflags;
   3549 		fg->fg_ref = 1;
   3550 		fg->fg_set = &softc->ipf_groups[unit][set];
   3551 		*fgp = fg;
   3552 	}
   3553 	return fg;
   3554 }
   3555 
   3556 
   3557 /* ------------------------------------------------------------------------ */
   3558 /* Function:    ipf_group_del                                               */
   3559 /* Returns:     int      - number of rules deleted                          */
   3560 /* Parameters:  softc(I) - pointer to soft context main structure           */
   3561 /*              group(I) - group name to delete                             */
   3562 /*              fr(I)    - filter rule from which group is referenced       */
   3563 /* Write Locks: ipf_mutex                                                   */
   3564 /*                                                                          */
   3565 /* This function is called whenever a reference to a group is to be dropped */
   3566 /* and thus its reference count needs to be lowered and the group free'd if */
   3567 /* the reference count reaches zero. Passing in fr is really for the sole   */
   3568 /* purpose of knowing when the head rule is being deleted.                  */
   3569 /* ------------------------------------------------------------------------ */
   3570 void
   3571 ipf_group_del(ipf_main_softc_t *softc, frgroup_t *group, frentry_t *fr)
   3572 {
   3573 
   3574 	if (group->fg_head == fr)
   3575 		group->fg_head = NULL;
   3576 
   3577 	group->fg_ref--;
   3578 	if ((group->fg_ref == 0) && (group->fg_start == NULL))
   3579 		ipf_group_free(group);
   3580 }
   3581 
   3582 
   3583 /* ------------------------------------------------------------------------ */
   3584 /* Function:    ipf_group_free                                              */
   3585 /* Returns:     Nil                                                         */
   3586 /* Parameters:  group(I) - pointer to filter rule group                     */
   3587 /*                                                                          */
   3588 /* Remove the group from the list of groups and free it.                    */
   3589 /* ------------------------------------------------------------------------ */
   3590 static void
   3591 ipf_group_free(frgroup_t *group)
   3592 {
   3593 	frgroup_t **gp;
   3594 
   3595 	for (gp = group->fg_set; *gp != NULL; gp = &(*gp)->fg_next) {
   3596 		if (*gp == group) {
   3597 			*gp = group->fg_next;
   3598 			break;
   3599 		}
   3600 	}
   3601 	KFREE(group);
   3602 }
   3603 
   3604 
   3605 /* ------------------------------------------------------------------------ */
   3606 /* Function:    ipf_group_flush                                             */
   3607 /* Returns:     int      - number of rules flush from group                 */
   3608 /* Parameters:  softc(I) - pointer to soft context main structure           */
   3609 /* Parameters:  group(I) - pointer to filter rule group                     */
   3610 /*                                                                          */
   3611 /* Remove all of the rules that currently are listed under the given group. */
   3612 /* ------------------------------------------------------------------------ */
   3613 static int
   3614 ipf_group_flush(ipf_main_softc_t *softc, frgroup_t *group)
   3615 {
   3616 	int gone = 0;
   3617 
   3618 	(void) ipf_flushlist(softc, &gone, &group->fg_start);
   3619 
   3620 	return gone;
   3621 }
   3622 
   3623 
   3624 /* ------------------------------------------------------------------------ */
   3625 /* Function:    ipf_getrulen                                                */
   3626 /* Returns:     frentry_t * - NULL == not found, else pointer to rule n     */
   3627 /* Parameters:  softc(I) - pointer to soft context main structure           */
   3628 /* Parameters:  unit(I)  - device for which to count the rule's number      */
   3629 /*              flags(I) - which set of rules to find the rule in           */
   3630 /*              group(I) - group name                                       */
   3631 /*              n(I)     - rule number to find                              */
   3632 /*                                                                          */
   3633 /* Find rule # n in group # g and return a pointer to it.  Return NULl if   */
   3634 /* group # g doesn't exist or there are less than n rules in the group.     */
   3635 /* ------------------------------------------------------------------------ */
   3636 frentry_t *
   3637 ipf_getrulen(ipf_main_softc_t *softc, int unit, char *group, u_32_t n)
   3638 {
   3639 	frentry_t *fr;
   3640 	frgroup_t *fg;
   3641 
   3642 	fg = ipf_findgroup(softc, group, unit, softc->ipf_active, NULL);
   3643 	if (fg == NULL)
   3644 		return NULL;
   3645 	for (fr = fg->fg_start; fr && n; fr = fr->fr_next, n--)
   3646 		;
   3647 	if (n != 0)
   3648 		return NULL;
   3649 	return fr;
   3650 }
   3651 
   3652 
   3653 /* ------------------------------------------------------------------------ */
   3654 /* Function:    ipf_flushlist                                               */
   3655 /* Returns:     int - >= 0 - number of flushed rules                        */
   3656 /* Parameters:  softc(I)   - pointer to soft context main structure         */
   3657 /*              nfreedp(O) - pointer to int where flush count is stored     */
   3658 /*              listp(I)   - pointer to list to flush pointer               */
   3659 /* Write Locks: ipf_mutex                                                   */
   3660 /*                                                                          */
   3661 /* Recursively flush rules from the list, descending groups as they are     */
   3662 /* encountered.  if a rule is the head of a group and it has lost all its   */
   3663 /* group members, then also delete the group reference.  nfreedp is needed  */
   3664 /* to store the accumulating count of rules removed, whereas the returned   */
   3665 /* value is just the number removed from the current list.  The latter is   */
   3666 /* needed to correctly adjust reference counts on rules that define groups. */
   3667 /*                                                                          */
   3668 /* NOTE: Rules not loaded from user space cannot be flushed.                */
   3669 /* ------------------------------------------------------------------------ */
   3670 static int
   3671 ipf_flushlist(ipf_main_softc_t *softc, int *nfreedp, frentry_t **listp)
   3672 {
   3673 	int freed = 0;
   3674 	frentry_t *fp;
   3675 
   3676 	while ((fp = *listp) != NULL) {
   3677 		if ((fp->fr_type & FR_T_BUILTIN) ||
   3678 		    !(fp->fr_flags & FR_COPIED)) {
   3679 			listp = &fp->fr_next;
   3680 			continue;
   3681 		}
   3682 		*listp = fp->fr_next;
   3683 		if (fp->fr_next != NULL)
   3684 			fp->fr_next->fr_pnext = fp->fr_pnext;
   3685 		fp->fr_pnext = NULL;
   3686 
   3687 		if (fp->fr_grphead != NULL) {
   3688 			freed += ipf_group_flush(softc, fp->fr_grphead);
   3689 			fp->fr_names[fp->fr_grhead] = '\0';
   3690 		}
   3691 
   3692 		if (fp->fr_icmpgrp != NULL) {
   3693 			freed += ipf_group_flush(softc, fp->fr_icmpgrp);
   3694 			fp->fr_names[fp->fr_icmphead] = '\0';
   3695 		}
   3696 
   3697 		if (fp->fr_srctrack.ht_max_nodes)
   3698 			ipf_rb_ht_flush(&fp->fr_srctrack);
   3699 
   3700 		fp->fr_next = NULL;
   3701 
   3702 		ASSERT(fp->fr_ref > 0);
   3703 		if (ipf_derefrule(softc, &fp) == 0)
   3704 			freed++;
   3705 	}
   3706 	*nfreedp += freed;
   3707 	return freed;
   3708 }
   3709 
   3710 
   3711 /* ------------------------------------------------------------------------ */
   3712 /* Function:    ipf_flush                                                   */
   3713 /* Returns:     int - >= 0 - number of flushed rules                        */
   3714 /* Parameters:  softc(I) - pointer to soft context main structure           */
   3715 /*              unit(I)  - device for which to flush rules                  */
   3716 /*              flags(I) - which set of rules to flush                      */
   3717 /*                                                                          */
   3718 /* Calls flushlist() for all filter rules (accounting, firewall - both IPv4 */
   3719 /* and IPv6) as defined by the value of flags.                              */
   3720 /* ------------------------------------------------------------------------ */
   3721 int
   3722 ipf_flush(ipf_main_softc_t *softc, minor_t unit, int flags)
   3723 {
   3724 	int flushed = 0, set;
   3725 
   3726 	WRITE_ENTER(&softc->ipf_mutex);
   3727 
   3728 	set = softc->ipf_active;
   3729 	if ((flags & FR_INACTIVE) == FR_INACTIVE)
   3730 		set = 1 - set;
   3731 
   3732 	if (flags & FR_OUTQUE) {
   3733 		ipf_flushlist(softc, &flushed, &softc->ipf_rules[1][set]);
   3734 		ipf_flushlist(softc, &flushed, &softc->ipf_acct[1][set]);
   3735 	}
   3736 	if (flags & FR_INQUE) {
   3737 		ipf_flushlist(softc, &flushed, &softc->ipf_rules[0][set]);
   3738 		ipf_flushlist(softc, &flushed, &softc->ipf_acct[0][set]);
   3739 	}
   3740 
   3741 	flushed += ipf_flush_groups(softc, &softc->ipf_groups[unit][set],
   3742 				    flags & (FR_INQUE|FR_OUTQUE));
   3743 
   3744 	RWLOCK_EXIT(&softc->ipf_mutex);
   3745 
   3746 	if (unit == IPL_LOGIPF) {
   3747 		int tmp;
   3748 
   3749 		tmp = ipf_flush(softc, IPL_LOGCOUNT, flags);
   3750 		if (tmp >= 0)
   3751 			flushed += tmp;
   3752 	}
   3753 	return flushed;
   3754 }
   3755 
   3756 
   3757 /* ------------------------------------------------------------------------ */
   3758 /* Function:    ipf_flush_groups                                            */
   3759 /* Returns:     int - >= 0 - number of flushed rules                        */
   3760 /* Parameters:  softc(I)  - soft context pointerto work with                */
   3761 /*              grhead(I) - pointer to the start of the group list to flush */
   3762 /*              flags(I)  - which set of rules to flush                     */
   3763 /*                                                                          */
   3764 /* Walk through all of the groups under the given group head and remove all */
   3765 /* of those that match the flags passed in. The for loop here is bit more   */
   3766 /* complicated than usual because the removal of a rule with ipf_derefrule  */
   3767 /* may end up removing not only the structure pointed to by "fg" but also   */
   3768 /* what is fg_next and fg_next after that. So if a filter rule is actually  */
   3769 /* removed from the group then it is necessary to start again.              */
   3770 /* ------------------------------------------------------------------------ */
   3771 static int
   3772 ipf_flush_groups( ipf_main_softc_t *softc, frgroup_t **grhead, int flags)
   3773 {
   3774 	frentry_t *fr, **frp;
   3775 	frgroup_t *fg, **fgp;
   3776 	int flushed = 0;
   3777 	int removed = 0;
   3778 
   3779 	for (fgp = grhead; (fg = *fgp) != NULL; ) {
   3780 		while ((fg != NULL) && ((fg->fg_flags & flags) == 0))
   3781 			fg = fg->fg_next;
   3782 		if (fg == NULL)
   3783 			break;
   3784 		removed = 0;
   3785 		frp = &fg->fg_start;
   3786 		while ((removed == 0) && ((fr = *frp) != NULL)) {
   3787 			if ((fr->fr_flags & flags) == 0) {
   3788 				frp = &fr->fr_next;
   3789 			} else {
   3790 				if (fr->fr_next != NULL)
   3791 					fr->fr_next->fr_pnext = fr->fr_pnext;
   3792 				*frp = fr->fr_next;
   3793 				fr->fr_pnext = NULL;
   3794 				fr->fr_next = NULL;
   3795 				(void) ipf_derefrule(softc, &fr);
   3796 				flushed++;
   3797 				removed++;
   3798 			}
   3799 		}
   3800 		if (removed == 0)
   3801 			fgp = &fg->fg_next;
   3802 	}
   3803 	return flushed;
   3804 }
   3805 
   3806 
   3807 /* ------------------------------------------------------------------------ */
   3808 /* Function:    memstr                                                      */
   3809 /* Returns:     char *  - NULL if failed, != NULL pointer to matching bytes */
   3810 /* Parameters:  src(I)  - pointer to byte sequence to match                 */
   3811 /*              dst(I)  - pointer to byte sequence to search                */
   3812 /*              slen(I) - match length                                      */
   3813 /*              dlen(I) - length available to search in                     */
   3814 /*                                                                          */
   3815 /* Search dst for a sequence of bytes matching those at src and extend for  */
   3816 /* slen bytes.                                                              */
   3817 /* ------------------------------------------------------------------------ */
   3818 char *
   3819 memstr(const char *src, char *dst, size_t slen, size_t dlen)
   3820 {
   3821 	char *s = NULL;
   3822 
   3823 	while (dlen >= slen) {
   3824 		if (memcmp(src, dst, slen) == 0) {
   3825 			s = dst;
   3826 			break;
   3827 		}
   3828 		dst++;
   3829 		dlen--;
   3830 	}
   3831 	return s;
   3832 }
   3833 
   3834 
   3835 /* ------------------------------------------------------------------------ */
   3836 /* Function:    ipf_fixskip                                                 */
   3837 /* Returns:     Nil                                                         */
   3838 /* Parameters:  listp(IO)    - pointer to start of list with skip rule      */
   3839 /*              rp(I)        - rule added/removed with skip in it.          */
   3840 /*              addremove(I) - adjustment (-1/+1) to make to skip count,    */
   3841 /*                             depending on whether a rule was just added   */
   3842 /*                             or removed.                                  */
   3843 /*                                                                          */
   3844 /* Adjust all the rules in a list which would have skip'd past the position */
   3845 /* where we are inserting to skip to the right place given the change.      */
   3846 /* ------------------------------------------------------------------------ */
   3847 void
   3848 ipf_fixskip(frentry_t **listp, frentry_t *rp, int addremove)
   3849 {
   3850 	int rules, rn;
   3851 	frentry_t *fp;
   3852 
   3853 	rules = 0;
   3854 	for (fp = *listp; (fp != NULL) && (fp != rp); fp = fp->fr_next)
   3855 		rules++;
   3856 
   3857 	if (!fp)
   3858 		return;
   3859 
   3860 	for (rn = 0, fp = *listp; fp && (fp != rp); fp = fp->fr_next, rn++)
   3861 		if (FR_ISSKIP(fp->fr_flags) && (rn + fp->fr_arg >= rules))
   3862 			fp->fr_arg += addremove;
   3863 }
   3864 
   3865 
   3866 #ifdef	_KERNEL
   3867 /* ------------------------------------------------------------------------ */
   3868 /* Function:    count4bits                                                  */
   3869 /* Returns:     int - >= 0 - number of consecutive bits in input            */
   3870 /* Parameters:  ip(I) - 32bit IP address                                    */
   3871 /*                                                                          */
   3872 /* IPv4 ONLY                                                                */
   3873 /* count consecutive 1's in bit mask.  If the mask generated by counting    */
   3874 /* consecutive 1's is different to that passed, return -1, else return #    */
   3875 /* of bits.                                                                 */
   3876 /* ------------------------------------------------------------------------ */
   3877 int
   3878 count4bits(u_32_t ip)
   3879 {
   3880 	u_32_t	ipn;
   3881 	int	cnt = 0, i, j;
   3882 
   3883 	ip = ipn = ntohl(ip);
   3884 	for (i = 32; i; i--, ipn *= 2)
   3885 		if (ipn & 0x80000000)
   3886 			cnt++;
   3887 		else
   3888 			break;
   3889 	ipn = 0;
   3890 	for (i = 32, j = cnt; i; i--, j--) {
   3891 		ipn *= 2;
   3892 		if (j > 0)
   3893 			ipn++;
   3894 	}
   3895 	if (ipn == ip)
   3896 		return cnt;
   3897 	return -1;
   3898 }
   3899 
   3900 
   3901 /* ------------------------------------------------------------------------ */
   3902 /* Function:    count6bits                                                  */
   3903 /* Returns:     int - >= 0 - number of consecutive bits in input            */
   3904 /* Parameters:  msk(I) - pointer to start of IPv6 bitmask                   */
   3905 /*                                                                          */
   3906 /* IPv6 ONLY                                                                */
   3907 /* count consecutive 1's in bit mask.                                       */
   3908 /* ------------------------------------------------------------------------ */
   3909 # ifdef USE_INET6
   3910 int
   3911 count6bits(u_32_t *msk)
   3912 {
   3913 	int i = 0, k;
   3914 	u_32_t j;
   3915 
   3916 	for (k = 3; k >= 0; k--)
   3917 		if (msk[k] == 0xffffffff)
   3918 			i += 32;
   3919 		else {
   3920 			for (j = msk[k]; j; j <<= 1)
   3921 				if (j & 0x80000000)
   3922 					i++;
   3923 		}
   3924 	return i;
   3925 }
   3926 # endif
   3927 #endif /* _KERNEL */
   3928 
   3929 
   3930 /* ------------------------------------------------------------------------ */
   3931 /* Function:    ipf_synclist                                                */
   3932 /* Returns:     int    - 0 = no failures, else indication of first failure  */
   3933 /* Parameters:  fr(I)  - start of filter list to sync interface names for   */
   3934 /*              ifp(I) - interface pointer for limiting sync lookups        */
   3935 /* Write Locks: ipf_mutex                                                   */
   3936 /*                                                                          */
   3937 /* Walk through a list of filter rules and resolve any interface names into */
   3938 /* pointers.  Where dynamic addresses are used, also update the IP address  */
   3939 /* used in the rule.  The interface pointer is used to limit the lookups to */
   3940 /* a specific set of matching names if it is non-NULL.                      */
   3941 /* Errors can occur when resolving the destination name of to/dup-to fields */
   3942 /* when the name points to a pool and that pool doest not exist. If this    */
   3943 /* does happen then it is necessary to check if there are any lookup refs   */
   3944 /* that need to be dropped before returning with an error.                  */
   3945 /* ------------------------------------------------------------------------ */
   3946 static int
   3947 ipf_synclist(ipf_main_softc_t *softc, frentry_t *fr, void *ifp)
   3948 {
   3949 	frentry_t *frt, *start = fr;
   3950 	frdest_t *fdp;
   3951 	char *name;
   3952 	int error;
   3953 	void *ifa;
   3954 	int v, i;
   3955 
   3956 	error = 0;
   3957 
   3958 	for (; fr; fr = fr->fr_next) {
   3959 		if (fr->fr_family == AF_INET)
   3960 			v = 4;
   3961 		else if (fr->fr_family == AF_INET6)
   3962 			v = 6;
   3963 		else
   3964 			v = 0;
   3965 
   3966 		/*
   3967 		 * Lookup all the interface names that are part of the rule.
   3968 		 */
   3969 		for (i = 0; i < 4; i++) {
   3970 			if ((ifp != NULL) && (fr->fr_ifas[i] != ifp))
   3971 				continue;
   3972 			if (fr->fr_ifnames[i] == -1)
   3973 				continue;
   3974 			name = FR_NAME(fr, fr_ifnames[i]);
   3975 			fr->fr_ifas[i] = ipf_resolvenic(softc, name, v);
   3976 		}
   3977 
   3978 		if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
   3979 			if (fr->fr_satype != FRI_NORMAL &&
   3980 			    fr->fr_satype != FRI_LOOKUP) {
   3981 				ifa = ipf_resolvenic(softc, fr->fr_names +
   3982 						     fr->fr_sifpidx, v);
   3983 				ipf_ifpaddr(softc, v, fr->fr_satype, ifa,
   3984 					    &fr->fr_src6, &fr->fr_smsk6);
   3985 			}
   3986 			if (fr->fr_datype != FRI_NORMAL &&
   3987 			    fr->fr_datype != FRI_LOOKUP) {
   3988 				ifa = ipf_resolvenic(softc, fr->fr_names +
   3989 						     fr->fr_sifpidx, v);
   3990 				ipf_ifpaddr(softc, v, fr->fr_datype, ifa,
   3991 					    &fr->fr_dst6, &fr->fr_dmsk6);
   3992 			}
   3993 		}
   3994 
   3995 		fdp = &fr->fr_tifs[0];
   3996 		if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
   3997 			error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
   3998 			if (error != 0)
   3999 				goto unwind;
   4000 		}
   4001 
   4002 		fdp = &fr->fr_tifs[1];
   4003 		if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
   4004 			error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
   4005 			if (error != 0)
   4006 				goto unwind;
   4007 		}
   4008 
   4009 		fdp = &fr->fr_dif;
   4010 		if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
   4011 			error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
   4012 			if (error != 0)
   4013 				goto unwind;
   4014 		}
   4015 
   4016 		if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
   4017 		    (fr->fr_satype == FRI_LOOKUP) && (fr->fr_srcptr == NULL)) {
   4018 			fr->fr_srcptr = ipf_lookup_res_num(softc,
   4019 							   fr->fr_srctype,
   4020 							   IPL_LOGIPF,
   4021 							   fr->fr_srcnum,
   4022 							   &fr->fr_srcfunc);
   4023 		}
   4024 		if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
   4025 		    (fr->fr_datype == FRI_LOOKUP) && (fr->fr_dstptr == NULL)) {
   4026 			fr->fr_dstptr = ipf_lookup_res_num(softc,
   4027 							   fr->fr_dsttype,
   4028 							   IPL_LOGIPF,
   4029 							   fr->fr_dstnum,
   4030 							   &fr->fr_dstfunc);
   4031 		}
   4032 	}
   4033 	return 0;
   4034 
   4035 unwind:
   4036 	for (frt = start; frt != fr; fr = fr->fr_next) {
   4037 		if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
   4038 		    (frt->fr_satype == FRI_LOOKUP) && (frt->fr_srcptr != NULL))
   4039 				ipf_lookup_deref(softc, frt->fr_srctype,
   4040 						 frt->fr_srcptr);
   4041 		if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
   4042 		    (frt->fr_datype == FRI_LOOKUP) && (frt->fr_dstptr != NULL))
   4043 				ipf_lookup_deref(softc, frt->fr_dsttype,
   4044 						 frt->fr_dstptr);
   4045 	}
   4046 	return error;
   4047 }
   4048 
   4049 
   4050 /* ------------------------------------------------------------------------ */
   4051 /* Function:    ipf_sync                                                    */
   4052 /* Returns:     void                                                        */
   4053 /* Parameters:  Nil                                                         */
   4054 /*                                                                          */
   4055 /* ipf_sync() is called when we suspect that the interface list or          */
   4056 /* information about interfaces (like IP#) has changed.  Go through all     */
   4057 /* filter rules, NAT entries and the state table and check if anything      */
   4058 /* needs to be changed/updated.                                             */
   4059 /* ------------------------------------------------------------------------ */
   4060 int
   4061 ipf_sync(ipf_main_softc_t *softc, void *ifp)
   4062 {
   4063 	int i;
   4064 
   4065 # if !SOLARIS
   4066 	ipf_nat_sync(softc, ifp);
   4067 	ipf_state_sync(softc, ifp);
   4068 	ipf_lookup_sync(softc, ifp);
   4069 # endif
   4070 
   4071 	WRITE_ENTER(&softc->ipf_mutex);
   4072 	(void) ipf_synclist(softc, softc->ipf_acct[0][softc->ipf_active], ifp);
   4073 	(void) ipf_synclist(softc, softc->ipf_acct[1][softc->ipf_active], ifp);
   4074 	(void) ipf_synclist(softc, softc->ipf_rules[0][softc->ipf_active], ifp);
   4075 	(void) ipf_synclist(softc, softc->ipf_rules[1][softc->ipf_active], ifp);
   4076 
   4077 	for (i = 0; i < IPL_LOGSIZE; i++) {
   4078 		frgroup_t *g;
   4079 
   4080 		for (g = softc->ipf_groups[i][0]; g != NULL; g = g->fg_next)
   4081 			(void) ipf_synclist(softc, g->fg_start, ifp);
   4082 		for (g = softc->ipf_groups[i][1]; g != NULL; g = g->fg_next)
   4083 			(void) ipf_synclist(softc, g->fg_start, ifp);
   4084 	}
   4085 	RWLOCK_EXIT(&softc->ipf_mutex);
   4086 
   4087 	return 0;
   4088 }
   4089 
   4090 
   4091 /*
   4092  * In the functions below, bcopy() is called because the pointer being
   4093  * copied _from_ in this instance is a pointer to a char buf (which could
   4094  * end up being unaligned) and on the kernel's local stack.
   4095  */
   4096 /* ------------------------------------------------------------------------ */
   4097 /* Function:    copyinptr                                                   */
   4098 /* Returns:     int - 0 = success, else failure                             */
   4099 /* Parameters:  src(I)  - pointer to the source address                     */
   4100 /*              dst(I)  - destination address                               */
   4101 /*              size(I) - number of bytes to copy                           */
   4102 /*                                                                          */
   4103 /* Copy a block of data in from user space, given a pointer to the pointer  */
   4104 /* to start copying from (src) and a pointer to where to store it (dst).    */
   4105 /* NB: src - pointer to user space pointer, dst - kernel space pointer      */
   4106 /* ------------------------------------------------------------------------ */
   4107 int
   4108 copyinptr(ipf_main_softc_t *softc, void *src, void *dst, size_t size)
   4109 {
   4110 	void *ca;
   4111 	int error;
   4112 
   4113 # if SOLARIS
   4114 	error = COPYIN(src, &ca, sizeof(ca));
   4115 	if (error != 0)
   4116 		return error;
   4117 # else
   4118 	bcopy(src, (void *)&ca, sizeof(ca));
   4119 # endif
   4120 	error = COPYIN(ca, dst, size);
   4121 	if (error != 0) {
   4122 		IPFERROR(3);
   4123 		error = EFAULT;
   4124 	}
   4125 	return error;
   4126 }
   4127 
   4128 
   4129 /* ------------------------------------------------------------------------ */
   4130 /* Function:    copyoutptr                                                  */
   4131 /* Returns:     int - 0 = success, else failure                             */
   4132 /* Parameters:  src(I)  - pointer to the source address                     */
   4133 /*              dst(I)  - destination address                               */
   4134 /*              size(I) - number of bytes to copy                           */
   4135 /*                                                                          */
   4136 /* Copy a block of data out to user space, given a pointer to the pointer   */
   4137 /* to start copying from (src) and a pointer to where to store it (dst).    */
   4138 /* NB: src - kernel space pointer, dst - pointer to user space pointer.     */
   4139 /* ------------------------------------------------------------------------ */
   4140 int
   4141 copyoutptr(ipf_main_softc_t *softc, void *src, void *dst, size_t size)
   4142 {
   4143 	void *ca;
   4144 	int error;
   4145 
   4146 	bcopy(dst, &ca, sizeof(ca));
   4147 	error = COPYOUT(src, ca, size);
   4148 	if (error != 0) {
   4149 		IPFERROR(4);
   4150 		error = EFAULT;
   4151 	}
   4152 	return error;
   4153 }
   4154 #ifdef	_KERNEL
   4155 #endif
   4156 
   4157 
   4158 /* ------------------------------------------------------------------------ */
   4159 /* Function:    ipf_lock                                                    */
   4160 /* Returns:     int      - 0 = success, else error                          */
   4161 /* Parameters:  data(I)  - pointer to lock value to set                     */
   4162 /*              lockp(O) - pointer to location to store old lock value      */
   4163 /*                                                                          */
   4164 /* Get the new value for the lock integer, set it and return the old value  */
   4165 /* in *lockp.                                                               */
   4166 /* ------------------------------------------------------------------------ */
   4167 int
   4168 ipf_lock(void *data, int *lockp)
   4169 {
   4170 	int arg, err;
   4171 
   4172 	err = BCOPYIN(data, &arg, sizeof(arg));
   4173 	if (err != 0)
   4174 		return EFAULT;
   4175 	err = BCOPYOUT(lockp, data, sizeof(*lockp));
   4176 	if (err != 0)
   4177 		return EFAULT;
   4178 	*lockp = arg;
   4179 	return 0;
   4180 }
   4181 
   4182 
   4183 /* ------------------------------------------------------------------------ */
   4184 /* Function:    ipf_getstat                                                 */
   4185 /* Returns:     Nil                                                         */
   4186 /* Parameters:  softc(I) - pointer to soft context main structure           */
   4187 /*              fiop(I)  - pointer to ipfilter stats structure              */
   4188 /*              rev(I)   - version claim by program doing ioctl             */
   4189 /*                                                                          */
   4190 /* Stores a copy of current pointers, counters, etc, in the friostat        */
   4191 /* structure.                                                               */
   4192 /* If IPFILTER_COMPAT is compiled, we pretend to be whatever version the    */
   4193 /* program is looking for. This ensure that validation of the version it    */
   4194 /* expects will always succeed. Thus kernels with IPFILTER_COMPAT will      */
   4195 /* allow older binaries to work but kernels without it will not.            */
   4196 /* ------------------------------------------------------------------------ */
   4197 /*ARGSUSED*/
   4198 static void
   4199 ipf_getstat(ipf_main_softc_t *softc, friostat_t *fiop, int rev)
   4200 {
   4201 	int i;
   4202 
   4203 	bcopy((char *)softc->ipf_stats, (char *)fiop->f_st,
   4204 	      sizeof(ipf_statistics_t) * 2);
   4205 	fiop->f_locks[IPL_LOGSTATE] = -1;
   4206 	fiop->f_locks[IPL_LOGNAT] = -1;
   4207 	fiop->f_locks[IPL_LOGIPF] = -1;
   4208 	fiop->f_locks[IPL_LOGAUTH] = -1;
   4209 
   4210 	fiop->f_ipf[0][0] = softc->ipf_rules[0][0];
   4211 	fiop->f_acct[0][0] = softc->ipf_acct[0][0];
   4212 	fiop->f_ipf[0][1] = softc->ipf_rules[0][1];
   4213 	fiop->f_acct[0][1] = softc->ipf_acct[0][1];
   4214 	fiop->f_ipf[1][0] = softc->ipf_rules[1][0];
   4215 	fiop->f_acct[1][0] = softc->ipf_acct[1][0];
   4216 	fiop->f_ipf[1][1] = softc->ipf_rules[1][1];
   4217 	fiop->f_acct[1][1] = softc->ipf_acct[1][1];
   4218 
   4219 	fiop->f_ticks = softc->ipf_ticks;
   4220 	fiop->f_active = softc->ipf_active;
   4221 	fiop->f_froute[0] = softc->ipf_frouteok[0];
   4222 	fiop->f_froute[1] = softc->ipf_frouteok[1];
   4223 	fiop->f_rb_no_mem = softc->ipf_rb_no_mem;
   4224 	fiop->f_rb_node_max = softc->ipf_rb_node_max;
   4225 
   4226 	fiop->f_running = softc->ipf_running;
   4227 	for (i = 0; i < IPL_LOGSIZE; i++) {
   4228 		fiop->f_groups[i][0] = softc->ipf_groups[i][0];
   4229 		fiop->f_groups[i][1] = softc->ipf_groups[i][1];
   4230 	}
   4231 #ifdef  IPFILTER_LOG
   4232 	fiop->f_log_ok = ipf_log_logok(softc, IPL_LOGIPF);
   4233 	fiop->f_log_fail = ipf_log_failures(softc, IPL_LOGIPF);
   4234 	fiop->f_logging = 1;
   4235 #else
   4236 	fiop->f_log_ok = 0;
   4237 	fiop->f_log_fail = 0;
   4238 	fiop->f_logging = 0;
   4239 #endif
   4240 	fiop->f_defpass = softc->ipf_pass;
   4241 	fiop->f_features = ipf_features;
   4242 
   4243 #ifdef IPFILTER_COMPAT
   4244 	snprintf(fiop->f_version, sizeof(fiop->f_version),
   4245 		 "IP Filter: v%d.%d.%d", (rev / 1000000) % 100,
   4246 		 (rev / 10000) % 100, (rev / 100) % 100);
   4247 #else
   4248 	rev = rev;
   4249 	(void) strncpy(fiop->f_version, ipfilter_version,
   4250 		       sizeof(fiop->f_version));
   4251         fiop->f_version[sizeof(fiop->f_version) - 1] = '\0';
   4252 #endif
   4253 }
   4254 
   4255 
   4256 #ifdef	USE_INET6
   4257 int icmptoicmp6types[ICMP_MAXTYPE+1] = {
   4258 	ICMP6_ECHO_REPLY,	/* 0: ICMP_ECHOREPLY */
   4259 	-1,			/* 1: UNUSED */
   4260 	-1,			/* 2: UNUSED */
   4261 	ICMP6_DST_UNREACH,	/* 3: ICMP_UNREACH */
   4262 	-1,			/* 4: ICMP_SOURCEQUENCH */
   4263 	ND_REDIRECT,		/* 5: ICMP_REDIRECT */
   4264 	-1,			/* 6: UNUSED */
   4265 	-1,			/* 7: UNUSED */
   4266 	ICMP6_ECHO_REQUEST,	/* 8: ICMP_ECHO */
   4267 	-1,			/* 9: UNUSED */
   4268 	-1,			/* 10: UNUSED */
   4269 	ICMP6_TIME_EXCEEDED,	/* 11: ICMP_TIMXCEED */
   4270 	ICMP6_PARAM_PROB,	/* 12: ICMP_PARAMPROB */
   4271 	-1,			/* 13: ICMP_TSTAMP */
   4272 	-1,			/* 14: ICMP_TSTAMPREPLY */
   4273 	-1,			/* 15: ICMP_IREQ */
   4274 	-1,			/* 16: ICMP_IREQREPLY */
   4275 	-1,			/* 17: ICMP_MASKREQ */
   4276 	-1,			/* 18: ICMP_MASKREPLY */
   4277 };
   4278 
   4279 
   4280 int	icmptoicmp6unreach[ICMP_MAX_UNREACH] = {
   4281 	ICMP6_DST_UNREACH_ADDR,		/* 0: ICMP_UNREACH_NET */
   4282 	ICMP6_DST_UNREACH_ADDR,		/* 1: ICMP_UNREACH_HOST */
   4283 	-1,				/* 2: ICMP_UNREACH_PROTOCOL */
   4284 	ICMP6_DST_UNREACH_NOPORT,	/* 3: ICMP_UNREACH_PORT */
   4285 	-1,				/* 4: ICMP_UNREACH_NEEDFRAG */
   4286 	ICMP6_DST_UNREACH_NOTNEIGHBOR,	/* 5: ICMP_UNREACH_SRCFAIL */
   4287 	ICMP6_DST_UNREACH_ADDR,		/* 6: ICMP_UNREACH_NET_UNKNOWN */
   4288 	ICMP6_DST_UNREACH_ADDR,		/* 7: ICMP_UNREACH_HOST_UNKNOWN */
   4289 	-1,				/* 8: ICMP_UNREACH_ISOLATED */
   4290 	ICMP6_DST_UNREACH_ADMIN,	/* 9: ICMP_UNREACH_NET_PROHIB */
   4291 	ICMP6_DST_UNREACH_ADMIN,	/* 10: ICMP_UNREACH_HOST_PROHIB */
   4292 	-1,				/* 11: ICMP_UNREACH_TOSNET */
   4293 	-1,				/* 12: ICMP_UNREACH_TOSHOST */
   4294 	ICMP6_DST_UNREACH_ADMIN,	/* 13: ICMP_UNREACH_ADMIN_PROHIBIT */
   4295 };
   4296 int	icmpreplytype6[ICMP6_MAXTYPE + 1];
   4297 #endif
   4298 
   4299 int	icmpreplytype4[ICMP_MAXTYPE + 1];
   4300 
   4301 
   4302 /* ------------------------------------------------------------------------ */
   4303 /* Function:    ipf_matchicmpqueryreply                                     */
   4304 /* Returns:     int - 1 if "icmp" is a valid reply to "ic" else 0.          */
   4305 /* Parameters:  v(I)    - IP protocol version (4 or 6)                      */
   4306 /*              ic(I)   - ICMP information                                  */
   4307 /*              icmp(I) - ICMP packet header                                */
   4308 /*              rev(I)  - direction (0 = forward/1 = reverse) of packet     */
   4309 /*                                                                          */
   4310 /* Check if the ICMP packet defined by the header pointed to by icmp is a   */
   4311 /* reply to one as described by what's in ic.  If it is a match, return 1,  */
   4312 /* else return 0 for no match.                                              */
   4313 /* ------------------------------------------------------------------------ */
   4314 int
   4315 ipf_matchicmpqueryreply(int v, icmpinfo_t *ic, icmphdr_t *icmp, int rev)
   4316 {
   4317 	int ictype;
   4318 
   4319 	ictype = ic->ici_type;
   4320 
   4321 	if (v == 4) {
   4322 		/*
   4323 		 * If we matched its type on the way in, then when going out
   4324 		 * it will still be the same type.
   4325 		 */
   4326 		if ((!rev && (icmp->icmp_type == ictype)) ||
   4327 		    (rev && (icmpreplytype4[ictype] == icmp->icmp_type))) {
   4328 			if (icmp->icmp_type != ICMP_ECHOREPLY)
   4329 				return 1;
   4330 			if (icmp->icmp_id == ic->ici_id)
   4331 				return 1;
   4332 		}
   4333 	}
   4334 #ifdef	USE_INET6
   4335 	else if (v == 6) {
   4336 		if ((!rev && (icmp->icmp_type == ictype)) ||
   4337 		    (rev && (icmpreplytype6[ictype] == icmp->icmp_type))) {
   4338 			if (icmp->icmp_type != ICMP6_ECHO_REPLY)
   4339 				return 1;
   4340 			if (icmp->icmp_id == ic->ici_id)
   4341 				return 1;
   4342 		}
   4343 	}
   4344 #endif
   4345 	return 0;
   4346 }
   4347 
   4348 /* ------------------------------------------------------------------------ */
   4349 /* Function:    ipf_rule_compare                                            */
   4350 /* Parameters:  fr1(I) - first rule structure to compare                    */
   4351 /*              fr2(I) - second rule structure to compare                   */
   4352 /* Returns:     int    - 0 == rules are the same, else mismatch             */
   4353 /*                                                                          */
   4354 /* Compare two rules and return 0 if they match or a number indicating      */
   4355 /* which of the individual checks failed.                                   */
   4356 /* ------------------------------------------------------------------------ */
   4357 static int
   4358 ipf_rule_compare(frentry_t *fr1, frentry_t *fr2)
   4359 {
   4360 	if (fr1->fr_cksum != fr2->fr_cksum)
   4361 		return 1;
   4362 	if (fr1->fr_size != fr2->fr_size)
   4363 		return 2;
   4364 	if (fr1->fr_dsize != fr2->fr_dsize)
   4365 		return 3;
   4366 	if (memcmp(&fr1->fr_func, &fr2->fr_func,
   4367 		 fr1->fr_size - offsetof(struct frentry, fr_func)) != 0)
   4368 		return 4;
   4369 	if (fr1->fr_data && !fr2->fr_data)
   4370 		return 5;
   4371 	if (!fr1->fr_data && fr2->fr_data)
   4372 		return 6;
   4373 	if (fr1->fr_data) {
   4374 		if (memcmp(fr1->fr_caddr, fr2->fr_caddr, fr1->fr_dsize))
   4375 			return 7;
   4376 	}
   4377 	return 0;
   4378 }
   4379 
   4380 
   4381 /* ------------------------------------------------------------------------ */
   4382 /* Function:    frrequest                                                   */
   4383 /* Returns:     int - 0 == success, > 0 == errno value                      */
   4384 /* Parameters:  unit(I)     - device for which this is for                  */
   4385 /*              req(I)      - ioctl command (SIOC*)                         */
   4386 /*              data(I)     - pointr to ioctl data                          */
   4387 /*              set(I)      - 1 or 0 (filter set)                           */
   4388 /*              makecopy(I) - flag indicating whether data points to a rule */
   4389 /*                            in kernel space & hence doesn't need copying. */
   4390 /*                                                                          */
   4391 /* This function handles all the requests which operate on the list of      */
   4392 /* filter rules.  This includes adding, deleting, insertion.  It is also    */
   4393 /* responsible for creating groups when a "head" rule is loaded.  Interface */
   4394 /* names are resolved here and other sanity checks are made on the content  */
   4395 /* of the rule structure being loaded.  If a rule has user defined timeouts */
   4396 /* then make sure they are created and initialised before exiting.          */
   4397 /* ------------------------------------------------------------------------ */
   4398 int
   4399 frrequest(ipf_main_softc_t *softc, int unit, ioctlcmd_t req, void *data,
   4400     int set, int makecopy)
   4401 {
   4402 	int error = 0, in, family, addrem, need_free = 0;
   4403 	frentry_t frd, *fp, *f, **fprev, **ftail;
   4404 	void *ptr, *uptr;
   4405 	u_int *p, *pp;
   4406 	frgroup_t *fg;
   4407 	char *group;
   4408 
   4409 	ptr = NULL;
   4410 	fg = NULL;
   4411 	fp = &frd;
   4412 	if (makecopy != 0) {
   4413 		bzero(fp, sizeof(frd));
   4414 		error = ipf_inobj(softc, data, NULL, fp, IPFOBJ_FRENTRY);
   4415 		if (error) {
   4416 			return error;
   4417 		}
   4418 		if ((fp->fr_type & FR_T_BUILTIN) != 0) {
   4419 			IPFERROR(6);
   4420 			return EINVAL;
   4421 		}
   4422 		KMALLOCS(f, frentry_t *, fp->fr_size);
   4423 		if (f == NULL) {
   4424 			IPFERROR(131);
   4425 			return ENOMEM;
   4426 		}
   4427 		bzero(f, fp->fr_size);
   4428 		error = ipf_inobjsz(softc, data, f, IPFOBJ_FRENTRY,
   4429 				    fp->fr_size);
   4430 		if (error) {
   4431 			KFREES(f, fp->fr_size);
   4432 			return error;
   4433 		}
   4434 
   4435 		fp = f;
   4436 		f = NULL;
   4437 		fp->fr_next = NULL;
   4438 		fp->fr_dnext = NULL;
   4439 		fp->fr_pnext = NULL;
   4440 		fp->fr_pdnext = NULL;
   4441 		fp->fr_grp = NULL;
   4442 		fp->fr_grphead = NULL;
   4443 		fp->fr_icmpgrp = NULL;
   4444 		fp->fr_isc = (void *)-1;
   4445 		fp->fr_ptr = NULL;
   4446 		fp->fr_ref = 0;
   4447 		fp->fr_flags |= FR_COPIED;
   4448 	} else {
   4449 		fp = (frentry_t *)data;
   4450 		if ((fp->fr_type & FR_T_BUILTIN) == 0) {
   4451 			IPFERROR(7);
   4452 			return EINVAL;
   4453 		}
   4454 		fp->fr_flags &= ~FR_COPIED;
   4455 	}
   4456 
   4457 	if (((fp->fr_dsize == 0) && (fp->fr_data != NULL)) ||
   4458 	    ((fp->fr_dsize != 0) && (fp->fr_data == NULL))) {
   4459 		IPFERROR(8);
   4460 		error = EINVAL;
   4461 		goto donenolock;
   4462 	}
   4463 
   4464 	family = fp->fr_family;
   4465 	uptr = fp->fr_data;
   4466 
   4467 	if (req == (ioctlcmd_t)SIOCINAFR || req == (ioctlcmd_t)SIOCINIFR ||
   4468 	    req == (ioctlcmd_t)SIOCADAFR || req == (ioctlcmd_t)SIOCADIFR)
   4469 		addrem = 0;
   4470 	else if (req == (ioctlcmd_t)SIOCRMAFR || req == (ioctlcmd_t)SIOCRMIFR)
   4471 		addrem = 1;
   4472 	else if (req == (ioctlcmd_t)SIOCZRLST)
   4473 		addrem = 2;
   4474 	else {
   4475 		IPFERROR(9);
   4476 		error = EINVAL;
   4477 		goto donenolock;
   4478 	}
   4479 
   4480 	/*
   4481 	 * Only filter rules for IPv4 or IPv6 are accepted.
   4482 	 */
   4483 	if (family == AF_INET) {
   4484 		/*EMPTY*/;
   4485 #ifdef	USE_INET6
   4486 	} else if (family == AF_INET6) {
   4487 		/*EMPTY*/;
   4488 #endif
   4489 	} else if (family != 0) {
   4490 		IPFERROR(10);
   4491 		error = EINVAL;
   4492 		goto donenolock;
   4493 	}
   4494 
   4495 	/*
   4496 	 * If the rule is being loaded from user space, i.e. we had to copy it
   4497 	 * into kernel space, then do not trust the function pointer in the
   4498 	 * rule.
   4499 	 */
   4500 	if ((makecopy == 1) && (fp->fr_func != NULL)) {
   4501 		if (ipf_findfunc(fp->fr_func) == NULL) {
   4502 			IPFERROR(11);
   4503 			error = ESRCH;
   4504 			goto donenolock;
   4505 		}
   4506 
   4507 		if (addrem == 0) {
   4508 			error = ipf_funcinit(softc, fp);
   4509 			if (error != 0)
   4510 				goto donenolock;
   4511 		}
   4512 	}
   4513 	if ((fp->fr_flags & FR_CALLNOW) &&
   4514 	    ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
   4515 		IPFERROR(142);
   4516 		error = ESRCH;
   4517 		goto donenolock;
   4518 	}
   4519 	if (((fp->fr_flags & FR_CMDMASK) == FR_CALL) &&
   4520 	    ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
   4521 		IPFERROR(143);
   4522 		error = ESRCH;
   4523 		goto donenolock;
   4524 	}
   4525 
   4526 	ptr = NULL;
   4527 
   4528 	if (FR_ISACCOUNT(fp->fr_flags))
   4529 		unit = IPL_LOGCOUNT;
   4530 
   4531 	/*
   4532 	 * Check that each group name in the rule has a start index that
   4533 	 * is valid.
   4534 	 */
   4535 	if (fp->fr_icmphead != -1) {
   4536 		if ((fp->fr_icmphead < 0) ||
   4537 		    (fp->fr_icmphead >= fp->fr_namelen)) {
   4538 			IPFERROR(136);
   4539 			error = EINVAL;
   4540 			goto donenolock;
   4541 		}
   4542 		if (!strcmp(FR_NAME(fp, fr_icmphead), "0"))
   4543 			fp->fr_names[fp->fr_icmphead] = '\0';
   4544 	}
   4545 
   4546 	if (fp->fr_grhead != -1) {
   4547 		if ((fp->fr_grhead < 0) ||
   4548 		    (fp->fr_grhead >= fp->fr_namelen)) {
   4549 			IPFERROR(137);
   4550 			error = EINVAL;
   4551 			goto donenolock;
   4552 		}
   4553 		if (!strcmp(FR_NAME(fp, fr_grhead), "0"))
   4554 			fp->fr_names[fp->fr_grhead] = '\0';
   4555 	}
   4556 
   4557 	if (fp->fr_group != -1) {
   4558 		if ((fp->fr_group < 0) ||
   4559 		    (fp->fr_group >= fp->fr_namelen)) {
   4560 			IPFERROR(138);
   4561 			error = EINVAL;
   4562 			goto donenolock;
   4563 		}
   4564 		if ((req != (int)SIOCZRLST) && (fp->fr_group != -1)) {
   4565 			/*
   4566 			 * Allow loading rules that are in groups to cause
   4567 			 * them to be created if they don't already exit.
   4568 			 */
   4569 			group = FR_NAME(fp, fr_group);
   4570 			if (addrem == 0) {
   4571 				fg = ipf_group_add(softc, group, NULL,
   4572 						   fp->fr_flags, unit, set);
   4573 				if (fg == NULL) {
   4574 					IPFERROR(152);
   4575 					error = ESRCH;
   4576 					goto donenolock;
   4577 				}
   4578 				fp->fr_grp = fg;
   4579 			} else {
   4580 				fg = ipf_findgroup(softc, group, unit,
   4581 						   set, NULL);
   4582 				if (fg == NULL) {
   4583 					IPFERROR(12);
   4584 					error = ESRCH;
   4585 					goto donenolock;
   4586 				}
   4587 			}
   4588 
   4589 			if (fg->fg_flags == 0) {
   4590 				fg->fg_flags = fp->fr_flags & FR_INOUT;
   4591 			} else if (fg->fg_flags != (fp->fr_flags & FR_INOUT)) {
   4592 				IPFERROR(13);
   4593 				error = ESRCH;
   4594 				goto donenolock;
   4595 			}
   4596 		}
   4597 	} else {
   4598 		/*
   4599 		 * If a rule is going to be part of a group then it does
   4600 		 * not matter whether it is an in or out rule, but if it
   4601 		 * isn't in a group, then it does...
   4602 		 */
   4603 		if ((fp->fr_flags & (FR_INQUE|FR_OUTQUE)) == 0) {
   4604 			IPFERROR(14);
   4605 			error = EINVAL;
   4606 			goto donenolock;
   4607 		}
   4608 	}
   4609 	in = (fp->fr_flags & FR_INQUE) ? 0 : 1;
   4610 
   4611 	/*
   4612 	 * Work out which rule list this change is being applied to.
   4613 	 */
   4614 	ftail = NULL;
   4615 	fprev = NULL;
   4616 	if (unit == IPL_LOGAUTH) {
   4617 		if ((fp->fr_tifs[0].fd_ptr != NULL) ||
   4618 		    (fp->fr_tifs[1].fd_ptr != NULL) ||
   4619 		    (fp->fr_dif.fd_ptr != NULL) ||
   4620 		    (fp->fr_flags & FR_FASTROUTE)) {
   4621 			IPFERROR(145);
   4622 			error = EINVAL;
   4623 			goto donenolock;
   4624 		}
   4625 		fprev = ipf_auth_rulehead(softc);
   4626 	} else {
   4627 		if (FR_ISACCOUNT(fp->fr_flags))
   4628 			fprev = &softc->ipf_acct[in][set];
   4629 		else if ((fp->fr_flags & (FR_OUTQUE|FR_INQUE)) != 0)
   4630 			fprev = &softc->ipf_rules[in][set];
   4631 	}
   4632 	if (fprev == NULL) {
   4633 		IPFERROR(15);
   4634 		error = ESRCH;
   4635 		goto donenolock;
   4636 	}
   4637 
   4638 	if (fg != NULL)
   4639 		fprev = &fg->fg_start;
   4640 
   4641 	/*
   4642 	 * Copy in extra data for the rule.
   4643 	 */
   4644 	if (fp->fr_dsize != 0) {
   4645 		if (makecopy != 0) {
   4646 			KMALLOCS(ptr, void *, fp->fr_dsize);
   4647 			if (ptr == NULL) {
   4648 				IPFERROR(16);
   4649 				error = ENOMEM;
   4650 				goto donenolock;
   4651 			}
   4652 
   4653 			/*
   4654 			 * The bcopy case is for when the data is appended
   4655 			 * to the rule by ipf_in_compat().
   4656 			 */
   4657 			if (uptr >= (void *)fp &&
   4658 			    uptr < (void *)((char *)fp + fp->fr_size)) {
   4659 				bcopy(uptr, ptr, fp->fr_dsize);
   4660 				error = 0;
   4661 			} else {
   4662 				error = COPYIN(uptr, ptr, fp->fr_dsize);
   4663 				if (error != 0) {
   4664 					IPFERROR(17);
   4665 					error = EFAULT;
   4666 					goto donenolock;
   4667 				}
   4668 			}
   4669 		} else {
   4670 			ptr = uptr;
   4671 		}
   4672 		fp->fr_data = ptr;
   4673 	} else {
   4674 		fp->fr_data = NULL;
   4675 	}
   4676 
   4677 	/*
   4678 	 * Perform per-rule type sanity checks of their members.
   4679 	 * All code after this needs to be aware that allocated memory
   4680 	 * may need to be free'd before exiting.
   4681 	 */
   4682 	switch (fp->fr_type & ~FR_T_BUILTIN)
   4683 	{
   4684 #if defined(IPFILTER_BPF)
   4685 	case FR_T_BPFOPC :
   4686 		if (fp->fr_dsize == 0) {
   4687 			IPFERROR(19);
   4688 			error = EINVAL;
   4689 			break;
   4690 		}
   4691 		if (!bpf_validate(ptr, fp->fr_dsize/sizeof(struct bpf_insn))) {
   4692 			IPFERROR(20);
   4693 			error = EINVAL;
   4694 			break;
   4695 		}
   4696 		break;
   4697 #endif
   4698 	case FR_T_IPF :
   4699 		/*
   4700 		 * Preparation for error case at the bottom of this function.
   4701 		 */
   4702 		if (fp->fr_datype == FRI_LOOKUP)
   4703 			fp->fr_dstptr = NULL;
   4704 		if (fp->fr_satype == FRI_LOOKUP)
   4705 			fp->fr_srcptr = NULL;
   4706 
   4707 		if (fp->fr_dsize != sizeof(fripf_t)) {
   4708 			IPFERROR(21);
   4709 			error = EINVAL;
   4710 			break;
   4711 		}
   4712 
   4713 		/*
   4714 		 * Allowing a rule with both "keep state" and "with oow" is
   4715 		 * pointless because adding a state entry to the table will
   4716 		 * fail with the out of window (oow) flag set.
   4717 		 */
   4718 		if ((fp->fr_flags & FR_KEEPSTATE) && (fp->fr_flx & FI_OOW)) {
   4719 			IPFERROR(22);
   4720 			error = EINVAL;
   4721 			break;
   4722 		}
   4723 
   4724 		switch (fp->fr_satype)
   4725 		{
   4726 		case FRI_BROADCAST :
   4727 		case FRI_DYNAMIC :
   4728 		case FRI_NETWORK :
   4729 		case FRI_NETMASKED :
   4730 		case FRI_PEERADDR :
   4731 			if (fp->fr_sifpidx < 0) {
   4732 				IPFERROR(23);
   4733 				error = EINVAL;
   4734 			}
   4735 			break;
   4736 		case FRI_LOOKUP :
   4737 			fp->fr_srcptr = ipf_findlookup(softc, unit, fp,
   4738 						       &fp->fr_src6,
   4739 						       &fp->fr_smsk6);
   4740 			if (fp->fr_srcfunc == NULL) {
   4741 				IPFERROR(132);
   4742 				error = ESRCH;
   4743 				break;
   4744 			}
   4745 			break;
   4746 		case FRI_NORMAL :
   4747 			break;
   4748 		default :
   4749 			IPFERROR(133);
   4750 			error = EINVAL;
   4751 			break;
   4752 		}
   4753 		if (error != 0)
   4754 			break;
   4755 
   4756 		switch (fp->fr_datype)
   4757 		{
   4758 		case FRI_BROADCAST :
   4759 		case FRI_DYNAMIC :
   4760 		case FRI_NETWORK :
   4761 		case FRI_NETMASKED :
   4762 		case FRI_PEERADDR :
   4763 			if (fp->fr_difpidx < 0) {
   4764 				IPFERROR(24);
   4765 				error = EINVAL;
   4766 			}
   4767 			break;
   4768 		case FRI_LOOKUP :
   4769 			fp->fr_dstptr = ipf_findlookup(softc, unit, fp,
   4770 						       &fp->fr_dst6,
   4771 						       &fp->fr_dmsk6);
   4772 			if (fp->fr_dstfunc == NULL) {
   4773 				IPFERROR(134);
   4774 				error = ESRCH;
   4775 			}
   4776 			break;
   4777 		case FRI_NORMAL :
   4778 			break;
   4779 		default :
   4780 			IPFERROR(135);
   4781 			error = EINVAL;
   4782 		}
   4783 		break;
   4784 
   4785 	case FR_T_NONE :
   4786 	case FR_T_CALLFUNC :
   4787 	case FR_T_COMPIPF :
   4788 		break;
   4789 
   4790 	case FR_T_IPFEXPR :
   4791 		if (ipf_matcharray_verify(fp->fr_data, fp->fr_dsize) == -1) {
   4792 			IPFERROR(25);
   4793 			error = EINVAL;
   4794 		}
   4795 		break;
   4796 
   4797 	default :
   4798 		IPFERROR(26);
   4799 		error = EINVAL;
   4800 		break;
   4801 	}
   4802 	if (error != 0)
   4803 		goto donenolock;
   4804 
   4805 	if (fp->fr_tif.fd_name != -1) {
   4806 		if ((fp->fr_tif.fd_name < 0) ||
   4807 		    (fp->fr_tif.fd_name >= fp->fr_namelen)) {
   4808 			IPFERROR(139);
   4809 			error = EINVAL;
   4810 			goto donenolock;
   4811 		}
   4812 	}
   4813 
   4814 	if (fp->fr_dif.fd_name != -1) {
   4815 		if ((fp->fr_dif.fd_name < 0) ||
   4816 		    (fp->fr_dif.fd_name >= fp->fr_namelen)) {
   4817 			IPFERROR(140);
   4818 			error = EINVAL;
   4819 			goto donenolock;
   4820 		}
   4821 	}
   4822 
   4823 	if (fp->fr_rif.fd_name != -1) {
   4824 		if ((fp->fr_rif.fd_name < 0) ||
   4825 		    (fp->fr_rif.fd_name >= fp->fr_namelen)) {
   4826 			IPFERROR(141);
   4827 			error = EINVAL;
   4828 			goto donenolock;
   4829 		}
   4830 	}
   4831 
   4832 	/*
   4833 	 * Lookup all the interface names that are part of the rule.
   4834 	 */
   4835 	error = ipf_synclist(softc, fp, NULL);
   4836 	if (error != 0)
   4837 		goto donenolock;
   4838 	fp->fr_statecnt = 0;
   4839 	if (fp->fr_srctrack.ht_max_nodes != 0)
   4840 		ipf_rb_ht_init(&fp->fr_srctrack);
   4841 
   4842 	/*
   4843 	 * Look for an existing matching filter rule, but don't include the
   4844 	 * next or interface pointer in the comparison (fr_next, fr_ifa).
   4845 	 * This elminates rules which are indentical being loaded.  Checksum
   4846 	 * the constant part of the filter rule to make comparisons quicker
   4847 	 * (this meaning no pointers are included).
   4848 	 */
   4849 	for (fp->fr_cksum = 0, p = (u_int *)&fp->fr_func, pp = &fp->fr_cksum;
   4850 	     p < pp; p++)
   4851 		fp->fr_cksum += *p;
   4852 	pp = (u_int *)((char *)fp->fr_caddr + fp->fr_dsize);
   4853 	for (p = (u_int *)fp->fr_data; p < pp; p++)
   4854 		fp->fr_cksum += *p;
   4855 
   4856 	WRITE_ENTER(&softc->ipf_mutex);
   4857 
   4858 	/*
   4859 	 * Now that the filter rule lists are locked, we can walk the
   4860 	 * chain of them without fear.
   4861 	 */
   4862 	ftail = fprev;
   4863 	for (f = *ftail; (f = *ftail) != NULL; ftail = &f->fr_next) {
   4864 		if (fp->fr_collect <= f->fr_collect) {
   4865 			ftail = fprev;
   4866 			f = NULL;
   4867 			break;
   4868 		}
   4869 		fprev = ftail;
   4870 	}
   4871 
   4872 	for (; (f = *ftail) != NULL; ftail = &f->fr_next) {
   4873 		DT2(rule_cmp, frentry_t *, fp, frentry_t *, f);
   4874 		if (ipf_rule_compare(fp, f) == 0)
   4875 			break;
   4876 	}
   4877 
   4878 	/*
   4879 	 * If zero'ing statistics, copy current to caller and zero.
   4880 	 */
   4881 	if (addrem == 2) {
   4882 		if (f == NULL) {
   4883 			IPFERROR(27);
   4884 			error = ESRCH;
   4885 		} else {
   4886 			/*
   4887 			 * Copy and reduce lock because of impending copyout.
   4888 			 * Well we should, but if we do then the atomicity of
   4889 			 * this call and the correctness of fr_hits and
   4890 			 * fr_bytes cannot be guaranteed.  As it is, this code
   4891 			 * only resets them to 0 if they are successfully
   4892 			 * copied out into user space.
   4893 			 */
   4894 			bcopy((char *)f, (char *)fp, f->fr_size);
   4895 			/* MUTEX_DOWNGRADE(&softc->ipf_mutex); */
   4896 
   4897 			/*
   4898 			 * When we copy this rule back out, set the data
   4899 			 * pointer to be what it was in user space.
   4900 			 */
   4901 			fp->fr_data = uptr;
   4902 			error = ipf_outobj(softc, data, fp, IPFOBJ_FRENTRY);
   4903 
   4904 			if (error == 0) {
   4905 				if ((f->fr_dsize != 0) && (uptr != NULL)) {
   4906 					error = COPYOUT(f->fr_data, uptr,
   4907 							f->fr_dsize);
   4908 					if (error != 0) {
   4909 						IPFERROR(28);
   4910 						error = EFAULT;
   4911 					}
   4912 				}
   4913 				if (error == 0) {
   4914 					f->fr_hits = 0;
   4915 					f->fr_bytes = 0;
   4916 				}
   4917 			}
   4918 		}
   4919 
   4920 		if (makecopy != 0) {
   4921 			if (ptr != NULL) {
   4922 				KFREES(ptr, fp->fr_dsize);
   4923 			}
   4924 			KFREES(fp, fp->fr_size);
   4925 		}
   4926 		RWLOCK_EXIT(&softc->ipf_mutex);
   4927 		return error;
   4928 	}
   4929 
   4930   	if (!f) {
   4931 		/*
   4932 		 * At the end of this, ftail must point to the place where the
   4933 		 * new rule is to be saved/inserted/added.
   4934 		 * For SIOCAD*FR, this should be the last rule in the group of
   4935 		 * rules that have equal fr_collect fields.
   4936 		 * For SIOCIN*FR, ...
   4937 		 */
   4938 		if (req == (ioctlcmd_t)SIOCADAFR ||
   4939 		    req == (ioctlcmd_t)SIOCADIFR) {
   4940 
   4941 			for (ftail = fprev; (f = *ftail) != NULL; ) {
   4942 				if (f->fr_collect > fp->fr_collect)
   4943 					break;
   4944 				ftail = &f->fr_next;
   4945 				fprev = ftail;
   4946 			}
   4947 			ftail = fprev;
   4948 			f = NULL;
   4949 			ptr = NULL;
   4950 		} else if (req == (ioctlcmd_t)SIOCINAFR ||
   4951 			   req == (ioctlcmd_t)SIOCINIFR) {
   4952 			while ((f = *fprev) != NULL) {
   4953 				if (f->fr_collect >= fp->fr_collect)
   4954 					break;
   4955 				fprev = &f->fr_next;
   4956 			}
   4957   			ftail = fprev;
   4958   			if (fp->fr_hits != 0) {
   4959 				while (fp->fr_hits && (f = *ftail)) {
   4960 					if (f->fr_collect != fp->fr_collect)
   4961 						break;
   4962 					fprev = ftail;
   4963   					ftail = &f->fr_next;
   4964 					fp->fr_hits--;
   4965 				}
   4966   			}
   4967   			f = NULL;
   4968   			ptr = NULL;
   4969 		}
   4970 	}
   4971 
   4972 	/*
   4973 	 * Request to remove a rule.
   4974 	 */
   4975 	if (addrem == 1) {
   4976 		if (!f) {
   4977 			IPFERROR(29);
   4978 			error = ESRCH;
   4979 		} else {
   4980 			/*
   4981 			 * Do not allow activity from user space to interfere
   4982 			 * with rules not loaded that way.
   4983 			 */
   4984 			if ((makecopy == 1) && !(f->fr_flags & FR_COPIED)) {
   4985 				IPFERROR(30);
   4986 				error = EPERM;
   4987 				goto done;
   4988 			}
   4989 
   4990 			/*
   4991 			 * Return EBUSY if the rule is being reference by
   4992 			 * something else (eg state information.)
   4993 			 */
   4994 			if (f->fr_ref > 1) {
   4995 				IPFERROR(31);
   4996 				error = EBUSY;
   4997 				goto done;
   4998 			}
   4999 #ifdef	IPFILTER_SCAN
   5000 			if (f->fr_isctag != -1 &&
   5001 			    (f->fr_isc != (struct ipscan *)-1))
   5002 				ipf_scan_detachfr(f);
   5003 #endif
   5004 
   5005 			if (unit == IPL_LOGAUTH) {
   5006 				error = ipf_auth_precmd(softc, req, f, ftail);
   5007 				goto done;
   5008 			}
   5009 
   5010 			ipf_rule_delete(softc, f, unit, set);
   5011 
   5012 			need_free = makecopy;
   5013 		}
   5014 	} else {
   5015 		/*
   5016 		 * Not removing, so we must be adding/inserting a rule.
   5017 		 */
   5018 		if (f != NULL) {
   5019 			IPFERROR(32);
   5020 			error = EEXIST;
   5021 			goto done;
   5022 		}
   5023 		if (unit == IPL_LOGAUTH) {
   5024 			error = ipf_auth_precmd(softc, req, fp, ftail);
   5025 			goto done;
   5026 		}
   5027 
   5028 		MUTEX_NUKE(&fp->fr_lock);
   5029 		MUTEX_INIT(&fp->fr_lock, "filter rule lock");
   5030 		if (fp->fr_die != 0)
   5031 			ipf_rule_expire_insert(softc, fp, set);
   5032 
   5033 		fp->fr_hits = 0;
   5034 		if (makecopy != 0)
   5035 			fp->fr_ref = 1;
   5036 		fp->fr_pnext = ftail;
   5037 		fp->fr_next = *ftail;
   5038 		if (fp->fr_next != NULL)
   5039 			fp->fr_next->fr_pnext = &fp->fr_next;
   5040 		*ftail = fp;
   5041 		if (addrem == 0)
   5042 			ipf_fixskip(ftail, fp, 1);
   5043 
   5044 		fp->fr_icmpgrp = NULL;
   5045 		if (fp->fr_icmphead != -1) {
   5046 			group = FR_NAME(fp, fr_icmphead);
   5047 			fg = ipf_group_add(softc, group, fp, 0, unit, set);
   5048 			fp->fr_icmpgrp = fg;
   5049 		}
   5050 
   5051 		fp->fr_grphead = NULL;
   5052 		if (fp->fr_grhead != -1) {
   5053 			group = FR_NAME(fp, fr_grhead);
   5054 			fg = ipf_group_add(softc, group, fp, fp->fr_flags,
   5055 					   unit, set);
   5056 			fp->fr_grphead = fg;
   5057 		}
   5058 	}
   5059 done:
   5060 	RWLOCK_EXIT(&softc->ipf_mutex);
   5061 donenolock:
   5062 	if (need_free || (error != 0)) {
   5063 		if ((fp->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
   5064 			if ((fp->fr_satype == FRI_LOOKUP) &&
   5065 			    (fp->fr_srcptr != NULL))
   5066 				ipf_lookup_deref(softc, fp->fr_srctype,
   5067 						 fp->fr_srcptr);
   5068 			if ((fp->fr_datype == FRI_LOOKUP) &&
   5069 			    (fp->fr_dstptr != NULL))
   5070 				ipf_lookup_deref(softc, fp->fr_dsttype,
   5071 						 fp->fr_dstptr);
   5072 		}
   5073 		if (fp->fr_grp != NULL) {
   5074 			WRITE_ENTER(&softc->ipf_mutex);
   5075 			ipf_group_del(softc, fp->fr_grp, fp);
   5076 			RWLOCK_EXIT(&softc->ipf_mutex);
   5077 		}
   5078 		if ((ptr != NULL) && (makecopy != 0)) {
   5079 			KFREES(ptr, fp->fr_dsize);
   5080 		}
   5081 		KFREES(fp, fp->fr_size);
   5082 	}
   5083 	return (error);
   5084 }
   5085 
   5086 
   5087 /* ------------------------------------------------------------------------ */
   5088 /* Function:   ipf_rule_delete                                              */
   5089 /* Returns:    Nil                                                          */
   5090 /* Parameters: softc(I) - pointer to soft context main structure            */
   5091 /*             f(I)     - pointer to the rule being deleted                 */
   5092 /*             ftail(I) - pointer to the pointer to f                       */
   5093 /*             unit(I)  - device for which this is for                      */
   5094 /*             set(I)   - 1 or 0 (filter set)                               */
   5095 /*                                                                          */
   5096 /* This function attempts to do what it can to delete a filter rule: remove */
   5097 /* it from any linked lists and remove any groups it is responsible for.    */
   5098 /* But in the end, removing a rule can only drop the reference count - we   */
   5099 /* must use that as the guide for whether or not it can be freed.           */
   5100 /* ------------------------------------------------------------------------ */
   5101 static void
   5102 ipf_rule_delete(ipf_main_softc_t *softc, frentry_t *f, int unit, int set)
   5103 {
   5104 
   5105 	/*
   5106 	 * If fr_pdnext is set, then the rule is on the expire list, so
   5107 	 * remove it from there.
   5108 	 */
   5109 	if (f->fr_pdnext != NULL) {
   5110 		*f->fr_pdnext = f->fr_dnext;
   5111 		if (f->fr_dnext != NULL)
   5112 			f->fr_dnext->fr_pdnext = f->fr_pdnext;
   5113 		f->fr_pdnext = NULL;
   5114 		f->fr_dnext = NULL;
   5115 	}
   5116 
   5117 	ipf_fixskip(f->fr_pnext, f, -1);
   5118 	if (f->fr_pnext != NULL)
   5119 		*f->fr_pnext = f->fr_next;
   5120 	if (f->fr_next != NULL)
   5121 		f->fr_next->fr_pnext = f->fr_pnext;
   5122 	f->fr_pnext = NULL;
   5123 	f->fr_next = NULL;
   5124 
   5125 	(void) ipf_derefrule(softc, &f);
   5126 }
   5127 
   5128 /* ------------------------------------------------------------------------ */
   5129 /* Function:   ipf_rule_expire_insert                                       */
   5130 /* Returns:    Nil                                                          */
   5131 /* Parameters: softc(I) - pointer to soft context main structure            */
   5132 /*             f(I)     - pointer to rule to be added to expire list        */
   5133 /*             set(I)   - 1 or 0 (filter set)                               */
   5134 /*                                                                          */
   5135 /* If the new rule has a given expiration time, insert it into the list of  */
   5136 /* expiring rules with the ones to be removed first added to the front of   */
   5137 /* the list. The insertion is O(n) but it is kept sorted for quick scans at */
   5138 /* expiration interval checks.                                              */
   5139 /* ------------------------------------------------------------------------ */
   5140 static void
   5141 ipf_rule_expire_insert(ipf_main_softc_t *softc, frentry_t *f, int set)
   5142 {
   5143 	frentry_t *fr;
   5144 
   5145 	/*
   5146 	 */
   5147 
   5148 	f->fr_die = softc->ipf_ticks + IPF_TTLVAL(f->fr_die);
   5149 	for (fr = softc->ipf_rule_explist[set]; fr != NULL;
   5150 	     fr = fr->fr_dnext) {
   5151 		if (f->fr_die < fr->fr_die)
   5152 			break;
   5153 		if (fr->fr_dnext == NULL) {
   5154 			/*
   5155 			 * We've got to the last rule and everything
   5156 			 * wanted to be expired before this new node,
   5157 			 * so we have to tack it on the end...
   5158 			 */
   5159 			fr->fr_dnext = f;
   5160 			f->fr_pdnext = &fr->fr_dnext;
   5161 			fr = NULL;
   5162 			break;
   5163 		}
   5164 	}
   5165 
   5166 	if (softc->ipf_rule_explist[set] == NULL) {
   5167 		softc->ipf_rule_explist[set] = f;
   5168 		f->fr_pdnext = &softc->ipf_rule_explist[set];
   5169 	} else if (fr != NULL) {
   5170 		f->fr_dnext = fr;
   5171 		f->fr_pdnext = fr->fr_pdnext;
   5172 		fr->fr_pdnext = &f->fr_dnext;
   5173 	}
   5174 }
   5175 
   5176 
   5177 /* ------------------------------------------------------------------------ */
   5178 /* Function:   ipf_findlookup                                               */
   5179 /* Returns:    NULL = failure, else success                                 */
   5180 /* Parameters: softc(I) - pointer to soft context main structure            */
   5181 /*             unit(I)  - ipf device we want to find match for              */
   5182 /*             fp(I)    - rule for which lookup is for                      */
   5183 /*             addrp(I) - pointer to lookup information in address struct   */
   5184 /*             maskp(O) - pointer to lookup information for storage         */
   5185 /*                                                                          */
   5186 /* When using pools and hash tables to store addresses for matching in      */
   5187 /* rules, it is necessary to resolve both the object referred to by the     */
   5188 /* name or address (and return that pointer) and also provide the means by  */
   5189 /* which to determine if an address belongs to that object to make the      */
   5190 /* packet matching quicker.                                                 */
   5191 /* ------------------------------------------------------------------------ */
   5192 static void *
   5193 ipf_findlookup(ipf_main_softc_t *softc, int unit, frentry_t *fr,
   5194     i6addr_t *addrp, i6addr_t *maskp)
   5195 {
   5196 	void *ptr = NULL;
   5197 
   5198 	switch (addrp->iplookupsubtype)
   5199 	{
   5200 	case 0 :
   5201 		ptr = ipf_lookup_res_num(softc, unit, addrp->iplookuptype,
   5202 					 addrp->iplookupnum,
   5203 					 &maskp->iplookupfunc);
   5204 		break;
   5205 	case 1 :
   5206 		if (addrp->iplookupname < 0)
   5207 			break;
   5208 		if (addrp->iplookupname >= fr->fr_namelen)
   5209 			break;
   5210 		ptr = ipf_lookup_res_name(softc, unit, addrp->iplookuptype,
   5211 					  fr->fr_names + addrp->iplookupname,
   5212 					  &maskp->iplookupfunc);
   5213 		break;
   5214 	default :
   5215 		break;
   5216 	}
   5217 
   5218 	return ptr;
   5219 }
   5220 
   5221 
   5222 /* ------------------------------------------------------------------------ */
   5223 /* Function:    ipf_funcinit                                                */
   5224 /* Returns:     int - 0 == success, else ESRCH: cannot resolve rule details */
   5225 /* Parameters:  softc(I) - pointer to soft context main structure           */
   5226 /*              fr(I)    - pointer to filter rule                           */
   5227 /*                                                                          */
   5228 /* If a rule is a call rule, then check if the function it points to needs  */
   5229 /* an init function to be called now the rule has been loaded.              */
   5230 /* ------------------------------------------------------------------------ */
   5231 static int
   5232 ipf_funcinit(ipf_main_softc_t *softc, frentry_t *fr)
   5233 {
   5234 	ipfunc_resolve_t *ft;
   5235 	int err;
   5236 
   5237 	IPFERROR(34);
   5238 	err = ESRCH;
   5239 
   5240 	for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
   5241 		if (ft->ipfu_addr == fr->fr_func) {
   5242 			err = 0;
   5243 			if (ft->ipfu_init != NULL)
   5244 				err = (*ft->ipfu_init)(softc, fr);
   5245 			break;
   5246 		}
   5247 	return err;
   5248 }
   5249 
   5250 
   5251 /* ------------------------------------------------------------------------ */
   5252 /* Function:    ipf_funcfini                                                */
   5253 /* Returns:     Nil                                                         */
   5254 /* Parameters:  softc(I) - pointer to soft context main structure           */
   5255 /*              fr(I)    - pointer to filter rule                           */
   5256 /*                                                                          */
   5257 /* For a given filter rule, call the matching "fini" function if the rule   */
   5258 /* is using a known function that would have resulted in the "init" being   */
   5259 /* called for ealier.                                                       */
   5260 /* ------------------------------------------------------------------------ */
   5261 static void
   5262 ipf_funcfini(ipf_main_softc_t *softc, frentry_t *fr)
   5263 {
   5264 	ipfunc_resolve_t *ft;
   5265 
   5266 	for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
   5267 		if (ft->ipfu_addr == fr->fr_func) {
   5268 			if (ft->ipfu_fini != NULL)
   5269 				(void) (*ft->ipfu_fini)(softc, fr);
   5270 			break;
   5271 		}
   5272 }
   5273 
   5274 
   5275 /* ------------------------------------------------------------------------ */
   5276 /* Function:    ipf_findfunc                                                */
   5277 /* Returns:     ipfunc_t - pointer to function if found, else NULL          */
   5278 /* Parameters:  funcptr(I) - function pointer to lookup                     */
   5279 /*                                                                          */
   5280 /* Look for a function in the table of known functions.                     */
   5281 /* ------------------------------------------------------------------------ */
   5282 static ipfunc_t
   5283 ipf_findfunc(ipfunc_t funcptr)
   5284 {
   5285 	ipfunc_resolve_t *ft;
   5286 
   5287 	for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
   5288 		if (ft->ipfu_addr == funcptr)
   5289 			return funcptr;
   5290 	return NULL;
   5291 }
   5292 
   5293 
   5294 /* ------------------------------------------------------------------------ */
   5295 /* Function:    ipf_resolvefunc                                             */
   5296 /* Returns:     int - 0 == success, else error                              */
   5297 /* Parameters:  data(IO) - ioctl data pointer to ipfunc_resolve_t struct    */
   5298 /*                                                                          */
   5299 /* Copy in a ipfunc_resolve_t structure and then fill in the missing field. */
   5300 /* This will either be the function name (if the pointer is set) or the     */
   5301 /* function pointer if the name is set.  When found, fill in the other one  */
   5302 /* so that the entire, complete, structure can be copied back to user space.*/
   5303 /* ------------------------------------------------------------------------ */
   5304 int
   5305 ipf_resolvefunc(ipf_main_softc_t *softc, void *data)
   5306 {
   5307 	ipfunc_resolve_t res, *ft;
   5308 	int error;
   5309 
   5310 	error = BCOPYIN(data, &res, sizeof(res));
   5311 	if (error != 0) {
   5312 		IPFERROR(123);
   5313 		return EFAULT;
   5314 	}
   5315 
   5316 	if (res.ipfu_addr == NULL && res.ipfu_name[0] != '\0') {
   5317 		for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
   5318 			if (strncmp(res.ipfu_name, ft->ipfu_name,
   5319 				    sizeof(res.ipfu_name)) == 0) {
   5320 				res.ipfu_addr = ft->ipfu_addr;
   5321 				res.ipfu_init = ft->ipfu_init;
   5322 				if (COPYOUT(&res, data, sizeof(res)) != 0) {
   5323 					IPFERROR(35);
   5324 					return EFAULT;
   5325 				}
   5326 				return 0;
   5327 			}
   5328 	}
   5329 	if (res.ipfu_addr != NULL && res.ipfu_name[0] == '\0') {
   5330 		for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
   5331 			if (ft->ipfu_addr == res.ipfu_addr) {
   5332 				(void) strncpy(res.ipfu_name, ft->ipfu_name,
   5333 					       sizeof(res.ipfu_name));
   5334 				res.ipfu_init = ft->ipfu_init;
   5335 				if (COPYOUT(&res, data, sizeof(res)) != 0) {
   5336 					IPFERROR(36);
   5337 					return EFAULT;
   5338 				}
   5339 				return 0;
   5340 			}
   5341 	}
   5342 	IPFERROR(37);
   5343 	return ESRCH;
   5344 }
   5345 
   5346 
   5347 #if !defined(_KERNEL) || (!defined(__NetBSD__) && !defined(__OpenBSD__) && \
   5348      !defined(__FreeBSD__)) || \
   5349     FREEBSD_LT_REV(501000) || NETBSD_LT_REV(105000000) || \
   5350     OPENBSD_LT_REV(200006)
   5351 /*
   5352  * From: NetBSD
   5353  * ppsratecheck(): packets (or events) per second limitation.
   5354  */
   5355 int
   5356 ppsratecheck(lasttime, curpps, maxpps)
   5357 	struct timeval *lasttime;
   5358 	int *curpps;
   5359 	int maxpps;	/* maximum pps allowed */
   5360 {
   5361 	struct timeval tv, delta;
   5362 	int rv;
   5363 
   5364 	GETKTIME(&tv);
   5365 
   5366 	delta.tv_sec = tv.tv_sec - lasttime->tv_sec;
   5367 	delta.tv_usec = tv.tv_usec - lasttime->tv_usec;
   5368 	if (delta.tv_usec < 0) {
   5369 		delta.tv_sec--;
   5370 		delta.tv_usec += 1000000;
   5371 	}
   5372 
   5373 	/*
   5374 	 * check for 0,0 is so that the message will be seen at least once.
   5375 	 * if more than one second have passed since the last update of
   5376 	 * lasttime, reset the counter.
   5377 	 *
   5378 	 * we do increment *curpps even in *curpps < maxpps case, as some may
   5379 	 * try to use *curpps for stat purposes as well.
   5380 	 */
   5381 	if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
   5382 	    delta.tv_sec >= 1) {
   5383 		*lasttime = tv;
   5384 		*curpps = 0;
   5385 		rv = 1;
   5386 	} else if (maxpps < 0)
   5387 		rv = 1;
   5388 	else if (*curpps < maxpps)
   5389 		rv = 1;
   5390 	else
   5391 		rv = 0;
   5392 	*curpps = *curpps + 1;
   5393 
   5394 	return (rv);
   5395 }
   5396 #endif
   5397 
   5398 
   5399 /* ------------------------------------------------------------------------ */
   5400 /* Function:    ipf_derefrule                                               */
   5401 /* Returns:     int   - 0 == rule freed up, else rule not freed             */
   5402 /* Parameters:  fr(I) - pointer to filter rule                              */
   5403 /*                                                                          */
   5404 /* Decrement the reference counter to a rule by one.  If it reaches zero,   */
   5405 /* free it and any associated storage space being used by it.               */
   5406 /* ------------------------------------------------------------------------ */
   5407 int
   5408 ipf_derefrule(ipf_main_softc_t *softc, frentry_t **frp)
   5409 {
   5410 	frentry_t *fr;
   5411 	frdest_t *fdp;
   5412 
   5413 	fr = *frp;
   5414 	*frp = NULL;
   5415 
   5416 	MUTEX_ENTER(&fr->fr_lock);
   5417 	fr->fr_ref--;
   5418 	if (fr->fr_ref == 0) {
   5419 		MUTEX_EXIT(&fr->fr_lock);
   5420 		MUTEX_DESTROY(&fr->fr_lock);
   5421 
   5422 		ipf_funcfini(softc, fr);
   5423 
   5424 		fdp = &fr->fr_tif;
   5425 		if (fdp->fd_type == FRD_DSTLIST)
   5426 			ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
   5427 
   5428 		fdp = &fr->fr_rif;
   5429 		if (fdp->fd_type == FRD_DSTLIST)
   5430 			ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
   5431 
   5432 		fdp = &fr->fr_dif;
   5433 		if (fdp->fd_type == FRD_DSTLIST)
   5434 			ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
   5435 
   5436 		if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
   5437 		    fr->fr_satype == FRI_LOOKUP)
   5438 			ipf_lookup_deref(softc, fr->fr_srctype, fr->fr_srcptr);
   5439 		if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
   5440 		    fr->fr_datype == FRI_LOOKUP)
   5441 			ipf_lookup_deref(softc, fr->fr_dsttype, fr->fr_dstptr);
   5442 
   5443 		if (fr->fr_grp != NULL)
   5444 			ipf_group_del(softc, fr->fr_grp, fr);
   5445 
   5446 		if (fr->fr_grphead != NULL)
   5447 			ipf_group_del(softc, fr->fr_grphead, fr);
   5448 
   5449 		if (fr->fr_icmpgrp != NULL)
   5450 			ipf_group_del(softc, fr->fr_icmpgrp, fr);
   5451 
   5452 		if ((fr->fr_flags & FR_COPIED) != 0) {
   5453 			if (fr->fr_dsize) {
   5454 				KFREES(fr->fr_data, fr->fr_dsize);
   5455 			}
   5456 			KFREES(fr, fr->fr_size);
   5457 			return 0;
   5458 		}
   5459 		return 1;
   5460 	} else {
   5461 		MUTEX_EXIT(&fr->fr_lock);
   5462 	}
   5463 	return -1;
   5464 }
   5465 
   5466 
   5467 /* ------------------------------------------------------------------------ */
   5468 /* Function:    ipf_grpmapinit                                              */
   5469 /* Returns:     int - 0 == success, else ESRCH because table entry not found*/
   5470 /* Parameters:  fr(I) - pointer to rule to find hash table for              */
   5471 /*                                                                          */
   5472 /* Looks for group hash table fr_arg and stores a pointer to it in fr_ptr.  */
   5473 /* fr_ptr is later used by ipf_srcgrpmap and ipf_dstgrpmap.                 */
   5474 /* ------------------------------------------------------------------------ */
   5475 static int
   5476 ipf_grpmapinit(ipf_main_softc_t *softc, frentry_t *fr)
   5477 {
   5478 	char name[FR_GROUPLEN];
   5479 	iphtable_t *iph;
   5480 
   5481 	(void) snprintf(name, sizeof(name), "%d", fr->fr_arg);
   5482 	iph = ipf_lookup_find_htable(softc, IPL_LOGIPF, name);
   5483 	if (iph == NULL) {
   5484 		IPFERROR(38);
   5485 		return ESRCH;
   5486 	}
   5487 	if ((iph->iph_flags & FR_INOUT) != (fr->fr_flags & FR_INOUT)) {
   5488 		IPFERROR(39);
   5489 		return ESRCH;
   5490 	}
   5491 	iph->iph_ref++;
   5492 	fr->fr_ptr = iph;
   5493 	return 0;
   5494 }
   5495 
   5496 
   5497 /* ------------------------------------------------------------------------ */
   5498 /* Function:    ipf_grpmapfini                                              */
   5499 /* Returns:     int - 0 == success, else ESRCH because table entry not found*/
   5500 /* Parameters:  softc(I) - pointer to soft context main structure           */
   5501 /*              fr(I)    - pointer to rule to release hash table for        */
   5502 /*                                                                          */
   5503 /* For rules that have had ipf_grpmapinit called, ipf_lookup_deref needs to */
   5504 /* be called to undo what ipf_grpmapinit caused to be done.                 */
   5505 /* ------------------------------------------------------------------------ */
   5506 static int
   5507 ipf_grpmapfini(ipf_main_softc_t *softc, frentry_t *fr)
   5508 {
   5509 	iphtable_t *iph;
   5510 	iph = fr->fr_ptr;
   5511 	if (iph != NULL)
   5512 		ipf_lookup_deref(softc, IPLT_HASH, iph);
   5513 	return 0;
   5514 }
   5515 
   5516 
   5517 /* ------------------------------------------------------------------------ */
   5518 /* Function:    ipf_srcgrpmap                                               */
   5519 /* Returns:     frentry_t * - pointer to "new last matching" rule or NULL   */
   5520 /* Parameters:  fin(I)    - pointer to packet information                   */
   5521 /*              passp(IO) - pointer to current/new filter decision (unused) */
   5522 /*                                                                          */
   5523 /* Look for a rule group head in a hash table, using the source address as  */
   5524 /* the key, and descend into that group and continue matching rules against */
   5525 /* the packet.                                                              */
   5526 /* ------------------------------------------------------------------------ */
   5527 frentry_t *
   5528 ipf_srcgrpmap(fr_info_t *fin, u_32_t *passp)
   5529 {
   5530 	frgroup_t *fg;
   5531 	void *rval;
   5532 
   5533 	rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
   5534 				 &fin->fin_src);
   5535 	if (rval == NULL)
   5536 		return NULL;
   5537 
   5538 	fg = rval;
   5539 	fin->fin_fr = fg->fg_start;
   5540 	(void) ipf_scanlist(fin, *passp);
   5541 	return fin->fin_fr;
   5542 }
   5543 
   5544 
   5545 /* ------------------------------------------------------------------------ */
   5546 /* Function:    ipf_dstgrpmap                                               */
   5547 /* Returns:     frentry_t * - pointer to "new last matching" rule or NULL   */
   5548 /* Parameters:  fin(I)    - pointer to packet information                   */
   5549 /*              passp(IO) - pointer to current/new filter decision (unused) */
   5550 /*                                                                          */
   5551 /* Look for a rule group head in a hash table, using the destination        */
   5552 /* address as the key, and descend into that group and continue matching    */
   5553 /* rules against  the packet.                                               */
   5554 /* ------------------------------------------------------------------------ */
   5555 frentry_t *
   5556 ipf_dstgrpmap(fr_info_t *fin, u_32_t *passp)
   5557 {
   5558 	frgroup_t *fg;
   5559 	void *rval;
   5560 
   5561 	rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
   5562 				 &fin->fin_dst);
   5563 	if (rval == NULL)
   5564 		return NULL;
   5565 
   5566 	fg = rval;
   5567 	fin->fin_fr = fg->fg_start;
   5568 	(void) ipf_scanlist(fin, *passp);
   5569 	return fin->fin_fr;
   5570 }
   5571 
   5572 /*
   5573  * Queue functions
   5574  * ===============
   5575  * These functions manage objects on queues for efficient timeouts.  There
   5576  * are a number of system defined queues as well as user defined timeouts.
   5577  * It is expected that a lock is held in the domain in which the queue
   5578  * belongs (i.e. either state or NAT) when calling any of these functions
   5579  * that prevents ipf_freetimeoutqueue() from being called at the same time
   5580  * as any other.
   5581  */
   5582 
   5583 
   5584 /* ------------------------------------------------------------------------ */
   5585 /* Function:    ipf_addtimeoutqueue                                         */
   5586 /* Returns:     struct ifqtq * - NULL if malloc fails, else pointer to      */
   5587 /*                               timeout queue with given interval.         */
   5588 /* Parameters:  parent(I)  - pointer to pointer to parent node of this list */
   5589 /*                           of interface queues.                           */
   5590 /*              seconds(I) - timeout value in seconds for this queue.       */
   5591 /*                                                                          */
   5592 /* This routine first looks for a timeout queue that matches the interval   */
   5593 /* being requested.  If it finds one, increments the reference counter and  */
   5594 /* returns a pointer to it.  If none are found, it allocates a new one and  */
   5595 /* inserts it at the top of the list.                                       */
   5596 /*                                                                          */
   5597 /* Locking.                                                                 */
   5598 /* It is assumed that the caller of this function has an appropriate lock   */
   5599 /* held (exclusively) in the domain that encompases 'parent'.               */
   5600 /* ------------------------------------------------------------------------ */
   5601 ipftq_t *
   5602 ipf_addtimeoutqueue(ipf_main_softc_t *softc, ipftq_t **parent, u_int seconds)
   5603 {
   5604 	ipftq_t *ifq;
   5605 	u_int period;
   5606 
   5607 	period = seconds * IPF_HZ_DIVIDE;
   5608 
   5609 	MUTEX_ENTER(&softc->ipf_timeoutlock);
   5610 	for (ifq = *parent; ifq != NULL; ifq = ifq->ifq_next) {
   5611 		if (ifq->ifq_ttl == period) {
   5612 			/*
   5613 			 * Reset the delete flag, if set, so the structure
   5614 			 * gets reused rather than freed and reallocated.
   5615 			 */
   5616 			MUTEX_ENTER(&ifq->ifq_lock);
   5617 			ifq->ifq_flags &= ~IFQF_DELETE;
   5618 			ifq->ifq_ref++;
   5619 			MUTEX_EXIT(&ifq->ifq_lock);
   5620 			MUTEX_EXIT(&softc->ipf_timeoutlock);
   5621 
   5622 			return ifq;
   5623 		}
   5624 	}
   5625 
   5626 	KMALLOC(ifq, ipftq_t *);
   5627 	if (ifq != NULL) {
   5628 		MUTEX_NUKE(&ifq->ifq_lock);
   5629 		IPFTQ_INIT(ifq, period, "ipftq mutex");
   5630 		ifq->ifq_next = *parent;
   5631 		ifq->ifq_pnext = parent;
   5632 		ifq->ifq_flags = IFQF_USER;
   5633 		ifq->ifq_ref++;
   5634 		*parent = ifq;
   5635 		softc->ipf_userifqs++;
   5636 	}
   5637 	MUTEX_EXIT(&softc->ipf_timeoutlock);
   5638 	return ifq;
   5639 }
   5640 
   5641 
   5642 /* ------------------------------------------------------------------------ */
   5643 /* Function:    ipf_deletetimeoutqueue                                      */
   5644 /* Returns:     int    - new reference count value of the timeout queue     */
   5645 /* Parameters:  ifq(I) - timeout queue which is losing a reference.         */
   5646 /* Locks:       ifq->ifq_lock                                               */
   5647 /*                                                                          */
   5648 /* This routine must be called when we're discarding a pointer to a timeout */
   5649 /* queue object, taking care of the reference counter.                      */
   5650 /*                                                                          */
   5651 /* Now that this just sets a DELETE flag, it requires the expire code to    */
   5652 /* check the list of user defined timeout queues and call the free function */
   5653 /* below (currently commented out) to stop memory leaking.  It is done this */
   5654 /* way because the locking may not be sufficient to safely do a free when   */
   5655 /* this function is called.                                                 */
   5656 /* ------------------------------------------------------------------------ */
   5657 int
   5658 ipf_deletetimeoutqueue(ipftq_t *ifq)
   5659 {
   5660 
   5661 	ifq->ifq_ref--;
   5662 	if ((ifq->ifq_ref == 0) && ((ifq->ifq_flags & IFQF_USER) != 0)) {
   5663 		ifq->ifq_flags |= IFQF_DELETE;
   5664 	}
   5665 
   5666 	return ifq->ifq_ref;
   5667 }
   5668 
   5669 
   5670 /* ------------------------------------------------------------------------ */
   5671 /* Function:    ipf_freetimeoutqueue                                        */
   5672 /* Parameters:  ifq(I) - timeout queue which is losing a reference.         */
   5673 /* Returns:     Nil                                                         */
   5674 /*                                                                          */
   5675 /* Locking:                                                                 */
   5676 /* It is assumed that the caller of this function has an appropriate lock   */
   5677 /* held (exclusively) in the domain that encompases the callers "domain".   */
   5678 /* The ifq_lock for this structure should not be held.                      */
   5679 /*                                                                          */
   5680 /* Remove a user defined timeout queue from the list of queues it is in and */
   5681 /* tidy up after this is done.                                              */
   5682 /* ------------------------------------------------------------------------ */
   5683 void
   5684 ipf_freetimeoutqueue(ipf_main_softc_t *softc, ipftq_t *ifq)
   5685 {
   5686 
   5687 	if (((ifq->ifq_flags & IFQF_DELETE) == 0) || (ifq->ifq_ref != 0) ||
   5688 	    ((ifq->ifq_flags & IFQF_USER) == 0)) {
   5689 		printf("ipf_freetimeoutqueue(%lx) flags 0x%x ttl %d ref %d\n",
   5690 		       (u_long)ifq, ifq->ifq_flags, ifq->ifq_ttl,
   5691 		       ifq->ifq_ref);
   5692 		return;
   5693 	}
   5694 
   5695 	/*
   5696 	 * Remove from its position in the list.
   5697 	 */
   5698 	*ifq->ifq_pnext = ifq->ifq_next;
   5699 	if (ifq->ifq_next != NULL)
   5700 		ifq->ifq_next->ifq_pnext = ifq->ifq_pnext;
   5701 	ifq->ifq_next = NULL;
   5702 	ifq->ifq_pnext = NULL;
   5703 
   5704 	MUTEX_DESTROY(&ifq->ifq_lock);
   5705 	ATOMIC_DEC(softc->ipf_userifqs);
   5706 	KFREE(ifq);
   5707 }
   5708 
   5709 
   5710 /* ------------------------------------------------------------------------ */
   5711 /* Function:    ipf_deletequeueentry                                        */
   5712 /* Returns:     Nil                                                         */
   5713 /* Parameters:  tqe(I) - timeout queue entry to delete                      */
   5714 /*                                                                          */
   5715 /* Remove a tail queue entry from its queue and make it an orphan.          */
   5716 /* ipf_deletetimeoutqueue is called to make sure the reference count on the */
   5717 /* queue is correct.  We can't, however, call ipf_freetimeoutqueue because  */
   5718 /* the correct lock(s) may not be held that would make it safe to do so.    */
   5719 /* ------------------------------------------------------------------------ */
   5720 void
   5721 ipf_deletequeueentry(ipftqent_t *tqe)
   5722 {
   5723 	ipftq_t *ifq;
   5724 
   5725 	ifq = tqe->tqe_ifq;
   5726 
   5727 	MUTEX_ENTER(&ifq->ifq_lock);
   5728 
   5729 	if (tqe->tqe_pnext != NULL) {
   5730 		*tqe->tqe_pnext = tqe->tqe_next;
   5731 		if (tqe->tqe_next != NULL)
   5732 			tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
   5733 		else    /* we must be the tail anyway */
   5734 			ifq->ifq_tail = tqe->tqe_pnext;
   5735 
   5736 		tqe->tqe_pnext = NULL;
   5737 		tqe->tqe_ifq = NULL;
   5738 	}
   5739 
   5740 	(void) ipf_deletetimeoutqueue(ifq);
   5741 	ASSERT(ifq->ifq_ref > 0);
   5742 
   5743 	MUTEX_EXIT(&ifq->ifq_lock);
   5744 }
   5745 
   5746 
   5747 /* ------------------------------------------------------------------------ */
   5748 /* Function:    ipf_queuefront                                              */
   5749 /* Returns:     Nil                                                         */
   5750 /* Parameters:  tqe(I) - pointer to timeout queue entry                     */
   5751 /*                                                                          */
   5752 /* Move a queue entry to the front of the queue, if it isn't already there. */
   5753 /* ------------------------------------------------------------------------ */
   5754 void
   5755 ipf_queuefront(ipftqent_t *tqe)
   5756 {
   5757 	ipftq_t *ifq;
   5758 
   5759 	ifq = tqe->tqe_ifq;
   5760 	if (ifq == NULL)
   5761 		return;
   5762 
   5763 	MUTEX_ENTER(&ifq->ifq_lock);
   5764 	if (ifq->ifq_head != tqe) {
   5765 		*tqe->tqe_pnext = tqe->tqe_next;
   5766 		if (tqe->tqe_next)
   5767 			tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
   5768 		else
   5769 			ifq->ifq_tail = tqe->tqe_pnext;
   5770 
   5771 		tqe->tqe_next = ifq->ifq_head;
   5772 		ifq->ifq_head->tqe_pnext = &tqe->tqe_next;
   5773 		ifq->ifq_head = tqe;
   5774 		tqe->tqe_pnext = &ifq->ifq_head;
   5775 	}
   5776 	MUTEX_EXIT(&ifq->ifq_lock);
   5777 }
   5778 
   5779 
   5780 /* ------------------------------------------------------------------------ */
   5781 /* Function:    ipf_queueback                                               */
   5782 /* Returns:     Nil                                                         */
   5783 /* Parameters:  ticks(I) - ipf tick time to use with this call              */
   5784 /*              tqe(I)   - pointer to timeout queue entry                   */
   5785 /*                                                                          */
   5786 /* Move a queue entry to the back of the queue, if it isn't already there.  */
   5787 /* We use use ticks to calculate the expiration and mark for when we last   */
   5788 /* touched the structure.                                                   */
   5789 /* ------------------------------------------------------------------------ */
   5790 void
   5791 ipf_queueback(u_long ticks, ipftqent_t *tqe)
   5792 {
   5793 	ipftq_t *ifq;
   5794 
   5795 	ifq = tqe->tqe_ifq;
   5796 	if (ifq == NULL)
   5797 		return;
   5798 	tqe->tqe_die = ticks + ifq->ifq_ttl;
   5799 	tqe->tqe_touched = ticks;
   5800 
   5801 	MUTEX_ENTER(&ifq->ifq_lock);
   5802 	if (tqe->tqe_next != NULL) {		/* at the end already ? */
   5803 		/*
   5804 		 * Remove from list
   5805 		 */
   5806 		*tqe->tqe_pnext = tqe->tqe_next;
   5807 		tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
   5808 
   5809 		/*
   5810 		 * Make it the last entry.
   5811 		 */
   5812 		tqe->tqe_next = NULL;
   5813 		tqe->tqe_pnext = ifq->ifq_tail;
   5814 		*ifq->ifq_tail = tqe;
   5815 		ifq->ifq_tail = &tqe->tqe_next;
   5816 	}
   5817 	MUTEX_EXIT(&ifq->ifq_lock);
   5818 }
   5819 
   5820 
   5821 /* ------------------------------------------------------------------------ */
   5822 /* Function:    ipf_queueappend                                             */
   5823 /* Returns:     Nil                                                         */
   5824 /* Parameters:  ticks(I)  - ipf tick time to use with this call             */
   5825 /*              tqe(I)    - pointer to timeout queue entry                  */
   5826 /*              ifq(I)    - pointer to timeout queue                        */
   5827 /*              parent(I) - owing object pointer                            */
   5828 /*                                                                          */
   5829 /* Add a new item to this queue and put it on the very end.                 */
   5830 /* We use use ticks to calculate the expiration and mark for when we last   */
   5831 /* touched the structure.                                                   */
   5832 /* ------------------------------------------------------------------------ */
   5833 void
   5834 ipf_queueappend(u_long ticks, ipftqent_t *tqe, ipftq_t *ifq, void *parent)
   5835 {
   5836 
   5837 	MUTEX_ENTER(&ifq->ifq_lock);
   5838 	tqe->tqe_parent = parent;
   5839 	tqe->tqe_pnext = ifq->ifq_tail;
   5840 	*ifq->ifq_tail = tqe;
   5841 	ifq->ifq_tail = &tqe->tqe_next;
   5842 	tqe->tqe_next = NULL;
   5843 	tqe->tqe_ifq = ifq;
   5844 	tqe->tqe_die = ticks + ifq->ifq_ttl;
   5845 	tqe->tqe_touched = ticks;
   5846 	ifq->ifq_ref++;
   5847 	MUTEX_EXIT(&ifq->ifq_lock);
   5848 }
   5849 
   5850 
   5851 /* ------------------------------------------------------------------------ */
   5852 /* Function:    ipf_movequeue                                               */
   5853 /* Returns:     Nil                                                         */
   5854 /* Parameters:  tq(I)   - pointer to timeout queue information              */
   5855 /*              oifp(I) - old timeout queue entry was on                    */
   5856 /*              nifp(I) - new timeout queue to put entry on                 */
   5857 /*                                                                          */
   5858 /* Move a queue entry from one timeout queue to another timeout queue.      */
   5859 /* If it notices that the current entry is already last and does not need   */
   5860 /* to move queue, the return.                                               */
   5861 /* ------------------------------------------------------------------------ */
   5862 void
   5863 ipf_movequeue(u_long ticks, ipftqent_t *tqe, ipftq_t *oifq, ipftq_t *nifq)
   5864 {
   5865 
   5866 	/*
   5867 	 * If the queue hasn't changed and we last touched this entry at the
   5868 	 * same ipf time, then we're not going to achieve anything by either
   5869 	 * changing the ttl or moving it on the queue.
   5870 	 */
   5871 	if (oifq == nifq && tqe->tqe_touched == ticks)
   5872 		return;
   5873 
   5874 	/*
   5875 	 * For any of this to be outside the lock, there is a risk that two
   5876 	 * packets entering simultaneously, with one changing to a different
   5877 	 * queue and one not, could end up with things in a bizarre state.
   5878 	 */
   5879 	MUTEX_ENTER(&oifq->ifq_lock);
   5880 
   5881 	tqe->tqe_touched = ticks;
   5882 	tqe->tqe_die = ticks + nifq->ifq_ttl;
   5883 	/*
   5884 	 * Is the operation here going to be a no-op ?
   5885 	 */
   5886 	if (oifq == nifq) {
   5887 		if ((tqe->tqe_next == NULL) ||
   5888 		    (tqe->tqe_next->tqe_die == tqe->tqe_die)) {
   5889 			MUTEX_EXIT(&oifq->ifq_lock);
   5890 			return;
   5891 		}
   5892 	}
   5893 
   5894 	/*
   5895 	 * Remove from the old queue
   5896 	 */
   5897 	*tqe->tqe_pnext = tqe->tqe_next;
   5898 	if (tqe->tqe_next)
   5899 		tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
   5900 	else
   5901 		oifq->ifq_tail = tqe->tqe_pnext;
   5902 	tqe->tqe_next = NULL;
   5903 
   5904 	/*
   5905 	 * If we're moving from one queue to another, release the
   5906 	 * lock on the old queue and get a lock on the new queue.
   5907 	 * For user defined queues, if we're moving off it, call
   5908 	 * delete in case it can now be freed.
   5909 	 */
   5910 	if (oifq != nifq) {
   5911 		tqe->tqe_ifq = NULL;
   5912 
   5913 		(void) ipf_deletetimeoutqueue(oifq);
   5914 
   5915 		MUTEX_EXIT(&oifq->ifq_lock);
   5916 
   5917 		MUTEX_ENTER(&nifq->ifq_lock);
   5918 
   5919 		tqe->tqe_ifq = nifq;
   5920 		nifq->ifq_ref++;
   5921 	}
   5922 
   5923 	/*
   5924 	 * Add to the bottom of the new queue
   5925 	 */
   5926 	tqe->tqe_pnext = nifq->ifq_tail;
   5927 	*nifq->ifq_tail = tqe;
   5928 	nifq->ifq_tail = &tqe->tqe_next;
   5929 	MUTEX_EXIT(&nifq->ifq_lock);
   5930 }
   5931 
   5932 
   5933 /* ------------------------------------------------------------------------ */
   5934 /* Function:    ipf_updateipid                                              */
   5935 /* Returns:     int - 0 == success, -1 == error (packet should be droppped) */
   5936 /* Parameters:  fin(I) - pointer to packet information                      */
   5937 /*                                                                          */
   5938 /* When we are doing NAT, change the IP of every packet to represent a      */
   5939 /* single sequence of packets coming from the host, hiding any host         */
   5940 /* specific sequencing that might otherwise be revealed.  If the packet is  */
   5941 /* a fragment, then store the 'new' IPid in the fragment cache and look up  */
   5942 /* the fragment cache for non-leading fragments.  If a non-leading fragment */
   5943 /* has no match in the cache, return an error.                              */
   5944 /* ------------------------------------------------------------------------ */
   5945 static int
   5946 ipf_updateipid(fr_info_t *fin)
   5947 {
   5948 	u_short id, ido, sums;
   5949 	u_32_t sumd, sum;
   5950 	ip_t *ip;
   5951 
   5952 	if (fin->fin_off != 0) {
   5953 		sum = ipf_frag_ipidknown(fin);
   5954 		if (sum == 0xffffffff)
   5955 			return -1;
   5956 		sum &= 0xffff;
   5957 		id = (u_short)sum;
   5958 	} else {
   5959 		id = ipf_nextipid(fin);
   5960 		if (fin->fin_off == 0 && (fin->fin_flx & FI_FRAG) != 0)
   5961 			(void) ipf_frag_ipidnew(fin, (u_32_t)id);
   5962 	}
   5963 
   5964 	ip = fin->fin_ip;
   5965 	ido = ntohs(ip->ip_id);
   5966 	if (id == ido)
   5967 		return 0;
   5968 	ip->ip_id = htons(id);
   5969 	CALC_SUMD(ido, id, sumd);	/* DESTRUCTIVE MACRO! id,ido change */
   5970 	sum = (~ntohs(ip->ip_sum)) & 0xffff;
   5971 	sum += sumd;
   5972 	sum = (sum >> 16) + (sum & 0xffff);
   5973 	sum = (sum >> 16) + (sum & 0xffff);
   5974 	sums = ~(u_short)sum;
   5975 	ip->ip_sum = htons(sums);
   5976 	return 0;
   5977 }
   5978 
   5979 
   5980 #ifdef	NEED_FRGETIFNAME
   5981 /* ------------------------------------------------------------------------ */
   5982 /* Function:    ipf_getifname                                               */
   5983 /* Returns:     char *    - pointer to interface name                       */
   5984 /* Parameters:  ifp(I)    - pointer to network interface                    */
   5985 /*              buffer(O) - pointer to where to store interface name        */
   5986 /*                                                                          */
   5987 /* Constructs an interface name in the buffer passed.  The buffer passed is */
   5988 /* expected to be at least LIFNAMSIZ in bytes big.  If buffer is passed in  */
   5989 /* as a NULL pointer then return a pointer to a static array.               */
   5990 /* ------------------------------------------------------------------------ */
   5991 char *
   5992 ipf_getifname(ifp, buffer)
   5993 	struct ifnet *ifp;
   5994 	char *buffer;
   5995 {
   5996 	static char namebuf[LIFNAMSIZ];
   5997 # if defined(MENTAT) || defined(__FreeBSD__) || defined(__osf__) || \
   5998      defined(__sgi) || defined(linux) || defined(_AIX51) || \
   5999      (defined(sun) && !defined(__SVR4) && !defined(__svr4__))
   6000 	int unit, space;
   6001 	char temp[20];
   6002 	char *s;
   6003 # endif
   6004 
   6005 	if (buffer == NULL)
   6006 		buffer = namebuf;
   6007 	(void) strncpy(buffer, ifp->if_name, LIFNAMSIZ);
   6008 	buffer[LIFNAMSIZ - 1] = '\0';
   6009 # if defined(MENTAT) || defined(__FreeBSD__) || defined(__osf__) || \
   6010      defined(__sgi) || defined(_AIX51) || \
   6011      (defined(sun) && !defined(__SVR4) && !defined(__svr4__))
   6012 	for (s = buffer; *s; s++)
   6013 		;
   6014 	unit = ifp->if_unit;
   6015 	space = LIFNAMSIZ - (s - buffer);
   6016 	if ((space > 0) && (unit >= 0)) {
   6017 		snprintf(temp, sizeof(temp), "%d", unit);
   6018 		(void) strncpy(s, temp, space);
   6019 		s[space - 1] = '\0';
   6020 	}
   6021 # endif
   6022 	return buffer;
   6023 }
   6024 #endif
   6025 
   6026 
   6027 /* ------------------------------------------------------------------------ */
   6028 /* Function:    ipf_ioctlswitch                                             */
   6029 /* Returns:     int     - -1 continue processing, else ioctl return value   */
   6030 /* Parameters:  unit(I) - device unit opened                                */
   6031 /*              data(I) - pointer to ioctl data                             */
   6032 /*              cmd(I)  - ioctl command                                     */
   6033 /*              mode(I) - mode value                                        */
   6034 /*              uid(I)  - uid making the ioctl call                         */
   6035 /*              ctx(I)  - pointer to context data                           */
   6036 /*                                                                          */
   6037 /* Based on the value of unit, call the appropriate ioctl handler or return */
   6038 /* EIO if ipfilter is not running.   Also checks if write perms are req'd   */
   6039 /* for the device in order to execute the ioctl.  A special case is made    */
   6040 /* SIOCIPFINTERROR so that the same code isn't required in every handler.   */
   6041 /* The context data pointer is passed through as this is used as the key    */
   6042 /* for locating a matching token for continued access for walking lists,    */
   6043 /* etc.                                                                     */
   6044 /* ------------------------------------------------------------------------ */
   6045 int
   6046 ipf_ioctlswitch(ipf_main_softc_t *softc, int unit, void *data, ioctlcmd_t cmd,
   6047     int mode, int uid, void *ctx)
   6048 {
   6049 	int error = 0;
   6050 
   6051 	switch (cmd)
   6052 	{
   6053 	case SIOCIPFINTERROR :
   6054 		error = BCOPYOUT(&softc->ipf_interror, data,
   6055 				 sizeof(softc->ipf_interror));
   6056 		if (error != 0) {
   6057 			IPFERROR(40);
   6058 			error = EFAULT;
   6059 		}
   6060 		return error;
   6061 	default :
   6062 		break;
   6063 	}
   6064 
   6065 	switch (unit)
   6066 	{
   6067 	case IPL_LOGIPF :
   6068 		error = ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx);
   6069 		break;
   6070 	case IPL_LOGNAT :
   6071 		if (softc->ipf_running > 0) {
   6072 			error = ipf_nat_ioctl(softc, data, cmd, mode,
   6073 					      uid, ctx);
   6074 		} else {
   6075 			IPFERROR(42);
   6076 			error = EIO;
   6077 		}
   6078 		break;
   6079 	case IPL_LOGSTATE :
   6080 		if (softc->ipf_running > 0) {
   6081 			error = ipf_state_ioctl(softc, data, cmd, mode,
   6082 						uid, ctx);
   6083 		} else {
   6084 			IPFERROR(43);
   6085 			error = EIO;
   6086 		}
   6087 		break;
   6088 	case IPL_LOGAUTH :
   6089 		if (softc->ipf_running > 0) {
   6090 			error = ipf_auth_ioctl(softc, data, cmd, mode,
   6091 					       uid, ctx);
   6092 		} else {
   6093 			IPFERROR(44);
   6094 			error = EIO;
   6095 		}
   6096 		break;
   6097 	case IPL_LOGSYNC :
   6098 		if (softc->ipf_running > 0) {
   6099 			error = ipf_sync_ioctl(softc, data, cmd, mode,
   6100 					       uid, ctx);
   6101 		} else {
   6102 			error = EIO;
   6103 			IPFERROR(45);
   6104 		}
   6105 		break;
   6106 	case IPL_LOGSCAN :
   6107 #ifdef IPFILTER_SCAN
   6108 		if (softc->ipf_running > 0)
   6109 			error = ipf_scan_ioctl(softc, data, cmd, mode,
   6110 					       uid, ctx);
   6111 		else
   6112 #endif
   6113 		{
   6114 			error = EIO;
   6115 			IPFERROR(46);
   6116 		}
   6117 		break;
   6118 	case IPL_LOGLOOKUP :
   6119 		if (softc->ipf_running > 0) {
   6120 			error = ipf_lookup_ioctl(softc, data, cmd, mode,
   6121 						 uid, ctx);
   6122 		} else {
   6123 			error = EIO;
   6124 			IPFERROR(47);
   6125 		}
   6126 		break;
   6127 	default :
   6128 		IPFERROR(48);
   6129 		error = EIO;
   6130 		break;
   6131 	}
   6132 
   6133 	return error;
   6134 }
   6135 
   6136 
   6137 /*
   6138  * This array defines the expected size of objects coming into the kernel
   6139  * for the various recognised object types. The first column is flags (see
   6140  * below), 2nd column is current size, 3rd column is the version number of
   6141  * when the current size became current.
   6142  * Flags:
   6143  * 1 = minimum size, not absolute size
   6144  */
   6145 static	int	ipf_objbytes[IPFOBJ_COUNT][3] = {
   6146 	{ 1,	sizeof(struct frentry),		5010000 },	/* 0 */
   6147 	{ 1,	sizeof(struct friostat),	5010000 },
   6148 	{ 0,	sizeof(struct fr_info),		5010000 },
   6149 	{ 0,	sizeof(struct ipf_authstat),	4010100 },
   6150 	{ 0,	sizeof(struct ipfrstat),	5010000 },
   6151 	{ 1,	sizeof(struct ipnat),		5010000 },	/* 5 */
   6152 	{ 0,	sizeof(struct natstat),		5010000 },
   6153 	{ 0,	sizeof(struct ipstate_save),	5010000 },
   6154 	{ 1,	sizeof(struct nat_save),	5010000 },
   6155 	{ 0,	sizeof(struct natlookup),	5010000 },
   6156 	{ 1,	sizeof(struct ipstate),		5010000 },	/* 10 */
   6157 	{ 0,	sizeof(struct ips_stat),	5010000 },
   6158 	{ 0,	sizeof(struct frauth),		5010000 },
   6159 	{ 0,	sizeof(struct ipftune),		4010100 },
   6160 	{ 0,	sizeof(struct nat),		5010000 },
   6161 	{ 0,	sizeof(struct ipfruleiter),	4011400 },	/* 15 */
   6162 	{ 0,	sizeof(struct ipfgeniter),	4011400 },
   6163 	{ 0,	sizeof(struct ipftable),	4011400 },
   6164 	{ 0,	sizeof(struct ipflookupiter),	4011400 },
   6165 	{ 0,	sizeof(struct ipftq) * IPF_TCP_NSTATES },
   6166 	{ 1,	0,				0	}, /* IPFEXPR */
   6167 	{ 0,	0,				0	}, /* PROXYCTL */
   6168 	{ 0,	sizeof (struct fripf),		5010000	}
   6169 };
   6170 
   6171 
   6172 /* ------------------------------------------------------------------------ */
   6173 /* Function:    ipf_inobj                                                   */
   6174 /* Returns:     int     - 0 = success, else failure                         */
   6175 /* Parameters:  softc(I) - soft context pointerto work with                 */
   6176 /*              data(I)  - pointer to ioctl data                            */
   6177 /*              objp(O)  - where to store ipfobj structure                  */
   6178 /*              ptr(I)   - pointer to data to copy out                      */
   6179 /*              type(I)  - type of structure being moved                    */
   6180 /*                                                                          */
   6181 /* Copy in the contents of what the ipfobj_t points to.  In future, we      */
   6182 /* add things to check for version numbers, sizes, etc, to make it backward */
   6183 /* compatible at the ABI for user land.                                     */
   6184 /* If objp is not NULL then we assume that the caller wants to see what is  */
   6185 /* in the ipfobj_t structure being copied in. As an example, this can tell  */
   6186 /* the caller what version of ipfilter the ioctl program was written to.    */
   6187 /* ------------------------------------------------------------------------ */
   6188 int
   6189 ipf_inobj(ipf_main_softc_t *softc, void *data, ipfobj_t *objp, void *ptr,
   6190     int type)
   6191 {
   6192 	ipfobj_t obj;
   6193 	int error;
   6194 	int size;
   6195 
   6196 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
   6197 		IPFERROR(49);
   6198 		return EINVAL;
   6199 	}
   6200 
   6201 	if (objp == NULL)
   6202 		objp = &obj;
   6203 	error = BCOPYIN(data, objp, sizeof(*objp));
   6204 	if (error != 0) {
   6205 		IPFERROR(124);
   6206 		return EFAULT;
   6207 	}
   6208 
   6209 	if (objp->ipfo_type != type) {
   6210 		IPFERROR(50);
   6211 		return EINVAL;
   6212 	}
   6213 
   6214 	if (objp->ipfo_rev >= ipf_objbytes[type][2]) {
   6215 		if ((ipf_objbytes[type][0] & 1) != 0) {
   6216 			if (objp->ipfo_size < ipf_objbytes[type][1]) {
   6217 				IPFERROR(51);
   6218 				return EINVAL;
   6219 			}
   6220 			size =  ipf_objbytes[type][1];
   6221 		} else if (objp->ipfo_size == ipf_objbytes[type][1]) {
   6222 			size =  objp->ipfo_size;
   6223 		} else {
   6224 			IPFERROR(52);
   6225 			return EINVAL;
   6226 		}
   6227 		error = COPYIN(objp->ipfo_ptr, ptr, size);
   6228 		if (error != 0) {
   6229 			IPFERROR(55);
   6230 			error = EFAULT;
   6231 		}
   6232 	} else {
   6233 #ifdef  IPFILTER_COMPAT
   6234 		error = ipf_in_compat(softc, objp, ptr, 0);
   6235 #else
   6236 		IPFERROR(54);
   6237 		error = EINVAL;
   6238 #endif
   6239 	}
   6240 	return error;
   6241 }
   6242 
   6243 
   6244 /* ------------------------------------------------------------------------ */
   6245 /* Function:    ipf_inobjsz                                                 */
   6246 /* Returns:     int     - 0 = success, else failure                         */
   6247 /* Parameters:  softc(I) - soft context pointerto work with                 */
   6248 /*              data(I)  - pointer to ioctl data                            */
   6249 /*              ptr(I)   - pointer to store real data in                    */
   6250 /*              type(I)  - type of structure being moved                    */
   6251 /*              sz(I)    - size of data to copy                             */
   6252 /*                                                                          */
   6253 /* As per ipf_inobj, except the size of the object to copy in is passed in  */
   6254 /* but it must not be smaller than the size defined for the type and the    */
   6255 /* type must allow for varied sized objects.  The extra requirement here is */
   6256 /* that sz must match the size of the object being passed in - this is not  */
   6257 /* not possible nor required in ipf_inobj().                                */
   6258 /* ------------------------------------------------------------------------ */
   6259 int
   6260 ipf_inobjsz(ipf_main_softc_t *softc, void *data, void *ptr, int type, int sz)
   6261 {
   6262 	ipfobj_t obj;
   6263 	int error;
   6264 
   6265 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
   6266 		IPFERROR(56);
   6267 		return EINVAL;
   6268 	}
   6269 
   6270 	error = BCOPYIN(data, &obj, sizeof(obj));
   6271 	if (error != 0) {
   6272 		IPFERROR(125);
   6273 		return EFAULT;
   6274 	}
   6275 
   6276 	if (obj.ipfo_type != type) {
   6277 		IPFERROR(58);
   6278 		return EINVAL;
   6279 	}
   6280 
   6281 	if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
   6282 		if (((ipf_objbytes[type][0] & 1) == 0) ||
   6283 		    (sz < ipf_objbytes[type][1])) {
   6284 			IPFERROR(57);
   6285 			return EINVAL;
   6286 		}
   6287 		error = COPYIN(obj.ipfo_ptr, ptr, sz);
   6288 		if (error != 0) {
   6289 			IPFERROR(61);
   6290 			error = EFAULT;
   6291 		}
   6292 	} else {
   6293 #ifdef	IPFILTER_COMPAT
   6294 		error = ipf_in_compat(softc, &obj, ptr, sz);
   6295 #else
   6296 		IPFERROR(60);
   6297 		error = EINVAL;
   6298 #endif
   6299 	}
   6300 	return error;
   6301 }
   6302 
   6303 
   6304 /* ------------------------------------------------------------------------ */
   6305 /* Function:    ipf_outobjsz                                                */
   6306 /* Returns:     int     - 0 = success, else failure                         */
   6307 /* Parameters:  data(I) - pointer to ioctl data                             */
   6308 /*              ptr(I)  - pointer to store real data in                     */
   6309 /*              type(I) - type of structure being moved                     */
   6310 /*              sz(I)   - size of data to copy                              */
   6311 /*                                                                          */
   6312 /* As per ipf_outobj, except the size of the object to copy out is passed in*/
   6313 /* but it must not be smaller than the size defined for the type and the    */
   6314 /* type must allow for varied sized objects.  The extra requirement here is */
   6315 /* that sz must match the size of the object being passed in - this is not  */
   6316 /* not possible nor required in ipf_outobj().                               */
   6317 /* ------------------------------------------------------------------------ */
   6318 int
   6319 ipf_outobjsz(ipf_main_softc_t *softc, void *data, void *ptr, int type, int sz)
   6320 {
   6321 	ipfobj_t obj;
   6322 	int error;
   6323 
   6324 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
   6325 		IPFERROR(62);
   6326 		return EINVAL;
   6327 	}
   6328 
   6329 	error = BCOPYIN(data, &obj, sizeof(obj));
   6330 	if (error != 0) {
   6331 		IPFERROR(127);
   6332 		return EFAULT;
   6333 	}
   6334 
   6335 	if (obj.ipfo_type != type) {
   6336 		IPFERROR(63);
   6337 		return EINVAL;
   6338 	}
   6339 
   6340 	if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
   6341 		if (((ipf_objbytes[type][0] & 1) == 0) ||
   6342 		    (sz < ipf_objbytes[type][1])) {
   6343 			IPFERROR(146);
   6344 			return EINVAL;
   6345 		}
   6346 		error = COPYOUT(ptr, obj.ipfo_ptr, sz);
   6347 		if (error != 0) {
   6348 			IPFERROR(66);
   6349 			error = EFAULT;
   6350 		}
   6351 	} else {
   6352 #ifdef	IPFILTER_COMPAT
   6353 		error = ipf_out_compat(softc, &obj, ptr);
   6354 #else
   6355 		IPFERROR(65);
   6356 		error = EINVAL;
   6357 #endif
   6358 	}
   6359 	return error;
   6360 }
   6361 
   6362 
   6363 /* ------------------------------------------------------------------------ */
   6364 /* Function:    ipf_outobj                                                  */
   6365 /* Returns:     int     - 0 = success, else failure                         */
   6366 /* Parameters:  data(I) - pointer to ioctl data                             */
   6367 /*              ptr(I)  - pointer to store real data in                     */
   6368 /*              type(I) - type of structure being moved                     */
   6369 /*                                                                          */
   6370 /* Copy out the contents of what ptr is to where ipfobj points to.  In      */
   6371 /* future, we add things to check for version numbers, sizes, etc, to make  */
   6372 /* it backward  compatible at the ABI for user land.                        */
   6373 /* ------------------------------------------------------------------------ */
   6374 int
   6375 ipf_outobj(ipf_main_softc_t *softc, void *data, void *ptr, int type)
   6376 {
   6377 	ipfobj_t obj;
   6378 	int error;
   6379 
   6380 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
   6381 		IPFERROR(67);
   6382 		return EINVAL;
   6383 	}
   6384 
   6385 	error = BCOPYIN(data, &obj, sizeof(obj));
   6386 	if (error != 0) {
   6387 		IPFERROR(126);
   6388 		return EFAULT;
   6389 	}
   6390 
   6391 	if (obj.ipfo_type != type) {
   6392 		IPFERROR(68);
   6393 		return EINVAL;
   6394 	}
   6395 
   6396 	if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
   6397 		if ((ipf_objbytes[type][0] & 1) != 0) {
   6398 			if (obj.ipfo_size < ipf_objbytes[type][1]) {
   6399 				IPFERROR(69);
   6400 				return EINVAL;
   6401 			}
   6402 		} else if (obj.ipfo_size != ipf_objbytes[type][1]) {
   6403 			IPFERROR(70);
   6404 			return EINVAL;
   6405 		}
   6406 
   6407 		error = COPYOUT(ptr, obj.ipfo_ptr, obj.ipfo_size);
   6408 		if (error != 0) {
   6409 			IPFERROR(73);
   6410 			error = EFAULT;
   6411 		}
   6412 	} else {
   6413 #ifdef	IPFILTER_COMPAT
   6414 		error = ipf_out_compat(softc, &obj, ptr);
   6415 #else
   6416 		IPFERROR(72);
   6417 		error = EINVAL;
   6418 #endif
   6419 	}
   6420 	return error;
   6421 }
   6422 
   6423 
   6424 /* ------------------------------------------------------------------------ */
   6425 /* Function:    ipf_outobjk                                                 */
   6426 /* Returns:     int     - 0 = success, else failure                         */
   6427 /* Parameters:  obj(I)  - pointer to data description structure             */
   6428 /*              ptr(I)  - pointer to kernel data to copy out                */
   6429 /*                                                                          */
   6430 /* In the above functions, the ipfobj_t structure is copied into the kernel,*/
   6431 /* telling ipfilter how to copy out data. In this instance, the ipfobj_t is */
   6432 /* already populated with information and now we just need to use it.       */
   6433 /* There is no need for this function to have a "type" parameter as there   */
   6434 /* is no point in validating information that comes from the kernel with    */
   6435 /* itself.                                                                  */
   6436 /* ------------------------------------------------------------------------ */
   6437 int
   6438 ipf_outobjk(ipf_main_softc_t *softc, ipfobj_t *obj, void *ptr)
   6439 {
   6440 	int type = obj->ipfo_type;
   6441 	int error;
   6442 
   6443 	if ((type < 0) || (type >= IPFOBJ_COUNT)) {
   6444 		IPFERROR(147);
   6445 		return EINVAL;
   6446 	}
   6447 
   6448 	if (obj->ipfo_rev >= ipf_objbytes[type][2]) {
   6449 		if ((ipf_objbytes[type][0] & 1) != 0) {
   6450 			if (obj->ipfo_size < ipf_objbytes[type][1]) {
   6451 				IPFERROR(148);
   6452 				return EINVAL;
   6453 			}
   6454 
   6455 		} else if (obj->ipfo_size != ipf_objbytes[type][1]) {
   6456 			IPFERROR(149);
   6457 			return EINVAL;
   6458 		}
   6459 
   6460 		error = COPYOUT(ptr, obj->ipfo_ptr, obj->ipfo_size);
   6461 		if (error != 0) {
   6462 			IPFERROR(150);
   6463 			error = EFAULT;
   6464 		}
   6465 	} else {
   6466 #ifdef  IPFILTER_COMPAT
   6467 		error = ipf_out_compat(softc, obj, ptr);
   6468 #else
   6469 		IPFERROR(151);
   6470 		error = EINVAL;
   6471 #endif
   6472 	}
   6473 	return error;
   6474 }
   6475 
   6476 
   6477 /* ------------------------------------------------------------------------ */
   6478 /* Function:    ipf_checkl4sum                                              */
   6479 /* Returns:     int     - 0 = good, -1 = bad, 1 = cannot check              */
   6480 /* Parameters:  fin(I) - pointer to packet information                      */
   6481 /*                                                                          */
   6482 /* If possible, calculate the layer 4 checksum for the packet.  If this is  */
   6483 /* not possible, return without indicating a failure or success but in a    */
   6484 /* way that is ditinguishable. This function should only be called by the   */
   6485 /* ipf_checkv6sum() for each platform.                                      */
   6486 /* ------------------------------------------------------------------------ */
   6487 int
   6488 ipf_checkl4sum(fr_info_t *fin)
   6489 {
   6490 	u_short sum, hdrsum, *csump;
   6491 	udphdr_t *udp;
   6492 	int dosum;
   6493 
   6494 	/*
   6495 	 * If the TCP packet isn't a fragment, isn't too short and otherwise
   6496 	 * isn't already considered "bad", then validate the checksum.  If
   6497 	 * this check fails then considered the packet to be "bad".
   6498 	 */
   6499 	if ((fin->fin_flx & (FI_FRAG|FI_SHORT|FI_BAD)) != 0)
   6500 		return 1;
   6501 
   6502 	csump = NULL;
   6503 	hdrsum = 0;
   6504 	dosum = 0;
   6505 	sum = 0;
   6506 
   6507 	switch (fin->fin_p)
   6508 	{
   6509 	case IPPROTO_TCP :
   6510 		csump = &((tcphdr_t *)fin->fin_dp)->th_sum;
   6511 		dosum = 1;
   6512 		break;
   6513 
   6514 	case IPPROTO_UDP :
   6515 		udp = fin->fin_dp;
   6516 		if (udp->uh_sum != 0) {
   6517 			csump = &udp->uh_sum;
   6518 			dosum = 1;
   6519 		}
   6520 		break;
   6521 
   6522 #ifdef USE_INET6
   6523 	case IPPROTO_ICMPV6 :
   6524 		csump = &((struct icmp6_hdr *)fin->fin_dp)->icmp6_cksum;
   6525 		dosum = 1;
   6526 		break;
   6527 #endif
   6528 
   6529 	case IPPROTO_ICMP :
   6530 		csump = &((struct icmp *)fin->fin_dp)->icmp_cksum;
   6531 		dosum = 1;
   6532 		break;
   6533 
   6534 	default :
   6535 		return 1;
   6536 		/*NOTREACHED*/
   6537 	}
   6538 
   6539 	if (csump != NULL) {
   6540 		hdrsum = *csump;
   6541 		if (fin->fin_p == IPPROTO_UDP && hdrsum == 0xffff)
   6542 			hdrsum = 0x0000;
   6543 	}
   6544 
   6545 	if (dosum) {
   6546 		sum = fr_cksum(fin, fin->fin_ip, fin->fin_p, fin->fin_dp);
   6547 	}
   6548 #if !defined(_KERNEL)
   6549 	if (sum == hdrsum) {
   6550 		FR_DEBUG(("checkl4sum: %hx == %hx\n", sum, hdrsum));
   6551 	} else {
   6552 		FR_DEBUG(("checkl4sum: %hx != %hx\n", sum, hdrsum));
   6553 	}
   6554 #endif
   6555 	DT2(l4sums, u_short, hdrsum, u_short, sum);
   6556 	if (hdrsum == sum) {
   6557 		fin->fin_cksum = FI_CK_SUMOK;
   6558 		return 0;
   6559 	}
   6560 	fin->fin_cksum = FI_CK_BAD;
   6561 	return -1;
   6562 }
   6563 
   6564 
   6565 /* ------------------------------------------------------------------------ */
   6566 /* Function:    ipf_ifpfillv4addr                                           */
   6567 /* Returns:     int     - 0 = address update, -1 = address not updated      */
   6568 /* Parameters:  atype(I)   - type of network address update to perform      */
   6569 /*              sin(I)     - pointer to source of address information       */
   6570 /*              mask(I)    - pointer to source of netmask information       */
   6571 /*              inp(I)     - pointer to destination address store           */
   6572 /*              inpmask(I) - pointer to destination netmask store           */
   6573 /*                                                                          */
   6574 /* Given a type of network address update (atype) to perform, copy          */
   6575 /* information from sin/mask into inp/inpmask.  If ipnmask is NULL then no  */
   6576 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in  */
   6577 /* which case the operation fails.  For all values of atype other than      */
   6578 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s  */
   6579 /* value.                                                                   */
   6580 /* ------------------------------------------------------------------------ */
   6581 int
   6582 ipf_ifpfillv4addr(int atype, struct sockaddr_in *sin, struct sockaddr_in *mask,
   6583     struct in_addr *inp, struct in_addr *inpmask)
   6584 {
   6585 	if (inpmask != NULL && atype != FRI_NETMASKED)
   6586 		inpmask->s_addr = 0xffffffff;
   6587 
   6588 	if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
   6589 		if (atype == FRI_NETMASKED) {
   6590 			if (inpmask == NULL)
   6591 				return -1;
   6592 			inpmask->s_addr = mask->sin_addr.s_addr;
   6593 		}
   6594 		inp->s_addr = sin->sin_addr.s_addr & mask->sin_addr.s_addr;
   6595 	} else {
   6596 		inp->s_addr = sin->sin_addr.s_addr;
   6597 	}
   6598 	return 0;
   6599 }
   6600 
   6601 
   6602 #ifdef	USE_INET6
   6603 /* ------------------------------------------------------------------------ */
   6604 /* Function:    ipf_ifpfillv6addr                                           */
   6605 /* Returns:     int     - 0 = address update, -1 = address not updated      */
   6606 /* Parameters:  atype(I)   - type of network address update to perform      */
   6607 /*              sin(I)     - pointer to source of address information       */
   6608 /*              mask(I)    - pointer to source of netmask information       */
   6609 /*              inp(I)     - pointer to destination address store           */
   6610 /*              inpmask(I) - pointer to destination netmask store           */
   6611 /*                                                                          */
   6612 /* Given a type of network address update (atype) to perform, copy          */
   6613 /* information from sin/mask into inp/inpmask.  If ipnmask is NULL then no  */
   6614 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in  */
   6615 /* which case the operation fails.  For all values of atype other than      */
   6616 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s  */
   6617 /* value.                                                                   */
   6618 /* ------------------------------------------------------------------------ */
   6619 int
   6620 ipf_ifpfillv6addr(int atype, struct sockaddr_in6 *sin,
   6621     struct sockaddr_in6 *mask, i6addr_t *inp, i6addr_t *inpmask)
   6622 {
   6623 	i6addr_t *src, *and;
   6624 
   6625 	src = (i6addr_t *)&sin->sin6_addr;
   6626 	and = (i6addr_t *)&mask->sin6_addr;
   6627 
   6628 	if (inpmask != NULL && atype != FRI_NETMASKED) {
   6629 		inpmask->i6[0] = 0xffffffff;
   6630 		inpmask->i6[1] = 0xffffffff;
   6631 		inpmask->i6[2] = 0xffffffff;
   6632 		inpmask->i6[3] = 0xffffffff;
   6633 	}
   6634 
   6635 	if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
   6636 		if (atype == FRI_NETMASKED) {
   6637 			if (inpmask == NULL)
   6638 				return -1;
   6639 			inpmask->i6[0] = and->i6[0];
   6640 			inpmask->i6[1] = and->i6[1];
   6641 			inpmask->i6[2] = and->i6[2];
   6642 			inpmask->i6[3] = and->i6[3];
   6643 		}
   6644 
   6645 		inp->i6[0] = src->i6[0] & and->i6[0];
   6646 		inp->i6[1] = src->i6[1] & and->i6[1];
   6647 		inp->i6[2] = src->i6[2] & and->i6[2];
   6648 		inp->i6[3] = src->i6[3] & and->i6[3];
   6649 	} else {
   6650 		inp->i6[0] = src->i6[0];
   6651 		inp->i6[1] = src->i6[1];
   6652 		inp->i6[2] = src->i6[2];
   6653 		inp->i6[3] = src->i6[3];
   6654 	}
   6655 	return 0;
   6656 }
   6657 #endif
   6658 
   6659 
   6660 /* ------------------------------------------------------------------------ */
   6661 /* Function:    ipf_matchtag                                                */
   6662 /* Returns:     0 == mismatch, 1 == match.                                  */
   6663 /* Parameters:  tag1(I) - pointer to first tag to compare                   */
   6664 /*              tag2(I) - pointer to second tag to compare                  */
   6665 /*                                                                          */
   6666 /* Returns true (non-zero) or false(0) if the two tag structures can be     */
   6667 /* considered to be a match or not match, respectively.  The tag is 16      */
   6668 /* bytes long (16 characters) but that is overlayed with 4 32bit ints so    */
   6669 /* compare the ints instead, for speed. tag1 is the master of the           */
   6670 /* comparison.  This function should only be called with both tag1 and tag2 */
   6671 /* as non-NULL pointers.                                                    */
   6672 /* ------------------------------------------------------------------------ */
   6673 int
   6674 ipf_matchtag(ipftag_t *tag1, ipftag_t *tag2)
   6675 {
   6676 	if (tag1 == tag2)
   6677 		return 1;
   6678 
   6679 	if ((tag1->ipt_num[0] == 0) && (tag2->ipt_num[0] == 0))
   6680 		return 1;
   6681 
   6682 	if ((tag1->ipt_num[0] == tag2->ipt_num[0]) &&
   6683 	    (tag1->ipt_num[1] == tag2->ipt_num[1]) &&
   6684 	    (tag1->ipt_num[2] == tag2->ipt_num[2]) &&
   6685 	    (tag1->ipt_num[3] == tag2->ipt_num[3]))
   6686 		return 1;
   6687 	return 0;
   6688 }
   6689 
   6690 
   6691 /* ------------------------------------------------------------------------ */
   6692 /* Function:    ipf_coalesce                                                */
   6693 /* Returns:     1 == success, -1 == failure, 0 == no change                 */
   6694 /* Parameters:  fin(I) - pointer to packet information                      */
   6695 /*                                                                          */
   6696 /* Attempt to get all of the packet data into a single, contiguous buffer.  */
   6697 /* If this call returns a failure then the buffers have also been freed.    */
   6698 /* ------------------------------------------------------------------------ */
   6699 int
   6700 ipf_coalesce(fr_info_t *fin)
   6701 {
   6702 
   6703 	if ((fin->fin_flx & FI_COALESCE) != 0)
   6704 		return 1;
   6705 
   6706 	/*
   6707 	 * If the mbuf pointers indicate that there is no mbuf to work with,
   6708 	 * return but do not indicate success or failure.
   6709 	 */
   6710 	if (fin->fin_m == NULL || fin->fin_mp == NULL)
   6711 		return 0;
   6712 
   6713 #if defined(_KERNEL)
   6714 	if (ipf_pullup(fin->fin_m, fin, fin->fin_plen) == NULL) {
   6715 		ipf_main_softc_t *softc = fin->fin_main_soft;
   6716 
   6717 		DT1(frb_coalesce, fr_info_t *, fin);
   6718 		LBUMP(ipf_stats[fin->fin_out].fr_badcoalesces);
   6719 # ifdef MENTAT
   6720 		FREE_MB_T(*fin->fin_mp);
   6721 # endif
   6722 		fin->fin_reason = FRB_COALESCE;
   6723 		*fin->fin_mp = NULL;
   6724 		fin->fin_m = NULL;
   6725 		return -1;
   6726 	}
   6727 #else
   6728 	fin = fin;	/* LINT */
   6729 #endif
   6730 	return 1;
   6731 }
   6732 
   6733 
   6734 /*
   6735  * The following table lists all of the tunable variables that can be
   6736  * accessed via SIOCIPFGET/SIOCIPFSET/SIOCIPFGETNEXt.  The format of each row
   6737  * in the table below is as follows:
   6738  *
   6739  * pointer to value, name of value, minimum, maximum, size of the value's
   6740  *     container, value attribute flags
   6741  *
   6742  * For convienience, IPFT_RDONLY means the value is read-only, IPFT_WRDISABLED
   6743  * means the value can only be written to when IPFilter is loaded but disabled.
   6744  * The obvious implication is if neither of these are set then the value can be
   6745  * changed at any time without harm.
   6746  */
   6747 
   6748 
   6749 /* ------------------------------------------------------------------------ */
   6750 /* Function:    ipf_tune_findbycookie                                       */
   6751 /* Returns:     NULL = search failed, else pointer to tune struct           */
   6752 /* Parameters:  cookie(I) - cookie value to search for amongst tuneables    */
   6753 /*              next(O)   - pointer to place to store the cookie for the    */
   6754 /*                          "next" tuneable, if it is desired.              */
   6755 /*                                                                          */
   6756 /* This function is used to walk through all of the existing tunables with  */
   6757 /* successive calls.  It searches the known tunables for the one which has  */
   6758 /* a matching value for "cookie" - ie its address.  When returning a match, */
   6759 /* the next one to be found may be returned inside next.                    */
   6760 /* ------------------------------------------------------------------------ */
   6761 static ipftuneable_t *
   6762 ipf_tune_findbycookie(ipftuneable_t **ptop, void *cookie, void **next)
   6763 {
   6764 	ipftuneable_t *ta, **tap;
   6765 
   6766 	for (ta = *ptop; ta->ipft_name != NULL; ta++)
   6767 		if (ta == cookie) {
   6768 			if (next != NULL) {
   6769 				/*
   6770 				 * If the next entry in the array has a name
   6771 				 * present, then return a pointer to it for
   6772 				 * where to go next, else return a pointer to
   6773 				 * the dynaminc list as a key to search there
   6774 				 * next.  This facilitates a weak linking of
   6775 				 * the two "lists" together.
   6776 				 */
   6777 				if ((ta + 1)->ipft_name != NULL)
   6778 					*next = ta + 1;
   6779 				else
   6780 					*next = ptop;
   6781 			}
   6782 			return ta;
   6783 		}
   6784 
   6785 	for (tap = ptop; (ta = *tap) != NULL; tap = &ta->ipft_next)
   6786 		if (tap == cookie) {
   6787 			if (next != NULL)
   6788 				*next = &ta->ipft_next;
   6789 			return ta;
   6790 		}
   6791 
   6792 	if (next != NULL)
   6793 		*next = NULL;
   6794 	return NULL;
   6795 }
   6796 
   6797 
   6798 /* ------------------------------------------------------------------------ */
   6799 /* Function:    ipf_tune_findbyname                                         */
   6800 /* Returns:     NULL = search failed, else pointer to tune struct           */
   6801 /* Parameters:  name(I) - name of the tuneable entry to find.               */
   6802 /*                                                                          */
   6803 /* Search the static array of tuneables and the list of dynamic tuneables   */
   6804 /* for an entry with a matching name.  If we can find one, return a pointer */
   6805 /* to the matching structure.                                               */
   6806 /* ------------------------------------------------------------------------ */
   6807 static ipftuneable_t *
   6808 ipf_tune_findbyname(ipftuneable_t *top, const char *name)
   6809 {
   6810 	ipftuneable_t *ta;
   6811 
   6812 	for (ta = top; ta != NULL; ta = ta->ipft_next)
   6813 		if (!strcmp(ta->ipft_name, name)) {
   6814 			return ta;
   6815 		}
   6816 
   6817 	return NULL;
   6818 }
   6819 
   6820 
   6821 /* ------------------------------------------------------------------------ */
   6822 /* Function:    ipf_tune_add_array                                          */
   6823 /* Returns:     int - 0 == success, else failure                            */
   6824 /* Parameters:  newtune - pointer to new tune array to add to tuneables     */
   6825 /*                                                                          */
   6826 /* Appends tune structures from the array passed in (newtune) to the end of */
   6827 /* the current list of "dynamic" tuneable parameters.                       */
   6828 /* If any entry to be added is already present (by name) then the operation */
   6829 /* is aborted - entries that have been added are removed before returning.  */
   6830 /* An entry with no name (NULL) is used as the indication that the end of   */
   6831 /* the array has been reached.                                              */
   6832 /* ------------------------------------------------------------------------ */
   6833 int
   6834 ipf_tune_add_array(ipf_main_softc_t *softc, ipftuneable_t *newtune)
   6835 {
   6836 	ipftuneable_t *nt, *dt;
   6837 	int error = 0;
   6838 
   6839 	for (nt = newtune; nt->ipft_name != NULL; nt++) {
   6840 		error = ipf_tune_add(softc, nt);
   6841 		if (error != 0) {
   6842 			for (dt = newtune; dt != nt; dt++) {
   6843 				(void) ipf_tune_del(softc, dt);
   6844 			}
   6845 		}
   6846 	}
   6847 
   6848 	return error;
   6849 }
   6850 
   6851 
   6852 /* ------------------------------------------------------------------------ */
   6853 /* Function:    ipf_tune_array_link                                         */
   6854 /* Returns:     0 == success, -1 == failure                                 */
   6855 /* Parameters:  softc(I) - soft context pointerto work with                 */
   6856 /*              array(I) - pointer to an array of tuneables                 */
   6857 /*                                                                          */
   6858 /* Given an array of tunables (array), append them to the current list of   */
   6859 /* tuneables for this context (softc->ipf_tuners.) To properly prepare the  */
   6860 /* the array for being appended to the list, initialise all of the next     */
   6861 /* pointers so we don't need to walk parts of it with ++ and others with    */
   6862 /* next. The array is expected to have an entry with a NULL name as the     */
   6863 /* terminator. Trying to add an array with no non-NULL names will return as */
   6864 /* a failure.                                                               */
   6865 /* ------------------------------------------------------------------------ */
   6866 int
   6867 ipf_tune_array_link(ipf_main_softc_t *softc, ipftuneable_t *array)
   6868 {
   6869 	ipftuneable_t *t, **p;
   6870 
   6871 	t = array;
   6872 	if (t->ipft_name == NULL)
   6873 		return -1;
   6874 
   6875 	for (; t[1].ipft_name != NULL; t++)
   6876 		t[0].ipft_next = &t[1];
   6877 	t->ipft_next = NULL;
   6878 
   6879 	/*
   6880 	 * Since a pointer to the last entry isn't kept, we need to find it
   6881 	 * each time we want to add new variables to the list.
   6882 	 */
   6883 	for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
   6884 		if (t->ipft_name == NULL)
   6885 			break;
   6886 	*p = array;
   6887 
   6888 	return 0;
   6889 }
   6890 
   6891 
   6892 /* ------------------------------------------------------------------------ */
   6893 /* Function:    ipf_tune_array_unlink                                       */
   6894 /* Returns:     0 == success, -1 == failure                                 */
   6895 /* Parameters:  softc(I) - soft context pointerto work with                 */
   6896 /*              array(I) - pointer to an array of tuneables                 */
   6897 /*                                                                          */
   6898 /* ------------------------------------------------------------------------ */
   6899 int
   6900 ipf_tune_array_unlink(ipf_main_softc_t *softc, ipftuneable_t *array)
   6901 {
   6902 	ipftuneable_t *t, **p;
   6903 
   6904 	for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
   6905 		if (t == array)
   6906 			break;
   6907 	if (t == NULL)
   6908 		return -1;
   6909 
   6910 	for (; t[1].ipft_name != NULL; t++)
   6911 		;
   6912 
   6913 	*p = t->ipft_next;
   6914 
   6915 	return 0;
   6916 }
   6917 
   6918 
   6919 /* ------------------------------------------------------------------------ */
   6920 /* Function:   ipf_tune_array_copy                                          */
   6921 /* Returns:    NULL = failure, else pointer to new array                    */
   6922 /* Parameters: base(I)     - pointer to structure base                      */
   6923 /*             size(I)     - size of the array at template                  */
   6924 /*             template(I) - original array to copy                         */
   6925 /*                                                                          */
   6926 /* Allocate memory for a new set of tuneable values and copy everything     */
   6927 /* from template into the new region of memory.  The new region is full of  */
   6928 /* uninitialised pointers (ipft_next) so set them up.  Now, ipftp_offset... */
   6929 /*                                                                          */
   6930 /* NOTE: the following assumes that sizeof(long) == sizeof(void *)          */
   6931 /* In the array template, ipftp_offset is the offset (in bytes) of the      */
   6932 /* location of the tuneable value inside the structure pointed to by base.  */
   6933 /* As ipftp_offset is a union over the pointers to the tuneable values, if  */
   6934 /* we add base to the copy's ipftp_offset, copy ends up with a pointer in   */
   6935 /* ipftp_void that points to the stored value.                              */
   6936 /* ------------------------------------------------------------------------ */
   6937 ipftuneable_t *
   6938 ipf_tune_array_copy(void *base, size_t size, const ipftuneable_t *template)
   6939 {
   6940 	ipftuneable_t *copy;
   6941 	int i;
   6942 
   6943 
   6944 	KMALLOCS(copy, ipftuneable_t *, size);
   6945 	if (copy == NULL) {
   6946 		return NULL;
   6947 	}
   6948 	bcopy(template, copy, size);
   6949 
   6950 	for (i = 0; copy[i].ipft_name; i++) {
   6951 		copy[i].ipft_una.ipftp_offset += (u_long)base;
   6952 		copy[i].ipft_next = copy + i + 1;
   6953 	}
   6954 
   6955 	return copy;
   6956 }
   6957 
   6958 
   6959 /* ------------------------------------------------------------------------ */
   6960 /* Function:    ipf_tune_add                                                */
   6961 /* Returns:     int - 0 == success, else failure                            */
   6962 /* Parameters:  newtune - pointer to new tune entry to add to tuneables     */
   6963 /*                                                                          */
   6964 /* Appends tune structures from the array passed in (newtune) to the end of */
   6965 /* the current list of "dynamic" tuneable parameters.  Once added, the      */
   6966 /* owner of the object is not expected to ever change "ipft_next".          */
   6967 /* ------------------------------------------------------------------------ */
   6968 int
   6969 ipf_tune_add(ipf_main_softc_t *softc, ipftuneable_t *newtune)
   6970 {
   6971 	ipftuneable_t *ta, **tap;
   6972 
   6973 	ta = ipf_tune_findbyname(softc->ipf_tuners, newtune->ipft_name);
   6974 	if (ta != NULL) {
   6975 		IPFERROR(74);
   6976 		return EEXIST;
   6977 	}
   6978 
   6979 	for (tap = &softc->ipf_tuners; *tap != NULL; tap = &(*tap)->ipft_next)
   6980 		;
   6981 
   6982 	newtune->ipft_next = NULL;
   6983 	*tap = newtune;
   6984 	return 0;
   6985 }
   6986 
   6987 
   6988 /* ------------------------------------------------------------------------ */
   6989 /* Function:    ipf_tune_del                                                */
   6990 /* Returns:     int - 0 == success, else failure                            */
   6991 /* Parameters:  oldtune - pointer to tune entry to remove from the list of  */
   6992 /*                        current dynamic tuneables                         */
   6993 /*                                                                          */
   6994 /* Search for the tune structure, by pointer, in the list of those that are */
   6995 /* dynamically added at run time.  If found, adjust the list so that this   */
   6996 /* structure is no longer part of it.                                       */
   6997 /* ------------------------------------------------------------------------ */
   6998 int
   6999 ipf_tune_del(ipf_main_softc_t *softc, ipftuneable_t *oldtune)
   7000 {
   7001 	ipftuneable_t *ta, **tap;
   7002 	int error = 0;
   7003 
   7004 	for (tap = &softc->ipf_tuners; (ta = *tap) != NULL;
   7005 	     tap = &ta->ipft_next) {
   7006 		if (ta == oldtune) {
   7007 			*tap = oldtune->ipft_next;
   7008 			oldtune->ipft_next = NULL;
   7009 			break;
   7010 		}
   7011 	}
   7012 
   7013 	if (ta == NULL) {
   7014 		error = ESRCH;
   7015 		IPFERROR(75);
   7016 	}
   7017 	return error;
   7018 }
   7019 
   7020 
   7021 /* ------------------------------------------------------------------------ */
   7022 /* Function:    ipf_tune_del_array                                          */
   7023 /* Returns:     int - 0 == success, else failure                            */
   7024 /* Parameters:  oldtune - pointer to tuneables array                        */
   7025 /*                                                                          */
   7026 /* Remove each tuneable entry in the array from the list of "dynamic"       */
   7027 /* tunables.  If one entry should fail to be found, an error will be        */
   7028 /* returned and no further ones removed.                                    */
   7029 /* An entry with a NULL name is used as the indicator of the last entry in  */
   7030 /* the array.                                                               */
   7031 /* ------------------------------------------------------------------------ */
   7032 int
   7033 ipf_tune_del_array(ipf_main_softc_t *softc, ipftuneable_t *oldtune)
   7034 {
   7035 	ipftuneable_t *ot;
   7036 	int error = 0;
   7037 
   7038 	for (ot = oldtune; ot->ipft_name != NULL; ot++) {
   7039 		error = ipf_tune_del(softc, ot);
   7040 		if (error != 0)
   7041 			break;
   7042 	}
   7043 
   7044 	return error;
   7045 
   7046 }
   7047 
   7048 
   7049 /* ------------------------------------------------------------------------ */
   7050 /* Function:    ipf_tune                                                    */
   7051 /* Returns:     int - 0 == success, else failure                            */
   7052 /* Parameters:  cmd(I)  - ioctl command number                              */
   7053 /*              data(I) - pointer to ioctl data structure                   */
   7054 /*                                                                          */
   7055 /* Implement handling of SIOCIPFGETNEXT, SIOCIPFGET and SIOCIPFSET.  These  */
   7056 /* three ioctls provide the means to access and control global variables    */
   7057 /* within IPFilter, allowing (for example) timeouts and table sizes to be   */
   7058 /* changed without rebooting, reloading or recompiling.  The initialisation */
   7059 /* and 'destruction' routines of the various components of ipfilter are all */
   7060 /* each responsible for handling their own values being too big.            */
   7061 /* ------------------------------------------------------------------------ */
   7062 int
   7063 ipf_ipftune(ipf_main_softc_t *softc, ioctlcmd_t cmd, void *data)
   7064 {
   7065 	ipftuneable_t *ta;
   7066 	ipftune_t tu;
   7067 	void *cookie;
   7068 	int error;
   7069 
   7070 	error = ipf_inobj(softc, data, NULL, &tu, IPFOBJ_TUNEABLE);
   7071 	if (error != 0)
   7072 		return error;
   7073 
   7074 	tu.ipft_name[sizeof(tu.ipft_name) - 1] = '\0';
   7075 	cookie = tu.ipft_cookie;
   7076 	ta = NULL;
   7077 
   7078 	switch (cmd)
   7079 	{
   7080 	case SIOCIPFGETNEXT :
   7081 		/*
   7082 		 * If cookie is non-NULL, assume it to be a pointer to the last
   7083 		 * entry we looked at, so find it (if possible) and return a
   7084 		 * pointer to the next one after it.  The last entry in the
   7085 		 * the table is a NULL entry, so when we get to it, set cookie
   7086 		 * to NULL and return that, indicating end of list, erstwhile
   7087 		 * if we come in with cookie set to NULL, we are starting anew
   7088 		 * at the front of the list.
   7089 		 */
   7090 		if (cookie != NULL) {
   7091 			ta = ipf_tune_findbycookie(&softc->ipf_tuners,
   7092 						   cookie, &tu.ipft_cookie);
   7093 		} else {
   7094 			ta = softc->ipf_tuners;
   7095 			tu.ipft_cookie = ta + 1;
   7096 		}
   7097 		if (ta != NULL) {
   7098 			/*
   7099 			 * Entry found, but does the data pointed to by that
   7100 			 * row fit in what we can return?
   7101 			 */
   7102 			if (ta->ipft_sz > sizeof(tu.ipft_un)) {
   7103 				IPFERROR(76);
   7104 				return EINVAL;
   7105 			}
   7106 
   7107 			tu.ipft_vlong = 0;
   7108 			if (ta->ipft_sz == sizeof(u_long))
   7109 				tu.ipft_vlong = *ta->ipft_plong;
   7110 			else if (ta->ipft_sz == sizeof(u_int))
   7111 				tu.ipft_vint = *ta->ipft_pint;
   7112 			else if (ta->ipft_sz == sizeof(u_short))
   7113 				tu.ipft_vshort = *ta->ipft_pshort;
   7114 			else if (ta->ipft_sz == sizeof(u_char))
   7115 				tu.ipft_vchar = *ta->ipft_pchar;
   7116 
   7117 			tu.ipft_sz = ta->ipft_sz;
   7118 			tu.ipft_min = ta->ipft_min;
   7119 			tu.ipft_max = ta->ipft_max;
   7120 			tu.ipft_flags = ta->ipft_flags;
   7121 			bcopy(ta->ipft_name, tu.ipft_name,
   7122 			      MIN(sizeof(tu.ipft_name),
   7123 				  strlen(ta->ipft_name) + 1));
   7124 		}
   7125 		error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
   7126 		break;
   7127 
   7128 	case SIOCIPFGET :
   7129 	case SIOCIPFSET :
   7130 		/*
   7131 		 * Search by name or by cookie value for a particular entry
   7132 		 * in the tuning paramter table.
   7133 		 */
   7134 		IPFERROR(77);
   7135 		error = ESRCH;
   7136 		if (cookie != NULL) {
   7137 			ta = ipf_tune_findbycookie(&softc->ipf_tuners,
   7138 						   cookie, NULL);
   7139 			if (ta != NULL)
   7140 				error = 0;
   7141 		} else if (tu.ipft_name[0] != '\0') {
   7142 			ta = ipf_tune_findbyname(softc->ipf_tuners,
   7143 						 tu.ipft_name);
   7144 			if (ta != NULL)
   7145 				error = 0;
   7146 		}
   7147 		if (error != 0)
   7148 			break;
   7149 
   7150 		if (cmd == (ioctlcmd_t)SIOCIPFGET) {
   7151 			/*
   7152 			 * Fetch the tuning parameters for a particular value
   7153 			 */
   7154 			tu.ipft_vlong = 0;
   7155 			if (ta->ipft_sz == sizeof(u_long))
   7156 				tu.ipft_vlong = *ta->ipft_plong;
   7157 			else if (ta->ipft_sz == sizeof(u_int))
   7158 				tu.ipft_vint = *ta->ipft_pint;
   7159 			else if (ta->ipft_sz == sizeof(u_short))
   7160 				tu.ipft_vshort = *ta->ipft_pshort;
   7161 			else if (ta->ipft_sz == sizeof(u_char))
   7162 				tu.ipft_vchar = *ta->ipft_pchar;
   7163 			tu.ipft_cookie = ta;
   7164 			tu.ipft_sz = ta->ipft_sz;
   7165 			tu.ipft_min = ta->ipft_min;
   7166 			tu.ipft_max = ta->ipft_max;
   7167 			tu.ipft_flags = ta->ipft_flags;
   7168 			error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
   7169 
   7170 		} else if (cmd == (ioctlcmd_t)SIOCIPFSET) {
   7171 			/*
   7172 			 * Set an internal parameter.  The hard part here is
   7173 			 * getting the new value safely and correctly out of
   7174 			 * the kernel (given we only know its size, not type.)
   7175 			 */
   7176 			u_long in;
   7177 
   7178 			if (((ta->ipft_flags & IPFT_WRDISABLED) != 0) &&
   7179 			    (softc->ipf_running > 0)) {
   7180 				IPFERROR(78);
   7181 				error = EBUSY;
   7182 				break;
   7183 			}
   7184 
   7185 			in = tu.ipft_vlong;
   7186 			if (in < ta->ipft_min || in > ta->ipft_max) {
   7187 				IPFERROR(79);
   7188 				error = EINVAL;
   7189 				break;
   7190 			}
   7191 
   7192 			if (ta->ipft_func != NULL) {
   7193 				SPL_INT(s);
   7194 
   7195 				SPL_NET(s);
   7196 				error = (*ta->ipft_func)(softc, ta,
   7197 							 &tu.ipft_un);
   7198 				SPL_X(s);
   7199 
   7200 			} else if (ta->ipft_sz == sizeof(u_long)) {
   7201 				tu.ipft_vlong = *ta->ipft_plong;
   7202 				*ta->ipft_plong = in;
   7203 
   7204 			} else if (ta->ipft_sz == sizeof(u_int)) {
   7205 				tu.ipft_vint = *ta->ipft_pint;
   7206 				*ta->ipft_pint = (u_int)(in & 0xffffffff);
   7207 
   7208 			} else if (ta->ipft_sz == sizeof(u_short)) {
   7209 				tu.ipft_vshort = *ta->ipft_pshort;
   7210 				*ta->ipft_pshort = (u_short)(in & 0xffff);
   7211 
   7212 			} else if (ta->ipft_sz == sizeof(u_char)) {
   7213 				tu.ipft_vchar = *ta->ipft_pchar;
   7214 				*ta->ipft_pchar = (u_char)(in & 0xff);
   7215 			}
   7216 			error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
   7217 		}
   7218 		break;
   7219 
   7220 	default :
   7221 		IPFERROR(80);
   7222 		error = EINVAL;
   7223 		break;
   7224 	}
   7225 
   7226 	return error;
   7227 }
   7228 
   7229 
   7230 /* ------------------------------------------------------------------------ */
   7231 /* Function:    ipf_zerostats                                               */
   7232 /* Returns:     int - 0 = success, else failure                             */
   7233 /* Parameters:  data(O) - pointer to pointer for copying data back to       */
   7234 /*                                                                          */
   7235 /* Copies the current statistics out to userspace and then zero's the       */
   7236 /* current ones in the kernel. The lock is only held across the bzero() as  */
   7237 /* the copyout may result in paging (ie network activity.)                  */
   7238 /* ------------------------------------------------------------------------ */
   7239 int
   7240 ipf_zerostats(ipf_main_softc_t *softc, void *data)
   7241 {
   7242 	friostat_t fio;
   7243 	ipfobj_t obj;
   7244 	int error;
   7245 
   7246 	error = ipf_inobj(softc, data, &obj, &fio, IPFOBJ_IPFSTAT);
   7247 	if (error != 0)
   7248 		return error;
   7249 	ipf_getstat(softc, &fio, obj.ipfo_rev);
   7250 	error = ipf_outobj(softc, data, &fio, IPFOBJ_IPFSTAT);
   7251 	if (error != 0)
   7252 		return error;
   7253 
   7254 	WRITE_ENTER(&softc->ipf_mutex);
   7255 	bzero(&softc->ipf_stats, sizeof(softc->ipf_stats));
   7256 	RWLOCK_EXIT(&softc->ipf_mutex);
   7257 
   7258 	return 0;
   7259 }
   7260 
   7261 
   7262 /* ------------------------------------------------------------------------ */
   7263 /* Function:    ipf_resolvedest                                             */
   7264 /* Returns:     Nil                                                         */
   7265 /* Parameters:  softc(I) - pointer to soft context main structure           */
   7266 /*              base(I)  - where strings are stored                         */
   7267 /*              fdp(IO)  - pointer to destination information to resolve    */
   7268 /*              v(I)     - IP protocol version to match                     */
   7269 /*                                                                          */
   7270 /* Looks up an interface name in the frdest structure pointed to by fdp and */
   7271 /* if a matching name can be found for the particular IP protocol version   */
   7272 /* then store the interface pointer in the frdest struct.  If no match is   */
   7273 /* found, then set the interface pointer to be -1 as NULL is considered to  */
   7274 /* indicate there is no information at all in the structure.                */
   7275 /* ------------------------------------------------------------------------ */
   7276 int
   7277 ipf_resolvedest(ipf_main_softc_t *softc, char *base, frdest_t *fdp, int v)
   7278 {
   7279 	int errval = 0;
   7280 	void *ifp;
   7281 
   7282 	ifp = NULL;
   7283 
   7284 	if (fdp->fd_name != -1) {
   7285 		if (fdp->fd_type == FRD_DSTLIST) {
   7286 			ifp = ipf_lookup_res_name(softc, IPL_LOGIPF,
   7287 						  IPLT_DSTLIST,
   7288 						  base + fdp->fd_name,
   7289 						  NULL);
   7290 			if (ifp == NULL) {
   7291 				IPFERROR(144);
   7292 				errval = ESRCH;
   7293 			}
   7294 		} else {
   7295 			ifp = GETIFP(base + fdp->fd_name, v);
   7296 		}
   7297 	}
   7298 	fdp->fd_ptr = ifp;
   7299 
   7300 	return errval;
   7301 }
   7302 
   7303 
   7304 /* ------------------------------------------------------------------------ */
   7305 /* Function:    ipf_resolvenic                                              */
   7306 /* Returns:     void* - NULL = wildcard name, -1 = failed to find NIC, else */
   7307 /*                      pointer to interface structure for NIC              */
   7308 /* Parameters:  softc(I)- pointer to soft context main structure            */
   7309 /*              name(I) - complete interface name                           */
   7310 /*              v(I)    - IP protocol version                               */
   7311 /*                                                                          */
   7312 /* Look for a network interface structure that firstly has a matching name  */
   7313 /* to that passed in and that is also being used for that IP protocol       */
   7314 /* version (necessary on some platforms where there are separate listings   */
   7315 /* for both IPv4 and IPv6 on the same physical NIC.                         */
   7316 /*                                                                          */
   7317 /* ------------------------------------------------------------------------ */
   7318 void *
   7319 ipf_resolvenic(ipf_main_softc_t *softc, char *name, int v)
   7320 {
   7321 	void *nic;
   7322 
   7323 	softc = softc;	/* gcc -Wextra */
   7324 	if (name[0] == '\0')
   7325 		return NULL;
   7326 
   7327 	if ((name[1] == '\0') && ((name[0] == '-') || (name[0] == '*'))) {
   7328 		return NULL;
   7329 	}
   7330 
   7331 	nic = GETIFP(name, v);
   7332 	if (nic == NULL)
   7333 		nic = (void *)-1;
   7334 	return nic;
   7335 }
   7336 
   7337 
   7338 /* ------------------------------------------------------------------------ */
   7339 /* Function:    ipf_token_expire                                            */
   7340 /* Returns:     None.                                                       */
   7341 /* Parameters:  softc(I) - pointer to soft context main structure           */
   7342 /*                                                                          */
   7343 /* This function is run every ipf tick to see if there are any tokens that  */
   7344 /* have been held for too long and need to be freed up.                     */
   7345 /* ------------------------------------------------------------------------ */
   7346 void
   7347 ipf_token_expire(ipf_main_softc_t *softc)
   7348 {
   7349 	ipftoken_t *it;
   7350 
   7351 	WRITE_ENTER(&softc->ipf_tokens);
   7352 	while ((it = softc->ipf_token_head) != NULL) {
   7353 		if (it->ipt_die > softc->ipf_ticks)
   7354 			break;
   7355 
   7356 		ipf_token_deref(softc, it);
   7357 	}
   7358 	RWLOCK_EXIT(&softc->ipf_tokens);
   7359 }
   7360 
   7361 
   7362 /* ------------------------------------------------------------------------ */
   7363 /* Function:    ipf_token_flush                                             */
   7364 /* Returns:     None.                                                       */
   7365 /* Parameters:  softc(I) - pointer to soft context main structure           */
   7366 /*                                                                          */
   7367 /* Loop through all of the existing tokens and call deref to see if they    */
   7368 /* can be freed. Normally a function like this might just loop on           */
   7369 /* ipf_token_head but there is a chance that a token might have a ref count */
   7370 /* of greater than one and in that case the the reference would drop twice  */
   7371 /* by code that is only entitled to drop it once.                           */
   7372 /* ------------------------------------------------------------------------ */
   7373 static void
   7374 ipf_token_flush(ipf_main_softc_t *softc)
   7375 {
   7376 	ipftoken_t *it, *next;
   7377 
   7378 	WRITE_ENTER(&softc->ipf_tokens);
   7379 	for (it = softc->ipf_token_head; it != NULL; it = next) {
   7380 		next = it->ipt_next;
   7381 		(void) ipf_token_deref(softc, it);
   7382 	}
   7383 	RWLOCK_EXIT(&softc->ipf_tokens);
   7384 }
   7385 
   7386 
   7387 /* ------------------------------------------------------------------------ */
   7388 /* Function:    ipf_token_del                                               */
   7389 /* Returns:     int     - 0 = success, else error                           */
   7390 /* Parameters:  softc(I)- pointer to soft context main structure            */
   7391 /*              type(I) - the token type to match                           */
   7392 /*              uid(I)  - uid owning the token                              */
   7393 /*              ptr(I)  - context pointer for the token                     */
   7394 /*                                                                          */
   7395 /* This function looks for a a token in the current list that matches up    */
   7396 /* the fields (type, uid, ptr).  If none is found, ESRCH is returned, else  */
   7397 /* call ipf_token_dewref() to remove it from the list. In the event that    */
   7398 /* the token has a reference held elsewhere, setting ipt_complete to 2      */
   7399 /* enables debugging to distinguish between the two paths that ultimately   */
   7400 /* lead to a token to be deleted.                                           */
   7401 /* ------------------------------------------------------------------------ */
   7402 int
   7403 ipf_token_del(ipf_main_softc_t *softc, int type, int uid, void *ptr)
   7404 {
   7405 	ipftoken_t *it;
   7406 	int error;
   7407 
   7408 	IPFERROR(82);
   7409 	error = ESRCH;
   7410 
   7411 	WRITE_ENTER(&softc->ipf_tokens);
   7412 	for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
   7413 		if (ptr == it->ipt_ctx && type == it->ipt_type &&
   7414 		    uid == it->ipt_uid) {
   7415 			it->ipt_complete = 2;
   7416 			ipf_token_deref(softc, it);
   7417 			error = 0;
   7418 			break;
   7419 		}
   7420 	}
   7421 	RWLOCK_EXIT(&softc->ipf_tokens);
   7422 
   7423 	return error;
   7424 }
   7425 
   7426 
   7427 /* ------------------------------------------------------------------------ */
   7428 /* Function:    ipf_token_mark_complete                                     */
   7429 /* Returns:     None.                                                       */
   7430 /* Parameters:  token(I) - pointer to token structure                       */
   7431 /*                                                                          */
   7432 /* Mark a token as being ineligable for being found with ipf_token_find.    */
   7433 /* ------------------------------------------------------------------------ */
   7434 void
   7435 ipf_token_mark_complete(ipftoken_t *token)
   7436 {
   7437 	if (token->ipt_complete == 0)
   7438 		token->ipt_complete = 1;
   7439 }
   7440 
   7441 
   7442 /* ------------------------------------------------------------------------ */
   7443 /* Function:    ipf_token_find                                               */
   7444 /* Returns:     ipftoken_t * - NULL if no memory, else pointer to token     */
   7445 /* Parameters:  softc(I)- pointer to soft context main structure            */
   7446 /*              type(I) - the token type to match                           */
   7447 /*              uid(I)  - uid owning the token                              */
   7448 /*              ptr(I)  - context pointer for the token                     */
   7449 /*                                                                          */
   7450 /* This function looks for a live token in the list of current tokens that  */
   7451 /* matches the tuple (type, uid, ptr).  If one cannot be found then one is  */
   7452 /* allocated.  If one is found then it is moved to the top of the list of   */
   7453 /* currently active tokens.                                                 */
   7454 /* ------------------------------------------------------------------------ */
   7455 ipftoken_t *
   7456 ipf_token_find(ipf_main_softc_t *softc, int type, int uid, void *ptr)
   7457 {
   7458 	ipftoken_t *it, *new;
   7459 
   7460 	KMALLOC(new, ipftoken_t *);
   7461 	if (new != NULL)
   7462 		bzero((char *)new, sizeof(*new));
   7463 
   7464 	WRITE_ENTER(&softc->ipf_tokens);
   7465 	for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
   7466 		if ((ptr == it->ipt_ctx) && (type == it->ipt_type) &&
   7467 		    (uid == it->ipt_uid) && (it->ipt_complete < 2))
   7468 			break;
   7469 	}
   7470 
   7471 	if (it == NULL) {
   7472 		it = new;
   7473 		new = NULL;
   7474 		if (it == NULL) {
   7475 			RWLOCK_EXIT(&softc->ipf_tokens);
   7476 			return NULL;
   7477 		}
   7478 		it->ipt_ctx = ptr;
   7479 		it->ipt_uid = uid;
   7480 		it->ipt_type = type;
   7481 		it->ipt_ref = 1;
   7482 	} else {
   7483 		if (new != NULL) {
   7484 			KFREE(new);
   7485 			new = NULL;
   7486 		}
   7487 
   7488 		if (it->ipt_complete > 0)
   7489 			it = NULL;
   7490 		else
   7491 			ipf_token_unlink(softc, it);
   7492 	}
   7493 
   7494 	if (it != NULL) {
   7495 		it->ipt_pnext = softc->ipf_token_tail;
   7496 		*softc->ipf_token_tail = it;
   7497 		softc->ipf_token_tail = &it->ipt_next;
   7498 		it->ipt_next = NULL;
   7499 		it->ipt_ref++;
   7500 
   7501 		it->ipt_die = softc->ipf_ticks + 20;
   7502 	}
   7503 
   7504 	RWLOCK_EXIT(&softc->ipf_tokens);
   7505 
   7506 	return it;
   7507 }
   7508 
   7509 
   7510 /* ------------------------------------------------------------------------ */
   7511 /* Function:    ipf_token_unlink                                            */
   7512 /* Returns:     None.                                                       */
   7513 /* Parameters:  softc(I) - pointer to soft context main structure           */
   7514 /*              token(I) - pointer to token structure                       */
   7515 /* Write Locks: ipf_tokens                                                  */
   7516 /*                                                                          */
   7517 /* This function unlinks a token structure from the linked list of tokens   */
   7518 /* that "own" it.  The head pointer never needs to be explicitly adjusted   */
   7519 /* but the tail does due to the linked list implementation.                 */
   7520 /* ------------------------------------------------------------------------ */
   7521 static void
   7522 ipf_token_unlink(ipf_main_softc_t *softc, ipftoken_t *token)
   7523 {
   7524 
   7525 	if (softc->ipf_token_tail == &token->ipt_next)
   7526 		softc->ipf_token_tail = token->ipt_pnext;
   7527 
   7528 	*token->ipt_pnext = token->ipt_next;
   7529 	if (token->ipt_next != NULL)
   7530 		token->ipt_next->ipt_pnext = token->ipt_pnext;
   7531 	token->ipt_next = NULL;
   7532 	token->ipt_pnext = NULL;
   7533 }
   7534 
   7535 
   7536 /* ------------------------------------------------------------------------ */
   7537 /* Function:    ipf_token_deref                                             */
   7538 /* Returns:     int      - 0 == token freed, else reference count           */
   7539 /* Parameters:  softc(I) - pointer to soft context main structure           */
   7540 /*              token(I) - pointer to token structure                       */
   7541 /* Write Locks: ipf_tokens                                                  */
   7542 /*                                                                          */
   7543 /* Drop the reference count on the token structure and if it drops to zero, */
   7544 /* call the dereference function for the token type because it is then      */
   7545 /* possible to free the token data structure.                               */
   7546 /* ------------------------------------------------------------------------ */
   7547 int
   7548 ipf_token_deref(ipf_main_softc_t *softc, ipftoken_t *token)
   7549 {
   7550 	void *data, **datap;
   7551 
   7552 	ASSERT(token->ipt_ref > 0);
   7553 	token->ipt_ref--;
   7554 	if (token->ipt_ref > 0)
   7555 		return token->ipt_ref;
   7556 
   7557 	data = token->ipt_data;
   7558 	datap = &data;
   7559 
   7560 	if ((data != NULL) && (data != (void *)-1)) {
   7561 		switch (token->ipt_type)
   7562 		{
   7563 		case IPFGENITER_IPF :
   7564 			(void) ipf_derefrule(softc, (frentry_t **)datap);
   7565 			break;
   7566 		case IPFGENITER_IPNAT :
   7567 			WRITE_ENTER(&softc->ipf_nat);
   7568 			ipf_nat_rule_deref(softc, (ipnat_t **)datap);
   7569 			RWLOCK_EXIT(&softc->ipf_nat);
   7570 			break;
   7571 		case IPFGENITER_NAT :
   7572 			ipf_nat_deref(softc, (nat_t **)datap);
   7573 			break;
   7574 		case IPFGENITER_STATE :
   7575 			ipf_state_deref(softc, (ipstate_t **)datap);
   7576 			break;
   7577 		case IPFGENITER_FRAG :
   7578 			ipf_frag_pkt_deref(softc, (ipfr_t **)datap);
   7579 			break;
   7580 		case IPFGENITER_NATFRAG :
   7581 			ipf_frag_nat_deref(softc, (ipfr_t **)datap);
   7582 			break;
   7583 		case IPFGENITER_HOSTMAP :
   7584 			WRITE_ENTER(&softc->ipf_nat);
   7585 			ipf_nat_hostmapdel(softc, (hostmap_t **)datap);
   7586 			RWLOCK_EXIT(&softc->ipf_nat);
   7587 			break;
   7588 		default :
   7589 			ipf_lookup_iterderef(softc, token->ipt_type, data);
   7590 			break;
   7591 		}
   7592 	}
   7593 
   7594 	ipf_token_unlink(softc, token);
   7595 	KFREE(token);
   7596 	return 0;
   7597 }
   7598 
   7599 
   7600 /* ------------------------------------------------------------------------ */
   7601 /* Function:    ipf_nextrule                                                */
   7602 /* Returns:     frentry_t * - NULL == no more rules, else pointer to next   */
   7603 /* Parameters:  softc(I)    - pointer to soft context main structure        */
   7604 /*              fr(I)       - pointer to filter rule                        */
   7605 /*              out(I)      - 1 == out rules, 0 == input rules              */
   7606 /*                                                                          */
   7607 /* Starting with "fr", find the next rule to visit. This includes visiting  */
   7608 /* the list of rule groups if either fr is NULL (empty list) or it is the   */
   7609 /* last rule in the list. When walking rule lists, it is either input or    */
   7610 /* output rules that are returned, never both.                              */
   7611 /* ------------------------------------------------------------------------ */
   7612 static frentry_t *
   7613 ipf_nextrule(ipf_main_softc_t *softc, int active, int unit,
   7614     frentry_t *fr, int out)
   7615 {
   7616 	frentry_t *next;
   7617 	frgroup_t *fg;
   7618 
   7619 	if (fr != NULL && fr->fr_group != -1) {
   7620 		fg = ipf_findgroup(softc, fr->fr_names + fr->fr_group,
   7621 				   unit, active, NULL);
   7622 		if (fg != NULL)
   7623 			fg = fg->fg_next;
   7624 	} else {
   7625 		fg = softc->ipf_groups[unit][active];
   7626 	}
   7627 
   7628 	while (fg != NULL) {
   7629 		next = fg->fg_start;
   7630 		while (next != NULL) {
   7631 			if (out) {
   7632 				if (next->fr_flags & FR_OUTQUE)
   7633 					return next;
   7634 			} else if (next->fr_flags & FR_INQUE) {
   7635 				return next;
   7636 			}
   7637 			next = next->fr_next;
   7638 		}
   7639 		if (next == NULL)
   7640 			fg = fg->fg_next;
   7641 	}
   7642 
   7643 	return NULL;
   7644 }
   7645 
   7646 /* ------------------------------------------------------------------------ */
   7647 /* Function:    ipf_getnextrule                                             */
   7648 /* Returns:     int - 0 = success, else error                               */
   7649 /* Parameters:  softc(I)- pointer to soft context main structure            */
   7650 /*              t(I)   - pointer to destination information to resolve      */
   7651 /*              ptr(I) - pointer to ipfobj_t to copyin from user space      */
   7652 /*                                                                          */
   7653 /* This function's first job is to bring in the ipfruleiter_t structure via */
   7654 /* the ipfobj_t structure to determine what should be the next rule to      */
   7655 /* return. Once the ipfruleiter_t has been brought in, it then tries to     */
   7656 /* find the 'next rule'.  This may include searching rule group lists or    */
   7657 /* just be as simple as looking at the 'next' field in the rule structure.  */
   7658 /* When we have found the rule to return, increase its reference count and  */
   7659 /* if we used an existing rule to get here, decrease its reference count.   */
   7660 /* ------------------------------------------------------------------------ */
   7661 int
   7662 ipf_getnextrule(ipf_main_softc_t *softc, ipftoken_t *t, void *ptr)
   7663 {
   7664 	frentry_t *fr, *next, zero;
   7665 	ipfruleiter_t it;
   7666 	int error, out;
   7667 	frgroup_t *fg;
   7668 	ipfobj_t obj;
   7669 	int predict;
   7670 	char *dst;
   7671 	int unit;
   7672 
   7673 	if (t == NULL || ptr == NULL) {
   7674 		IPFERROR(84);
   7675 		return EFAULT;
   7676 	}
   7677 
   7678 	error = ipf_inobj(softc, ptr, &obj, &it, IPFOBJ_IPFITER);
   7679 	if (error != 0)
   7680 		return error;
   7681 
   7682 	if ((it.iri_inout < 0) || (it.iri_inout > 3)) {
   7683 		IPFERROR(85);
   7684 		return EINVAL;
   7685 	}
   7686 	if ((it.iri_active != 0) && (it.iri_active != 1)) {
   7687 		IPFERROR(86);
   7688 		return EINVAL;
   7689 	}
   7690 	if (it.iri_nrules == 0) {
   7691 		IPFERROR(87);
   7692 		return ENOSPC;
   7693 	}
   7694 	if (it.iri_rule == NULL) {
   7695 		IPFERROR(88);
   7696 		return EFAULT;
   7697 	}
   7698 
   7699 	fg = NULL;
   7700 	fr = t->ipt_data;
   7701 	if ((it.iri_inout & F_OUT) != 0)
   7702 		out = 1;
   7703 	else
   7704 		out = 0;
   7705 	if ((it.iri_inout & F_ACIN) != 0)
   7706 		unit = IPL_LOGCOUNT;
   7707 	else
   7708 		unit = IPL_LOGIPF;
   7709 
   7710 	READ_ENTER(&softc->ipf_mutex);
   7711 	if (fr == NULL) {
   7712 		if (*it.iri_group == '\0') {
   7713 			if (unit == IPL_LOGCOUNT) {
   7714 				next = softc->ipf_acct[out][it.iri_active];
   7715 			} else {
   7716 				next = softc->ipf_rules[out][it.iri_active];
   7717 			}
   7718 			if (next == NULL)
   7719 				next = ipf_nextrule(softc, it.iri_active,
   7720 						    unit, NULL, out);
   7721 		} else {
   7722 			fg = ipf_findgroup(softc, it.iri_group, unit,
   7723 					   it.iri_active, NULL);
   7724 			if (fg != NULL)
   7725 				next = fg->fg_start;
   7726 			else
   7727 				next = NULL;
   7728 		}
   7729 	} else {
   7730 		next = fr->fr_next;
   7731 		if (next == NULL)
   7732 			next = ipf_nextrule(softc, it.iri_active, unit,
   7733 					    fr, out);
   7734 	}
   7735 
   7736 	if (next != NULL && next->fr_next != NULL)
   7737 		predict = 1;
   7738 	else if (ipf_nextrule(softc, it.iri_active, unit, next, out) != NULL)
   7739 		predict = 1;
   7740 	else
   7741 		predict = 0;
   7742 
   7743 	if (fr != NULL)
   7744 		(void) ipf_derefrule(softc, &fr);
   7745 
   7746 	obj.ipfo_type = IPFOBJ_FRENTRY;
   7747 	dst = (char *)it.iri_rule;
   7748 
   7749 	if (next != NULL) {
   7750 		obj.ipfo_size = next->fr_size;
   7751 		MUTEX_ENTER(&next->fr_lock);
   7752 		next->fr_ref++;
   7753 		MUTEX_EXIT(&next->fr_lock);
   7754 		t->ipt_data = next;
   7755 	} else {
   7756 		obj.ipfo_size = sizeof(frentry_t);
   7757 		bzero(&zero, sizeof(zero));
   7758 		next = &zero;
   7759 		t->ipt_data = NULL;
   7760 	}
   7761 	it.iri_rule = predict ? next : NULL;
   7762 	if (predict == 0)
   7763 		ipf_token_mark_complete(t);
   7764 
   7765 	RWLOCK_EXIT(&softc->ipf_mutex);
   7766 
   7767 	obj.ipfo_ptr = dst;
   7768 	error = ipf_outobjk(softc, &obj, next);
   7769 	if (error == 0 && t->ipt_data != NULL) {
   7770 		dst += obj.ipfo_size;
   7771 		if (next->fr_data != NULL) {
   7772 			ipfobj_t dobj;
   7773 
   7774 			if (next->fr_type == FR_T_IPFEXPR)
   7775 				dobj.ipfo_type = IPFOBJ_IPFEXPR;
   7776 			else
   7777 				dobj.ipfo_type = IPFOBJ_FRIPF;
   7778 			dobj.ipfo_size = next->fr_dsize;
   7779 			dobj.ipfo_rev = obj.ipfo_rev;
   7780 			dobj.ipfo_ptr = dst;
   7781 			error = ipf_outobjk(softc, &dobj, next->fr_data);
   7782 		}
   7783 	}
   7784 
   7785 	if ((fr != NULL) && (next == &zero))
   7786 		(void) ipf_derefrule(softc, &fr);
   7787 
   7788 	return error;
   7789 }
   7790 
   7791 
   7792 /* ------------------------------------------------------------------------ */
   7793 /* Function:    ipf_frruleiter                                              */
   7794 /* Returns:     int - 0 = success, else error                               */
   7795 /* Parameters:  softc(I)- pointer to soft context main structure            */
   7796 /*              data(I) - the token type to match                           */
   7797 /*              uid(I)  - uid owning the token                              */
   7798 /*              ptr(I)  - context pointer for the token                     */
   7799 /*                                                                          */
   7800 /* This function serves as a stepping stone between ipf_ipf_ioctl and       */
   7801 /* ipf_getnextrule.  It's role is to find the right token in the kernel for */
   7802 /* the process doing the ioctl and use that to ask for the next rule.       */
   7803 /* ------------------------------------------------------------------------ */
   7804 static int
   7805 ipf_frruleiter(ipf_main_softc_t *softc, void *data, int uid, void *ctx)
   7806 {
   7807 	ipftoken_t *token;
   7808 	ipfruleiter_t it;
   7809 	ipfobj_t obj;
   7810 	int error;
   7811 
   7812 	token = ipf_token_find(softc, IPFGENITER_IPF, uid, ctx);
   7813 	if (token != NULL) {
   7814 		error = ipf_getnextrule(softc, token, data);
   7815 		WRITE_ENTER(&softc->ipf_tokens);
   7816 		ipf_token_deref(softc, token);
   7817 		RWLOCK_EXIT(&softc->ipf_tokens);
   7818 	} else {
   7819 		error = ipf_inobj(softc, data, &obj, &it, IPFOBJ_IPFITER);
   7820 		if (error != 0)
   7821 			return error;
   7822 		it.iri_rule = NULL;
   7823 		error = ipf_outobj(softc, data, &it, IPFOBJ_IPFITER);
   7824 	}
   7825 
   7826 	return error;
   7827 }
   7828 
   7829 
   7830 /* ------------------------------------------------------------------------ */
   7831 /* Function:    ipf_geniter                                                 */
   7832 /* Returns:     int - 0 = success, else error                               */
   7833 /* Parameters:  softc(I) - pointer to soft context main structure           */
   7834 /*              token(I) - pointer to ipftoken_t structure                  */
   7835 /*              itp(I)   - pointer to iterator data                         */
   7836 /*                                                                          */
   7837 /* Decide which iterator function to call using information passed through  */
   7838 /* the ipfgeniter_t structure at itp.                                       */
   7839 /* ------------------------------------------------------------------------ */
   7840 static int
   7841 ipf_geniter(ipf_main_softc_t *softc, ipftoken_t *token, ipfgeniter_t *itp)
   7842 {
   7843 	int error;
   7844 
   7845 	switch (itp->igi_type)
   7846 	{
   7847 	case IPFGENITER_FRAG :
   7848 		error = ipf_frag_pkt_next(softc, token, itp);
   7849 		break;
   7850 	default :
   7851 		IPFERROR(92);
   7852 		error = EINVAL;
   7853 		break;
   7854 	}
   7855 
   7856 	return error;
   7857 }
   7858 
   7859 
   7860 /* ------------------------------------------------------------------------ */
   7861 /* Function:    ipf_genericiter                                             */
   7862 /* Returns:     int - 0 = success, else error                               */
   7863 /* Parameters:  softc(I)- pointer to soft context main structure            */
   7864 /*              data(I) - the token type to match                           */
   7865 /*              uid(I)  - uid owning the token                              */
   7866 /*              ptr(I)  - context pointer for the token                     */
   7867 /*                                                                          */
   7868 /* Handle the SIOCGENITER ioctl for the ipfilter device. The primary role   */
   7869 /* ------------------------------------------------------------------------ */
   7870 int
   7871 ipf_genericiter(ipf_main_softc_t *softc, void *data, int uid, void *ctx)
   7872 {
   7873 	ipftoken_t *token;
   7874 	ipfgeniter_t iter;
   7875 	int error;
   7876 
   7877 	error = ipf_inobj(softc, data, NULL, &iter, IPFOBJ_GENITER);
   7878 	if (error != 0)
   7879 		return error;
   7880 
   7881 	token = ipf_token_find(softc, iter.igi_type, uid, ctx);
   7882 	if (token != NULL) {
   7883 		token->ipt_subtype = iter.igi_type;
   7884 		error = ipf_geniter(softc, token, &iter);
   7885 		WRITE_ENTER(&softc->ipf_tokens);
   7886 		ipf_token_deref(softc, token);
   7887 		RWLOCK_EXIT(&softc->ipf_tokens);
   7888 	} else {
   7889 		IPFERROR(93);
   7890 		error = 0;
   7891 	}
   7892 
   7893 	return error;
   7894 }
   7895 
   7896 
   7897 /* ------------------------------------------------------------------------ */
   7898 /* Function:    ipf_ipf_ioctl                                               */
   7899 /* Returns:     int - 0 = success, else error                               */
   7900 /* Parameters:  softc(I)- pointer to soft context main structure           */
   7901 /*              data(I) - the token type to match                           */
   7902 /*              cmd(I)  - the ioctl command number                          */
   7903 /*              mode(I) - mode flags for the ioctl                          */
   7904 /*              uid(I)  - uid owning the token                              */
   7905 /*              ptr(I)  - context pointer for the token                     */
   7906 /*                                                                          */
   7907 /* This function handles all of the ioctl command that are actually isssued */
   7908 /* to the /dev/ipl device.                                                  */
   7909 /* ------------------------------------------------------------------------ */
   7910 int
   7911 ipf_ipf_ioctl(ipf_main_softc_t *softc, void *data, ioctlcmd_t cmd, int mode,
   7912     int uid, void *ctx)
   7913 {
   7914 	friostat_t fio;
   7915 	int error, tmp;
   7916 	ipfobj_t obj;
   7917 	SPL_INT(s);
   7918 
   7919 	switch (cmd)
   7920 	{
   7921 	case SIOCFRENB :
   7922 		if (!(mode & FWRITE)) {
   7923 			IPFERROR(94);
   7924 			error = EPERM;
   7925 		} else {
   7926 			error = BCOPYIN(data, &tmp, sizeof(tmp));
   7927 			if (error != 0) {
   7928 				IPFERROR(95);
   7929 				error = EFAULT;
   7930 				break;
   7931 			}
   7932 
   7933 			WRITE_ENTER(&softc->ipf_global);
   7934 			if (tmp) {
   7935 				if (softc->ipf_running > 0)
   7936 					error = 0;
   7937 				else
   7938 					error = ipfattach(softc);
   7939 				if (error == 0)
   7940 					softc->ipf_running = 1;
   7941 				else
   7942 					(void) ipfdetach(softc);
   7943 			} else {
   7944 				if (softc->ipf_running == 1)
   7945 					error = ipfdetach(softc);
   7946 				else
   7947 					error = 0;
   7948 				if (error == 0)
   7949 					softc->ipf_running = -1;
   7950 			}
   7951 			RWLOCK_EXIT(&softc->ipf_global);
   7952 		}
   7953 		break;
   7954 
   7955 	case SIOCIPFSET :
   7956 		if (!(mode & FWRITE)) {
   7957 			IPFERROR(96);
   7958 			error = EPERM;
   7959 			break;
   7960 		}
   7961 		/* FALLTHRU */
   7962 	case SIOCIPFGETNEXT :
   7963 	case SIOCIPFGET :
   7964 		error = ipf_ipftune(softc, cmd, (void *)data);
   7965 		break;
   7966 
   7967 	case SIOCSETFF :
   7968 		if (!(mode & FWRITE)) {
   7969 			IPFERROR(97);
   7970 			error = EPERM;
   7971 		} else {
   7972 			error = BCOPYIN(data, &softc->ipf_flags,
   7973 					sizeof(softc->ipf_flags));
   7974 			if (error != 0) {
   7975 				IPFERROR(98);
   7976 				error = EFAULT;
   7977 			}
   7978 		}
   7979 		break;
   7980 
   7981 	case SIOCGETFF :
   7982 		error = BCOPYOUT(&softc->ipf_flags, data,
   7983 				 sizeof(softc->ipf_flags));
   7984 		if (error != 0) {
   7985 			IPFERROR(99);
   7986 			error = EFAULT;
   7987 		}
   7988 		break;
   7989 
   7990 	case SIOCFUNCL :
   7991 		error = ipf_resolvefunc(softc, (void *)data);
   7992 		break;
   7993 
   7994 	case SIOCINAFR :
   7995 	case SIOCRMAFR :
   7996 	case SIOCADAFR :
   7997 	case SIOCZRLST :
   7998 		if (!(mode & FWRITE)) {
   7999 			IPFERROR(100);
   8000 			error = EPERM;
   8001 		} else {
   8002 			error = frrequest(softc, IPL_LOGIPF, cmd, data,
   8003 					  softc->ipf_active, 1);
   8004 		}
   8005 		break;
   8006 
   8007 	case SIOCINIFR :
   8008 	case SIOCRMIFR :
   8009 	case SIOCADIFR :
   8010 		if (!(mode & FWRITE)) {
   8011 			IPFERROR(101);
   8012 			error = EPERM;
   8013 		} else {
   8014 			error = frrequest(softc, IPL_LOGIPF, cmd, data,
   8015 					  1 - softc->ipf_active, 1);
   8016 		}
   8017 		break;
   8018 
   8019 	case SIOCSWAPA :
   8020 		if (!(mode & FWRITE)) {
   8021 			IPFERROR(102);
   8022 			error = EPERM;
   8023 		} else {
   8024 			WRITE_ENTER(&softc->ipf_mutex);
   8025 			error = BCOPYOUT(&softc->ipf_active, data,
   8026 					 sizeof(softc->ipf_active));
   8027 			if (error != 0) {
   8028 				IPFERROR(103);
   8029 				error = EFAULT;
   8030 			} else {
   8031 				softc->ipf_active = 1 - softc->ipf_active;
   8032 			}
   8033 			RWLOCK_EXIT(&softc->ipf_mutex);
   8034 		}
   8035 		break;
   8036 
   8037 	case SIOCGETFS :
   8038 		error = ipf_inobj(softc, (void *)data, &obj, &fio,
   8039 				  IPFOBJ_IPFSTAT);
   8040 		if (error != 0)
   8041 			break;
   8042 		ipf_getstat(softc, &fio, obj.ipfo_rev);
   8043 		error = ipf_outobj(softc, (void *)data, &fio, IPFOBJ_IPFSTAT);
   8044 		break;
   8045 
   8046 	case SIOCFRZST :
   8047 		if (!(mode & FWRITE)) {
   8048 			IPFERROR(104);
   8049 			error = EPERM;
   8050 		} else
   8051 			error = ipf_zerostats(softc, data);
   8052 		break;
   8053 
   8054 	case SIOCIPFFL :
   8055 		if (!(mode & FWRITE)) {
   8056 			IPFERROR(105);
   8057 			error = EPERM;
   8058 		} else {
   8059 			error = BCOPYIN(data, &tmp, sizeof(tmp));
   8060 			if (!error) {
   8061 				tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
   8062 				error = BCOPYOUT(&tmp, data, sizeof(tmp));
   8063 				if (error != 0) {
   8064 					IPFERROR(106);
   8065 					error = EFAULT;
   8066 				}
   8067 			} else {
   8068 				IPFERROR(107);
   8069 				error = EFAULT;
   8070 			}
   8071 		}
   8072 		break;
   8073 
   8074 #ifdef USE_INET6
   8075 	case SIOCIPFL6 :
   8076 		if (!(mode & FWRITE)) {
   8077 			IPFERROR(108);
   8078 			error = EPERM;
   8079 		} else {
   8080 			error = BCOPYIN(data, &tmp, sizeof(tmp));
   8081 			if (!error) {
   8082 				tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
   8083 				error = BCOPYOUT(&tmp, data, sizeof(tmp));
   8084 				if (error != 0) {
   8085 					IPFERROR(109);
   8086 					error = EFAULT;
   8087 				}
   8088 			} else {
   8089 				IPFERROR(110);
   8090 				error = EFAULT;
   8091 			}
   8092 		}
   8093 		break;
   8094 #endif
   8095 
   8096 	case SIOCSTLCK :
   8097 		if (!(mode & FWRITE)) {
   8098 			IPFERROR(122);
   8099 			error = EPERM;
   8100 		} else {
   8101 			error = BCOPYIN(data, &tmp, sizeof(tmp));
   8102 			if (error == 0) {
   8103 				ipf_state_setlock(softc->ipf_state_soft, tmp);
   8104 				ipf_nat_setlock(softc->ipf_nat_soft, tmp);
   8105 				ipf_frag_setlock(softc->ipf_frag_soft, tmp);
   8106 				ipf_auth_setlock(softc->ipf_auth_soft, tmp);
   8107 			} else {
   8108 				IPFERROR(111);
   8109 				error = EFAULT;
   8110 			}
   8111 		}
   8112 		break;
   8113 
   8114 #ifdef	IPFILTER_LOG
   8115 	case SIOCIPFFB :
   8116 		if (!(mode & FWRITE)) {
   8117 			IPFERROR(112);
   8118 			error = EPERM;
   8119 		} else {
   8120 			tmp = ipf_log_clear(softc, IPL_LOGIPF);
   8121 			error = BCOPYOUT(&tmp, data, sizeof(tmp));
   8122 			if (error) {
   8123 				IPFERROR(113);
   8124 				error = EFAULT;
   8125 			}
   8126 		}
   8127 		break;
   8128 #endif /* IPFILTER_LOG */
   8129 
   8130 	case SIOCFRSYN :
   8131 		if (!(mode & FWRITE)) {
   8132 			IPFERROR(114);
   8133 			error = EPERM;
   8134 		} else {
   8135 			WRITE_ENTER(&softc->ipf_global);
   8136 #if (defined(MENTAT) && defined(_KERNEL)) && !defined(INSTANCES)
   8137 			error = ipfsync();
   8138 #else
   8139 			ipf_sync(softc, NULL);
   8140 			error = 0;
   8141 #endif
   8142 			RWLOCK_EXIT(&softc->ipf_global);
   8143 
   8144 		}
   8145 		break;
   8146 
   8147 	case SIOCGFRST :
   8148 		error = ipf_outobj(softc, (void *)data,
   8149 				   ipf_frag_stats(softc->ipf_frag_soft),
   8150 				   IPFOBJ_FRAGSTAT);
   8151 		break;
   8152 
   8153 #ifdef	IPFILTER_LOG
   8154 	case FIONREAD :
   8155 		tmp = ipf_log_bytesused(softc, IPL_LOGIPF);
   8156 		error = BCOPYOUT(&tmp, data, sizeof(tmp));
   8157 		break;
   8158 #endif
   8159 
   8160 	case SIOCIPFITER :
   8161 		SPL_SCHED(s);
   8162 		error = ipf_frruleiter(softc, data, uid, ctx);
   8163 		SPL_X(s);
   8164 		break;
   8165 
   8166 	case SIOCGENITER :
   8167 		SPL_SCHED(s);
   8168 		error = ipf_genericiter(softc, data, uid, ctx);
   8169 		SPL_X(s);
   8170 		break;
   8171 
   8172 	case SIOCIPFDELTOK :
   8173 		error = BCOPYIN(data, &tmp, sizeof(tmp));
   8174 		if (error == 0) {
   8175 			SPL_SCHED(s);
   8176 			error = ipf_token_del(softc, tmp, uid, ctx);
   8177 			SPL_X(s);
   8178 		}
   8179 		break;
   8180 
   8181 	default :
   8182 		IPFERROR(115);
   8183 		error = EINVAL;
   8184 		break;
   8185 	}
   8186 
   8187 	return error;
   8188 }
   8189 
   8190 
   8191 /* ------------------------------------------------------------------------ */
   8192 /* Function:    ipf_decaps                                                  */
   8193 /* Returns:     int        - -1 == decapsulation failed, else bit mask of   */
   8194 /*                           flags indicating packet filtering decision.    */
   8195 /* Parameters:  fin(I)     - pointer to packet information                  */
   8196 /*              pass(I)    - IP protocol version to match                   */
   8197 /*              l5proto(I) - layer 5 protocol to decode UDP data as.        */
   8198 /*                                                                          */
   8199 /* This function is called for packets that are wrapt up in other packets,  */
   8200 /* for example, an IP packet that is the entire data segment for another IP */
   8201 /* packet.  If the basic constraints for this are satisfied, change the     */
   8202 /* buffer to point to the start of the inner packet and start processing    */
   8203 /* rules belonging to the head group this rule specifies.                   */
   8204 /* ------------------------------------------------------------------------ */
   8205 u_32_t
   8206 ipf_decaps(fr_info_t *fin, u_32_t pass, int l5proto)
   8207 {
   8208 	fr_info_t fin2, *fino = NULL;
   8209 	int elen, hlen, nh;
   8210 	grehdr_t gre;
   8211 	ip_t *ip;
   8212 	mb_t *m;
   8213 
   8214 	if ((fin->fin_flx & FI_COALESCE) == 0)
   8215 		if (ipf_coalesce(fin) == -1)
   8216 			goto cantdecaps;
   8217 
   8218 	m = fin->fin_m;
   8219 	hlen = fin->fin_hlen;
   8220 
   8221 	switch (fin->fin_p)
   8222 	{
   8223 	case IPPROTO_UDP :
   8224 		/*
   8225 		 * In this case, the specific protocol being decapsulated
   8226 		 * inside UDP frames comes from the rule.
   8227 		 */
   8228 		nh = fin->fin_fr->fr_icode;
   8229 		break;
   8230 
   8231 	case IPPROTO_GRE :	/* 47 */
   8232 		bcopy(fin->fin_dp, (char *)&gre, sizeof(gre));
   8233 		hlen += sizeof(grehdr_t);
   8234 		if (gre.gr_R|gre.gr_s)
   8235 			goto cantdecaps;
   8236 		if (gre.gr_C)
   8237 			hlen += 4;
   8238 		if (gre.gr_K)
   8239 			hlen += 4;
   8240 		if (gre.gr_S)
   8241 			hlen += 4;
   8242 
   8243 		nh = IPPROTO_IP;
   8244 
   8245 		/*
   8246 		 * If the routing options flag is set, validate that it is
   8247 		 * there and bounce over it.
   8248 		 */
   8249 #if 0
   8250 		/* This is really heavy weight and lots of room for error, */
   8251 		/* so for now, put it off and get the simple stuff right.  */
   8252 		if (gre.gr_R) {
   8253 			u_char off, len, *s;
   8254 			u_short af;
   8255 			int end;
   8256 
   8257 			end = 0;
   8258 			s = fin->fin_dp;
   8259 			s += hlen;
   8260 			aplen = fin->fin_plen - hlen;
   8261 			while (aplen > 3) {
   8262 				af = (s[0] << 8) | s[1];
   8263 				off = s[2];
   8264 				len = s[3];
   8265 				aplen -= 4;
   8266 				s += 4;
   8267 				if (af == 0 && len == 0) {
   8268 					end = 1;
   8269 					break;
   8270 				}
   8271 				if (aplen < len)
   8272 					break;
   8273 				s += len;
   8274 				aplen -= len;
   8275 			}
   8276 			if (end != 1)
   8277 				goto cantdecaps;
   8278 			hlen = s - (u_char *)fin->fin_dp;
   8279 		}
   8280 #endif
   8281 		break;
   8282 
   8283 #ifdef IPPROTO_IPIP
   8284 	case IPPROTO_IPIP :	/* 4 */
   8285 #endif
   8286 		nh = IPPROTO_IP;
   8287 		break;
   8288 
   8289 	default :	/* Includes ESP, AH is special for IPv4 */
   8290 		goto cantdecaps;
   8291 	}
   8292 
   8293 	switch (nh)
   8294 	{
   8295 	case IPPROTO_IP :
   8296 	case IPPROTO_IPV6 :
   8297 		break;
   8298 	default :
   8299 		goto cantdecaps;
   8300 	}
   8301 
   8302 	bcopy((char *)fin, (char *)&fin2, sizeof(fin2));
   8303 	fino = fin;
   8304 	fin = &fin2;
   8305 	elen = hlen;
   8306 #if defined(MENTAT) && defined(_KERNEL)
   8307 	m->b_rptr += elen;
   8308 #else
   8309 	m->m_data += elen;
   8310 	m->m_len -= elen;
   8311 #endif
   8312 	fin->fin_plen -= elen;
   8313 
   8314 	ip = (ip_t *)((char *)fin->fin_ip + elen);
   8315 
   8316 	/*
   8317 	 * Make sure we have at least enough data for the network layer
   8318 	 * header.
   8319 	 */
   8320 	if (IP_V(ip) == 4)
   8321 		hlen = IP_HL(ip) << 2;
   8322 #ifdef USE_INET6
   8323 	else if (IP_V(ip) == 6)
   8324 		hlen = sizeof(ip6_t);
   8325 #endif
   8326 	else
   8327 		goto cantdecaps2;
   8328 
   8329 	if (fin->fin_plen < hlen)
   8330 		goto cantdecaps2;
   8331 
   8332 	fin->fin_dp = (char *)ip + hlen;
   8333 
   8334 	if (IP_V(ip) == 4) {
   8335 		/*
   8336 		 * Perform IPv4 header checksum validation.
   8337 		 */
   8338 		if (ipf_cksum((u_short *)ip, hlen))
   8339 			goto cantdecaps2;
   8340 	}
   8341 
   8342 	if (ipf_makefrip(hlen, ip, fin) == -1) {
   8343 cantdecaps2:
   8344 		if (m != NULL) {
   8345 #if defined(MENTAT) && defined(_KERNEL)
   8346 			m->b_rptr -= elen;
   8347 #else
   8348 			m->m_data -= elen;
   8349 			m->m_len += elen;
   8350 #endif
   8351 		}
   8352 cantdecaps:
   8353 		DT1(frb_decapfrip, fr_info_t *, fin);
   8354 		pass &= ~FR_CMDMASK;
   8355 		pass |= FR_BLOCK|FR_QUICK;
   8356 		fin->fin_reason = FRB_DECAPFRIP;
   8357 		return -1;
   8358 	}
   8359 
   8360 	pass = ipf_scanlist(fin, pass);
   8361 
   8362 	/*
   8363 	 * Copy the packet filter "result" fields out of the fr_info_t struct
   8364 	 * that is local to the decapsulation processing and back into the
   8365 	 * one we were called with.
   8366 	 */
   8367 	fino->fin_flx = fin->fin_flx;
   8368 	fino->fin_rev = fin->fin_rev;
   8369 	fino->fin_icode = fin->fin_icode;
   8370 	fino->fin_rule = fin->fin_rule;
   8371 	(void) strncpy(fino->fin_group, fin->fin_group, FR_GROUPLEN);
   8372 	fino->fin_fr = fin->fin_fr;
   8373 	fino->fin_error = fin->fin_error;
   8374 	fino->fin_mp = fin->fin_mp;
   8375 	fino->fin_m = fin->fin_m;
   8376 	m = fin->fin_m;
   8377 	if (m != NULL) {
   8378 #if defined(MENTAT) && defined(_KERNEL)
   8379 		m->b_rptr -= elen;
   8380 #else
   8381 		m->m_data -= elen;
   8382 		m->m_len += elen;
   8383 #endif
   8384 	}
   8385 	return pass;
   8386 }
   8387 
   8388 
   8389 /* ------------------------------------------------------------------------ */
   8390 /* Function:    ipf_matcharray_load                                         */
   8391 /* Returns:     int         - 0 = success, else error                       */
   8392 /* Parameters:  softc(I)    - pointer to soft context main structure        */
   8393 /*              data(I)     - pointer to ioctl data                         */
   8394 /*              objp(I)     - ipfobj_t structure to load data into          */
   8395 /*              arrayptr(I) - pointer to location to store array pointer    */
   8396 /*                                                                          */
   8397 /* This function loads in a mathing array through the ipfobj_t struct that  */
   8398 /* describes it.  Sanity checking and array size limitations are enforced   */
   8399 /* in this function to prevent userspace from trying to load in something   */
   8400 /* that is insanely big.  Once the size of the array is known, the memory   */
   8401 /* required is malloc'd and returned through changing *arrayptr.  The       */
   8402 /* contents of the array are verified before returning.  Only in the event  */
   8403 /* of a successful call is the caller required to free up the malloc area.  */
   8404 /* ------------------------------------------------------------------------ */
   8405 int
   8406 ipf_matcharray_load(ipf_main_softc_t *softc, void *data, ipfobj_t *objp,
   8407     int **arrayptr)
   8408 {
   8409 	int arraysize, *array, error;
   8410 
   8411 	*arrayptr = NULL;
   8412 
   8413 	error = BCOPYIN(data, objp, sizeof(*objp));
   8414 	if (error != 0) {
   8415 		IPFERROR(116);
   8416 		return EFAULT;
   8417 	}
   8418 
   8419 	if (objp->ipfo_type != IPFOBJ_IPFEXPR) {
   8420 		IPFERROR(117);
   8421 		return EINVAL;
   8422 	}
   8423 
   8424 	if (((objp->ipfo_size & 3) != 0) || (objp->ipfo_size == 0) ||
   8425 	    (objp->ipfo_size > 1024)) {
   8426 		IPFERROR(118);
   8427 		return EINVAL;
   8428 	}
   8429 
   8430 	arraysize = objp->ipfo_size * sizeof(*array);
   8431 	KMALLOCS(array, int *, arraysize);
   8432 	if (array == NULL) {
   8433 		IPFERROR(119);
   8434 		return ENOMEM;
   8435 	}
   8436 
   8437 	error = COPYIN(objp->ipfo_ptr, array, arraysize);
   8438 	if (error != 0) {
   8439 		KFREES(array, arraysize);
   8440 		IPFERROR(120);
   8441 		return EFAULT;
   8442 	}
   8443 
   8444 	if (ipf_matcharray_verify(array, arraysize) != 0) {
   8445 		KFREES(array, arraysize);
   8446 		IPFERROR(121);
   8447 		return EINVAL;
   8448 	}
   8449 
   8450 	*arrayptr = array;
   8451 	return 0;
   8452 }
   8453 
   8454 
   8455 /* ------------------------------------------------------------------------ */
   8456 /* Function:    ipf_matcharray_verify                                       */
   8457 /* Returns:     Nil                                                         */
   8458 /* Parameters:  array(I)     - pointer to matching array                    */
   8459 /*              arraysize(I) - number of elements in the array              */
   8460 /*                                                                          */
   8461 /* Verify the contents of a matching array by stepping through each element */
   8462 /* in it.  The actual commands in the array are not verified for            */
   8463 /* correctness, only that all of the sizes are correctly within limits.     */
   8464 /* ------------------------------------------------------------------------ */
   8465 int
   8466 ipf_matcharray_verify(int *array, int arraysize)
   8467 {
   8468 	int i, nelem, maxidx;
   8469 	ipfexp_t *e;
   8470 
   8471 	nelem = arraysize / sizeof(*array);
   8472 
   8473 	/*
   8474 	 * Currently, it makes no sense to have an array less than 6
   8475 	 * elements long - the initial size at the from, a single operation
   8476 	 * (minimum 4 in length) and a trailer, for a total of 6.
   8477 	 */
   8478 	if ((array[0] < 6) || (arraysize < 24) || (arraysize > 4096)) {
   8479 		return -1;
   8480 	}
   8481 
   8482 	/*
   8483 	 * Verify the size of data pointed to by array with how long
   8484 	 * the array claims to be itself.
   8485 	 */
   8486 	if (array[0] * sizeof(*array) != arraysize) {
   8487 		return -1;
   8488 	}
   8489 
   8490 	maxidx = nelem - 1;
   8491 	/*
   8492 	 * The last opcode in this array should be an IPF_EXP_END.
   8493 	 */
   8494 	if (array[maxidx] != IPF_EXP_END) {
   8495 		return -1;
   8496 	}
   8497 
   8498 	for (i = 1; i < maxidx; ) {
   8499 		e = (ipfexp_t *)(array + i);
   8500 
   8501 		/*
   8502 		 * The length of the bits to check must be at least 1
   8503 		 * (or else there is nothing to comapre with!) and it
   8504 		 * cannot exceed the length of the data present.
   8505 		 */
   8506 		if ((e->ipfe_size < 1 ) ||
   8507 		    (e->ipfe_size + i > maxidx)) {
   8508 			return -1;
   8509 		}
   8510 		i += e->ipfe_size;
   8511 	}
   8512 	return 0;
   8513 }
   8514 
   8515 
   8516 /* ------------------------------------------------------------------------ */
   8517 /* Function:    ipf_fr_matcharray                                           */
   8518 /* Returns:     int      - 0 = match failed, else positive match            */
   8519 /* Parameters:  fin(I)   - pointer to packet information                    */
   8520 /*              array(I) - pointer to matching array                        */
   8521 /*                                                                          */
   8522 /* This function is used to apply a matching array against a packet and     */
   8523 /* return an indication of whether or not the packet successfully matches   */
   8524 /* all of the commands in it.                                               */
   8525 /* ------------------------------------------------------------------------ */
   8526 static int
   8527 ipf_fr_matcharray(fr_info_t *fin, int *array)
   8528 {
   8529 	int i, n, *x, rv, p;
   8530 	ipfexp_t *e;
   8531 
   8532 	rv = 0;
   8533 	n = array[0];
   8534 	x = array + 1;
   8535 
   8536 	for (; n > 0; x += 3 + x[3], rv = 0) {
   8537 		e = (ipfexp_t *)x;
   8538 		if (e->ipfe_cmd == IPF_EXP_END)
   8539 			break;
   8540 		n -= e->ipfe_size;
   8541 
   8542 		/*
   8543 		 * The upper 16 bits currently store the protocol value.
   8544 		 * This is currently used with TCP and UDP port compares and
   8545 		 * allows "tcp.port = 80" without requiring an explicit
   8546 		 " "ip.pr = tcp" first.
   8547 		 */
   8548 		p = e->ipfe_cmd >> 16;
   8549 		if ((p != 0) && (p != fin->fin_p))
   8550 			break;
   8551 
   8552 		switch (e->ipfe_cmd)
   8553 		{
   8554 		case IPF_EXP_IP_PR :
   8555 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
   8556 				rv |= (fin->fin_p == e->ipfe_arg0[i]);
   8557 			}
   8558 			break;
   8559 
   8560 		case IPF_EXP_IP_SRCADDR :
   8561 			if (fin->fin_v != 4)
   8562 				break;
   8563 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
   8564 				rv |= ((fin->fin_saddr &
   8565 					e->ipfe_arg0[i * 2 + 1]) ==
   8566 				       e->ipfe_arg0[i * 2]);
   8567 			}
   8568 			break;
   8569 
   8570 		case IPF_EXP_IP_DSTADDR :
   8571 			if (fin->fin_v != 4)
   8572 				break;
   8573 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
   8574 				rv |= ((fin->fin_daddr &
   8575 					e->ipfe_arg0[i * 2 + 1]) ==
   8576 				       e->ipfe_arg0[i * 2]);
   8577 			}
   8578 			break;
   8579 
   8580 		case IPF_EXP_IP_ADDR :
   8581 			if (fin->fin_v != 4)
   8582 				break;
   8583 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
   8584 				rv |= ((fin->fin_saddr &
   8585 					e->ipfe_arg0[i * 2 + 1]) ==
   8586 				       e->ipfe_arg0[i * 2]) ||
   8587 				      ((fin->fin_daddr &
   8588 					e->ipfe_arg0[i * 2 + 1]) ==
   8589 				       e->ipfe_arg0[i * 2]);
   8590 			}
   8591 			break;
   8592 
   8593 #ifdef USE_INET6
   8594 		case IPF_EXP_IP6_SRCADDR :
   8595 			if (fin->fin_v != 6)
   8596 				break;
   8597 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
   8598 				rv |= IP6_MASKEQ(&fin->fin_src6,
   8599 						 &e->ipfe_arg0[i * 8 + 4],
   8600 						 &e->ipfe_arg0[i * 8]);
   8601 			}
   8602 			break;
   8603 
   8604 		case IPF_EXP_IP6_DSTADDR :
   8605 			if (fin->fin_v != 6)
   8606 				break;
   8607 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
   8608 				rv |= IP6_MASKEQ(&fin->fin_dst6,
   8609 						 &e->ipfe_arg0[i * 8 + 4],
   8610 						 &e->ipfe_arg0[i * 8]);
   8611 			}
   8612 			break;
   8613 
   8614 		case IPF_EXP_IP6_ADDR :
   8615 			if (fin->fin_v != 6)
   8616 				break;
   8617 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
   8618 				rv |= IP6_MASKEQ(&fin->fin_src6,
   8619 						 &e->ipfe_arg0[i * 8 + 4],
   8620 						 &e->ipfe_arg0[i * 8]) ||
   8621 				      IP6_MASKEQ(&fin->fin_dst6,
   8622 						 &e->ipfe_arg0[i * 8 + 4],
   8623 						 &e->ipfe_arg0[i * 8]);
   8624 			}
   8625 			break;
   8626 #endif
   8627 
   8628 		case IPF_EXP_UDP_PORT :
   8629 		case IPF_EXP_TCP_PORT :
   8630 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
   8631 				rv |= (fin->fin_sport == e->ipfe_arg0[i]) ||
   8632 				      (fin->fin_dport == e->ipfe_arg0[i]);
   8633 			}
   8634 			break;
   8635 
   8636 		case IPF_EXP_UDP_SPORT :
   8637 		case IPF_EXP_TCP_SPORT :
   8638 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
   8639 				rv |= (fin->fin_sport == e->ipfe_arg0[i]);
   8640 			}
   8641 			break;
   8642 
   8643 		case IPF_EXP_UDP_DPORT :
   8644 		case IPF_EXP_TCP_DPORT :
   8645 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
   8646 				rv |= (fin->fin_dport == e->ipfe_arg0[i]);
   8647 			}
   8648 			break;
   8649 
   8650 		case IPF_EXP_TCP_FLAGS :
   8651 			for (i = 0; !rv && i < e->ipfe_narg; i++) {
   8652 				rv |= ((fin->fin_tcpf &
   8653 					e->ipfe_arg0[i * 2 + 1]) ==
   8654 				       e->ipfe_arg0[i * 2]);
   8655 			}
   8656 			break;
   8657 		}
   8658 		rv ^= e->ipfe_not;
   8659 
   8660 		if (rv == 0)
   8661 			break;
   8662 	}
   8663 
   8664 	return rv;
   8665 }
   8666 
   8667 
   8668 /* ------------------------------------------------------------------------ */
   8669 /* Function:    ipf_queueflush                                              */
   8670 /* Returns:     int - number of entries flushed (0 = none)                  */
   8671 /* Parameters:  softc(I)    - pointer to soft context main structure        */
   8672 /*              deletefn(I) - function to call to delete entry              */
   8673 /*              ipfqs(I)    - top of the list of ipf internal queues        */
   8674 /*              userqs(I)   - top of the list of user defined timeouts      */
   8675 /*                                                                          */
   8676 /* This fucntion gets called when the state/NAT hash tables fill up and we  */
   8677 /* need to try a bit harder to free up some space.  The algorithm used here */
   8678 /* split into two parts but both halves have the same goal: to reduce the   */
   8679 /* number of connections considered to be "active" to the low watermark.    */
   8680 /* There are two steps in doing this:                                       */
   8681 /* 1) Remove any TCP connections that are already considered to be "closed" */
   8682 /*    but have not yet been removed from the state table.  The two states   */
   8683 /*    TCPS_TIME_WAIT and TCPS_CLOSED are considered to be the perfect       */
   8684 /*    candidates for this style of removal.  If freeing up entries in       */
   8685 /*    CLOSED or both CLOSED and TIME_WAIT brings us to the low watermark,   */
   8686 /*    we do not go on to step 2.                                            */
   8687 /*                                                                          */
   8688 /* 2) Look for the oldest entries on each timeout queue and free them if    */
   8689 /*    they are within the given window we are considering.  Where the       */
   8690 /*    window starts and the steps taken to increase its size depend upon    */
   8691 /*    how long ipf has been running (ipf_ticks.)  Anything modified in the  */
   8692 /*    last 30 seconds is not touched.                                       */
   8693 /*                                              touched                     */
   8694 /*         die     ipf_ticks  30*1.5    1800*1.5   |  43200*1.5             */
   8695 /*           |          |        |           |     |     |                  */
   8696 /* future <--+----------+--------+-----------+-----+-----+-----------> past */
   8697 /*                     now        \_int=30s_/ \_int=1hr_/ \_int=12hr        */
   8698 /*                                                                          */
   8699 /* Points to note:                                                          */
   8700 /* - tqe_die is the time, in the future, when entries die.                  */
   8701 /* - tqe_die - ipf_ticks is how long left the connection has to live in ipf */
   8702 /*   ticks.                                                                 */
   8703 /* - tqe_touched is when the entry was last used by NAT/state               */
   8704 /* - the closer tqe_touched is to ipf_ticks, the further tqe_die will be    */
   8705 /*   ipf_ticks any given timeout queue and vice versa.                      */
   8706 /* - both tqe_die and tqe_touched increase over time                        */
   8707 /* - timeout queues are sorted with the highest value of tqe_die at the     */
   8708 /*   bottom and therefore the smallest values of each are at the top        */
   8709 /* - the pointer passed in as ipfqs should point to an array of timeout     */
   8710 /*   queues representing each of the TCP states                             */
   8711 /*                                                                          */
   8712 /* We start by setting up a maximum range to scan for things to move of     */
   8713 /* iend (newest) to istart (oldest) in chunks of "interval".  If nothing is */
   8714 /* found in that range, "interval" is adjusted (so long as it isn't 30) and */
   8715 /* we start again with a new value for "iend" and "istart".  This is        */
   8716 /* continued until we either finish the scan of 30 second intervals or the  */
   8717 /* low water mark is reached.                                               */
   8718 /* ------------------------------------------------------------------------ */
   8719 int
   8720 ipf_queueflush(ipf_main_softc_t *softc, ipftq_delete_fn_t deletefn,
   8721     ipftq_t *ipfqs, ipftq_t *userqs, u_int *activep, int size, int low)
   8722 {
   8723 	u_long interval, istart, iend;
   8724 	ipftq_t *ifq, *ifqnext;
   8725 	ipftqent_t *tqe, *tqn;
   8726 	int removed = 0;
   8727 
   8728 	for (tqn = ipfqs[IPF_TCPS_CLOSED].ifq_head; ((tqe = tqn) != NULL); ) {
   8729 		tqn = tqe->tqe_next;
   8730 		if ((*deletefn)(softc, tqe->tqe_parent) == 0)
   8731 			removed++;
   8732 	}
   8733 	if ((*activep * 100 / size) > low) {
   8734 		for (tqn = ipfqs[IPF_TCPS_TIME_WAIT].ifq_head;
   8735 		     ((tqe = tqn) != NULL); ) {
   8736 			tqn = tqe->tqe_next;
   8737 			if ((*deletefn)(softc, tqe->tqe_parent) == 0)
   8738 				removed++;
   8739 		}
   8740 	}
   8741 
   8742 	if ((*activep * 100 / size) <= low) {
   8743 		return removed;
   8744 	}
   8745 
   8746 	/*
   8747 	 * NOTE: Use of "* 15 / 10" is required here because if "* 1.5" is
   8748 	 *       used then the operations are upgraded to floating point
   8749 	 *       and kernels don't like floating point...
   8750 	 */
   8751 	if (softc->ipf_ticks > IPF_TTLVAL(43200 * 15 / 10)) {
   8752 		istart = IPF_TTLVAL(86400 * 4);
   8753 		interval = IPF_TTLVAL(43200);
   8754 	} else if (softc->ipf_ticks > IPF_TTLVAL(1800 * 15 / 10)) {
   8755 		istart = IPF_TTLVAL(43200);
   8756 		interval = IPF_TTLVAL(1800);
   8757 	} else if (softc->ipf_ticks > IPF_TTLVAL(30 * 15 / 10)) {
   8758 		istart = IPF_TTLVAL(1800);
   8759 		interval = IPF_TTLVAL(30);
   8760 	} else {
   8761 		return 0;
   8762 	}
   8763 	if (istart > softc->ipf_ticks) {
   8764 		if (softc->ipf_ticks - interval < interval)
   8765 			istart = interval;
   8766 		else
   8767 			istart = (softc->ipf_ticks / interval) * interval;
   8768 	}
   8769 
   8770 	iend = softc->ipf_ticks - interval;
   8771 
   8772 	while ((*activep * 100 / size) > low) {
   8773 		u_long try;
   8774 
   8775 		try = softc->ipf_ticks - istart;
   8776 
   8777 		for (ifq = ipfqs; ifq != NULL; ifq = ifq->ifq_next) {
   8778 			for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
   8779 				if (try < tqe->tqe_touched)
   8780 					break;
   8781 				tqn = tqe->tqe_next;
   8782 				if ((*deletefn)(softc, tqe->tqe_parent) == 0)
   8783 					removed++;
   8784 			}
   8785 		}
   8786 
   8787 		for (ifq = userqs; ifq != NULL; ifq = ifqnext) {
   8788 			ifqnext = ifq->ifq_next;
   8789 
   8790 			for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
   8791 				if (try < tqe->tqe_touched)
   8792 					break;
   8793 				tqn = tqe->tqe_next;
   8794 				if ((*deletefn)(softc, tqe->tqe_parent) == 0)
   8795 					removed++;
   8796 			}
   8797 		}
   8798 
   8799 		if (try >= iend) {
   8800 			if (interval == IPF_TTLVAL(43200)) {
   8801 				interval = IPF_TTLVAL(1800);
   8802 			} else if (interval == IPF_TTLVAL(1800)) {
   8803 				interval = IPF_TTLVAL(30);
   8804 			} else {
   8805 				break;
   8806 			}
   8807 			if (interval >= softc->ipf_ticks)
   8808 				break;
   8809 
   8810 			iend = softc->ipf_ticks - interval;
   8811 		}
   8812 		istart -= interval;
   8813 	}
   8814 
   8815 	return removed;
   8816 }
   8817 
   8818 
   8819 /* ------------------------------------------------------------------------ */
   8820 /* Function:    ipf_deliverlocal                                            */
   8821 /* Returns:     int - 1 = local address, 0 = non-local address              */
   8822 /* Parameters:  softc(I)     - pointer to soft context main structure       */
   8823 /*              ipversion(I) - IP protocol version (4 or 6)                 */
   8824 /*              ifp(I)       - network interface pointer                    */
   8825 /*              ipaddr(I)    - IPv4/6 destination address                   */
   8826 /*                                                                          */
   8827 /* This fucntion is used to determine in the address "ipaddr" belongs to    */
   8828 /* the network interface represented by ifp.                                */
   8829 /* ------------------------------------------------------------------------ */
   8830 int
   8831 ipf_deliverlocal(ipf_main_softc_t *softc, int ipversion, void *ifp,
   8832     i6addr_t *ipaddr)
   8833 {
   8834 	i6addr_t addr;
   8835 	int islocal = 0;
   8836 
   8837 	if (ipversion == 4) {
   8838 		if (ipf_ifpaddr(softc, 4, FRI_NORMAL, ifp, &addr, NULL) == 0) {
   8839 			if (addr.in4.s_addr == ipaddr->in4.s_addr)
   8840 				islocal = 1;
   8841 		}
   8842 
   8843 #ifdef USE_INET6
   8844 	} else if (ipversion == 6) {
   8845 		if (ipf_ifpaddr(softc, 6, FRI_NORMAL, ifp, &addr, NULL) == 0) {
   8846 			if (IP6_EQ(&addr, ipaddr))
   8847 				islocal = 1;
   8848 		}
   8849 #endif
   8850 	}
   8851 
   8852 	return islocal;
   8853 }
   8854 
   8855 
   8856 /* ------------------------------------------------------------------------ */
   8857 /* Function:    ipf_settimeout                                              */
   8858 /* Returns:     int - 0 = success, -1 = failure                             */
   8859 /* Parameters:  softc(I) - pointer to soft context main structure           */
   8860 /*              t(I)     - pointer to tuneable array entry                  */
   8861 /*              p(I)     - pointer to values passed in to apply             */
   8862 /*                                                                          */
   8863 /* This function is called to set the timeout values for each distinct      */
   8864 /* queue timeout that is available.  When called, it calls into both the    */
   8865 /* state and NAT code, telling them to update their timeout queues.         */
   8866 /* ------------------------------------------------------------------------ */
   8867 static int
   8868 ipf_settimeout(struct ipf_main_softc_s *softc, ipftuneable_t *t,
   8869     ipftuneval_t *p)
   8870 {
   8871 
   8872 	/*
   8873 	 * ipf_interror should be set by the functions called here, not
   8874 	 * by this function - it's just a middle man.
   8875 	 */
   8876 	if (ipf_state_settimeout(softc, t, p) == -1)
   8877 		return -1;
   8878 	if (ipf_nat_settimeout(softc, t, p) == -1)
   8879 		return -1;
   8880 	return 0;
   8881 }
   8882 
   8883 
   8884 /* ------------------------------------------------------------------------ */
   8885 /* Function:    ipf_apply_timeout                                           */
   8886 /* Returns:     int - 0 = success, -1 = failure                             */
   8887 /* Parameters:  head(I)    - pointer to tuneable array entry                */
   8888 /*              seconds(I) - pointer to values passed in to apply           */
   8889 /*                                                                          */
   8890 /* This function applies a timeout of "seconds" to the timeout queue that   */
   8891 /* is pointed to by "head".  All entries on this list have an expiration    */
   8892 /* set to be the current tick value of ipf plus the ttl.  Given that this   */
   8893 /* function should only be called when the delta is non-zero, the task is   */
   8894 /* to walk the entire list and apply the change.  The sort order will not   */
   8895 /* change.  The only catch is that this is O(n) across the list, so if the  */
   8896 /* queue has lots of entries (10s of thousands or 100s of thousands), it    */
   8897 /* could take a relatively long time to work through them all.              */
   8898 /* ------------------------------------------------------------------------ */
   8899 void
   8900 ipf_apply_timeout(ipftq_t *head, u_int seconds)
   8901 {
   8902 	u_int oldtimeout, newtimeout;
   8903 	ipftqent_t *tqe;
   8904 	int delta;
   8905 
   8906 	MUTEX_ENTER(&head->ifq_lock);
   8907 	oldtimeout = head->ifq_ttl;
   8908 	newtimeout = IPF_TTLVAL(seconds);
   8909 	delta = oldtimeout - newtimeout;
   8910 
   8911 	head->ifq_ttl = newtimeout;
   8912 
   8913 	for (tqe = head->ifq_head; tqe != NULL; tqe = tqe->tqe_next) {
   8914 		tqe->tqe_die += delta;
   8915 	}
   8916 	MUTEX_EXIT(&head->ifq_lock);
   8917 }
   8918 
   8919 
   8920 /* ------------------------------------------------------------------------ */
   8921 /* Function:   ipf_settimeout_tcp                                           */
   8922 /* Returns:    int - 0 = successfully applied, -1 = failed                  */
   8923 /* Parameters: t(I)   - pointer to tuneable to change                       */
   8924 /*             p(I)   - pointer to new timeout information                  */
   8925 /*             tab(I) - pointer to table of TCP queues                      */
   8926 /*                                                                          */
   8927 /* This function applies the new timeout (p) to the TCP tunable (t) and     */
   8928 /* updates all of the entries on the relevant timeout queue by calling      */
   8929 /* ipf_apply_timeout().                                                     */
   8930 /* ------------------------------------------------------------------------ */
   8931 int
   8932 ipf_settimeout_tcp(ipftuneable_t *t, ipftuneval_t *p, ipftq_t *tab)
   8933 {
   8934 	if (!strcmp(t->ipft_name, "tcp_idle_timeout") ||
   8935 	    !strcmp(t->ipft_name, "tcp_established")) {
   8936 		ipf_apply_timeout(&tab[IPF_TCPS_ESTABLISHED], p->ipftu_int);
   8937 	} else if (!strcmp(t->ipft_name, "tcp_close_wait")) {
   8938 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSE_WAIT], p->ipftu_int);
   8939 	} else if (!strcmp(t->ipft_name, "tcp_last_ack")) {
   8940 		ipf_apply_timeout(&tab[IPF_TCPS_LAST_ACK], p->ipftu_int);
   8941 	} else if (!strcmp(t->ipft_name, "tcp_timeout")) {
   8942 		ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
   8943 		ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
   8944 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
   8945 	} else if (!strcmp(t->ipft_name, "tcp_listen")) {
   8946 		ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
   8947 	} else if (!strcmp(t->ipft_name, "tcp_half_established")) {
   8948 		ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
   8949 	} else if (!strcmp(t->ipft_name, "tcp_closing")) {
   8950 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
   8951 	} else if (!strcmp(t->ipft_name, "tcp_syn_received")) {
   8952 		ipf_apply_timeout(&tab[IPF_TCPS_SYN_RECEIVED], p->ipftu_int);
   8953 	} else if (!strcmp(t->ipft_name, "tcp_syn_sent")) {
   8954 		ipf_apply_timeout(&tab[IPF_TCPS_SYN_SENT], p->ipftu_int);
   8955 	} else if (!strcmp(t->ipft_name, "tcp_closed")) {
   8956 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
   8957 	} else if (!strcmp(t->ipft_name, "tcp_half_closed")) {
   8958 		ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
   8959 	} else if (!strcmp(t->ipft_name, "tcp_time_wait")) {
   8960 		ipf_apply_timeout(&tab[IPF_TCPS_TIME_WAIT], p->ipftu_int);
   8961 	} else {
   8962 		/*
   8963 		 * ipf_interror isn't set here because it should be set
   8964 		 * by whatever called this function.
   8965 		 */
   8966 		return -1;
   8967 	}
   8968 	return 0;
   8969 }
   8970 
   8971 
   8972 /* ------------------------------------------------------------------------ */
   8973 /* Function:   ipf_main_soft_create                                         */
   8974 /* Returns:    NULL = failure, else success                                 */
   8975 /* Parameters: arg(I) - pointer to soft context structure if already allocd */
   8976 /*                                                                          */
   8977 /* Create the foundation soft context structure. In circumstances where it  */
   8978 /* is not required to dynamically allocate the context, a pointer can be    */
   8979 /* passed in (rather than NULL) to a structure to be initialised.           */
   8980 /* The main thing of interest is that a number of locks are initialised     */
   8981 /* here instead of in the where might be expected - in the relevant create  */
   8982 /* function elsewhere.  This is done because the current locking design has */
   8983 /* some areas where these locks are used outside of their module.           */
   8984 /* Possibly the most important exercise that is done here is setting of all */
   8985 /* the timeout values, allowing them to be changed before init().           */
   8986 /* ------------------------------------------------------------------------ */
   8987 void *
   8988 ipf_main_soft_create(void *arg)
   8989 {
   8990 	ipf_main_softc_t *softc;
   8991 
   8992 	if (arg == NULL) {
   8993 		KMALLOC(softc, ipf_main_softc_t *);
   8994 		if (softc == NULL)
   8995 			return NULL;
   8996 	} else {
   8997 		softc = arg;
   8998 	}
   8999 
   9000 	bzero((char *)softc, sizeof(*softc));
   9001 
   9002 	/*
   9003 	 * This serves as a flag as to whether or not the softc should be
   9004 	 * free'd when _destroy is called.
   9005 	 */
   9006 	softc->ipf_dynamic_softc = (arg == NULL) ? 1 : 0;
   9007 
   9008 	softc->ipf_tuners = ipf_tune_array_copy(softc,
   9009 						sizeof(ipf_main_tuneables),
   9010 						ipf_main_tuneables);
   9011 	if (softc->ipf_tuners == NULL) {
   9012 		ipf_main_soft_destroy(softc);
   9013 		return NULL;
   9014 	}
   9015 
   9016 	MUTEX_INIT(&softc->ipf_rw, "ipf rw mutex");
   9017 	MUTEX_INIT(&softc->ipf_timeoutlock, "ipf timeout lock");
   9018 	RWLOCK_INIT(&softc->ipf_global, "ipf filter load/unload mutex");
   9019 	RWLOCK_INIT(&softc->ipf_mutex, "ipf filter rwlock");
   9020 	RWLOCK_INIT(&softc->ipf_tokens, "ipf token rwlock");
   9021 	RWLOCK_INIT(&softc->ipf_state, "ipf state rwlock");
   9022 	RWLOCK_INIT(&softc->ipf_nat, "ipf IP NAT rwlock");
   9023 	RWLOCK_INIT(&softc->ipf_poolrw, "ipf pool rwlock");
   9024 	RWLOCK_INIT(&softc->ipf_frag, "ipf frag rwlock");
   9025 
   9026 	softc->ipf_token_head = NULL;
   9027 	softc->ipf_token_tail = &softc->ipf_token_head;
   9028 
   9029 	softc->ipf_tcpidletimeout = FIVE_DAYS;
   9030 	softc->ipf_tcpclosewait = IPF_TTLVAL(2 * TCP_MSL);
   9031 	softc->ipf_tcplastack = IPF_TTLVAL(30);
   9032 	softc->ipf_tcptimewait = IPF_TTLVAL(2 * TCP_MSL);
   9033 	softc->ipf_tcptimeout = IPF_TTLVAL(2 * TCP_MSL);
   9034 	softc->ipf_tcpsynsent = IPF_TTLVAL(2 * TCP_MSL);
   9035 	softc->ipf_tcpsynrecv = IPF_TTLVAL(2 * TCP_MSL);
   9036 	softc->ipf_tcpclosed = IPF_TTLVAL(30);
   9037 	softc->ipf_tcphalfclosed = IPF_TTLVAL(2 * 3600);
   9038 	softc->ipf_udptimeout = IPF_TTLVAL(120);
   9039 	softc->ipf_udpacktimeout = IPF_TTLVAL(12);
   9040 	softc->ipf_icmptimeout = IPF_TTLVAL(60);
   9041 	softc->ipf_icmpacktimeout = IPF_TTLVAL(6);
   9042 	softc->ipf_iptimeout = IPF_TTLVAL(60);
   9043 
   9044 #if defined(IPFILTER_DEFAULT_BLOCK)
   9045 	softc->ipf_pass = FR_BLOCK|FR_NOMATCH;
   9046 #else
   9047 	softc->ipf_pass = (IPF_DEFAULT_PASS)|FR_NOMATCH;
   9048 #endif
   9049 	softc->ipf_minttl = 4;
   9050 	softc->ipf_icmpminfragmtu = 68;
   9051 	softc->ipf_flags = IPF_LOGGING;
   9052 
   9053 	return softc;
   9054 }
   9055 
   9056 /* ------------------------------------------------------------------------ */
   9057 /* Function:   ipf_main_soft_init                                           */
   9058 /* Returns:    0 = success, -1 = failure                                    */
   9059 /* Parameters: softc(I) - pointer to soft context main structure            */
   9060 /*                                                                          */
   9061 /* A null-op function that exists as a placeholder so that the flow in      */
   9062 /* other functions is obvious.                                              */
   9063 /* ------------------------------------------------------------------------ */
   9064 /*ARGSUSED*/
   9065 int
   9066 ipf_main_soft_init(ipf_main_softc_t *softc)
   9067 {
   9068 	return 0;
   9069 }
   9070 
   9071 
   9072 /* ------------------------------------------------------------------------ */
   9073 /* Function:   ipf_main_soft_destroy                                        */
   9074 /* Returns:    void                                                         */
   9075 /* Parameters: softc(I) - pointer to soft context main structure            */
   9076 /*                                                                          */
   9077 /* Undo everything that we did in ipf_main_soft_create.                     */
   9078 /*                                                                          */
   9079 /* The most important check that needs to be made here is whether or not    */
   9080 /* the structure was allocated by ipf_main_soft_create() by checking what   */
   9081 /* value is stored in ipf_dynamic_main.                                     */
   9082 /* ------------------------------------------------------------------------ */
   9083 /*ARGSUSED*/
   9084 void
   9085 ipf_main_soft_destroy(ipf_main_softc_t *softc)
   9086 {
   9087 
   9088 	RW_DESTROY(&softc->ipf_frag);
   9089 	RW_DESTROY(&softc->ipf_poolrw);
   9090 	RW_DESTROY(&softc->ipf_nat);
   9091 	RW_DESTROY(&softc->ipf_state);
   9092 	RW_DESTROY(&softc->ipf_tokens);
   9093 	RW_DESTROY(&softc->ipf_mutex);
   9094 	RW_DESTROY(&softc->ipf_global);
   9095 	MUTEX_DESTROY(&softc->ipf_timeoutlock);
   9096 	MUTEX_DESTROY(&softc->ipf_rw);
   9097 
   9098 	if (softc->ipf_tuners != NULL) {
   9099 		KFREES(softc->ipf_tuners, sizeof(ipf_main_tuneables));
   9100 	}
   9101 	if (softc->ipf_dynamic_softc == 1) {
   9102 		KFREE(softc);
   9103 	}
   9104 }
   9105 
   9106 
   9107 /* ------------------------------------------------------------------------ */
   9108 /* Function:   ipf_main_soft_fini                                           */
   9109 /* Returns:    0 = success, -1 = failure                                    */
   9110 /* Parameters: softc(I) - pointer to soft context main structure            */
   9111 /*                                                                          */
   9112 /* Clean out the rules which have been added since _init was last called,   */
   9113 /* the only dynamic part of the mainline.                                   */
   9114 /* ------------------------------------------------------------------------ */
   9115 int
   9116 ipf_main_soft_fini(ipf_main_softc_t *softc)
   9117 {
   9118 	(void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
   9119 	(void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE);
   9120 	(void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
   9121 	(void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE);
   9122 
   9123 	return 0;
   9124 }
   9125 
   9126 
   9127 /* ------------------------------------------------------------------------ */
   9128 /* Function:   ipf_main_load                                                */
   9129 /* Returns:    0 = success, -1 = failure                                    */
   9130 /* Parameters: none                                                         */
   9131 /*                                                                          */
   9132 /* Handle global initialisation that needs to be done for the base part of  */
   9133 /* IPFilter. At present this just amounts to initialising some ICMP lookup  */
   9134 /* arrays that get used by the state/NAT code.                              */
   9135 /* ------------------------------------------------------------------------ */
   9136 int
   9137 ipf_main_load(void)
   9138 {
   9139 	int i;
   9140 
   9141 	/* fill icmp reply type table */
   9142 	for (i = 0; i <= ICMP_MAXTYPE; i++)
   9143 		icmpreplytype4[i] = -1;
   9144 	icmpreplytype4[ICMP_ECHO] = ICMP_ECHOREPLY;
   9145 	icmpreplytype4[ICMP_TSTAMP] = ICMP_TSTAMPREPLY;
   9146 	icmpreplytype4[ICMP_IREQ] = ICMP_IREQREPLY;
   9147 	icmpreplytype4[ICMP_MASKREQ] = ICMP_MASKREPLY;
   9148 
   9149 #ifdef  USE_INET6
   9150 	/* fill icmp reply type table */
   9151 	for (i = 0; i <= ICMP6_MAXTYPE; i++)
   9152 		icmpreplytype6[i] = -1;
   9153 	icmpreplytype6[ICMP6_ECHO_REQUEST] = ICMP6_ECHO_REPLY;
   9154 	icmpreplytype6[ICMP6_MEMBERSHIP_QUERY] = ICMP6_MEMBERSHIP_REPORT;
   9155 	icmpreplytype6[ICMP6_NI_QUERY] = ICMP6_NI_REPLY;
   9156 	icmpreplytype6[ND_ROUTER_SOLICIT] = ND_ROUTER_ADVERT;
   9157 	icmpreplytype6[ND_NEIGHBOR_SOLICIT] = ND_NEIGHBOR_ADVERT;
   9158 #endif
   9159 
   9160 	return 0;
   9161 }
   9162 
   9163 
   9164 /* ------------------------------------------------------------------------ */
   9165 /* Function:   ipf_main_unload                                              */
   9166 /* Returns:    0 = success, -1 = failure                                    */
   9167 /* Parameters: none                                                         */
   9168 /*                                                                          */
   9169 /* A null-op function that exists as a placeholder so that the flow in      */
   9170 /* other functions is obvious.                                              */
   9171 /* ------------------------------------------------------------------------ */
   9172 int
   9173 ipf_main_unload(void)
   9174 {
   9175 	return 0;
   9176 }
   9177 
   9178 
   9179 /* ------------------------------------------------------------------------ */
   9180 /* Function:   ipf_load_all                                                 */
   9181 /* Returns:    0 = success, -1 = failure                                    */
   9182 /* Parameters: none                                                         */
   9183 /*                                                                          */
   9184 /* Work through all of the subsystems inside IPFilter and call the load     */
   9185 /* function for each in an order that won't lead to a crash :)              */
   9186 /* ------------------------------------------------------------------------ */
   9187 int
   9188 ipf_load_all(void)
   9189 {
   9190 	if (ipf_main_load() == -1)
   9191 		return -1;
   9192 
   9193 	if (ipf_state_main_load() == -1)
   9194 		return -1;
   9195 
   9196 	if (ipf_nat_main_load() == -1)
   9197 		return -1;
   9198 
   9199 	if (ipf_frag_main_load() == -1)
   9200 		return -1;
   9201 
   9202 	if (ipf_auth_main_load() == -1)
   9203 		return -1;
   9204 
   9205 	if (ipf_proxy_main_load() == -1)
   9206 		return -1;
   9207 
   9208 	return 0;
   9209 }
   9210 
   9211 
   9212 /* ------------------------------------------------------------------------ */
   9213 /* Function:   ipf_unload_all                                               */
   9214 /* Returns:    0 = success, -1 = failure                                    */
   9215 /* Parameters: none                                                         */
   9216 /*                                                                          */
   9217 /* Work through all of the subsystems inside IPFilter and call the unload   */
   9218 /* function for each in an order that won't lead to a crash :)              */
   9219 /* ------------------------------------------------------------------------ */
   9220 int
   9221 ipf_unload_all(void)
   9222 {
   9223 	if (ipf_proxy_main_unload() == -1)
   9224 		return -1;
   9225 
   9226 	if (ipf_auth_main_unload() == -1)
   9227 		return -1;
   9228 
   9229 	if (ipf_frag_main_unload() == -1)
   9230 		return -1;
   9231 
   9232 	if (ipf_nat_main_unload() == -1)
   9233 		return -1;
   9234 
   9235 	if (ipf_state_main_unload() == -1)
   9236 		return -1;
   9237 
   9238 	if (ipf_main_unload() == -1)
   9239 		return -1;
   9240 
   9241 	return 0;
   9242 }
   9243 
   9244 
   9245 /* ------------------------------------------------------------------------ */
   9246 /* Function:   ipf_create_all                                               */
   9247 /* Returns:    NULL = failure, else success                                 */
   9248 /* Parameters: arg(I) - pointer to soft context main structure              */
   9249 /*                                                                          */
   9250 /* Work through all of the subsystems inside IPFilter and call the create   */
   9251 /* function for each in an order that won't lead to a crash :)              */
   9252 /* ------------------------------------------------------------------------ */
   9253 ipf_main_softc_t *
   9254 ipf_create_all(void *arg)
   9255 {
   9256 	ipf_main_softc_t *softc;
   9257 
   9258 	softc = ipf_main_soft_create(arg);
   9259 	if (softc == NULL)
   9260 		return NULL;
   9261 
   9262 #ifdef IPFILTER_LOG
   9263 	softc->ipf_log_soft = ipf_log_soft_create(softc);
   9264 	if (softc->ipf_log_soft == NULL) {
   9265 		ipf_destroy_all(softc);
   9266 		return NULL;
   9267 	}
   9268 #endif
   9269 
   9270 	softc->ipf_lookup_soft = ipf_lookup_soft_create(softc);
   9271 	if (softc->ipf_lookup_soft == NULL) {
   9272 		ipf_destroy_all(softc);
   9273 		return NULL;
   9274 	}
   9275 
   9276 	softc->ipf_sync_soft = ipf_sync_soft_create(softc);
   9277 	if (softc->ipf_sync_soft == NULL) {
   9278 		ipf_destroy_all(softc);
   9279 		return NULL;
   9280 	}
   9281 
   9282 	softc->ipf_state_soft = ipf_state_soft_create(softc);
   9283 	if (softc->ipf_state_soft == NULL) {
   9284 		ipf_destroy_all(softc);
   9285 		return NULL;
   9286 	}
   9287 
   9288 	softc->ipf_nat_soft = ipf_nat_soft_create(softc);
   9289 	if (softc->ipf_nat_soft == NULL) {
   9290 		ipf_destroy_all(softc);
   9291 		return NULL;
   9292 	}
   9293 
   9294 	softc->ipf_frag_soft = ipf_frag_soft_create(softc);
   9295 	if (softc->ipf_frag_soft == NULL) {
   9296 		ipf_destroy_all(softc);
   9297 		return NULL;
   9298 	}
   9299 
   9300 	softc->ipf_auth_soft = ipf_auth_soft_create(softc);
   9301 	if (softc->ipf_auth_soft == NULL) {
   9302 		ipf_destroy_all(softc);
   9303 		return NULL;
   9304 	}
   9305 
   9306 	softc->ipf_proxy_soft = ipf_proxy_soft_create(softc);
   9307 	if (softc->ipf_proxy_soft == NULL) {
   9308 		ipf_destroy_all(softc);
   9309 		return NULL;
   9310 	}
   9311 
   9312 	return softc;
   9313 }
   9314 
   9315 
   9316 /* ------------------------------------------------------------------------ */
   9317 /* Function:   ipf_destroy_all                                              */
   9318 /* Returns:    void                                                         */
   9319 /* Parameters: softc(I) - pointer to soft context main structure            */
   9320 /*                                                                          */
   9321 /* Work through all of the subsystems inside IPFilter and call the destroy  */
   9322 /* function for each in an order that won't lead to a crash :)              */
   9323 /*                                                                          */
   9324 /* Every one of these functions is expected to succeed, so there is no      */
   9325 /* checking of return values.                                               */
   9326 /* ------------------------------------------------------------------------ */
   9327 void
   9328 ipf_destroy_all(ipf_main_softc_t *softc)
   9329 {
   9330 
   9331 	if (softc->ipf_state_soft != NULL) {
   9332 		ipf_state_soft_destroy(softc, softc->ipf_state_soft);
   9333 		softc->ipf_state_soft = NULL;
   9334 	}
   9335 
   9336 	if (softc->ipf_nat_soft != NULL) {
   9337 		ipf_nat_soft_destroy(softc, softc->ipf_nat_soft);
   9338 		softc->ipf_nat_soft = NULL;
   9339 	}
   9340 
   9341 	if (softc->ipf_frag_soft != NULL) {
   9342 		ipf_frag_soft_destroy(softc, softc->ipf_frag_soft);
   9343 		softc->ipf_frag_soft = NULL;
   9344 	}
   9345 
   9346 	if (softc->ipf_auth_soft != NULL) {
   9347 		ipf_auth_soft_destroy(softc, softc->ipf_auth_soft);
   9348 		softc->ipf_auth_soft = NULL;
   9349 	}
   9350 
   9351 	if (softc->ipf_proxy_soft != NULL) {
   9352 		ipf_proxy_soft_destroy(softc, softc->ipf_proxy_soft);
   9353 		softc->ipf_proxy_soft = NULL;
   9354 	}
   9355 
   9356 	if (softc->ipf_sync_soft != NULL) {
   9357 		ipf_sync_soft_destroy(softc, softc->ipf_sync_soft);
   9358 		softc->ipf_sync_soft = NULL;
   9359 	}
   9360 
   9361 	if (softc->ipf_lookup_soft != NULL) {
   9362 		ipf_lookup_soft_destroy(softc, softc->ipf_lookup_soft);
   9363 		softc->ipf_lookup_soft = NULL;
   9364 	}
   9365 
   9366 #ifdef IPFILTER_LOG
   9367 	if (softc->ipf_log_soft != NULL) {
   9368 		ipf_log_soft_destroy(softc, softc->ipf_log_soft);
   9369 		softc->ipf_log_soft = NULL;
   9370 	}
   9371 #endif
   9372 
   9373 	ipf_main_soft_destroy(softc);
   9374 }
   9375 
   9376 
   9377 /* ------------------------------------------------------------------------ */
   9378 /* Function:   ipf_init_all                                                 */
   9379 /* Returns:    0 = success, -1 = failure                                    */
   9380 /* Parameters: softc(I) - pointer to soft context main structure            */
   9381 /*                                                                          */
   9382 /* Work through all of the subsystems inside IPFilter and call the init     */
   9383 /* function for each in an order that won't lead to a crash :)              */
   9384 /* ------------------------------------------------------------------------ */
   9385 int
   9386 ipf_init_all(ipf_main_softc_t *softc)
   9387 {
   9388 
   9389 	if (ipf_main_soft_init(softc) == -1)
   9390 		return -1;
   9391 
   9392 #ifdef IPFILTER_LOG
   9393 	if (ipf_log_soft_init(softc, softc->ipf_log_soft) == -1)
   9394 		return -1;
   9395 #endif
   9396 
   9397 	if (ipf_lookup_soft_init(softc, softc->ipf_lookup_soft) == -1)
   9398 		return -1;
   9399 
   9400 	if (ipf_sync_soft_init(softc, softc->ipf_sync_soft) == -1)
   9401 		return -1;
   9402 
   9403 	if (ipf_state_soft_init(softc, softc->ipf_state_soft) == -1)
   9404 		return -1;
   9405 
   9406 	if (ipf_nat_soft_init(softc, softc->ipf_nat_soft) == -1)
   9407 		return -1;
   9408 
   9409 	if (ipf_frag_soft_init(softc, softc->ipf_frag_soft) == -1)
   9410 		return -1;
   9411 
   9412 	if (ipf_auth_soft_init(softc, softc->ipf_auth_soft) == -1)
   9413 		return -1;
   9414 
   9415 	if (ipf_proxy_soft_init(softc, softc->ipf_proxy_soft) == -1)
   9416 		return -1;
   9417 
   9418 	return 0;
   9419 }
   9420 
   9421 
   9422 /* ------------------------------------------------------------------------ */
   9423 /* Function:   ipf_fini_all                                                 */
   9424 /* Returns:    0 = success, -1 = failure                                    */
   9425 /* Parameters: softc(I) - pointer to soft context main structure            */
   9426 /*                                                                          */
   9427 /* Work through all of the subsystems inside IPFilter and call the fini     */
   9428 /* function for each in an order that won't lead to a crash :)              */
   9429 /* ------------------------------------------------------------------------ */
   9430 int
   9431 ipf_fini_all(ipf_main_softc_t *softc)
   9432 {
   9433 
   9434 	ipf_token_flush(softc);
   9435 
   9436 	if (ipf_proxy_soft_fini(softc, softc->ipf_proxy_soft) == -1)
   9437 		return -1;
   9438 
   9439 	if (ipf_auth_soft_fini(softc, softc->ipf_auth_soft) == -1)
   9440 		return -1;
   9441 
   9442 	if (ipf_frag_soft_fini(softc, softc->ipf_frag_soft) == -1)
   9443 		return -1;
   9444 
   9445 	if (ipf_nat_soft_fini(softc, softc->ipf_nat_soft) == -1)
   9446 		return -1;
   9447 
   9448 	if (ipf_state_soft_fini(softc, softc->ipf_state_soft) == -1)
   9449 		return -1;
   9450 
   9451 	if (ipf_sync_soft_fini(softc, softc->ipf_sync_soft) == -1)
   9452 		return -1;
   9453 
   9454 	if (ipf_lookup_soft_fini(softc, softc->ipf_lookup_soft) == -1)
   9455 		return -1;
   9456 
   9457 #ifdef IPFILTER_LOG
   9458 	if (ipf_log_soft_fini(softc, softc->ipf_log_soft) == -1)
   9459 		return -1;
   9460 #endif
   9461 
   9462 	if (ipf_main_soft_fini(softc) == -1)
   9463 		return -1;
   9464 
   9465 	return 0;
   9466 }
   9467 
   9468 
   9469 /* ------------------------------------------------------------------------ */
   9470 /* Function:    ipf_rule_expire                                             */
   9471 /* Returns:     Nil                                                         */
   9472 /* Parameters:  softc(I) - pointer to soft context main structure           */
   9473 /*                                                                          */
   9474 /* At present this function exists just to support temporary addition of    */
   9475 /* firewall rules. Both inactive and active lists are scanned for items to  */
   9476 /* purge, as by rights, the expiration is computed as soon as the rule is   */
   9477 /* loaded in.                                                               */
   9478 /* ------------------------------------------------------------------------ */
   9479 void
   9480 ipf_rule_expire(ipf_main_softc_t *softc)
   9481 {
   9482 	frentry_t *fr;
   9483 
   9484 	if ((softc->ipf_rule_explist[0] == NULL) &&
   9485 	    (softc->ipf_rule_explist[1] == NULL))
   9486 		return;
   9487 
   9488 	WRITE_ENTER(&softc->ipf_mutex);
   9489 
   9490 	while ((fr = softc->ipf_rule_explist[0]) != NULL) {
   9491 		/*
   9492 		 * Because the list is kept sorted on insertion, the fist
   9493 		 * one that dies in the future means no more work to do.
   9494 		 */
   9495 		if (fr->fr_die > softc->ipf_ticks)
   9496 			break;
   9497 		ipf_rule_delete(softc, fr, IPL_LOGIPF, 0);
   9498 	}
   9499 
   9500 	while ((fr = softc->ipf_rule_explist[1]) != NULL) {
   9501 		/*
   9502 		 * Because the list is kept sorted on insertion, the fist
   9503 		 * one that dies in the future means no more work to do.
   9504 		 */
   9505 		if (fr->fr_die > softc->ipf_ticks)
   9506 			break;
   9507 		ipf_rule_delete(softc, fr, IPL_LOGIPF, 1);
   9508 	}
   9509 
   9510 	RWLOCK_EXIT(&softc->ipf_mutex);
   9511 }
   9512 
   9513 
   9514 static int ipf_ht_node_cmp(const struct host_node_s *, const struct host_node_s *);
   9515 static void ipf_ht_node_make_key(host_track_t *, host_node_t *, int,
   9516 				 i6addr_t *);
   9517 
   9518 RBI_CODE(ipf_rb, host_node_t, hn_entry, ipf_ht_node_cmp)
   9519 
   9520 
   9521 /* ------------------------------------------------------------------------ */
   9522 /* Function:    ipf_ht_node_cmp                                             */
   9523 /* Returns:     int   - 0 == nodes are the same, ..                         */
   9524 /* Parameters:  k1(I) - pointer to first key to compare                     */
   9525 /*              k2(I) - pointer to second key to compare                    */
   9526 /*                                                                          */
   9527 /* The "key" for the node is a combination of two fields: the address       */
   9528 /* family and the address itself.                                           */
   9529 /*                                                                          */
   9530 /* Because we're not actually interpreting the address data, it isn't       */
   9531 /* necessary to convert them to/from network/host byte order. The mask is   */
   9532 /* just used to remove bits that aren't significant - it doesn't matter     */
   9533 /* where they are, as long as they're always in the same place.             */
   9534 /*                                                                          */
   9535 /* As with IP6_EQ, comparing IPv6 addresses starts at the bottom because    */
   9536 /* this is where individual ones will differ the most - but not true for    */
   9537 /* for /48's, etc.                                                          */
   9538 /* ------------------------------------------------------------------------ */
   9539 static int
   9540 ipf_ht_node_cmp(const struct host_node_s *k1, const struct host_node_s *k2)
   9541 {
   9542 	int i;
   9543 
   9544 	i = (k2->hn_addr.adf_family - k1->hn_addr.adf_family);
   9545 	if (i != 0)
   9546 		return i;
   9547 
   9548 	if (k1->hn_addr.adf_family == AF_INET)
   9549 		return (k2->hn_addr.adf_addr.in4.s_addr -
   9550 			k1->hn_addr.adf_addr.in4.s_addr);
   9551 
   9552 	i = k2->hn_addr.adf_addr.i6[3] - k1->hn_addr.adf_addr.i6[3];
   9553 	if (i != 0)
   9554 		return i;
   9555 	i = k2->hn_addr.adf_addr.i6[2] - k1->hn_addr.adf_addr.i6[2];
   9556 	if (i != 0)
   9557 		return i;
   9558 	i = k2->hn_addr.adf_addr.i6[1] - k1->hn_addr.adf_addr.i6[1];
   9559 	if (i != 0)
   9560 		return i;
   9561 	i = k2->hn_addr.adf_addr.i6[0] - k1->hn_addr.adf_addr.i6[0];
   9562 	return i;
   9563 }
   9564 
   9565 
   9566 /* ------------------------------------------------------------------------ */
   9567 /* Function:    ipf_ht_node_make_key                                        */
   9568 /* Returns:     Nil                                                         */
   9569 /* parameters:  htp(I)    - pointer to address tracking structure           */
   9570 /*              key(I)    - where to store masked address for lookup        */
   9571 /*              family(I) - protocol family of address                      */
   9572 /*              addr(I)   - pointer to network address                      */
   9573 /*                                                                          */
   9574 /* Using the "netmask" (number of bits) stored parent host tracking struct, */
   9575 /* copy the address passed in into the key structure whilst masking out the */
   9576 /* bits that we don't want.                                                 */
   9577 /*                                                                          */
   9578 /* Because the parser will set ht_netmask to 128 if there is no protocol    */
   9579 /* specified (the parser doesn't know if it should be a v4 or v6 rule), we  */
   9580 /* have to be wary of that and not allow 32-128 to happen.                  */
   9581 /* ------------------------------------------------------------------------ */
   9582 static void
   9583 ipf_ht_node_make_key(host_track_t *htp, host_node_t *key, int family,
   9584     i6addr_t *addr)
   9585 {
   9586 	key->hn_addr.adf_family = family;
   9587 	if (family == AF_INET) {
   9588 		u_32_t mask;
   9589 		int bits;
   9590 
   9591 		key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in4);
   9592 		bits = htp->ht_netmask;
   9593 		if (bits >= 32) {
   9594 			mask = 0xffffffff;
   9595 		} else {
   9596 			mask = htonl(0xffffffff << (32 - bits));
   9597 		}
   9598 		key->hn_addr.adf_addr.in4.s_addr = addr->in4.s_addr & mask;
   9599 #ifdef USE_INET6
   9600 	} else {
   9601 		int bits = htp->ht_netmask;
   9602 
   9603 		key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in6);
   9604 		if (bits > 96) {
   9605 			key->hn_addr.adf_addr.i6[3] = addr->i6[3] &
   9606 					     htonl(0xffffffff << (128 - bits));
   9607 			key->hn_addr.adf_addr.i6[2] = addr->i6[2];
   9608 			key->hn_addr.adf_addr.i6[1] = addr->i6[2];
   9609 			key->hn_addr.adf_addr.i6[0] = addr->i6[2];
   9610 		} else if (bits > 64) {
   9611 			key->hn_addr.adf_addr.i6[3] = 0;
   9612 			key->hn_addr.adf_addr.i6[2] = addr->i6[2] &
   9613 					     htonl(0xffffffff << (96 - bits));
   9614 			key->hn_addr.adf_addr.i6[1] = addr->i6[1];
   9615 			key->hn_addr.adf_addr.i6[0] = addr->i6[0];
   9616 		} else if (bits > 32) {
   9617 			key->hn_addr.adf_addr.i6[3] = 0;
   9618 			key->hn_addr.adf_addr.i6[2] = 0;
   9619 			key->hn_addr.adf_addr.i6[1] = addr->i6[1] &
   9620 					     htonl(0xffffffff << (64 - bits));
   9621 			key->hn_addr.adf_addr.i6[0] = addr->i6[0];
   9622 		} else {
   9623 			key->hn_addr.adf_addr.i6[3] = 0;
   9624 			key->hn_addr.adf_addr.i6[2] = 0;
   9625 			key->hn_addr.adf_addr.i6[1] = 0;
   9626 			key->hn_addr.adf_addr.i6[0] = addr->i6[0] &
   9627 					     htonl(0xffffffff << (32 - bits));
   9628 		}
   9629 #endif
   9630 	}
   9631 }
   9632 
   9633 
   9634 /* ------------------------------------------------------------------------ */
   9635 /* Function:    ipf_ht_node_add                                             */
   9636 /* Returns:     int       - 0 == success,  -1 == failure                    */
   9637 /* Parameters:  softc(I)  - pointer to soft context main structure          */
   9638 /*              htp(I)    - pointer to address tracking structure           */
   9639 /*              family(I) - protocol family of address                      */
   9640 /*              addr(I)   - pointer to network address                      */
   9641 /*                                                                          */
   9642 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS  */
   9643 /*       ipf_ht_node_del FROM RUNNING CONCURRENTLY ON THE SAME htp.         */
   9644 /*                                                                          */
   9645 /* After preparing the key with the address information to find, look in    */
   9646 /* the red-black tree to see if the address is known. A successful call to  */
   9647 /* this function can mean one of two things: a new node was added to the    */
   9648 /* tree or a matching node exists and we're able to bump up its activity.   */
   9649 /* ------------------------------------------------------------------------ */
   9650 int
   9651 ipf_ht_node_add(ipf_main_softc_t *softc, host_track_t *htp, int family,
   9652     i6addr_t *addr)
   9653 {
   9654 	host_node_t *h;
   9655 	host_node_t k;
   9656 
   9657 	ipf_ht_node_make_key(htp, &k, family, addr);
   9658 
   9659 	h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
   9660 	if (h == NULL) {
   9661 		if (htp->ht_cur_nodes >= htp->ht_max_nodes)
   9662 			return -1;
   9663 		KMALLOC(h, host_node_t *);
   9664 		if (h == NULL) {
   9665 			DT(ipf_rb_no_mem);
   9666 			LBUMP(ipf_rb_no_mem);
   9667 			return -1;
   9668 		}
   9669 
   9670 		/*
   9671 		 * If there was a macro to initialise the RB node then that
   9672 		 * would get used here, but there isn't...
   9673 		 */
   9674 		bzero((char *)h, sizeof(*h));
   9675 		h->hn_addr = k.hn_addr;
   9676 		h->hn_addr.adf_family = k.hn_addr.adf_family;
   9677 		RBI_INSERT(ipf_rb, &htp->ht_root, h);
   9678 		htp->ht_cur_nodes++;
   9679 	} else {
   9680 		if ((htp->ht_max_per_node != 0) &&
   9681 		    (h->hn_active >= htp->ht_max_per_node)) {
   9682 			DT(ipf_rb_node_max);
   9683 			LBUMP(ipf_rb_node_max);
   9684 			return -1;
   9685 		}
   9686 	}
   9687 
   9688 	h->hn_active++;
   9689 
   9690 	return 0;
   9691 }
   9692 
   9693 
   9694 /* ------------------------------------------------------------------------ */
   9695 /* Function:    ipf_ht_node_del                                             */
   9696 /* Returns:     int       - 0 == success,  -1 == failure                    */
   9697 /* parameters:  htp(I)    - pointer to address tracking structure           */
   9698 /*              family(I) - protocol family of address                      */
   9699 /*              addr(I)   - pointer to network address                      */
   9700 /*                                                                          */
   9701 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS  */
   9702 /*       ipf_ht_node_add FROM RUNNING CONCURRENTLY ON THE SAME htp.         */
   9703 /*                                                                          */
   9704 /* Try and find the address passed in amongst the leaves on this tree to    */
   9705 /* be friend. If found then drop the active account for that node drops by  */
   9706 /* one. If that count reaches 0, it is time to free it all up.              */
   9707 /* ------------------------------------------------------------------------ */
   9708 int
   9709 ipf_ht_node_del(host_track_t *htp, int family, i6addr_t *addr)
   9710 {
   9711 	host_node_t *h;
   9712 	host_node_t k;
   9713 
   9714 	ipf_ht_node_make_key(htp, &k, family, addr);
   9715 
   9716 	h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
   9717 	if (h == NULL) {
   9718 		return -1;
   9719 	} else {
   9720 		h->hn_active--;
   9721 		if (h->hn_active == 0) {
   9722 			(void) RBI_DELETE(ipf_rb, &htp->ht_root, h);
   9723 			htp->ht_cur_nodes--;
   9724 			KFREE(h);
   9725 		}
   9726 	}
   9727 
   9728 	return 0;
   9729 }
   9730 
   9731 
   9732 /* ------------------------------------------------------------------------ */
   9733 /* Function:    ipf_rb_ht_init                                              */
   9734 /* Returns:     Nil                                                         */
   9735 /* Parameters:  head(I) - pointer to host tracking structure                */
   9736 /*                                                                          */
   9737 /* Initialise the host tracking structure to be ready for use above.        */
   9738 /* ------------------------------------------------------------------------ */
   9739 void
   9740 ipf_rb_ht_init(host_track_t *head)
   9741 {
   9742 	memset(head, 0, sizeof(*head));
   9743 	RBI_INIT(ipf_rb, &head->ht_root);
   9744 }
   9745 
   9746 
   9747 /* ------------------------------------------------------------------------ */
   9748 /* Function:    ipf_rb_ht_freenode                                          */
   9749 /* Returns:     Nil                                                         */
   9750 /* Parameters:  head(I) - pointer to host tracking structure                */
   9751 /*              arg(I)  - additional argument from walk caller              */
   9752 /*                                                                          */
   9753 /* Free an actual host_node_t structure.                                    */
   9754 /* ------------------------------------------------------------------------ */
   9755 void
   9756 ipf_rb_ht_freenode(host_node_t *node, void *arg)
   9757 {
   9758 	KFREE(node);
   9759 }
   9760 
   9761 
   9762 /* ------------------------------------------------------------------------ */
   9763 /* Function:    ipf_rb_ht_flush                                             */
   9764 /* Returns:     Nil                                                         */
   9765 /* Parameters:  head(I) - pointer to host tracking structure                */
   9766 /*                                                                          */
   9767 /* Remove all of the nodes in the tree tracking hosts by calling a walker   */
   9768 /* and free'ing each one.                                                   */
   9769 /* ------------------------------------------------------------------------ */
   9770 void
   9771 ipf_rb_ht_flush(host_track_t *head)
   9772 {
   9773 	/* XXX - May use node members after freeing the node. */
   9774 	RBI_WALK(ipf_rb, &head->ht_root, ipf_rb_ht_freenode, NULL);
   9775 }
   9776 
   9777 
   9778 /* ------------------------------------------------------------------------ */
   9779 /* Function:    ipf_slowtimer                                               */
   9780 /* Returns:     Nil                                                         */
   9781 /* Parameters:  ptr(I) - pointer to main ipf soft context structure         */
   9782 /*                                                                          */
   9783 /* Slowly expire held state for fragments.  Timeouts are set * in           */
   9784 /* expectation of this being called twice per second.                       */
   9785 /* ------------------------------------------------------------------------ */
   9786 void
   9787 ipf_slowtimer(ipf_main_softc_t *softc)
   9788 {
   9789 
   9790 	ipf_token_expire(softc);
   9791 	ipf_frag_expire(softc);
   9792 	ipf_state_expire(softc);
   9793 	ipf_nat_expire(softc);
   9794 	ipf_auth_expire(softc);
   9795 	ipf_lookup_expire(softc);
   9796 	ipf_rule_expire(softc);
   9797 	ipf_sync_expire(softc);
   9798 	softc->ipf_ticks++;
   9799 #   if defined(__OpenBSD__)
   9800 	timeout_add(&ipf_slowtimer_ch, hz/2);
   9801 #   endif
   9802 }
   9803 
   9804 
   9805 /* ------------------------------------------------------------------------ */
   9806 /* Function:    ipf_inet_mask_add                                           */
   9807 /* Returns:     Nil                                                         */
   9808 /* Parameters:  bits(I) - pointer to nat context information                */
   9809 /*              mtab(I) - pointer to mask hash table structure              */
   9810 /*                                                                          */
   9811 /* When called, bits represents the mask of a new NAT rule that has just    */
   9812 /* been added. This function inserts a bitmask into the array of masks to   */
   9813 /* search when searching for a matching NAT rule for a packet.              */
   9814 /* Prevention of duplicate masks is achieved by checking the use count for  */
   9815 /* a given netmask.                                                         */
   9816 /* ------------------------------------------------------------------------ */
   9817 void
   9818 ipf_inet_mask_add(int bits, ipf_v4_masktab_t *mtab)
   9819 {
   9820 	u_32_t mask;
   9821 	int i, j;
   9822 
   9823 	mtab->imt4_masks[bits]++;
   9824 	if (mtab->imt4_masks[bits] > 1)
   9825 		return;
   9826 
   9827 	if (bits == 0)
   9828 		mask = 0;
   9829 	else
   9830 		mask = 0xffffffff << (32 - bits);
   9831 
   9832 	for (i = 0; i < 33; i++) {
   9833 		if (ntohl(mtab->imt4_active[i]) < mask) {
   9834 			for (j = 32; j > i; j--)
   9835 				mtab->imt4_active[j] = mtab->imt4_active[j - 1];
   9836 			mtab->imt4_active[i] = htonl(mask);
   9837 			break;
   9838 		}
   9839 	}
   9840 	mtab->imt4_max++;
   9841 }
   9842 
   9843 
   9844 /* ------------------------------------------------------------------------ */
   9845 /* Function:    ipf_inet_mask_del                                           */
   9846 /* Returns:     Nil                                                         */
   9847 /* Parameters:  bits(I) - number of bits set in the netmask                 */
   9848 /*              mtab(I) - pointer to mask hash table structure              */
   9849 /*                                                                          */
   9850 /* Remove the 32bit bitmask represented by "bits" from the collection of    */
   9851 /* netmasks stored inside of mtab.                                          */
   9852 /* ------------------------------------------------------------------------ */
   9853 void
   9854 ipf_inet_mask_del(int bits, ipf_v4_masktab_t *mtab)
   9855 {
   9856 	u_32_t mask;
   9857 	int i, j;
   9858 
   9859 	mtab->imt4_masks[bits]--;
   9860 	if (mtab->imt4_masks[bits] > 0)
   9861 		return;
   9862 
   9863 	mask = htonl(0xffffffff << (32 - bits));
   9864 	for (i = 0; i < 33; i++) {
   9865 		if (mtab->imt4_active[i] == mask) {
   9866 			for (j = i + 1; j < 33; j++)
   9867 				mtab->imt4_active[j - 1] = mtab->imt4_active[j];
   9868 			break;
   9869 		}
   9870 	}
   9871 	mtab->imt4_max--;
   9872 	ASSERT(mtab->imt4_max >= 0);
   9873 }
   9874 
   9875 
   9876 #ifdef USE_INET6
   9877 /* ------------------------------------------------------------------------ */
   9878 /* Function:    ipf_inet6_mask_add                                          */
   9879 /* Returns:     Nil                                                         */
   9880 /* Parameters:  bits(I) - number of bits set in mask                        */
   9881 /*              mask(I) - pointer to mask to add                            */
   9882 /*              mtab(I) - pointer to mask hash table structure              */
   9883 /*                                                                          */
   9884 /* When called, bitcount represents the mask of a IPv6 NAT map rule that    */
   9885 /* has just been added. This function inserts a bitmask into the array of   */
   9886 /* masks to search when searching for a matching NAT rule for a packet.     */
   9887 /* Prevention of duplicate masks is achieved by checking the use count for  */
   9888 /* a given netmask.                                                         */
   9889 /* ------------------------------------------------------------------------ */
   9890 void
   9891 ipf_inet6_mask_add(int bits, i6addr_t *mask, ipf_v6_masktab_t *mtab)
   9892 {
   9893 	i6addr_t zero;
   9894 	int i, j;
   9895 
   9896 	mtab->imt6_masks[bits]++;
   9897 	if (mtab->imt6_masks[bits] > 1)
   9898 		return;
   9899 
   9900 	if (bits == 0) {
   9901 		mask = &zero;
   9902 		zero.i6[0] = 0;
   9903 		zero.i6[1] = 0;
   9904 		zero.i6[2] = 0;
   9905 		zero.i6[3] = 0;
   9906 	}
   9907 
   9908 	for (i = 0; i < 129; i++) {
   9909 		if (IP6_LT(&mtab->imt6_active[i], mask)) {
   9910 			for (j = 128; j > i; j--)
   9911 				mtab->imt6_active[j] = mtab->imt6_active[j - 1];
   9912 			mtab->imt6_active[i] = *mask;
   9913 			break;
   9914 		}
   9915 	}
   9916 	mtab->imt6_max++;
   9917 }
   9918 
   9919 
   9920 /* ------------------------------------------------------------------------ */
   9921 /* Function:    ipf_inet6_mask_del                                          */
   9922 /* Returns:     Nil                                                         */
   9923 /* Parameters:  bits(I) - number of bits set in mask                        */
   9924 /*              mask(I) - pointer to mask to remove                         */
   9925 /*              mtab(I) - pointer to mask hash table structure              */
   9926 /*                                                                          */
   9927 /* Remove the 128bit bitmask represented by "bits" from the collection of   */
   9928 /* netmasks stored inside of mtab.                                          */
   9929 /* ------------------------------------------------------------------------ */
   9930 void
   9931 ipf_inet6_mask_del(int bits, i6addr_t *mask, ipf_v6_masktab_t *mtab)
   9932 {
   9933 	i6addr_t zero;
   9934 	int i, j;
   9935 
   9936 	mtab->imt6_masks[bits]--;
   9937 	if (mtab->imt6_masks[bits] > 0)
   9938 		return;
   9939 
   9940 	if (bits == 0)
   9941 		mask = &zero;
   9942 	zero.i6[0] = 0;
   9943 	zero.i6[1] = 0;
   9944 	zero.i6[2] = 0;
   9945 	zero.i6[3] = 0;
   9946 
   9947 	for (i = 0; i < 129; i++) {
   9948 		if (IP6_EQ(&mtab->imt6_active[i], mask)) {
   9949 			for (j = i + 1; j < 129; j++) {
   9950 				mtab->imt6_active[j - 1] = mtab->imt6_active[j];
   9951 				if (IP6_EQ(&mtab->imt6_active[j - 1], &zero))
   9952 					break;
   9953 			}
   9954 			break;
   9955 		}
   9956 	}
   9957 	mtab->imt6_max--;
   9958 	ASSERT(mtab->imt6_max >= 0);
   9959 }
   9960 #endif
   9961