Home | History | Annotate | Line # | Download | only in netinet
ip_nat.c revision 1.1.1.2
      1 /*	$NetBSD: ip_nat.c,v 1.1.1.2 2012/07/22 13:45:27 darrenr Exp $	*/
      2 
      3 /*
      4  * Copyright (C) 2012 by Darren Reed.
      5  *
      6  * See the IPFILTER.LICENCE file for details on licencing.
      7  */
      8 #if defined(KERNEL) || defined(_KERNEL)
      9 # undef KERNEL
     10 # undef KERNEL
     11 # define        KERNEL	1
     12 # define        KERNEL	1
     13 #endif
     14 #include <sys/errno.h>
     15 #include <sys/types.h>
     16 #include <sys/param.h>
     17 #include <sys/time.h>
     18 #include <sys/file.h>
     19 #if defined(_KERNEL) && \
     20     (defined(__NetBSD_Version) && (__NetBSD_Version >= 399002000))
     21 # include <sys/kauth.h>
     22 #endif
     23 #if !defined(_KERNEL)
     24 # include <stdio.h>
     25 # include <string.h>
     26 # include <stdlib.h>
     27 # define KERNEL
     28 # ifdef _OpenBSD__
     29 struct file;
     30 # endif
     31 # include <sys/uio.h>
     32 # undef KERNEL
     33 #endif
     34 #if defined(_KERNEL) && \
     35     defined(__FreeBSD_version) && (__FreeBSD_version >= 220000)
     36 # include <sys/filio.h>
     37 # include <sys/fcntl.h>
     38 #else
     39 # include <sys/ioctl.h>
     40 #endif
     41 #if !defined(AIX)
     42 # include <sys/fcntl.h>
     43 #endif
     44 #if !defined(linux)
     45 # include <sys/protosw.h>
     46 #endif
     47 #include <sys/socket.h>
     48 #if defined(_KERNEL)
     49 # include <sys/systm.h>
     50 # if !defined(__SVR4) && !defined(__svr4__)
     51 #  include <sys/mbuf.h>
     52 # endif
     53 #endif
     54 #if defined(__SVR4) || defined(__svr4__)
     55 # include <sys/filio.h>
     56 # include <sys/byteorder.h>
     57 # ifdef KERNEL
     58 #  include <sys/dditypes.h>
     59 # endif
     60 # include <sys/stream.h>
     61 # include <sys/kmem.h>
     62 #endif
     63 #if _FreeBSD_version >= 300000
     64 # include <sys/queue.h>
     65 #endif
     66 #include <net/if.h>
     67 #if _FreeBSD_version >= 300000
     68 # include <net/if_var.h>
     69 #endif
     70 #ifdef sun
     71 # include <net/af.h>
     72 #endif
     73 #include <netinet/in.h>
     74 #include <netinet/in_systm.h>
     75 #include <netinet/ip.h>
     76 
     77 #ifdef RFC1825
     78 # include <vpn/md5.h>
     79 # include <vpn/ipsec.h>
     80 extern struct ifnet vpnif;
     81 #endif
     82 
     83 #if !defined(linux)
     84 # include <netinet/ip_var.h>
     85 #endif
     86 #include <netinet/tcp.h>
     87 #include <netinet/udp.h>
     88 #include <netinet/ip_icmp.h>
     89 #include "netinet/ip_compat.h"
     90 #include <netinet/tcpip.h>
     91 #include "netinet/ipl.h"
     92 #include "netinet/ip_fil.h"
     93 #include "netinet/ip_nat.h"
     94 #include "netinet/ip_frag.h"
     95 #include "netinet/ip_state.h"
     96 #include "netinet/ip_proxy.h"
     97 #include "netinet/ip_lookup.h"
     98 #include "netinet/ip_dstlist.h"
     99 #include "netinet/ip_sync.h"
    100 #if FREEBSD_GE_REV(300000)
    101 # include <sys/malloc.h>
    102 #endif
    103 #ifdef HAS_SYS_MD5_H
    104 # include <sys/md5.h>
    105 #else
    106 # include "md5.h"
    107 #endif
    108 /* END OF INCLUDES */
    109 
    110 #undef	SOCKADDR_IN
    111 #define	SOCKADDR_IN	struct sockaddr_in
    112 
    113 #if !defined(lint)
    114 static const char sccsid[] = "@(#)ip_nat.c	1.11 6/5/96 (C) 1995 Darren Reed";
    115 static const char rcsid[] = "@(#)$Id: ip_nat.c,v 1.1.1.2 2012/07/22 13:45:27 darrenr Exp $";
    116 #endif
    117 
    118 
    119 #define	NATFSUM(n,v,f)	((v) == 4 ? (n)->f.in4.s_addr : (n)->f.i6[0] + \
    120 			 (n)->f.i6[1] + (n)->f.i6[2] + (n)->f.i6[3])
    121 #define	NBUMP(x)	softn->(x)++
    122 #define	NBUMPD(x, y)	do { \
    123 				softn->x.y++; \
    124 				DT(y); \
    125 			} while (0)
    126 #define	NBUMPSIDE(y,x)	softn->ipf_nat_stats.ns_side[y].x++
    127 #define	NBUMPSIDED(y,x)	do { softn->ipf_nat_stats.ns_side[y].x++; \
    128 			     DT(x); } while (0)
    129 #define	NBUMPSIDEX(y,x,z) \
    130 			do { softn->ipf_nat_stats.ns_side[y].x++; \
    131 			     DT(z); } while (0)
    132 #define	NBUMPSIDEDF(y,x)do { softn->ipf_nat_stats.ns_side[y].x++; \
    133 			     DT1(x, fr_info_t *, fin); } while (0)
    134 
    135 frentry_t	ipfnatblock;
    136 
    137 static ipftuneable_t ipf_nat_tuneables[] = {
    138 	/* nat */
    139 	{ { (void *)offsetof(ipf_nat_softc_t, ipf_nat_lock) },
    140 		"nat_lock",	0,	1,
    141 		stsizeof(ipf_nat_softc_t, ipf_nat_lock),
    142 		IPFT_RDONLY,		NULL,	NULL },
    143 	{ { (void *)offsetof(ipf_nat_softc_t, ipf_nat_table_sz) },
    144 		"nat_table_size", 1,	0x7fffffff,
    145 		stsizeof(ipf_nat_softc_t, ipf_nat_table_sz),
    146 		0,			NULL,	ipf_nat_rehash },
    147 	{ { (void *)offsetof(ipf_nat_softc_t, ipf_nat_table_max) },
    148 		"nat_table_max", 1,	0x7fffffff,
    149 		stsizeof(ipf_nat_softc_t, ipf_nat_table_max),
    150 		0,			NULL,	NULL },
    151 	{ { (void *)offsetof(ipf_nat_softc_t, ipf_nat_maprules_sz) },
    152 		"nat_rules_size", 1,	0x7fffffff,
    153 		stsizeof(ipf_nat_softc_t, ipf_nat_maprules_sz),
    154 		0,			NULL,	ipf_nat_rehash_rules },
    155 	{ { (void *)offsetof(ipf_nat_softc_t, ipf_nat_rdrrules_sz) },
    156 		"rdr_rules_size", 1,	0x7fffffff,
    157 		stsizeof(ipf_nat_softc_t, ipf_nat_rdrrules_sz),
    158 		0,			NULL,	ipf_nat_rehash_rules },
    159 	{ { (void *)offsetof(ipf_nat_softc_t, ipf_nat_hostmap_sz) },
    160 		"hostmap_size",	1,	0x7fffffff,
    161 		stsizeof(ipf_nat_softc_t, ipf_nat_hostmap_sz),
    162 		0,			NULL,	ipf_nat_hostmap_rehash },
    163 	{ { (void *)offsetof(ipf_nat_softc_t, ipf_nat_maxbucket) },
    164 		"nat_maxbucket",1,	0x7fffffff,
    165 		stsizeof(ipf_nat_softc_t, ipf_nat_maxbucket),
    166 		0,			NULL,	NULL },
    167 	{ { (void *)offsetof(ipf_nat_softc_t, ipf_nat_logging) },
    168 		"nat_logging",	0,	1,
    169 		stsizeof(ipf_nat_softc_t, ipf_nat_logging),
    170 		0,			NULL,	NULL },
    171 	{ { (void *)offsetof(ipf_nat_softc_t, ipf_nat_doflush) },
    172 		"nat_doflush",	0,	1,
    173 		stsizeof(ipf_nat_softc_t, ipf_nat_doflush),
    174 		0,			NULL,	NULL },
    175 	{ { (void *)offsetof(ipf_nat_softc_t, ipf_nat_table_wm_low) },
    176 		"nat_table_wm_low",	1,	99,
    177 		stsizeof(ipf_nat_softc_t, ipf_nat_table_wm_low),
    178 		0,			NULL,	NULL },
    179 	{ { (void *)offsetof(ipf_nat_softc_t, ipf_nat_table_wm_high) },
    180 		"nat_table_wm_high",	2,	100,
    181 		stsizeof(ipf_nat_softc_t, ipf_nat_table_wm_high),
    182 		0,			NULL,	NULL },
    183 	{ { 0 },
    184 		NULL,			0,	0,
    185 		0,
    186 		0,			NULL,	NULL }
    187 };
    188 
    189 /* ======================================================================== */
    190 /* How the NAT is organised and works.                                      */
    191 /*                                                                          */
    192 /* Inside (interface y) NAT       Outside (interface x)                     */
    193 /* -------------------- -+- -------------------------------------           */
    194 /* Packet going          |   out, processsed by ipf_nat_checkout() for x    */
    195 /* ------------>         |   ------------>                                  */
    196 /* src=10.1.1.1          |   src=192.1.1.1                                  */
    197 /*                       |                                                  */
    198 /*                       |   in, processed by ipf_nat_checkin() for x       */
    199 /* <------------         |   <------------                                  */
    200 /* dst=10.1.1.1          |   dst=192.1.1.1                                  */
    201 /* -------------------- -+- -------------------------------------           */
    202 /* ipf_nat_checkout() - changes ip_src and if required, sport               */
    203 /*             - creates a new mapping, if required.                        */
    204 /* ipf_nat_checkin()  - changes ip_dst and if required, dport               */
    205 /*                                                                          */
    206 /* In the NAT table, internal source is recorded as "in" and externally     */
    207 /* seen as "out".                                                           */
    208 /* ======================================================================== */
    209 
    210 
    211 #if SOLARIS && !defined(INSTANCES)
    212 extern	int		pfil_delayed_copy;
    213 #endif
    214 
    215 static	int	ipf_nat_flush_entry __P((ipf_main_softc_t *, void *));
    216 static	int	ipf_nat_getent __P((ipf_main_softc_t *, caddr_t, int));
    217 static	int	ipf_nat_getsz __P((ipf_main_softc_t *, caddr_t, int));
    218 static	int	ipf_nat_putent __P((ipf_main_softc_t *, caddr_t, int));
    219 static	void	ipf_nat_addmap __P((ipf_nat_softc_t *, ipnat_t *));
    220 static	void	ipf_nat_addrdr __P((ipf_nat_softc_t *, ipnat_t *));
    221 static	int	ipf_nat_builddivertmp __P((ipf_nat_softc_t *, ipnat_t *));
    222 static	int	ipf_nat_clearlist __P((ipf_main_softc_t *, ipf_nat_softc_t *));
    223 static	int	ipf_nat_cmp_rules __P((ipnat_t *, ipnat_t *));
    224 static	int	ipf_nat_decap __P((fr_info_t *, nat_t *));
    225 static	void	ipf_nat_delrule __P((ipf_main_softc_t *, ipf_nat_softc_t *,
    226 				     ipnat_t *, int));
    227 static	int	ipf_nat_extraflush __P((ipf_main_softc_t *, ipf_nat_softc_t *, int));
    228 static	int	ipf_nat_finalise __P((fr_info_t *, nat_t *));
    229 static	int	ipf_nat_flushtable __P((ipf_main_softc_t *, ipf_nat_softc_t *));
    230 static	int	ipf_nat_getnext __P((ipf_main_softc_t *, ipftoken_t *,
    231 				     ipfgeniter_t *, ipfobj_t *));
    232 static	int	ipf_nat_gettable __P((ipf_main_softc_t *, ipf_nat_softc_t *,
    233 				      char *));
    234 static	hostmap_t *ipf_nat_hostmap __P((ipf_nat_softc_t *, ipnat_t *,
    235 					struct in_addr, struct in_addr,
    236 					struct in_addr, u_32_t));
    237 static	int	ipf_nat_icmpquerytype __P((int));
    238 static	int	ipf_nat_iterator __P((ipf_main_softc_t *, ipftoken_t *,
    239 				      ipfgeniter_t *, ipfobj_t *));
    240 static	int	ipf_nat_match __P((fr_info_t *, ipnat_t *));
    241 static	int	ipf_nat_matcharray __P((nat_t *, int *, u_long));
    242 static	int	ipf_nat_matchflush __P((ipf_main_softc_t *, ipf_nat_softc_t *,
    243 					caddr_t));
    244 static	void	ipf_nat_mssclamp __P((tcphdr_t *, u_32_t, fr_info_t *,
    245 				      u_short *));
    246 static	int	ipf_nat_newmap __P((fr_info_t *, nat_t *, natinfo_t *));
    247 static	int	ipf_nat_newdivert __P((fr_info_t *, nat_t *, natinfo_t *));
    248 static	int	ipf_nat_newrdr __P((fr_info_t *, nat_t *, natinfo_t *));
    249 static	int	ipf_nat_newrewrite __P((fr_info_t *, nat_t *, natinfo_t *));
    250 static	int	ipf_nat_nextaddr __P((fr_info_t *, nat_addr_t *, u_32_t *,
    251 				      u_32_t *));
    252 static	int	ipf_nat_nextaddrinit __P((ipf_main_softc_t *, char *,
    253 					  nat_addr_t *, int, void *));
    254 static	int	ipf_nat_resolverule __P((ipf_main_softc_t *, ipnat_t *));
    255 static	int	ipf_nat_ruleaddrinit __P((ipf_main_softc_t *,
    256 					  ipf_nat_softc_t *, ipnat_t *));
    257 static	void	ipf_nat_rule_fini __P((ipf_main_softc_t *, ipnat_t *));
    258 static	int	ipf_nat_rule_init __P((ipf_main_softc_t *, ipf_nat_softc_t *,
    259 				       ipnat_t *));
    260 static	int	ipf_nat_siocaddnat __P((ipf_main_softc_t *, ipf_nat_softc_t *,
    261 					ipnat_t *, int));
    262 static	void	ipf_nat_siocdelnat __P((ipf_main_softc_t *, ipf_nat_softc_t *,
    263 					ipnat_t *, int));
    264 static	void	ipf_nat_tabmove __P((ipf_nat_softc_t *, nat_t *));
    265 
    266 /* ------------------------------------------------------------------------ */
    267 /* Function:    ipf_nat_main_load                                           */
    268 /* Returns:     int - 0 == success, -1 == failure                           */
    269 /* Parameters:  Nil                                                         */
    270 /*                                                                          */
    271 /* The only global NAT structure that needs to be initialised is the filter */
    272 /* rule that is used with blocking packets.                                 */
    273 /* ------------------------------------------------------------------------ */
    274 int
    275 ipf_nat_main_load()
    276 {
    277 	bzero((char *)&ipfnatblock, sizeof(ipfnatblock));
    278 	ipfnatblock.fr_flags = FR_BLOCK|FR_QUICK;
    279 	ipfnatblock.fr_ref = 1;
    280 
    281 	return 0;
    282 }
    283 
    284 
    285 /* ------------------------------------------------------------------------ */
    286 /* Function:    ipf_nat_main_unload                                         */
    287 /* Returns:     int - 0 == success, -1 == failure                           */
    288 /* Parameters:  Nil                                                         */
    289 /*                                                                          */
    290 /* A null-op function that exists as a placeholder so that the flow in      */
    291 /* other functions is obvious.                                              */
    292 /* ------------------------------------------------------------------------ */
    293 int
    294 ipf_nat_main_unload()
    295 {
    296 	return 0;
    297 }
    298 
    299 
    300 /* ------------------------------------------------------------------------ */
    301 /* Function:    ipf_nat_soft_create                                         */
    302 /* Returns:     void * - NULL = failure, else pointer to NAT context        */
    303 /* Parameters:  softc(I) - pointer to soft context main structure           */
    304 /*                                                                          */
    305 /* Allocate the initial soft context structure for NAT and populate it with */
    306 /* some default values. Creating the tables is left until we call _init so  */
    307 /* that sizes can be changed before we get under way.                       */
    308 /* ------------------------------------------------------------------------ */
    309 void *
    310 ipf_nat_soft_create(softc)
    311 	ipf_main_softc_t *softc;
    312 {
    313 	ipf_nat_softc_t *softn;
    314 
    315 	KMALLOC(softn, ipf_nat_softc_t *);
    316 	if (softn == NULL)
    317 		return NULL;
    318 
    319 	bzero((char *)softn, sizeof(*softn));
    320 
    321 	softn->ipf_nat_tune = ipf_tune_array_copy(softn,
    322 						  sizeof(ipf_nat_tuneables),
    323 						  ipf_nat_tuneables);
    324 	if (softn->ipf_nat_tune == NULL) {
    325 		ipf_nat_soft_destroy(softc, softn);
    326 		return NULL;
    327 	}
    328 	if (ipf_tune_array_link(softc, softn->ipf_nat_tune) == -1) {
    329 		ipf_nat_soft_destroy(softc, softn);
    330 		return NULL;
    331 	}
    332 
    333 	softn->ipf_nat_list_tail = &softn->ipf_nat_list;
    334 
    335 	softn->ipf_nat_table_max = NAT_TABLE_MAX;
    336 	softn->ipf_nat_table_sz = NAT_TABLE_SZ;
    337 	softn->ipf_nat_maprules_sz = NAT_SIZE;
    338 	softn->ipf_nat_rdrrules_sz = RDR_SIZE;
    339 	softn->ipf_nat_hostmap_sz = HOSTMAP_SIZE;
    340 	softn->ipf_nat_doflush = 0;
    341 #ifdef  IPFILTER_LOG
    342 	softn->ipf_nat_logging = 1;
    343 #else
    344 	softn->ipf_nat_logging = 0;
    345 #endif
    346 
    347 	softn->ipf_nat_defage = DEF_NAT_AGE;
    348 	softn->ipf_nat_defipage = IPF_TTLVAL(60);
    349 	softn->ipf_nat_deficmpage = IPF_TTLVAL(3);
    350 	softn->ipf_nat_table_wm_high = 99;
    351 	softn->ipf_nat_table_wm_low = 90;
    352 
    353 	return softn;
    354 }
    355 
    356 /* ------------------------------------------------------------------------ */
    357 /* Function:    ipf_nat_soft_destroy                                        */
    358 /* Returns:     Nil                                                         */
    359 /* Parameters:  softc(I) - pointer to soft context main structure           */
    360 /*                                                                          */
    361 /* ------------------------------------------------------------------------ */
    362 void
    363 ipf_nat_soft_destroy(softc, arg)
    364 	ipf_main_softc_t *softc;
    365 	void *arg;
    366 {
    367 	ipf_nat_softc_t *softn = arg;
    368 
    369 	if (softn->ipf_nat_tune != NULL) {
    370 		ipf_tune_array_unlink(softc, softn->ipf_nat_tune);
    371 		KFREES(softn->ipf_nat_tune, sizeof(ipf_nat_tuneables));
    372 		softn->ipf_nat_tune = NULL;
    373 	}
    374 
    375 	KFREE(softn);
    376 }
    377 
    378 
    379 /* ------------------------------------------------------------------------ */
    380 /* Function:    ipf_nat_init                                                */
    381 /* Returns:     int - 0 == success, -1 == failure                           */
    382 /* Parameters:  softc(I) - pointer to soft context main structure           */
    383 /*                                                                          */
    384 /* Initialise all of the NAT locks, tables and other structures.            */
    385 /* ------------------------------------------------------------------------ */
    386 int
    387 ipf_nat_soft_init(softc, arg)
    388 	ipf_main_softc_t *softc;
    389 	void *arg;
    390 {
    391 	ipf_nat_softc_t *softn = arg;
    392 	ipftq_t *tq;
    393 	int i;
    394 
    395 	KMALLOCS(softn->ipf_nat_table[0], nat_t **, \
    396 		 sizeof(nat_t *) * softn->ipf_nat_table_sz);
    397 
    398 	if (softn->ipf_nat_table[0] != NULL) {
    399 		bzero((char *)softn->ipf_nat_table[0],
    400 		      softn->ipf_nat_table_sz * sizeof(nat_t *));
    401 	} else {
    402 		return -1;
    403 	}
    404 
    405 	KMALLOCS(softn->ipf_nat_table[1], nat_t **, \
    406 		 sizeof(nat_t *) * softn->ipf_nat_table_sz);
    407 
    408 	if (softn->ipf_nat_table[1] != NULL) {
    409 		bzero((char *)softn->ipf_nat_table[1],
    410 		      softn->ipf_nat_table_sz * sizeof(nat_t *));
    411 	} else {
    412 		return -2;
    413 	}
    414 
    415 	KMALLOCS(softn->ipf_nat_map_rules, ipnat_t **, \
    416 		 sizeof(ipnat_t *) * softn->ipf_nat_maprules_sz);
    417 
    418 	if (softn->ipf_nat_map_rules != NULL) {
    419 		bzero((char *)softn->ipf_nat_map_rules,
    420 		      softn->ipf_nat_maprules_sz * sizeof(ipnat_t *));
    421 	} else {
    422 		return -3;
    423 	}
    424 
    425 	KMALLOCS(softn->ipf_nat_rdr_rules, ipnat_t **, \
    426 		 sizeof(ipnat_t *) * softn->ipf_nat_rdrrules_sz);
    427 
    428 	if (softn->ipf_nat_rdr_rules != NULL) {
    429 		bzero((char *)softn->ipf_nat_rdr_rules,
    430 		      softn->ipf_nat_rdrrules_sz * sizeof(ipnat_t *));
    431 	} else {
    432 		return -4;
    433 	}
    434 
    435 	KMALLOCS(softn->ipf_hm_maptable, hostmap_t **, \
    436 		 sizeof(hostmap_t *) * softn->ipf_nat_hostmap_sz);
    437 
    438 	if (softn->ipf_hm_maptable != NULL) {
    439 		bzero((char *)softn->ipf_hm_maptable,
    440 		      sizeof(hostmap_t *) * softn->ipf_nat_hostmap_sz);
    441 	} else {
    442 		return -5;
    443 	}
    444 	softn->ipf_hm_maplist = NULL;
    445 
    446 	KMALLOCS(softn->ipf_nat_stats.ns_side[0].ns_bucketlen, u_int *,
    447 		 softn->ipf_nat_table_sz * sizeof(u_int));
    448 
    449 	if (softn->ipf_nat_stats.ns_side[0].ns_bucketlen == NULL) {
    450 		return -6;
    451 	}
    452 	bzero((char *)softn->ipf_nat_stats.ns_side[0].ns_bucketlen,
    453 	      softn->ipf_nat_table_sz * sizeof(u_int));
    454 
    455 	KMALLOCS(softn->ipf_nat_stats.ns_side[1].ns_bucketlen, u_int *,
    456 		 softn->ipf_nat_table_sz * sizeof(u_int));
    457 
    458 	if (softn->ipf_nat_stats.ns_side[1].ns_bucketlen == NULL) {
    459 		return -7;
    460 	}
    461 
    462 	bzero((char *)softn->ipf_nat_stats.ns_side[1].ns_bucketlen,
    463 	      softn->ipf_nat_table_sz * sizeof(u_int));
    464 
    465 	if (softn->ipf_nat_maxbucket == 0) {
    466 		for (i = softn->ipf_nat_table_sz; i > 0; i >>= 1)
    467 			softn->ipf_nat_maxbucket++;
    468 		softn->ipf_nat_maxbucket *= 2;
    469 	}
    470 
    471 	ipf_sttab_init(softc, softn->ipf_nat_tcptq);
    472 	/*
    473 	 * Increase this because we may have "keep state" following this too
    474 	 * and packet storms can occur if this is removed too quickly.
    475 	 */
    476 	softn->ipf_nat_tcptq[IPF_TCPS_CLOSED].ifq_ttl = softc->ipf_tcplastack;
    477 	softn->ipf_nat_tcptq[IPF_TCP_NSTATES - 1].ifq_next =
    478 							&softn->ipf_nat_udptq;
    479 
    480 	IPFTQ_INIT(&softn->ipf_nat_udptq, softn->ipf_nat_defage,
    481 		   "nat ipftq udp tab");
    482 	softn->ipf_nat_udptq.ifq_next = &softn->ipf_nat_udpacktq;
    483 
    484 	IPFTQ_INIT(&softn->ipf_nat_udpacktq, softn->ipf_nat_defage,
    485 		   "nat ipftq udpack tab");
    486 	softn->ipf_nat_udpacktq.ifq_next = &softn->ipf_nat_icmptq;
    487 
    488 	IPFTQ_INIT(&softn->ipf_nat_icmptq, softn->ipf_nat_deficmpage,
    489 		   "nat icmp ipftq tab");
    490 	softn->ipf_nat_icmptq.ifq_next = &softn->ipf_nat_icmpacktq;
    491 
    492 	IPFTQ_INIT(&softn->ipf_nat_icmpacktq, softn->ipf_nat_defage,
    493 		   "nat icmpack ipftq tab");
    494 	softn->ipf_nat_icmpacktq.ifq_next = &softn->ipf_nat_iptq;
    495 
    496 	IPFTQ_INIT(&softn->ipf_nat_iptq, softn->ipf_nat_defipage,
    497 		   "nat ip ipftq tab");
    498 	softn->ipf_nat_iptq.ifq_next = &softn->ipf_nat_pending;
    499 
    500 	IPFTQ_INIT(&softn->ipf_nat_pending, 1, "nat pending ipftq tab");
    501 	softn->ipf_nat_pending.ifq_next = NULL;
    502 
    503 	for (i = 0, tq = softn->ipf_nat_tcptq; i < IPF_TCP_NSTATES; i++, tq++) {
    504 		if (tq->ifq_ttl < softn->ipf_nat_deficmpage)
    505 			tq->ifq_ttl = softn->ipf_nat_deficmpage;
    506 #ifdef LARGE_NAT
    507 		else if (tq->ifq_ttl > softn->ipf_nat_defage)
    508 			tq->ifq_ttl = softn->ipf_nat_defage;
    509 #endif
    510 	}
    511 
    512 	/*
    513 	 * Increase this because we may have "keep state" following
    514 	 * this too and packet storms can occur if this is removed
    515 	 * too quickly.
    516 	 */
    517 	softn->ipf_nat_tcptq[IPF_TCPS_CLOSED].ifq_ttl = softc->ipf_tcplastack;
    518 
    519 	MUTEX_INIT(&softn->ipf_nat_new, "ipf nat new mutex");
    520 	MUTEX_INIT(&softn->ipf_nat_io, "ipf nat io mutex");
    521 
    522 	softn->ipf_nat_inited = 1;
    523 
    524 	return 0;
    525 }
    526 
    527 
    528 /* ------------------------------------------------------------------------ */
    529 /* Function:    ipf_nat_soft_fini                                           */
    530 /* Returns:     Nil                                                         */
    531 /* Parameters:  softc(I) - pointer to soft context main structure           */
    532 /*                                                                          */
    533 /* Free all memory used by NAT structures allocated at runtime.             */
    534 /* ------------------------------------------------------------------------ */
    535 int
    536 ipf_nat_soft_fini(softc, arg)
    537 	ipf_main_softc_t *softc;
    538 	void *arg;
    539 {
    540 	ipf_nat_softc_t *softn = arg;
    541 	ipftq_t *ifq, *ifqnext;
    542 
    543 	(void) ipf_nat_clearlist(softc, softn);
    544 	(void) ipf_nat_flushtable(softc, softn);
    545 
    546 	/*
    547 	 * Proxy timeout queues are not cleaned here because although they
    548 	 * exist on the NAT list, ipf_proxy_unload is called after unload
    549 	 * and the proxies actually are responsible for them being created.
    550 	 * Should the proxy timeouts have their own list?  There's no real
    551 	 * justification as this is the only complication.
    552 	 */
    553 	for (ifq = softn->ipf_nat_utqe; ifq != NULL; ifq = ifqnext) {
    554 		ifqnext = ifq->ifq_next;
    555 		if (ipf_deletetimeoutqueue(ifq) == 0)
    556 			ipf_freetimeoutqueue(softc, ifq);
    557 	}
    558 
    559 	if (softn->ipf_nat_table[0] != NULL) {
    560 		KFREES(softn->ipf_nat_table[0],
    561 		       sizeof(nat_t *) * softn->ipf_nat_table_sz);
    562 		softn->ipf_nat_table[0] = NULL;
    563 	}
    564 	if (softn->ipf_nat_table[1] != NULL) {
    565 		KFREES(softn->ipf_nat_table[1],
    566 		       sizeof(nat_t *) * softn->ipf_nat_table_sz);
    567 		softn->ipf_nat_table[1] = NULL;
    568 	}
    569 	if (softn->ipf_nat_map_rules != NULL) {
    570 		KFREES(softn->ipf_nat_map_rules,
    571 		       sizeof(ipnat_t *) * softn->ipf_nat_maprules_sz);
    572 		softn->ipf_nat_map_rules = NULL;
    573 	}
    574 	if (softn->ipf_nat_rdr_rules != NULL) {
    575 		KFREES(softn->ipf_nat_rdr_rules,
    576 		       sizeof(ipnat_t *) * softn->ipf_nat_rdrrules_sz);
    577 		softn->ipf_nat_rdr_rules = NULL;
    578 	}
    579 	if (softn->ipf_hm_maptable != NULL) {
    580 		KFREES(softn->ipf_hm_maptable,
    581 		       sizeof(hostmap_t *) * softn->ipf_nat_hostmap_sz);
    582 		softn->ipf_hm_maptable = NULL;
    583 	}
    584 	if (softn->ipf_nat_stats.ns_side[0].ns_bucketlen != NULL) {
    585 		KFREES(softn->ipf_nat_stats.ns_side[0].ns_bucketlen,
    586 		       sizeof(u_int) * softn->ipf_nat_table_sz);
    587 		softn->ipf_nat_stats.ns_side[0].ns_bucketlen = NULL;
    588 	}
    589 	if (softn->ipf_nat_stats.ns_side[1].ns_bucketlen != NULL) {
    590 		KFREES(softn->ipf_nat_stats.ns_side[1].ns_bucketlen,
    591 		       sizeof(u_int) * softn->ipf_nat_table_sz);
    592 		softn->ipf_nat_stats.ns_side[1].ns_bucketlen = NULL;
    593 	}
    594 
    595 	if (softn->ipf_nat_inited == 1) {
    596 		softn->ipf_nat_inited = 0;
    597 		ipf_sttab_destroy(softn->ipf_nat_tcptq);
    598 
    599 		MUTEX_DESTROY(&softn->ipf_nat_new);
    600 		MUTEX_DESTROY(&softn->ipf_nat_io);
    601 
    602 		MUTEX_DESTROY(&softn->ipf_nat_udptq.ifq_lock);
    603 		MUTEX_DESTROY(&softn->ipf_nat_udpacktq.ifq_lock);
    604 		MUTEX_DESTROY(&softn->ipf_nat_icmptq.ifq_lock);
    605 		MUTEX_DESTROY(&softn->ipf_nat_icmpacktq.ifq_lock);
    606 		MUTEX_DESTROY(&softn->ipf_nat_iptq.ifq_lock);
    607 		MUTEX_DESTROY(&softn->ipf_nat_pending.ifq_lock);
    608 	}
    609 
    610 	return 0;
    611 }
    612 
    613 
    614 /* ------------------------------------------------------------------------ */
    615 /* Function:    ipf_nat_setlock                                             */
    616 /* Returns:     Nil                                                         */
    617 /* Parameters:  arg(I) - pointer to soft state information                  */
    618 /*              tmp(I) - new lock value                                     */
    619 /*                                                                          */
    620 /* Set the "lock status" of NAT to the value in tmp.                        */
    621 /* ------------------------------------------------------------------------ */
    622 void
    623 ipf_nat_setlock(arg, tmp)
    624 	void *arg;
    625 	int tmp;
    626 {
    627 	ipf_nat_softc_t *softn = arg;
    628 
    629 	softn->ipf_nat_lock = tmp;
    630 }
    631 
    632 
    633 /* ------------------------------------------------------------------------ */
    634 /* Function:    ipf_nat_addrdr                                              */
    635 /* Returns:     Nil                                                         */
    636 /* Parameters:  n(I) - pointer to NAT rule to add                           */
    637 /*                                                                          */
    638 /* Adds a redirect rule to the hash table of redirect rules and the list of */
    639 /* loaded NAT rules.  Updates the bitmask indicating which netmasks are in  */
    640 /* use by redirect rules.                                                   */
    641 /* ------------------------------------------------------------------------ */
    642 static void
    643 ipf_nat_addrdr(softn, n)
    644 	ipf_nat_softc_t *softn;
    645 	ipnat_t *n;
    646 {
    647 	ipnat_t **np;
    648 	u_32_t j;
    649 	u_int hv;
    650 	u_int rhv;
    651 	int k;
    652 
    653 	if (n->in_odstatype == FRI_NORMAL) {
    654 		k = count4bits(n->in_odstmsk);
    655 		ipf_inet_mask_add(k, &softn->ipf_nat_rdr_mask);
    656 		j = (n->in_odstaddr & n->in_odstmsk);
    657 		rhv = NAT_HASH_FN(j, 0, 0xffffffff);
    658 	} else {
    659 		ipf_inet_mask_add(0, &softn->ipf_nat_rdr_mask);
    660 		j = 0;
    661 		rhv = 0;
    662 	}
    663 	hv = rhv % softn->ipf_nat_rdrrules_sz;
    664 	np = softn->ipf_nat_rdr_rules + hv;
    665 	while (*np != NULL)
    666 		np = &(*np)->in_rnext;
    667 	n->in_rnext = NULL;
    668 	n->in_prnext = np;
    669 	n->in_hv[0] = hv;
    670 	n->in_use++;
    671 	*np = n;
    672 }
    673 
    674 
    675 /* ------------------------------------------------------------------------ */
    676 /* Function:    ipf_nat_addmap                                              */
    677 /* Returns:     Nil                                                         */
    678 /* Parameters:  n(I) - pointer to NAT rule to add                           */
    679 /*                                                                          */
    680 /* Adds a NAT map rule to the hash table of rules and the list of  loaded   */
    681 /* NAT rules.  Updates the bitmask indicating which netmasks are in use by  */
    682 /* redirect rules.                                                          */
    683 /* ------------------------------------------------------------------------ */
    684 static void
    685 ipf_nat_addmap(softn, n)
    686 	ipf_nat_softc_t *softn;
    687 	ipnat_t *n;
    688 {
    689 	ipnat_t **np;
    690 	u_32_t j;
    691 	u_int hv;
    692 	u_int rhv;
    693 	int k;
    694 
    695 	if (n->in_osrcatype == FRI_NORMAL) {
    696 		k = count4bits(n->in_osrcmsk);
    697 		ipf_inet_mask_add(k, &softn->ipf_nat_map_mask);
    698 		j = (n->in_osrcaddr & n->in_osrcmsk);
    699 		rhv = NAT_HASH_FN(j, 0, 0xffffffff);
    700 	} else {
    701 		ipf_inet_mask_add(0, &softn->ipf_nat_map_mask);
    702 		j = 0;
    703 		rhv = 0;
    704 	}
    705 	hv = rhv % softn->ipf_nat_maprules_sz;
    706 	np = softn->ipf_nat_map_rules + hv;
    707 	while (*np != NULL)
    708 		np = &(*np)->in_mnext;
    709 	n->in_mnext = NULL;
    710 	n->in_pmnext = np;
    711 	n->in_hv[1] = rhv;
    712 	n->in_use++;
    713 	*np = n;
    714 }
    715 
    716 
    717 /* ------------------------------------------------------------------------ */
    718 /* Function:    ipf_nat_delrdr                                              */
    719 /* Returns:     Nil                                                         */
    720 /* Parameters:  n(I) - pointer to NAT rule to delete                        */
    721 /*                                                                          */
    722 /* Removes a redirect rule from the hash table of redirect rules.           */
    723 /* ------------------------------------------------------------------------ */
    724 void
    725 ipf_nat_delrdr(softn, n)
    726 	ipf_nat_softc_t *softn;
    727 	ipnat_t *n;
    728 {
    729 	if (n->in_odstatype == FRI_NORMAL) {
    730 		int k = count4bits(n->in_odstmsk);
    731 		ipf_inet_mask_del(k, &softn->ipf_nat_rdr_mask);
    732 	} else {
    733 		ipf_inet_mask_del(0, &softn->ipf_nat_rdr_mask);
    734 	}
    735 	if (n->in_rnext)
    736 		n->in_rnext->in_prnext = n->in_prnext;
    737 	*n->in_prnext = n->in_rnext;
    738 	n->in_use--;
    739 }
    740 
    741 
    742 /* ------------------------------------------------------------------------ */
    743 /* Function:    ipf_nat_delmap                                              */
    744 /* Returns:     Nil                                                         */
    745 /* Parameters:  n(I) - pointer to NAT rule to delete                        */
    746 /*                                                                          */
    747 /* Removes a NAT map rule from the hash table of NAT map rules.             */
    748 /* ------------------------------------------------------------------------ */
    749 void
    750 ipf_nat_delmap(softn, n)
    751 	ipf_nat_softc_t *softn;
    752 	ipnat_t *n;
    753 {
    754 	if (n->in_osrcatype == FRI_NORMAL) {
    755 		int k = count4bits(n->in_osrcmsk);
    756 		ipf_inet_mask_del(k, &softn->ipf_nat_map_mask);
    757 	} else {
    758 		ipf_inet_mask_del(0, &softn->ipf_nat_map_mask);
    759 	}
    760 	if (n->in_mnext != NULL)
    761 		n->in_mnext->in_pmnext = n->in_pmnext;
    762 	*n->in_pmnext = n->in_mnext;
    763 	n->in_use--;
    764 }
    765 
    766 
    767 /* ------------------------------------------------------------------------ */
    768 /* Function:    ipf_nat_hostmap                                             */
    769 /* Returns:     struct hostmap* - NULL if no hostmap could be created,      */
    770 /*                                else a pointer to the hostmapping to use  */
    771 /* Parameters:  np(I)   - pointer to NAT rule                               */
    772 /*              real(I) - real IP address                                   */
    773 /*              map(I)  - mapped IP address                                 */
    774 /*              port(I) - destination port number                           */
    775 /* Write Locks: ipf_nat                                                     */
    776 /*                                                                          */
    777 /* Check if an ip address has already been allocated for a given mapping    */
    778 /* that is not doing port based translation.  If is not yet allocated, then */
    779 /* create a new entry if a non-NULL NAT rule pointer has been supplied.     */
    780 /* ------------------------------------------------------------------------ */
    781 static struct hostmap *
    782 ipf_nat_hostmap(softn, np, src, dst, map, port)
    783 	ipf_nat_softc_t *softn;
    784 	ipnat_t *np;
    785 	struct in_addr src;
    786 	struct in_addr dst;
    787 	struct in_addr map;
    788 	u_32_t port;
    789 {
    790 	hostmap_t *hm;
    791 	u_int hv, rhv;
    792 
    793 	hv = (src.s_addr ^ dst.s_addr);
    794 	hv += src.s_addr;
    795 	hv += dst.s_addr;
    796 	rhv = hv;
    797 	hv %= softn->ipf_nat_hostmap_sz;
    798 	for (hm = softn->ipf_hm_maptable[hv]; hm; hm = hm->hm_hnext)
    799 		if ((hm->hm_osrcip.s_addr == src.s_addr) &&
    800 		    (hm->hm_odstip.s_addr == dst.s_addr) &&
    801 		    ((np == NULL) || (np == hm->hm_ipnat)) &&
    802 		    ((port == 0) || (port == hm->hm_port))) {
    803 			softn->ipf_nat_stats.ns_hm_addref++;
    804 			hm->hm_ref++;
    805 			return hm;
    806 		}
    807 
    808 	if (np == NULL) {
    809 		softn->ipf_nat_stats.ns_hm_nullnp++;
    810 		return NULL;
    811 	}
    812 
    813 	KMALLOC(hm, hostmap_t *);
    814 	if (hm) {
    815 		hm->hm_next = softn->ipf_hm_maplist;
    816 		hm->hm_pnext = &softn->ipf_hm_maplist;
    817 		if (softn->ipf_hm_maplist != NULL)
    818 			softn->ipf_hm_maplist->hm_pnext = &hm->hm_next;
    819 		softn->ipf_hm_maplist = hm;
    820 		hm->hm_hnext = softn->ipf_hm_maptable[hv];
    821 		hm->hm_phnext = softn->ipf_hm_maptable + hv;
    822 		if (softn->ipf_hm_maptable[hv] != NULL)
    823 			softn->ipf_hm_maptable[hv]->hm_phnext = &hm->hm_hnext;
    824 		softn->ipf_hm_maptable[hv] = hm;
    825 		hm->hm_ipnat = np;
    826 		np->in_use++;
    827 		hm->hm_osrcip = src;
    828 		hm->hm_odstip = dst;
    829 		hm->hm_nsrcip = map;
    830 		hm->hm_ndstip.s_addr = 0;
    831 		hm->hm_ref = 1;
    832 		hm->hm_port = port;
    833 		hm->hm_hv = rhv;
    834 		hm->hm_v = 4;
    835 		softn->ipf_nat_stats.ns_hm_new++;
    836 	} else {
    837 		softn->ipf_nat_stats.ns_hm_newfail++;
    838 	}
    839 	return hm;
    840 }
    841 
    842 
    843 /* ------------------------------------------------------------------------ */
    844 /* Function:    ipf_nat_hostmapdel                                          */
    845 /* Returns:     Nil                                                         */
    846 /* Parameters:  hmp(I) - pointer to hostmap structure pointer               */
    847 /* Write Locks: ipf_nat                                                     */
    848 /*                                                                          */
    849 /* Decrement the references to this hostmap structure by one.  If this      */
    850 /* reaches zero then remove it and free it.                                 */
    851 /* ------------------------------------------------------------------------ */
    852 void
    853 ipf_nat_hostmapdel(softc, hmp)
    854 	ipf_main_softc_t *softc;
    855 	struct hostmap **hmp;
    856 {
    857 	struct hostmap *hm;
    858 
    859 	hm = *hmp;
    860 	*hmp = NULL;
    861 
    862 	hm->hm_ref--;
    863 	if (hm->hm_ref == 0) {
    864 		ipf_nat_rule_deref(softc, &hm->hm_ipnat);
    865 		if (hm->hm_hnext)
    866 			hm->hm_hnext->hm_phnext = hm->hm_phnext;
    867 		*hm->hm_phnext = hm->hm_hnext;
    868 		if (hm->hm_next)
    869 			hm->hm_next->hm_pnext = hm->hm_pnext;
    870 		*hm->hm_pnext = hm->hm_next;
    871 		KFREE(hm);
    872 	}
    873 }
    874 
    875 
    876 /* ------------------------------------------------------------------------ */
    877 /* Function:    ipf_fix_outcksum                                            */
    878 /* Returns:     Nil                                                         */
    879 /* Parameters:  fin(I) - pointer to packet information                      */
    880 /*              sp(I)  - location of 16bit checksum to update               */
    881 /*              n((I)  - amount to adjust checksum by                       */
    882 /*                                                                          */
    883 /* Adjusts the 16bit checksum by "n" for packets going out.                 */
    884 /* ------------------------------------------------------------------------ */
    885 void
    886 ipf_fix_outcksum(cksum, sp, n, partial)
    887 	int cksum;
    888 	u_short *sp;
    889 	u_32_t n, partial;
    890 {
    891 	u_short sumshort;
    892 	u_32_t sum1;
    893 
    894 	if (n == 0)
    895 		return;
    896 
    897 	if (cksum == 4) {
    898 		*sp = 0;
    899 		return;
    900 	}
    901 	if (cksum == 2) {
    902 		sum1 = partial;
    903 		sum1 = (sum1 & 0xffff) + (sum1 >> 16);
    904 		*sp = htons(sum1);
    905 		return;
    906 	}
    907 	sum1 = (~ntohs(*sp)) & 0xffff;
    908 	sum1 += (n);
    909 	sum1 = (sum1 >> 16) + (sum1 & 0xffff);
    910 	/* Again */
    911 	sum1 = (sum1 >> 16) + (sum1 & 0xffff);
    912 	sumshort = ~(u_short)sum1;
    913 	*(sp) = htons(sumshort);
    914 }
    915 
    916 
    917 /* ------------------------------------------------------------------------ */
    918 /* Function:    ipf_fix_incksum                                             */
    919 /* Returns:     Nil                                                         */
    920 /* Parameters:  fin(I) - pointer to packet information                      */
    921 /*              sp(I)  - location of 16bit checksum to update               */
    922 /*              n((I)  - amount to adjust checksum by                       */
    923 /*                                                                          */
    924 /* Adjusts the 16bit checksum by "n" for packets going in.                  */
    925 /* ------------------------------------------------------------------------ */
    926 void
    927 ipf_fix_incksum(cksum, sp, n, partial)
    928 	int cksum;
    929 	u_short *sp;
    930 	u_32_t n, partial;
    931 {
    932 	u_short sumshort;
    933 	u_32_t sum1;
    934 
    935 	if (n == 0)
    936 		return;
    937 
    938 	if (cksum == 4) {
    939 		*sp = 0;
    940 		return;
    941 	}
    942 	if (cksum == 2) {
    943 		sum1 = partial;
    944 		sum1 = (sum1 & 0xffff) + (sum1 >> 16);
    945 		*sp = htons(sum1);
    946 		return;
    947 	}
    948 
    949 	sum1 = (~ntohs(*sp)) & 0xffff;
    950 	sum1 += ~(n) & 0xffff;
    951 	sum1 = (sum1 >> 16) + (sum1 & 0xffff);
    952 	/* Again */
    953 	sum1 = (sum1 >> 16) + (sum1 & 0xffff);
    954 	sumshort = ~(u_short)sum1;
    955 	*(sp) = htons(sumshort);
    956 }
    957 
    958 
    959 /* ------------------------------------------------------------------------ */
    960 /* Function:    ipf_fix_datacksum                                           */
    961 /* Returns:     Nil                                                         */
    962 /* Parameters:  sp(I)  - location of 16bit checksum to update               */
    963 /*              n((I)  - amount to adjust checksum by                       */
    964 /*                                                                          */
    965 /* Fix_datacksum is used *only* for the adjustments of checksums in the     */
    966 /* data section of an IP packet.                                            */
    967 /*                                                                          */
    968 /* The only situation in which you need to do this is when NAT'ing an       */
    969 /* ICMP error message. Such a message, contains in its body the IP header   */
    970 /* of the original IP packet, that causes the error.                        */
    971 /*                                                                          */
    972 /* You can't use fix_incksum or fix_outcksum in that case, because for the  */
    973 /* kernel the data section of the ICMP error is just data, and no special   */
    974 /* processing like hardware cksum or ntohs processing have been done by the */
    975 /* kernel on the data section.                                              */
    976 /* ------------------------------------------------------------------------ */
    977 void
    978 ipf_fix_datacksum(sp, n)
    979 	u_short *sp;
    980 	u_32_t n;
    981 {
    982 	u_short sumshort;
    983 	u_32_t sum1;
    984 
    985 	if (n == 0)
    986 		return;
    987 
    988 	sum1 = (~ntohs(*sp)) & 0xffff;
    989 	sum1 += (n);
    990 	sum1 = (sum1 >> 16) + (sum1 & 0xffff);
    991 	/* Again */
    992 	sum1 = (sum1 >> 16) + (sum1 & 0xffff);
    993 	sumshort = ~(u_short)sum1;
    994 	*(sp) = htons(sumshort);
    995 }
    996 
    997 
    998 /* ------------------------------------------------------------------------ */
    999 /* Function:    ipf_nat_ioctl                                               */
   1000 /* Returns:     int - 0 == success, != 0 == failure                         */
   1001 /* Parameters:  softc(I) - pointer to soft context main structure           */
   1002 /*              data(I)  - pointer to ioctl data                            */
   1003 /*              cmd(I)   - ioctl command integer                            */
   1004 /*              mode(I)  - file mode bits used with open                    */
   1005 /*              uid(I)   - uid of calling process                           */
   1006 /*              ctx(I)   - pointer used as key for finding context          */
   1007 /*                                                                          */
   1008 /* Processes an ioctl call made to operate on the IP Filter NAT device.     */
   1009 /* ------------------------------------------------------------------------ */
   1010 int
   1011 ipf_nat_ioctl(softc, data, cmd, mode, uid, ctx)
   1012 	ipf_main_softc_t *softc;
   1013 	ioctlcmd_t cmd;
   1014 	caddr_t data;
   1015 	int mode, uid;
   1016 	void *ctx;
   1017 {
   1018 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   1019 	int error = 0, ret, arg, getlock;
   1020 	ipnat_t *nat, *nt, *n;
   1021 	ipnat_t natd;
   1022 	SPL_INT(s);
   1023 
   1024 #if BSD_GE_YEAR(199306) && defined(_KERNEL)
   1025 # if NETBSD_GE_REV(399002000)
   1026 	if ((mode & FWRITE) &&
   1027 	     kauth_authorize_network(curlwp->l_cred, KAUTH_NETWORK_FIREWALL,
   1028 				     KAUTH_REQ_NETWORK_FIREWALL_FW,
   1029 				     NULL, NULL, NULL))
   1030 # else
   1031 #  if defined(__FreeBSD_version) && (__FreeBSD_version >= 500034)
   1032 	if (securelevel_ge(curthread->td_ucred, 3) && (mode & FWRITE))
   1033 #  else
   1034 	if ((securelevel >= 3) && (mode & FWRITE))
   1035 #  endif
   1036 # endif
   1037 	{
   1038 		IPFERROR(60001);
   1039 		return EPERM;
   1040 	}
   1041 #endif
   1042 
   1043 #if defined(__osf__) && defined(_KERNEL)
   1044 	getlock = 0;
   1045 #else
   1046 	getlock = (mode & NAT_LOCKHELD) ? 0 : 1;
   1047 #endif
   1048 
   1049 	n = NULL;
   1050 	nt = NULL;
   1051 	nat = NULL;
   1052 
   1053 	if ((cmd == (ioctlcmd_t)SIOCADNAT) || (cmd == (ioctlcmd_t)SIOCRMNAT) ||
   1054 	    (cmd == (ioctlcmd_t)SIOCPURGENAT)) {
   1055 		if (mode & NAT_SYSSPACE) {
   1056 			bcopy(data, (char *)&natd, sizeof(natd));
   1057 			nat = &natd;
   1058 			error = 0;
   1059 		} else {
   1060 			bzero(&natd, sizeof(natd));
   1061 			error = ipf_inobj(softc, data, NULL, &natd,
   1062 					  IPFOBJ_IPNAT);
   1063 			if (error != 0)
   1064 				goto done;
   1065 
   1066 			if (natd.in_size < sizeof(ipnat_t)) {
   1067 				error = EINVAL;
   1068 				goto done;
   1069 			}
   1070 			KMALLOCS(nt, ipnat_t *, natd.in_size);
   1071 			if (nt == NULL) {
   1072 				IPFERROR(60070);
   1073 				error = ENOMEM;
   1074 				goto done;
   1075 			}
   1076 			bzero(nt, natd.in_size);
   1077 			error = ipf_inobjsz(softc, data, nt, IPFOBJ_IPNAT,
   1078 					    natd.in_size);
   1079 			if (error)
   1080 				goto done;
   1081 			nat = nt;
   1082 		}
   1083 
   1084 		/*
   1085 		 * For add/delete, look to see if the NAT entry is
   1086 		 * already present
   1087 		 */
   1088 		nat->in_flags &= IPN_USERFLAGS;
   1089 		if ((nat->in_redir & NAT_MAPBLK) == 0) {
   1090 			if (nat->in_osrcatype == FRI_NORMAL ||
   1091 			    nat->in_osrcatype == FRI_NONE)
   1092 				nat->in_osrcaddr &= nat->in_osrcmsk;
   1093 			if (nat->in_odstatype == FRI_NORMAL ||
   1094 			    nat->in_odstatype == FRI_NONE)
   1095 				nat->in_odstaddr &= nat->in_odstmsk;
   1096 			if ((nat->in_flags & (IPN_SPLIT|IPN_SIPRANGE)) == 0) {
   1097 				if (nat->in_nsrcatype == FRI_NORMAL)
   1098 					nat->in_nsrcaddr &= nat->in_nsrcmsk;
   1099 				if (nat->in_ndstatype == FRI_NORMAL)
   1100 					nat->in_ndstaddr &= nat->in_ndstmsk;
   1101 			}
   1102 		}
   1103 
   1104 		error = ipf_nat_rule_init(softc, softn, nat);
   1105 		if (error != 0)
   1106 			goto done;
   1107 
   1108 		MUTEX_ENTER(&softn->ipf_nat_io);
   1109 		for (n = softn->ipf_nat_list; n != NULL; n = n->in_next)
   1110 			if (ipf_nat_cmp_rules(nat, n) == 0)
   1111 				break;
   1112 	}
   1113 
   1114 	switch (cmd)
   1115 	{
   1116 #ifdef  IPFILTER_LOG
   1117 	case SIOCIPFFB :
   1118 	{
   1119 		int tmp;
   1120 
   1121 		if (!(mode & FWRITE)) {
   1122 			IPFERROR(60002);
   1123 			error = EPERM;
   1124 		} else {
   1125 			tmp = ipf_log_clear(softc, IPL_LOGNAT);
   1126 			error = BCOPYOUT(&tmp, data, sizeof(tmp));
   1127 			if (error != 0) {
   1128 				IPFERROR(60057);
   1129 				error = EFAULT;
   1130 			}
   1131 		}
   1132 		break;
   1133 	}
   1134 
   1135 	case SIOCSETLG :
   1136 		if (!(mode & FWRITE)) {
   1137 			IPFERROR(60003);
   1138 			error = EPERM;
   1139 		} else {
   1140 			error = BCOPYIN(data, &softn->ipf_nat_logging,
   1141 					sizeof(softn->ipf_nat_logging));
   1142 			if (error != 0)
   1143 				error = EFAULT;
   1144 		}
   1145 		break;
   1146 
   1147 	case SIOCGETLG :
   1148 		error = BCOPYOUT(&softn->ipf_nat_logging, data,
   1149 				 sizeof(softn->ipf_nat_logging));
   1150 		if (error != 0) {
   1151 			IPFERROR(60004);
   1152 			error = EFAULT;
   1153 		}
   1154 		break;
   1155 
   1156 	case FIONREAD :
   1157 		arg = ipf_log_bytesused(softc, IPL_LOGNAT);
   1158 		error = BCOPYOUT(&arg, data, sizeof(arg));
   1159 		if (error != 0) {
   1160 			IPFERROR(60005);
   1161 			error = EFAULT;
   1162 		}
   1163 		break;
   1164 #endif
   1165 	case SIOCADNAT :
   1166 		if (!(mode & FWRITE)) {
   1167 			IPFERROR(60006);
   1168 			error = EPERM;
   1169 		} else if (n != NULL) {
   1170 			natd.in_flineno = n->in_flineno;
   1171 			(void) ipf_outobj(softc, data, &natd, IPFOBJ_IPNAT);
   1172 			IPFERROR(60007);
   1173 			error = EEXIST;
   1174 		} else if (nt == NULL) {
   1175 			IPFERROR(60008);
   1176 			error = ENOMEM;
   1177 		}
   1178 		if (error != 0) {
   1179 			MUTEX_EXIT(&softn->ipf_nat_io);
   1180 			break;
   1181 		}
   1182 		if (nat != nt)
   1183 			bcopy((char *)nat, (char *)nt, sizeof(*n));
   1184 		error = ipf_nat_siocaddnat(softc, softn, nt, getlock);
   1185 		MUTEX_EXIT(&softn->ipf_nat_io);
   1186 		if (error == 0) {
   1187 			nat = NULL;
   1188 			nt = NULL;
   1189 		}
   1190 		break;
   1191 
   1192 	case SIOCRMNAT :
   1193 	case SIOCPURGENAT :
   1194 		if (!(mode & FWRITE)) {
   1195 			IPFERROR(60009);
   1196 			error = EPERM;
   1197 			n = NULL;
   1198 		} else if (n == NULL) {
   1199 			IPFERROR(60010);
   1200 			error = ESRCH;
   1201 		}
   1202 
   1203 		if (error != 0) {
   1204 			MUTEX_EXIT(&softn->ipf_nat_io);
   1205 			break;
   1206 		}
   1207 		if (cmd == (ioctlcmd_t)SIOCPURGENAT) {
   1208 			error = ipf_outobjsz(softc, data, n, IPFOBJ_IPNAT,
   1209 					     n->in_size);
   1210 			if (error) {
   1211 				MUTEX_EXIT(&softn->ipf_nat_io);
   1212 				goto done;
   1213 			}
   1214 			n->in_flags |= IPN_PURGE;
   1215 		}
   1216 		ipf_nat_siocdelnat(softc, softn, n, getlock);
   1217 
   1218 		MUTEX_EXIT(&softn->ipf_nat_io);
   1219 		n = NULL;
   1220 		break;
   1221 
   1222 	case SIOCGNATS :
   1223 	    {
   1224 		natstat_t *nsp = &softn->ipf_nat_stats;
   1225 
   1226 		nsp->ns_side[0].ns_table = softn->ipf_nat_table[0];
   1227 		nsp->ns_side[1].ns_table = softn->ipf_nat_table[1];
   1228 		nsp->ns_list = softn->ipf_nat_list;
   1229 		nsp->ns_maptable = softn->ipf_hm_maptable;
   1230 		nsp->ns_maplist = softn->ipf_hm_maplist;
   1231 		nsp->ns_nattab_sz = softn->ipf_nat_table_sz;
   1232 		nsp->ns_nattab_max = softn->ipf_nat_table_max;
   1233 		nsp->ns_rultab_sz = softn->ipf_nat_maprules_sz;
   1234 		nsp->ns_rdrtab_sz = softn->ipf_nat_rdrrules_sz;
   1235 		nsp->ns_hostmap_sz = softn->ipf_nat_hostmap_sz;
   1236 		nsp->ns_instances = softn->ipf_nat_instances;
   1237 		nsp->ns_ticks = softc->ipf_ticks;
   1238 #ifdef IPFILTER_LOGGING
   1239 		nsp->ns_log_ok = ipf_log_logok(softc, IPF_LOGNAT);
   1240 		nsp->ns_log_fail = ipf_log_failures(softc, IPF_LOGNAT);
   1241 #else
   1242 		nsp->ns_log_ok = 0;
   1243 		nsp->ns_log_fail = 0;
   1244 #endif
   1245 		error = ipf_outobj(softc, data, nsp, IPFOBJ_NATSTAT);
   1246 		break;
   1247 	    }
   1248 
   1249 	case SIOCGNATL :
   1250 	    {
   1251 		natlookup_t nl;
   1252 
   1253 		error = ipf_inobj(softc, data, NULL, &nl, IPFOBJ_NATLOOKUP);
   1254 		if (error == 0) {
   1255 			void *ptr;
   1256 
   1257 			if (getlock) {
   1258 				READ_ENTER(&softc->ipf_nat);
   1259 			}
   1260 
   1261 			switch (nl.nl_v)
   1262 			{
   1263 			case 4 :
   1264 				ptr = ipf_nat_lookupredir(&nl);
   1265 				break;
   1266 #ifdef USE_INET6
   1267 			case 6 :
   1268 				ptr = ipf_nat6_lookupredir(&nl);
   1269 				break;
   1270 #endif
   1271 			default:
   1272 				ptr = NULL;
   1273 				break;
   1274 			}
   1275 
   1276 			if (getlock) {
   1277 				RWLOCK_EXIT(&softc->ipf_nat);
   1278 			}
   1279 			if (ptr != NULL) {
   1280 				error = ipf_outobj(softc, data, &nl,
   1281 						   IPFOBJ_NATLOOKUP);
   1282 			} else {
   1283 				IPFERROR(60011);
   1284 				error = ESRCH;
   1285 			}
   1286 		}
   1287 		break;
   1288 	    }
   1289 
   1290 	case SIOCIPFFL :	/* old SIOCFLNAT & SIOCCNATL */
   1291 		if (!(mode & FWRITE)) {
   1292 			IPFERROR(60012);
   1293 			error = EPERM;
   1294 			break;
   1295 		}
   1296 		if (getlock) {
   1297 			WRITE_ENTER(&softc->ipf_nat);
   1298 		}
   1299 
   1300 		error = BCOPYIN(data, &arg, sizeof(arg));
   1301 		if (error != 0) {
   1302 			IPFERROR(60013);
   1303 			error = EFAULT;
   1304 		} else {
   1305 			if (arg == 0)
   1306 				ret = ipf_nat_flushtable(softc, softn);
   1307 			else if (arg == 1)
   1308 				ret = ipf_nat_clearlist(softc, softn);
   1309 			else
   1310 				ret = ipf_nat_extraflush(softc, softn, arg);
   1311 			ipf_proxy_flush(softc->ipf_proxy_soft, arg);
   1312 		}
   1313 
   1314 		if (getlock) {
   1315 			RWLOCK_EXIT(&softc->ipf_nat);
   1316 		}
   1317 		if (error == 0) {
   1318 			error = BCOPYOUT(&ret, data, sizeof(ret));
   1319 		}
   1320 		break;
   1321 
   1322 	case SIOCMATCHFLUSH :
   1323 		if (!(mode & FWRITE)) {
   1324 			IPFERROR(60014);
   1325 			error = EPERM;
   1326 			break;
   1327 		}
   1328 		if (getlock) {
   1329 			WRITE_ENTER(&softc->ipf_nat);
   1330 		}
   1331 
   1332 		error = ipf_nat_matchflush(softc, softn, data);
   1333 
   1334 		if (getlock) {
   1335 			RWLOCK_EXIT(&softc->ipf_nat);
   1336 		}
   1337 		break;
   1338 
   1339 	case SIOCPROXY :
   1340 		error = ipf_proxy_ioctl(softc, data, cmd, mode, ctx);
   1341 		break;
   1342 
   1343 	case SIOCSTLCK :
   1344 		if (!(mode & FWRITE)) {
   1345 			IPFERROR(60015);
   1346 			error = EPERM;
   1347 		} else {
   1348 			error = ipf_lock(data, &softn->ipf_nat_lock);
   1349 		}
   1350 		break;
   1351 
   1352 	case SIOCSTPUT :
   1353 		if ((mode & FWRITE) != 0) {
   1354 			error = ipf_nat_putent(softc, data, getlock);
   1355 		} else {
   1356 			IPFERROR(60016);
   1357 			error = EACCES;
   1358 		}
   1359 		break;
   1360 
   1361 	case SIOCSTGSZ :
   1362 		if (softn->ipf_nat_lock) {
   1363 			error = ipf_nat_getsz(softc, data, getlock);
   1364 		} else {
   1365 			IPFERROR(60017);
   1366 			error = EACCES;
   1367 		}
   1368 		break;
   1369 
   1370 	case SIOCSTGET :
   1371 		if (softn->ipf_nat_lock) {
   1372 			error = ipf_nat_getent(softc, data, getlock);
   1373 		} else {
   1374 			IPFERROR(60018);
   1375 			error = EACCES;
   1376 		}
   1377 		break;
   1378 
   1379 	case SIOCGENITER :
   1380 	    {
   1381 		ipfgeniter_t iter;
   1382 		ipftoken_t *token;
   1383 		ipfobj_t obj;
   1384 
   1385 		error = ipf_inobj(softc, data, &obj, &iter, IPFOBJ_GENITER);
   1386 		if (error != 0)
   1387 			break;
   1388 
   1389 		SPL_SCHED(s);
   1390 		token = ipf_token_find(softc, iter.igi_type, uid, ctx);
   1391 		if (token != NULL) {
   1392 			error  = ipf_nat_iterator(softc, token, &iter, &obj);
   1393 			WRITE_ENTER(&softc->ipf_tokens);
   1394 			ipf_token_deref(softc, token);
   1395 			RWLOCK_EXIT(&softc->ipf_tokens);
   1396 		}
   1397 		SPL_X(s);
   1398 		break;
   1399 	    }
   1400 
   1401 	case SIOCIPFDELTOK :
   1402 		error = BCOPYIN(data, &arg, sizeof(arg));
   1403 		if (error == 0) {
   1404 			SPL_SCHED(s);
   1405 			error = ipf_token_del(softc, arg, uid, ctx);
   1406 			SPL_X(s);
   1407 		} else {
   1408 			IPFERROR(60019);
   1409 			error = EFAULT;
   1410 		}
   1411 		break;
   1412 
   1413 	case SIOCGTQTAB :
   1414 		error = ipf_outobj(softc, data, softn->ipf_nat_tcptq,
   1415 				   IPFOBJ_STATETQTAB);
   1416 		break;
   1417 
   1418 	case SIOCGTABL :
   1419 		error = ipf_nat_gettable(softc, softn, data);
   1420 		break;
   1421 
   1422 	default :
   1423 		IPFERROR(60020);
   1424 		error = EINVAL;
   1425 		break;
   1426 	}
   1427 done:
   1428 	if (nat != NULL)
   1429 		ipf_nat_rule_fini(softc, nat);
   1430 	if (nt != NULL)
   1431 		KFREES(nt, nt->in_size);
   1432 	return error;
   1433 }
   1434 
   1435 
   1436 /* ------------------------------------------------------------------------ */
   1437 /* Function:    ipf_nat_siocaddnat                                          */
   1438 /* Returns:     int - 0 == success, != 0 == failure                         */
   1439 /* Parameters:  softc(I) - pointer to soft context main structure           */
   1440 /*              softn(I) - pointer to NAT context structure                 */
   1441 /*              n(I)       - pointer to new NAT rule                        */
   1442 /*              np(I)      - pointer to where to insert new NAT rule        */
   1443 /*              getlock(I) - flag indicating if lock on  is held            */
   1444 /* Mutex Locks: ipf_nat_io                                                   */
   1445 /*                                                                          */
   1446 /* Handle SIOCADNAT.  Resolve and calculate details inside the NAT rule     */
   1447 /* from information passed to the kernel, then add it  to the appropriate   */
   1448 /* NAT rule table(s).                                                       */
   1449 /* ------------------------------------------------------------------------ */
   1450 static int
   1451 ipf_nat_siocaddnat(softc, softn, n, getlock)
   1452 	ipf_main_softc_t *softc;
   1453 	ipf_nat_softc_t *softn;
   1454 	ipnat_t *n;
   1455 	int getlock;
   1456 {
   1457 	int error = 0;
   1458 
   1459 	if (ipf_nat_resolverule(softc, n) != 0) {
   1460 		IPFERROR(60022);
   1461 		return ENOENT;
   1462 	}
   1463 
   1464 	if ((n->in_age[0] == 0) && (n->in_age[1] != 0)) {
   1465 		IPFERROR(60023);
   1466 		return EINVAL;
   1467 	}
   1468 
   1469 	if (n->in_redir == (NAT_DIVERTUDP|NAT_MAP)) {
   1470 		/*
   1471 		 * Prerecord whether or not the destination of the divert
   1472 		 * is local or not to the interface the packet is going
   1473 		 * to be sent out.
   1474 		 */
   1475 		n->in_dlocal = ipf_deliverlocal(softc, n->in_v[1],
   1476 						n->in_ifps[1], &n->in_ndstip6);
   1477 	}
   1478 
   1479 	if (getlock) {
   1480 		WRITE_ENTER(&softc->ipf_nat);
   1481 	}
   1482 	n->in_next = NULL;
   1483 	n->in_pnext = softn->ipf_nat_list_tail;
   1484 	*n->in_pnext = n;
   1485 	softn->ipf_nat_list_tail = &n->in_next;
   1486 	n->in_use++;
   1487 
   1488 	if (n->in_redir & NAT_REDIRECT) {
   1489 		n->in_flags &= ~IPN_NOTDST;
   1490 		switch (n->in_v[0])
   1491 		{
   1492 		case 4 :
   1493 			ipf_nat_addrdr(softn, n);
   1494 			break;
   1495 #ifdef USE_INET6
   1496 		case 6 :
   1497 			ipf_nat6_addrdr(softn, n);
   1498 			break;
   1499 #endif
   1500 		default :
   1501 			break;
   1502 		}
   1503 		ATOMIC_INC32(softn->ipf_nat_stats.ns_rules_rdr);
   1504 	}
   1505 
   1506 	if (n->in_redir & (NAT_MAP|NAT_MAPBLK)) {
   1507 		n->in_flags &= ~IPN_NOTSRC;
   1508 		switch (n->in_v[0])
   1509 		{
   1510 		case 4 :
   1511 			ipf_nat_addmap(softn, n);
   1512 			break;
   1513 #ifdef USE_INET6
   1514 		case 6 :
   1515 			ipf_nat6_addmap(softn, n);
   1516 			break;
   1517 #endif
   1518 		default :
   1519 			break;
   1520 		}
   1521 		ATOMIC_INC32(softn->ipf_nat_stats.ns_rules_map);
   1522 	}
   1523 
   1524 	if (n->in_age[0] != 0)
   1525 		n->in_tqehead[0] = ipf_addtimeoutqueue(softc,
   1526 						       &softn->ipf_nat_utqe,
   1527 						       n->in_age[0]);
   1528 
   1529 	if (n->in_age[1] != 0)
   1530 		n->in_tqehead[1] = ipf_addtimeoutqueue(softc,
   1531 						       &softn->ipf_nat_utqe,
   1532 						       n->in_age[1]);
   1533 
   1534 	MUTEX_INIT(&n->in_lock, "ipnat rule lock");
   1535 
   1536 	n = NULL;
   1537 	ATOMIC_INC32(softn->ipf_nat_stats.ns_rules);
   1538 #if SOLARIS && !defined(INSTANCES)
   1539 	pfil_delayed_copy = 0;
   1540 #endif
   1541 	if (getlock) {
   1542 		RWLOCK_EXIT(&softc->ipf_nat);			/* WRITE */
   1543 	}
   1544 
   1545 	return error;
   1546 }
   1547 
   1548 
   1549 /* ------------------------------------------------------------------------ */
   1550 /* Function:    ipf_nat_ruleaddrinit                                        */
   1551 /* Parameters:  softc(I) - pointer to soft context main structure           */
   1552 /*              softn(I) - pointer to NAT context structure                 */
   1553 /*              n(I)     - pointer to NAT rule                              */
   1554 /*                                                                          */
   1555 /* Initialise all of the NAT address structures in a NAT rule.              */
   1556 /* ------------------------------------------------------------------------ */
   1557 static int
   1558 ipf_nat_ruleaddrinit(softc, softn, n)
   1559 	ipf_main_softc_t *softc;
   1560 	ipf_nat_softc_t *softn;
   1561 	ipnat_t *n;
   1562 {
   1563 	int idx, error;
   1564 
   1565 	if ((n->in_ndst.na_atype == FRI_LOOKUP) &&
   1566 	    (n->in_ndst.na_type != IPLT_DSTLIST)) {
   1567 		IPFERROR(60071);
   1568 		return EINVAL;
   1569 	}
   1570 	if ((n->in_nsrc.na_atype == FRI_LOOKUP) &&
   1571 	    (n->in_nsrc.na_type != IPLT_DSTLIST)) {
   1572 		IPFERROR(60069);
   1573 		return EINVAL;
   1574 	}
   1575 
   1576 	if (n->in_redir == NAT_BIMAP) {
   1577 		n->in_ndstaddr = n->in_osrcaddr;
   1578 		n->in_ndstmsk = n->in_osrcmsk;
   1579 		n->in_odstaddr = n->in_nsrcaddr;
   1580 		n->in_odstmsk = n->in_nsrcmsk;
   1581 
   1582 	}
   1583 
   1584 	if (n->in_redir & NAT_REDIRECT)
   1585 		idx = 1;
   1586 	else
   1587 		idx = 0;
   1588 	/*
   1589 	 * Initialise all of the address fields.
   1590 	 */
   1591 	error = ipf_nat_nextaddrinit(softc, n->in_names, &n->in_osrc, 1,
   1592 				     n->in_ifps[idx]);
   1593 	if (error != 0)
   1594 		return error;
   1595 
   1596 	error = ipf_nat_nextaddrinit(softc, n->in_names, &n->in_odst, 1,
   1597 				     n->in_ifps[idx]);
   1598 	if (error != 0)
   1599 		return error;
   1600 
   1601 	error = ipf_nat_nextaddrinit(softc, n->in_names, &n->in_nsrc, 1,
   1602 				     n->in_ifps[idx]);
   1603 	if (error != 0)
   1604 		return error;
   1605 
   1606 	error = ipf_nat_nextaddrinit(softc, n->in_names, &n->in_ndst, 1,
   1607 				     n->in_ifps[idx]);
   1608 	if (error != 0)
   1609 		return error;
   1610 
   1611 	if (n->in_redir & NAT_DIVERTUDP)
   1612 		ipf_nat_builddivertmp(softn, n);
   1613 
   1614 	return 0;
   1615 }
   1616 
   1617 
   1618 /* ------------------------------------------------------------------------ */
   1619 /* Function:    ipf_nat_resolvrule                                          */
   1620 /* Returns:     Nil                                                         */
   1621 /* Parameters:  softc(I) - pointer to soft context main structure           */
   1622 /*              n(I)     - pointer to NAT rule                              */
   1623 /*                                                                          */
   1624 /* Handle SIOCADNAT.  Resolve and calculate details inside the NAT rule     */
   1625 /* from information passed to the kernel, then add it  to the appropriate   */
   1626 /* NAT rule table(s).                                                       */
   1627 /* ------------------------------------------------------------------------ */
   1628 static int
   1629 ipf_nat_resolverule(softc, n)
   1630 	ipf_main_softc_t *softc;
   1631 	ipnat_t *n;
   1632 {
   1633 	char *base;
   1634 
   1635 	base = n->in_names;
   1636 
   1637 	n->in_ifps[0] = ipf_resolvenic(softc, base + n->in_ifnames[0],
   1638 				       n->in_v[0]);
   1639 
   1640 	if (n->in_ifnames[1] == -1) {
   1641 		n->in_ifnames[1] = n->in_ifnames[0];
   1642 		n->in_ifps[1] = n->in_ifps[0];
   1643 	} else {
   1644 		n->in_ifps[1] = ipf_resolvenic(softc, base + n->in_ifnames[1],
   1645 					       n->in_v[1]);
   1646 	}
   1647 
   1648 	if (n->in_plabel != -1) {
   1649 		if (n->in_redir & NAT_REDIRECT)
   1650 			n->in_apr = ipf_proxy_lookup(softc->ipf_proxy_soft,
   1651 						     n->in_pr[0],
   1652 						     base + n->in_plabel);
   1653 		else
   1654 			n->in_apr = ipf_proxy_lookup(softc->ipf_proxy_soft,
   1655 						     n->in_pr[1],
   1656 						     base + n->in_plabel);
   1657 		if (n->in_apr == NULL)
   1658 			return -1;
   1659 	}
   1660 	return 0;
   1661 }
   1662 
   1663 
   1664 /* ------------------------------------------------------------------------ */
   1665 /* Function:    ipf_nat_siocdelnat                                          */
   1666 /* Returns:     int - 0 == success, != 0 == failure                         */
   1667 /* Parameters:  softc(I)   - pointer to soft context main structure         */
   1668 /*              softn(I)   - pointer to NAT context structure               */
   1669 /*              n(I)       - pointer to new NAT rule                        */
   1670 /*              getlock(I) - flag indicating if lock on  is held            */
   1671 /* Mutex Locks: ipf_nat_io                                                  */
   1672 /*                                                                          */
   1673 /* Handle SIOCADNAT.  Resolve and calculate details inside the NAT rule     */
   1674 /* from information passed to the kernel, then add it  to the appropriate   */
   1675 /* NAT rule table(s).                                                       */
   1676 /* ------------------------------------------------------------------------ */
   1677 static void
   1678 ipf_nat_siocdelnat(softc, softn, n, getlock)
   1679 	ipf_main_softc_t *softc;
   1680 	ipf_nat_softc_t *softn;
   1681 	ipnat_t *n;
   1682 	int getlock;
   1683 {
   1684 #ifdef IPF_NAT6
   1685 	int i;
   1686 #endif
   1687 
   1688 	if (getlock) {
   1689 		WRITE_ENTER(&softc->ipf_nat);
   1690 	}
   1691 
   1692 	ipf_nat_delrule(softc, softn, n, 1);
   1693 
   1694 	if (getlock) {
   1695 		RWLOCK_EXIT(&softc->ipf_nat);			/* READ/WRITE */
   1696 	}
   1697 }
   1698 
   1699 
   1700 /* ------------------------------------------------------------------------ */
   1701 /* Function:    ipf_nat_getsz                                               */
   1702 /* Returns:     int - 0 == success, != 0 is the error value.                */
   1703 /* Parameters:  softc(I)   - pointer to soft context main structure         */
   1704 /*              data(I)    - pointer to natget structure with kernel        */
   1705 /*                           pointer get the size of.                       */
   1706 /*              getlock(I) - flag indicating whether or not the caller      */
   1707 /*                           holds a lock on ipf_nat                        */
   1708 /*                                                                          */
   1709 /* Handle SIOCSTGSZ.                                                        */
   1710 /* Return the size of the nat list entry to be copied back to user space.   */
   1711 /* The size of the entry is stored in the ng_sz field and the enture natget */
   1712 /* structure is copied back to the user.                                    */
   1713 /* ------------------------------------------------------------------------ */
   1714 static int
   1715 ipf_nat_getsz(softc, data, getlock)
   1716 	ipf_main_softc_t *softc;
   1717 	caddr_t data;
   1718 	int getlock;
   1719 {
   1720 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   1721 	ap_session_t *aps;
   1722 	nat_t *nat, *n;
   1723 	natget_t ng;
   1724 	int error;
   1725 
   1726 	error = BCOPYIN(data, &ng, sizeof(ng));
   1727 	if (error != 0) {
   1728 		IPFERROR(60024);
   1729 		return EFAULT;
   1730 	}
   1731 
   1732 	if (getlock) {
   1733 		READ_ENTER(&softc->ipf_nat);
   1734 	}
   1735 
   1736 	nat = ng.ng_ptr;
   1737 	if (!nat) {
   1738 		nat = softn->ipf_nat_instances;
   1739 		ng.ng_sz = 0;
   1740 		/*
   1741 		 * Empty list so the size returned is 0.  Simple.
   1742 		 */
   1743 		if (nat == NULL) {
   1744 			if (getlock) {
   1745 				RWLOCK_EXIT(&softc->ipf_nat);
   1746 			}
   1747 			error = BCOPYOUT(&ng, data, sizeof(ng));
   1748 			if (error != 0) {
   1749 				IPFERROR(60025);
   1750 				return EFAULT;
   1751 			}
   1752 			return 0;
   1753 		}
   1754 	} else {
   1755 		/*
   1756 		 * Make sure the pointer we're copying from exists in the
   1757 		 * current list of entries.  Security precaution to prevent
   1758 		 * copying of random kernel data.
   1759 		 */
   1760 		for (n = softn->ipf_nat_instances; n; n = n->nat_next)
   1761 			if (n == nat)
   1762 				break;
   1763 		if (n == NULL) {
   1764 			if (getlock) {
   1765 				RWLOCK_EXIT(&softc->ipf_nat);
   1766 			}
   1767 			IPFERROR(60026);
   1768 			return ESRCH;
   1769 		}
   1770 	}
   1771 
   1772 	/*
   1773 	 * Incluse any space required for proxy data structures.
   1774 	 */
   1775 	ng.ng_sz = sizeof(nat_save_t);
   1776 	aps = nat->nat_aps;
   1777 	if (aps != NULL) {
   1778 		ng.ng_sz += sizeof(ap_session_t) - 4;
   1779 		if (aps->aps_data != 0)
   1780 			ng.ng_sz += aps->aps_psiz;
   1781 	}
   1782 	if (getlock) {
   1783 		RWLOCK_EXIT(&softc->ipf_nat);
   1784 	}
   1785 
   1786 	error = BCOPYOUT(&ng, data, sizeof(ng));
   1787 	if (error != 0) {
   1788 		IPFERROR(60027);
   1789 		return EFAULT;
   1790 	}
   1791 	return 0;
   1792 }
   1793 
   1794 
   1795 /* ------------------------------------------------------------------------ */
   1796 /* Function:    ipf_nat_getent                                              */
   1797 /* Returns:     int - 0 == success, != 0 is the error value.                */
   1798 /* Parameters:  softc(I)   - pointer to soft context main structure         */
   1799 /*              data(I)    - pointer to natget structure with kernel pointer*/
   1800 /*                           to NAT structure to copy out.                  */
   1801 /*              getlock(I) - flag indicating whether or not the caller      */
   1802 /*                           holds a lock on ipf_nat                        */
   1803 /*                                                                          */
   1804 /* Handle SIOCSTGET.                                                        */
   1805 /* Copies out NAT entry to user space.  Any additional data held for a      */
   1806 /* proxy is also copied, as to is the NAT rule which was responsible for it */
   1807 /* ------------------------------------------------------------------------ */
   1808 static int
   1809 ipf_nat_getent(softc, data, getlock)
   1810 	ipf_main_softc_t *softc;
   1811 	caddr_t data;
   1812 	int getlock;
   1813 {
   1814 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   1815 	int error, outsize;
   1816 	ap_session_t *aps;
   1817 	nat_save_t *ipn, ipns;
   1818 	nat_t *n, *nat;
   1819 
   1820 	error = ipf_inobj(softc, data, NULL, &ipns, IPFOBJ_NATSAVE);
   1821 	if (error != 0)
   1822 		return error;
   1823 
   1824 	if ((ipns.ipn_dsize < sizeof(ipns)) || (ipns.ipn_dsize > 81920)) {
   1825 		IPFERROR(60028);
   1826 		return EINVAL;
   1827 	}
   1828 
   1829 	KMALLOCS(ipn, nat_save_t *, ipns.ipn_dsize);
   1830 	if (ipn == NULL) {
   1831 		IPFERROR(60029);
   1832 		return ENOMEM;
   1833 	}
   1834 
   1835 	if (getlock) {
   1836 		READ_ENTER(&softc->ipf_nat);
   1837 	}
   1838 
   1839 	ipn->ipn_dsize = ipns.ipn_dsize;
   1840 	nat = ipns.ipn_next;
   1841 	if (nat == NULL) {
   1842 		nat = softn->ipf_nat_instances;
   1843 		if (nat == NULL) {
   1844 			if (softn->ipf_nat_instances == NULL) {
   1845 				IPFERROR(60030);
   1846 				error = ENOENT;
   1847 			}
   1848 			goto finished;
   1849 		}
   1850 	} else {
   1851 		/*
   1852 		 * Make sure the pointer we're copying from exists in the
   1853 		 * current list of entries.  Security precaution to prevent
   1854 		 * copying of random kernel data.
   1855 		 */
   1856 		for (n = softn->ipf_nat_instances; n; n = n->nat_next)
   1857 			if (n == nat)
   1858 				break;
   1859 		if (n == NULL) {
   1860 			IPFERROR(60031);
   1861 			error = ESRCH;
   1862 			goto finished;
   1863 		}
   1864 	}
   1865 	ipn->ipn_next = nat->nat_next;
   1866 
   1867 	/*
   1868 	 * Copy the NAT structure.
   1869 	 */
   1870 	bcopy((char *)nat, &ipn->ipn_nat, sizeof(*nat));
   1871 
   1872 	/*
   1873 	 * If we have a pointer to the NAT rule it belongs to, save that too.
   1874 	 */
   1875 	if (nat->nat_ptr != NULL)
   1876 		bcopy((char *)nat->nat_ptr, (char *)&ipn->ipn_ipnat,
   1877 		      ipn->ipn_ipnat.in_size);
   1878 
   1879 	/*
   1880 	 * If we also know the NAT entry has an associated filter rule,
   1881 	 * save that too.
   1882 	 */
   1883 	if (nat->nat_fr != NULL)
   1884 		bcopy((char *)nat->nat_fr, (char *)&ipn->ipn_fr,
   1885 		      sizeof(ipn->ipn_fr));
   1886 
   1887 	/*
   1888 	 * Last but not least, if there is an application proxy session set
   1889 	 * up for this NAT entry, then copy that out too, including any
   1890 	 * private data saved along side it by the proxy.
   1891 	 */
   1892 	aps = nat->nat_aps;
   1893 	outsize = ipn->ipn_dsize - sizeof(*ipn) + sizeof(ipn->ipn_data);
   1894 	if (aps != NULL) {
   1895 		char *s;
   1896 
   1897 		if (outsize < sizeof(*aps)) {
   1898 			IPFERROR(60032);
   1899 			error = ENOBUFS;
   1900 			goto finished;
   1901 		}
   1902 
   1903 		s = ipn->ipn_data;
   1904 		bcopy((char *)aps, s, sizeof(*aps));
   1905 		s += sizeof(*aps);
   1906 		outsize -= sizeof(*aps);
   1907 		if ((aps->aps_data != NULL) && (outsize >= aps->aps_psiz))
   1908 			bcopy(aps->aps_data, s, aps->aps_psiz);
   1909 		else {
   1910 			IPFERROR(60033);
   1911 			error = ENOBUFS;
   1912 		}
   1913 	}
   1914 	if (error == 0) {
   1915 		if (getlock) {
   1916 			READ_ENTER(&softc->ipf_nat);
   1917 			getlock = 0;
   1918 		}
   1919 		error = ipf_outobjsz(softc, data, ipn, IPFOBJ_NATSAVE,
   1920 				     ipns.ipn_dsize);
   1921 	}
   1922 
   1923 finished:
   1924 	if (getlock) {
   1925 		READ_ENTER(&softc->ipf_nat);
   1926 	}
   1927 	if (ipn != NULL) {
   1928 		KFREES(ipn, ipns.ipn_dsize);
   1929 	}
   1930 	return error;
   1931 }
   1932 
   1933 
   1934 /* ------------------------------------------------------------------------ */
   1935 /* Function:    ipf_nat_putent                                              */
   1936 /* Returns:     int - 0 == success, != 0 is the error value.                */
   1937 /* Parameters:  softc(I)   - pointer to soft context main structure         */
   1938 /*              data(I)    - pointer to natget structure with NAT           */
   1939 /*                           structure information to load into the kernel  */
   1940 /*              getlock(I) - flag indicating whether or not a write lock    */
   1941 /*                           on is already held.                            */
   1942 /*                                                                          */
   1943 /* Handle SIOCSTPUT.                                                        */
   1944 /* Loads a NAT table entry from user space, including a NAT rule, proxy and */
   1945 /* firewall rule data structures, if pointers to them indicate so.          */
   1946 /* ------------------------------------------------------------------------ */
   1947 static int
   1948 ipf_nat_putent(softc, data, getlock)
   1949 	ipf_main_softc_t *softc;
   1950 	caddr_t data;
   1951 	int getlock;
   1952 {
   1953 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   1954 	nat_save_t ipn, *ipnn;
   1955 	ap_session_t *aps;
   1956 	nat_t *n, *nat;
   1957 	frentry_t *fr;
   1958 	fr_info_t fin;
   1959 	ipnat_t *in;
   1960 	int error;
   1961 
   1962 	error = ipf_inobj(softc, data, NULL, &ipn, IPFOBJ_NATSAVE);
   1963 	if (error != 0)
   1964 		return error;
   1965 
   1966 	/*
   1967 	 * Initialise early because of code at junkput label.
   1968 	 */
   1969 	n = NULL;
   1970 	in = NULL;
   1971 	aps = NULL;
   1972 	nat = NULL;
   1973 	ipnn = NULL;
   1974 	fr = NULL;
   1975 
   1976 	/*
   1977 	 * New entry, copy in the rest of the NAT entry if it's size is more
   1978 	 * than just the nat_t structure.
   1979 	 */
   1980 	if (ipn.ipn_dsize > sizeof(ipn)) {
   1981 		if (ipn.ipn_dsize > 81920) {
   1982 			IPFERROR(60034);
   1983 			error = ENOMEM;
   1984 			goto junkput;
   1985 		}
   1986 
   1987 		KMALLOCS(ipnn, nat_save_t *, ipn.ipn_dsize);
   1988 		if (ipnn == NULL) {
   1989 			IPFERROR(60035);
   1990 			return ENOMEM;
   1991 		}
   1992 
   1993 		bzero(ipnn, ipn.ipn_dsize);
   1994 		error = ipf_inobjsz(softc, data, ipnn, IPFOBJ_NATSAVE,
   1995 				    ipn.ipn_dsize);
   1996 		if (error != 0) {
   1997 			goto junkput;
   1998 		}
   1999 	} else
   2000 		ipnn = &ipn;
   2001 
   2002 	KMALLOC(nat, nat_t *);
   2003 	if (nat == NULL) {
   2004 		IPFERROR(60037);
   2005 		error = ENOMEM;
   2006 		goto junkput;
   2007 	}
   2008 
   2009 	bcopy((char *)&ipnn->ipn_nat, (char *)nat, sizeof(*nat));
   2010 
   2011 	switch (nat->nat_v[0])
   2012 	{
   2013 	case 4:
   2014 #ifdef USE_IENT6
   2015 	case 6 :
   2016 #endif
   2017 		break;
   2018 	default :
   2019 		IPFERROR(60061);
   2020 		error = EPROTONOSUPPORT;
   2021 		goto junkput;
   2022 		/*NOTREACHED*/
   2023 	}
   2024 
   2025 	/*
   2026 	 * Initialize all these so that ipf_nat_delete() doesn't cause a crash.
   2027 	 */
   2028 	bzero((char *)nat, offsetof(struct nat, nat_tqe));
   2029 	nat->nat_tqe.tqe_pnext = NULL;
   2030 	nat->nat_tqe.tqe_next = NULL;
   2031 	nat->nat_tqe.tqe_ifq = NULL;
   2032 	nat->nat_tqe.tqe_parent = nat;
   2033 
   2034 	/*
   2035 	 * Restore the rule associated with this nat session
   2036 	 */
   2037 	in = ipnn->ipn_nat.nat_ptr;
   2038 	if (in != NULL) {
   2039 		KMALLOCS(in, ipnat_t *, ipnn->ipn_ipnat.in_size);
   2040 		nat->nat_ptr = in;
   2041 		if (in == NULL) {
   2042 			IPFERROR(60038);
   2043 			error = ENOMEM;
   2044 			goto junkput;
   2045 		}
   2046 		bcopy((char *)&ipnn->ipn_ipnat, (char *)in,
   2047 		      ipnn->ipn_ipnat.in_size);
   2048 		in->in_use = 1;
   2049 		in->in_flags |= IPN_DELETE;
   2050 
   2051 		ATOMIC_INC32(softn->ipf_nat_stats.ns_rules);
   2052 
   2053 		if (ipf_nat_resolverule(softc, in) != 0) {
   2054 			IPFERROR(60039);
   2055 			error = ESRCH;
   2056 			goto junkput;
   2057 		}
   2058 	}
   2059 
   2060 	/*
   2061 	 * Check that the NAT entry doesn't already exist in the kernel.
   2062 	 *
   2063 	 * For NAT_OUTBOUND, we're lookup for a duplicate MAP entry.  To do
   2064 	 * this, we check to see if the inbound combination of addresses and
   2065 	 * ports is already known.  Similar logic is applied for NAT_INBOUND.
   2066 	 *
   2067 	 */
   2068 	bzero((char *)&fin, sizeof(fin));
   2069 	fin.fin_v = nat->nat_v[0];
   2070 	fin.fin_p = nat->nat_pr[0];
   2071 	fin.fin_rev = nat->nat_rev;
   2072 	fin.fin_ifp = nat->nat_ifps[0];
   2073 	fin.fin_data[0] = ntohs(nat->nat_ndport);
   2074 	fin.fin_data[1] = ntohs(nat->nat_nsport);
   2075 
   2076 	switch (nat->nat_dir)
   2077 	{
   2078 	case NAT_OUTBOUND :
   2079 	case NAT_DIVERTOUT :
   2080 		if (getlock) {
   2081 			READ_ENTER(&softc->ipf_nat);
   2082 		}
   2083 
   2084 		fin.fin_v = nat->nat_v[1];
   2085 		if (nat->nat_v[1] == 4) {
   2086 			n = ipf_nat_inlookup(&fin, nat->nat_flags, fin.fin_p,
   2087 					     nat->nat_ndstip, nat->nat_nsrcip);
   2088 #ifdef USE_INET6
   2089 		} else if (nat->nat_v[1] == 6) {
   2090 			n = ipf_nat6_inlookup(&fin, nat->nat_flags, fin.fin_p,
   2091 					      &nat->nat_ndst6.in6,
   2092 					      &nat->nat_nsrc6.in6);
   2093 #endif
   2094 		}
   2095 
   2096 		if (getlock) {
   2097 			RWLOCK_EXIT(&softc->ipf_nat);
   2098 		}
   2099 		if (n != NULL) {
   2100 			IPFERROR(60040);
   2101 			error = EEXIST;
   2102 			goto junkput;
   2103 		}
   2104 		break;
   2105 
   2106 	case NAT_INBOUND :
   2107 	case NAT_DIVERTIN :
   2108 		if (getlock) {
   2109 			READ_ENTER(&softc->ipf_nat);
   2110 		}
   2111 
   2112 		if (fin.fin_v == 4) {
   2113 			n = ipf_nat_outlookup(&fin, nat->nat_flags, fin.fin_p,
   2114 					      nat->nat_ndstip,
   2115 					      nat->nat_nsrcip);
   2116 #ifdef USE_INET6
   2117 		} else if (fin.fin_v == 6) {
   2118 			n = ipf_nat6_outlookup(&fin, nat->nat_flags, fin.fin_p,
   2119 					       &nat->nat_ndst6.in6,
   2120 					       &nat->nat_nsrc6.in6);
   2121 #endif
   2122 		}
   2123 
   2124 		if (getlock) {
   2125 			RWLOCK_EXIT(&softc->ipf_nat);
   2126 		}
   2127 		if (n != NULL) {
   2128 			IPFERROR(60041);
   2129 			error = EEXIST;
   2130 			goto junkput;
   2131 		}
   2132 		break;
   2133 
   2134 	default :
   2135 		IPFERROR(60042);
   2136 		error = EINVAL;
   2137 		goto junkput;
   2138 	}
   2139 
   2140 	/*
   2141 	 * Restore ap_session_t structure.  Include the private data allocated
   2142 	 * if it was there.
   2143 	 */
   2144 	aps = nat->nat_aps;
   2145 	if (aps != NULL) {
   2146 		KMALLOC(aps, ap_session_t *);
   2147 		nat->nat_aps = aps;
   2148 		if (aps == NULL) {
   2149 			IPFERROR(60043);
   2150 			error = ENOMEM;
   2151 			goto junkput;
   2152 		}
   2153 		bcopy(ipnn->ipn_data, (char *)aps, sizeof(*aps));
   2154 		if (in != NULL)
   2155 			aps->aps_apr = in->in_apr;
   2156 		else
   2157 			aps->aps_apr = NULL;
   2158 		if (aps->aps_psiz != 0) {
   2159 			if (aps->aps_psiz > 81920) {
   2160 				IPFERROR(60044);
   2161 				error = ENOMEM;
   2162 				goto junkput;
   2163 			}
   2164 			KMALLOCS(aps->aps_data, void *, aps->aps_psiz);
   2165 			if (aps->aps_data == NULL) {
   2166 				IPFERROR(60045);
   2167 				error = ENOMEM;
   2168 				goto junkput;
   2169 			}
   2170 			bcopy(ipnn->ipn_data + sizeof(*aps), aps->aps_data,
   2171 			      aps->aps_psiz);
   2172 		} else {
   2173 			aps->aps_psiz = 0;
   2174 			aps->aps_data = NULL;
   2175 		}
   2176 	}
   2177 
   2178 	/*
   2179 	 * If there was a filtering rule associated with this entry then
   2180 	 * build up a new one.
   2181 	 */
   2182 	fr = nat->nat_fr;
   2183 	if (fr != NULL) {
   2184 		if ((nat->nat_flags & SI_NEWFR) != 0) {
   2185 			KMALLOC(fr, frentry_t *);
   2186 			nat->nat_fr = fr;
   2187 			if (fr == NULL) {
   2188 				IPFERROR(60046);
   2189 				error = ENOMEM;
   2190 				goto junkput;
   2191 			}
   2192 			ipnn->ipn_nat.nat_fr = fr;
   2193 			fr->fr_ref = 1;
   2194 			(void) ipf_outobj(softc, data, ipnn, IPFOBJ_NATSAVE);
   2195 			bcopy((char *)&ipnn->ipn_fr, (char *)fr, sizeof(*fr));
   2196 
   2197 			fr->fr_ref = 1;
   2198 			fr->fr_dsize = 0;
   2199 			fr->fr_data = NULL;
   2200 			fr->fr_type = FR_T_NONE;
   2201 
   2202 			MUTEX_NUKE(&fr->fr_lock);
   2203 			MUTEX_INIT(&fr->fr_lock, "nat-filter rule lock");
   2204 		} else {
   2205 			if (getlock) {
   2206 				READ_ENTER(&softc->ipf_nat);
   2207 			}
   2208 			for (n = softn->ipf_nat_instances; n; n = n->nat_next)
   2209 				if (n->nat_fr == fr)
   2210 					break;
   2211 
   2212 			if (n != NULL) {
   2213 				MUTEX_ENTER(&fr->fr_lock);
   2214 				fr->fr_ref++;
   2215 				MUTEX_EXIT(&fr->fr_lock);
   2216 			}
   2217 			if (getlock) {
   2218 				RWLOCK_EXIT(&softc->ipf_nat);
   2219 			}
   2220 
   2221 			if (n == NULL) {
   2222 				IPFERROR(60047);
   2223 				error = ESRCH;
   2224 				goto junkput;
   2225 			}
   2226 		}
   2227 	}
   2228 
   2229 	if (ipnn != &ipn) {
   2230 		KFREES(ipnn, ipn.ipn_dsize);
   2231 		ipnn = NULL;
   2232 	}
   2233 
   2234 	if (getlock) {
   2235 		WRITE_ENTER(&softc->ipf_nat);
   2236 	}
   2237 
   2238 	if (fin.fin_v == 4)
   2239 		error = ipf_nat_finalise(&fin, nat);
   2240 #ifdef USE_INET6
   2241 	else
   2242 		error = ipf_nat6_finalise(&fin, nat);
   2243 #endif
   2244 
   2245 	if (getlock) {
   2246 		RWLOCK_EXIT(&softc->ipf_nat);
   2247 	}
   2248 
   2249 	if (error == 0)
   2250 		return 0;
   2251 
   2252 	IPFERROR(60048);
   2253 	error = ENOMEM;
   2254 
   2255 junkput:
   2256 	if (fr != NULL) {
   2257 		(void) ipf_derefrule(softc, &fr);
   2258 	}
   2259 
   2260 	if ((ipnn != NULL) && (ipnn != &ipn)) {
   2261 		KFREES(ipnn, ipn.ipn_dsize);
   2262 	}
   2263 	if (nat != NULL) {
   2264 		if (aps != NULL) {
   2265 			if (aps->aps_data != NULL) {
   2266 				KFREES(aps->aps_data, aps->aps_psiz);
   2267 			}
   2268 			KFREE(aps);
   2269 		}
   2270 		if (in != NULL) {
   2271 			if (in->in_apr)
   2272 				ipf_proxy_deref(in->in_apr);
   2273 			KFREES(in, in->in_size);
   2274 		}
   2275 		KFREE(nat);
   2276 	}
   2277 	return error;
   2278 }
   2279 
   2280 
   2281 /* ------------------------------------------------------------------------ */
   2282 /* Function:    ipf_nat_delete                                              */
   2283 /* Returns:     Nil                                                         */
   2284 /* Parameters:  softc(I)   - pointer to soft context main structure         */
   2285 /*              nat(I)     - pointer to NAT structure to delete             */
   2286 /*              logtype(I) - type of LOG record to create before deleting   */
   2287 /* Write Lock:  ipf_nat                                                     */
   2288 /*                                                                          */
   2289 /* Delete a nat entry from the various lists and table.  If NAT logging is  */
   2290 /* enabled then generate a NAT log record for this event.                   */
   2291 /* ------------------------------------------------------------------------ */
   2292 void
   2293 ipf_nat_delete(softc, nat, logtype)
   2294 	ipf_main_softc_t *softc;
   2295 	struct nat *nat;
   2296 	int logtype;
   2297 {
   2298 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   2299 	int madeorphan = 0, bkt, removed = 0;
   2300 	nat_stat_side_t *nss;
   2301 	struct ipnat *ipn;
   2302 
   2303 	if (logtype != 0 && softn->ipf_nat_logging != 0)
   2304 		ipf_nat_log(softc, softn, nat, logtype);
   2305 
   2306 	/*
   2307 	 * Take it as a general indication that all the pointers are set if
   2308 	 * nat_pnext is set.
   2309 	 */
   2310 	if (nat->nat_pnext != NULL) {
   2311 		removed = 1;
   2312 
   2313 		bkt = nat->nat_hv[0] % softn->ipf_nat_table_sz;
   2314 		nss = &softn->ipf_nat_stats.ns_side[0];
   2315 		nss->ns_bucketlen[bkt]--;
   2316 		if (nss->ns_bucketlen[bkt] == 0) {
   2317 			nss->ns_inuse--;
   2318 		}
   2319 
   2320 		bkt = nat->nat_hv[1] % softn->ipf_nat_table_sz;
   2321 		nss = &softn->ipf_nat_stats.ns_side[1];
   2322 		nss->ns_bucketlen[bkt]--;
   2323 		if (nss->ns_bucketlen[bkt] == 0) {
   2324 			nss->ns_inuse--;
   2325 		}
   2326 
   2327 		*nat->nat_pnext = nat->nat_next;
   2328 		if (nat->nat_next != NULL) {
   2329 			nat->nat_next->nat_pnext = nat->nat_pnext;
   2330 			nat->nat_next = NULL;
   2331 		}
   2332 		nat->nat_pnext = NULL;
   2333 
   2334 		*nat->nat_phnext[0] = nat->nat_hnext[0];
   2335 		if (nat->nat_hnext[0] != NULL) {
   2336 			nat->nat_hnext[0]->nat_phnext[0] = nat->nat_phnext[0];
   2337 			nat->nat_hnext[0] = NULL;
   2338 		}
   2339 		nat->nat_phnext[0] = NULL;
   2340 
   2341 		*nat->nat_phnext[1] = nat->nat_hnext[1];
   2342 		if (nat->nat_hnext[1] != NULL) {
   2343 			nat->nat_hnext[1]->nat_phnext[1] = nat->nat_phnext[1];
   2344 			nat->nat_hnext[1] = NULL;
   2345 		}
   2346 		nat->nat_phnext[1] = NULL;
   2347 
   2348 		if ((nat->nat_flags & SI_WILDP) != 0) {
   2349 			ATOMIC_DEC32(softn->ipf_nat_stats.ns_wilds);
   2350 		}
   2351 		madeorphan = 1;
   2352 	}
   2353 
   2354 	if (nat->nat_me != NULL) {
   2355 		*nat->nat_me = NULL;
   2356 		nat->nat_me = NULL;
   2357 		nat->nat_ref--;
   2358 		ASSERT(nat->nat_ref >= 0);
   2359 	}
   2360 
   2361 	if (nat->nat_tqe.tqe_ifq != NULL) {
   2362 		/*
   2363 		 * No call to ipf_freetimeoutqueue() is made here, they are
   2364 		 * garbage collected in ipf_nat_expire().
   2365 		 */
   2366 		(void) ipf_deletequeueentry(&nat->nat_tqe);
   2367 	}
   2368 
   2369 	if (nat->nat_sync) {
   2370 		ipf_sync_del_nat(softc->ipf_sync_soft, nat->nat_sync);
   2371 		nat->nat_sync = NULL;
   2372 	}
   2373 
   2374 	if (logtype == NL_EXPIRE)
   2375 		softn->ipf_nat_stats.ns_expire++;
   2376 
   2377 	MUTEX_ENTER(&nat->nat_lock);
   2378 	/*
   2379 	 * NL_DESTROY should only be passed in when we've got nat_ref >= 2.
   2380 	 * This happens when a nat'd packet is blocked and we want to throw
   2381 	 * away the NAT session.
   2382 	 */
   2383 	if (logtype == NL_DESTROY) {
   2384 		if (nat->nat_ref > 2) {
   2385 			nat->nat_ref -= 2;
   2386 			MUTEX_EXIT(&nat->nat_lock);
   2387 			if (removed)
   2388 				softn->ipf_nat_stats.ns_orphans++;
   2389 			return;
   2390 		}
   2391 	} else if (nat->nat_ref > 1) {
   2392 		nat->nat_ref--;
   2393 		MUTEX_EXIT(&nat->nat_lock);
   2394 		if (madeorphan == 1)
   2395 			softn->ipf_nat_stats.ns_orphans++;
   2396 		return;
   2397 	}
   2398 	ASSERT(nat->nat_ref >= 0);
   2399 	MUTEX_EXIT(&nat->nat_lock);
   2400 
   2401 	nat->nat_ref = 0;
   2402 
   2403 	if (madeorphan == 0)
   2404 		softn->ipf_nat_stats.ns_orphans--;
   2405 
   2406 	/*
   2407 	 * At this point, nat_ref can be either 0 or -1
   2408 	 */
   2409 	softn->ipf_nat_stats.ns_proto[nat->nat_pr[0]]--;
   2410 
   2411 	if (nat->nat_fr != NULL) {
   2412 		(void) ipf_derefrule(softc, &nat->nat_fr);
   2413 	}
   2414 
   2415 	if (nat->nat_hm != NULL) {
   2416 		ipf_nat_hostmapdel(softc, &nat->nat_hm);
   2417 	}
   2418 
   2419 	/*
   2420 	 * If there is an active reference from the nat entry to its parent
   2421 	 * rule, decrement the rule's reference count and free it too if no
   2422 	 * longer being used.
   2423 	 */
   2424 	ipn = nat->nat_ptr;
   2425 	nat->nat_ptr = NULL;
   2426 
   2427 	if (ipn != NULL) {
   2428 		ipn->in_space++;
   2429 		ipf_nat_rule_deref(softc, &ipn);
   2430 	}
   2431 
   2432 	if (nat->nat_aps != NULL) {
   2433 		ipf_proxy_free(softc, nat->nat_aps);
   2434 		nat->nat_aps = NULL;
   2435 	}
   2436 
   2437 	MUTEX_DESTROY(&nat->nat_lock);
   2438 
   2439 	softn->ipf_nat_stats.ns_active--;
   2440 
   2441 	/*
   2442 	 * If there's a fragment table entry too for this nat entry, then
   2443 	 * dereference that as well.  This is after nat_lock is released
   2444 	 * because of Tru64.
   2445 	 */
   2446 	ipf_frag_natforget(softc, (void *)nat);
   2447 
   2448 	KFREE(nat);
   2449 }
   2450 
   2451 
   2452 /* ------------------------------------------------------------------------ */
   2453 /* Function:    ipf_nat_flushtable                                          */
   2454 /* Returns:     int - number of NAT rules deleted                           */
   2455 /* Parameters:  softc(I) - pointer to soft context main structure           */
   2456 /*              softn(I) - pointer to NAT context structure                 */
   2457 /* Write Lock:  ipf_nat                                                     */
   2458 /*                                                                          */
   2459 /* Deletes all currently active NAT sessions.  In deleting each NAT entry a */
   2460 /* log record should be emitted in ipf_nat_delete() if NAT logging is       */
   2461 /* enabled.                                                                 */
   2462 /* ------------------------------------------------------------------------ */
   2463 /*
   2464  * nat_flushtable - clear the NAT table of all mapping entries.
   2465  */
   2466 static int
   2467 ipf_nat_flushtable(softc, softn)
   2468 	ipf_main_softc_t *softc;
   2469 	ipf_nat_softc_t *softn;
   2470 {
   2471 	nat_t *nat;
   2472 	int j = 0;
   2473 
   2474 	/*
   2475 	 * ALL NAT mappings deleted, so lets just make the deletions
   2476 	 * quicker.
   2477 	 */
   2478 	if (softn->ipf_nat_table[0] != NULL)
   2479 		bzero((char *)softn->ipf_nat_table[0],
   2480 		      sizeof(softn->ipf_nat_table[0]) *
   2481 		      softn->ipf_nat_table_sz);
   2482 	if (softn->ipf_nat_table[1] != NULL)
   2483 		bzero((char *)softn->ipf_nat_table[1],
   2484 		      sizeof(softn->ipf_nat_table[1]) *
   2485 		      softn->ipf_nat_table_sz);
   2486 
   2487 	while ((nat = softn->ipf_nat_instances) != NULL) {
   2488 		ipf_nat_delete(softc, nat, NL_FLUSH);
   2489 		j++;
   2490 	}
   2491 
   2492 	return j;
   2493 }
   2494 
   2495 
   2496 /* ------------------------------------------------------------------------ */
   2497 /* Function:    ipf_nat_clearlist                                           */
   2498 /* Returns:     int - number of NAT/RDR rules deleted                       */
   2499 /* Parameters:  softc(I) - pointer to soft context main structure           */
   2500 /*              softn(I) - pointer to NAT context structure                 */
   2501 /*                                                                          */
   2502 /* Delete all rules in the current list of rules.  There is nothing elegant */
   2503 /* about this cleanup: simply free all entries on the list of rules and     */
   2504 /* clear out the tables used for hashed NAT rule lookups.                   */
   2505 /* ------------------------------------------------------------------------ */
   2506 static int
   2507 ipf_nat_clearlist(softc, softn)
   2508 	ipf_main_softc_t *softc;
   2509 	ipf_nat_softc_t *softn;
   2510 {
   2511 	ipnat_t *n;
   2512 	int i = 0;
   2513 
   2514 	if (softn->ipf_nat_map_rules != NULL) {
   2515 		bzero((char *)softn->ipf_nat_map_rules,
   2516 		      sizeof(*softn->ipf_nat_map_rules) *
   2517 		      softn->ipf_nat_maprules_sz);
   2518 	}
   2519 	if (softn->ipf_nat_rdr_rules != NULL) {
   2520 		bzero((char *)softn->ipf_nat_rdr_rules,
   2521 		      sizeof(*softn->ipf_nat_rdr_rules) *
   2522 		      softn->ipf_nat_rdrrules_sz);
   2523 	}
   2524 
   2525 	while ((n = softn->ipf_nat_list) != NULL) {
   2526 		ipf_nat_delrule(softc, softn, n, 0);
   2527 		i++;
   2528 	}
   2529 #if SOLARIS && !defined(INSTANCES)
   2530 	pfil_delayed_copy = 1;
   2531 #endif
   2532 	return i;
   2533 }
   2534 
   2535 
   2536 /* ------------------------------------------------------------------------ */
   2537 /* Function:    ipf_nat_delrule                                             */
   2538 /* Returns:     Nil                                                         */
   2539 /* Parameters:  softc(I) - pointer to soft context main structure           */
   2540 /*              softn(I) - pointer to NAT context structure                 */
   2541 /*              np(I)    - pointer to NAT rule to delete                    */
   2542 /*              purge(I) - 1 == allow purge, 0 == prevent purge             */
   2543 /* Locks:       WRITE(ipf_nat)                                              */
   2544 /*                                                                          */
   2545 /* Preventing "purge" from occuring is allowed because when all of the NAT  */
   2546 /* rules are being removed, allowing the "purge" to walk through the list   */
   2547 /* of NAT sessions, possibly multiple times, would be a large performance   */
   2548 /* hit, on the order of O(N^2).                                             */
   2549 /* ------------------------------------------------------------------------ */
   2550 static void
   2551 ipf_nat_delrule(softc, softn, np, purge)
   2552 	ipf_main_softc_t *softc;
   2553 	ipf_nat_softc_t *softn;
   2554 	ipnat_t *np;
   2555 	int purge;
   2556 {
   2557 
   2558 	if (np->in_pnext != NULL) {
   2559 		*np->in_pnext = np->in_next;
   2560 		if (np->in_next != NULL)
   2561 			np->in_next->in_pnext = np->in_pnext;
   2562 		if (softn->ipf_nat_list_tail == &np->in_next)
   2563 			softn->ipf_nat_list_tail = np->in_pnext;
   2564 	}
   2565 
   2566 	if ((purge == 1) && ((np->in_flags & IPN_PURGE) != 0)) {
   2567 		nat_t *next;
   2568 		nat_t *nat;
   2569 
   2570 		for (next = softn->ipf_nat_instances; (nat = next) != NULL;) {
   2571 			next = nat->nat_next;
   2572 			if (nat->nat_ptr == np)
   2573 				ipf_nat_delete(softc, nat, NL_PURGE);
   2574 		}
   2575 	}
   2576 
   2577 	if ((np->in_flags & IPN_DELETE) == 0) {
   2578 		if (np->in_redir & NAT_REDIRECT) {
   2579 			switch (np->in_v[0])
   2580 			{
   2581 			case 4 :
   2582 				ipf_nat_delrdr(softn, np);
   2583 				break;
   2584 			case 6 :
   2585 				ipf_nat6_delrdr(softn, np);
   2586 				break;
   2587 			}
   2588 		}
   2589 		if (np->in_redir & (NAT_MAPBLK|NAT_MAP)) {
   2590 			switch (np->in_v[0])
   2591 			{
   2592 			case 4 :
   2593 				ipf_nat_delmap(softn, np);
   2594 				break;
   2595 			case 6 :
   2596 				ipf_nat6_delmap(softn, np);
   2597 				break;
   2598 			}
   2599 		}
   2600 	}
   2601 
   2602 	np->in_flags |= IPN_DELETE;
   2603 	ipf_nat_rule_deref(softc, &np);
   2604 }
   2605 
   2606 
   2607 /* ------------------------------------------------------------------------ */
   2608 /* Function:    ipf_nat_newmap                                              */
   2609 /* Returns:     int - -1 == error, 0 == success                             */
   2610 /* Parameters:  fin(I) - pointer to packet information                      */
   2611 /*              nat(I) - pointer to NAT entry                               */
   2612 /*              ni(I)  - pointer to structure with misc. information needed */
   2613 /*                       to create new NAT entry.                           */
   2614 /*                                                                          */
   2615 /* Given an empty NAT structure, populate it with new information about a   */
   2616 /* new NAT session, as defined by the matching NAT rule.                    */
   2617 /* ni.nai_ip is passed in uninitialised and must be set, in host byte order,*/
   2618 /* to the new IP address for the translation.                               */
   2619 /* ------------------------------------------------------------------------ */
   2620 static int
   2621 ipf_nat_newmap(fin, nat, ni)
   2622 	fr_info_t *fin;
   2623 	nat_t *nat;
   2624 	natinfo_t *ni;
   2625 {
   2626 	ipf_main_softc_t *softc = fin->fin_main_soft;
   2627 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   2628 	u_short st_port, dport, sport, port, sp, dp;
   2629 	struct in_addr in, inb;
   2630 	hostmap_t *hm;
   2631 	u_32_t flags;
   2632 	u_32_t st_ip;
   2633 	ipnat_t *np;
   2634 	nat_t *natl;
   2635 	int l;
   2636 
   2637 	/*
   2638 	 * If it's an outbound packet which doesn't match any existing
   2639 	 * record, then create a new port
   2640 	 */
   2641 	l = 0;
   2642 	hm = NULL;
   2643 	np = ni->nai_np;
   2644 	st_ip = np->in_snip;
   2645 	st_port = np->in_spnext;
   2646 	flags = nat->nat_flags;
   2647 
   2648 	if (flags & IPN_ICMPQUERY) {
   2649 		sport = fin->fin_data[1];
   2650 		dport = 0;
   2651 	} else {
   2652 		sport = htons(fin->fin_data[0]);
   2653 		dport = htons(fin->fin_data[1]);
   2654 	}
   2655 
   2656 	/*
   2657 	 * Do a loop until we either run out of entries to try or we find
   2658 	 * a NAT mapping that isn't currently being used.  This is done
   2659 	 * because the change to the source is not (usually) being fixed.
   2660 	 */
   2661 	do {
   2662 		port = 0;
   2663 		in.s_addr = htonl(np->in_snip);
   2664 		if (l == 0) {
   2665 			/*
   2666 			 * Check to see if there is an existing NAT
   2667 			 * setup for this IP address pair.
   2668 			 */
   2669 			hm = ipf_nat_hostmap(softn, np, fin->fin_src,
   2670 					     fin->fin_dst, in, 0);
   2671 			if (hm != NULL)
   2672 				in.s_addr = hm->hm_nsrcip.s_addr;
   2673 		} else if ((l == 1) && (hm != NULL)) {
   2674 			ipf_nat_hostmapdel(softc, &hm);
   2675 		}
   2676 		in.s_addr = ntohl(in.s_addr);
   2677 
   2678 		nat->nat_hm = hm;
   2679 
   2680 		if ((np->in_nsrcmsk == 0xffffffff) && (np->in_spnext == 0)) {
   2681 			if (l > 0) {
   2682 				NBUMPSIDEX(1, ns_exhausted, ns_exhausted_1);
   2683 				return -1;
   2684 			}
   2685 		}
   2686 
   2687 		if (np->in_redir == NAT_BIMAP &&
   2688 		    np->in_osrcmsk == np->in_nsrcmsk) {
   2689 			/*
   2690 			 * map the address block in a 1:1 fashion
   2691 			 */
   2692 			in.s_addr = np->in_nsrcaddr;
   2693 			in.s_addr |= fin->fin_saddr & ~np->in_osrcmsk;
   2694 			in.s_addr = ntohl(in.s_addr);
   2695 
   2696 		} else if (np->in_redir & NAT_MAPBLK) {
   2697 			if ((l >= np->in_ppip) || ((l > 0) &&
   2698 			     !(flags & IPN_TCPUDP))) {
   2699 				NBUMPSIDEX(1, ns_exhausted, ns_exhausted_2);
   2700 				return -1;
   2701 			}
   2702 			/*
   2703 			 * map-block - Calculate destination address.
   2704 			 */
   2705 			in.s_addr = ntohl(fin->fin_saddr);
   2706 			in.s_addr &= ntohl(~np->in_osrcmsk);
   2707 			inb.s_addr = in.s_addr;
   2708 			in.s_addr /= np->in_ippip;
   2709 			in.s_addr &= ntohl(~np->in_nsrcmsk);
   2710 			in.s_addr += ntohl(np->in_nsrcaddr);
   2711 			/*
   2712 			 * Calculate destination port.
   2713 			 */
   2714 			if ((flags & IPN_TCPUDP) &&
   2715 			    (np->in_ppip != 0)) {
   2716 				port = ntohs(sport) + l;
   2717 				port %= np->in_ppip;
   2718 				port += np->in_ppip *
   2719 					(inb.s_addr % np->in_ippip);
   2720 				port += MAPBLK_MINPORT;
   2721 				port = htons(port);
   2722 			}
   2723 
   2724 		} else if ((np->in_nsrcaddr == 0) &&
   2725 			   (np->in_nsrcmsk == 0xffffffff)) {
   2726 			i6addr_t in6;
   2727 
   2728 			/*
   2729 			 * 0/32 - use the interface's IP address.
   2730 			 */
   2731 			if ((l > 0) ||
   2732 			    ipf_ifpaddr(softc, 4, FRI_NORMAL, fin->fin_ifp,
   2733 				       &in6, NULL) == -1) {
   2734 				NBUMPSIDEX(1, ns_new_ifpaddr, ns_new_ifpaddr_1);
   2735 				return -1;
   2736 			}
   2737 			in.s_addr = ntohl(in6.in4.s_addr);
   2738 
   2739 		} else if ((np->in_nsrcaddr == 0) && (np->in_nsrcmsk == 0)) {
   2740 			/*
   2741 			 * 0/0 - use the original source address/port.
   2742 			 */
   2743 			if (l > 0) {
   2744 				NBUMPSIDEX(1, ns_exhausted, ns_exhausted_3);
   2745 				return -1;
   2746 			}
   2747 			in.s_addr = ntohl(fin->fin_saddr);
   2748 
   2749 		} else if ((np->in_nsrcmsk != 0xffffffff) &&
   2750 			   (np->in_spnext == 0) && ((l > 0) || (hm == NULL)))
   2751 			np->in_snip++;
   2752 
   2753 		natl = NULL;
   2754 
   2755 		if ((flags & IPN_TCPUDP) &&
   2756 		    ((np->in_redir & NAT_MAPBLK) == 0) &&
   2757 		    (np->in_flags & IPN_AUTOPORTMAP)) {
   2758 			/*
   2759 			 * "ports auto" (without map-block)
   2760 			 */
   2761 			if ((l > 0) && (l % np->in_ppip == 0)) {
   2762 				if ((l > np->in_ppip) &&
   2763 				    np->in_nsrcmsk != 0xffffffff)
   2764 					np->in_snip++;
   2765 			}
   2766 			if (np->in_ppip != 0) {
   2767 				port = ntohs(sport);
   2768 				port += (l % np->in_ppip);
   2769 				port %= np->in_ppip;
   2770 				port += np->in_ppip *
   2771 					(ntohl(fin->fin_saddr) %
   2772 					 np->in_ippip);
   2773 				port += MAPBLK_MINPORT;
   2774 				port = htons(port);
   2775 			}
   2776 
   2777 		} else if (((np->in_redir & NAT_MAPBLK) == 0) &&
   2778 			   (flags & IPN_TCPUDPICMP) && (np->in_spnext != 0)) {
   2779 			/*
   2780 			 * Standard port translation.  Select next port.
   2781 			 */
   2782 			if (np->in_flags & IPN_SEQUENTIAL) {
   2783 				port = np->in_spnext;
   2784 			} else {
   2785 				port = ipf_random() % (np->in_spmax -
   2786 						       np->in_spmin + 1);
   2787 				port += np->in_spmin;
   2788 			}
   2789 			port = htons(port);
   2790 			np->in_spnext++;
   2791 
   2792 			if (np->in_spnext > np->in_spmax) {
   2793 				np->in_spnext = np->in_spmin;
   2794 				if (np->in_nsrcmsk != 0xffffffff)
   2795 					np->in_snip++;
   2796 			}
   2797 		}
   2798 
   2799 		if (np->in_flags & IPN_SIPRANGE) {
   2800 			if (np->in_snip > ntohl(np->in_nsrcmsk))
   2801 				np->in_snip = ntohl(np->in_nsrcaddr);
   2802 		} else {
   2803 			if ((np->in_nsrcmsk != 0xffffffff) &&
   2804 			    ((np->in_snip + 1) & ntohl(np->in_nsrcmsk)) >
   2805 			    ntohl(np->in_nsrcaddr))
   2806 				np->in_snip = ntohl(np->in_nsrcaddr) + 1;
   2807 		}
   2808 
   2809 		if ((port == 0) && (flags & (IPN_TCPUDPICMP|IPN_ICMPQUERY)))
   2810 			port = sport;
   2811 
   2812 		/*
   2813 		 * Here we do a lookup of the connection as seen from
   2814 		 * the outside.  If an IP# pair already exists, try
   2815 		 * again.  So if you have A->B becomes C->B, you can
   2816 		 * also have D->E become C->E but not D->B causing
   2817 		 * another C->B.  Also take protocol and ports into
   2818 		 * account when determining whether a pre-existing
   2819 		 * NAT setup will cause an external conflict where
   2820 		 * this is appropriate.
   2821 		 */
   2822 		inb.s_addr = htonl(in.s_addr);
   2823 		sp = fin->fin_data[0];
   2824 		dp = fin->fin_data[1];
   2825 		fin->fin_data[0] = fin->fin_data[1];
   2826 		fin->fin_data[1] = ntohs(port);
   2827 		natl = ipf_nat_inlookup(fin, flags & ~(SI_WILDP|NAT_SEARCH),
   2828 					(u_int)fin->fin_p, fin->fin_dst, inb);
   2829 		fin->fin_data[0] = sp;
   2830 		fin->fin_data[1] = dp;
   2831 
   2832 		/*
   2833 		 * Has the search wrapped around and come back to the
   2834 		 * start ?
   2835 		 */
   2836 		if ((natl != NULL) &&
   2837 		    (np->in_spnext != 0) && (st_port == np->in_spnext) &&
   2838 		    (np->in_snip != 0) && (st_ip == np->in_snip)) {
   2839 			NBUMPSIDED(1, ns_wrap);
   2840 			return -1;
   2841 		}
   2842 		l++;
   2843 	} while (natl != NULL);
   2844 
   2845 	/* Setup the NAT table */
   2846 	nat->nat_osrcip = fin->fin_src;
   2847 	nat->nat_nsrcaddr = htonl(in.s_addr);
   2848 	nat->nat_odstip = fin->fin_dst;
   2849 	nat->nat_ndstip = fin->fin_dst;
   2850 	if (nat->nat_hm == NULL)
   2851 		nat->nat_hm = ipf_nat_hostmap(softn, np, fin->fin_src,
   2852 					      fin->fin_dst, nat->nat_nsrcip,
   2853 					      0);
   2854 
   2855 	if (flags & IPN_TCPUDP) {
   2856 		nat->nat_osport = sport;
   2857 		nat->nat_nsport = port;	/* sport */
   2858 		nat->nat_odport = dport;
   2859 		nat->nat_ndport = dport;
   2860 		((tcphdr_t *)fin->fin_dp)->th_sport = port;
   2861 	} else if (flags & IPN_ICMPQUERY) {
   2862 		nat->nat_oicmpid = fin->fin_data[1];
   2863 		((icmphdr_t *)fin->fin_dp)->icmp_id = port;
   2864 		nat->nat_nicmpid = port;
   2865 	}
   2866 	return 0;
   2867 }
   2868 
   2869 
   2870 /* ------------------------------------------------------------------------ */
   2871 /* Function:    ipf_nat_newrdr                                              */
   2872 /* Returns:     int - -1 == error, 0 == success (no move), 1 == success and */
   2873 /*                    allow rule to be moved if IPN_ROUNDR is set.          */
   2874 /* Parameters:  fin(I) - pointer to packet information                      */
   2875 /*              nat(I) - pointer to NAT entry                               */
   2876 /*              ni(I)  - pointer to structure with misc. information needed */
   2877 /*                       to create new NAT entry.                           */
   2878 /*                                                                          */
   2879 /* ni.nai_ip is passed in uninitialised and must be set, in host byte order,*/
   2880 /* to the new IP address for the translation.                               */
   2881 /* ------------------------------------------------------------------------ */
   2882 static int
   2883 ipf_nat_newrdr(fin, nat, ni)
   2884 	fr_info_t *fin;
   2885 	nat_t *nat;
   2886 	natinfo_t *ni;
   2887 {
   2888 	ipf_main_softc_t *softc = fin->fin_main_soft;
   2889 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   2890 	u_short nport, dport, sport;
   2891 	struct in_addr in, inb;
   2892 	u_short sp, dp;
   2893 	hostmap_t *hm;
   2894 	u_32_t flags;
   2895 	ipnat_t *np;
   2896 	nat_t *natl;
   2897 	int move;
   2898 
   2899 	move = 1;
   2900 	hm = NULL;
   2901 	in.s_addr = 0;
   2902 	np = ni->nai_np;
   2903 	flags = nat->nat_flags;
   2904 
   2905 	if (flags & IPN_ICMPQUERY) {
   2906 		dport = fin->fin_data[1];
   2907 		sport = 0;
   2908 	} else {
   2909 		sport = htons(fin->fin_data[0]);
   2910 		dport = htons(fin->fin_data[1]);
   2911 	}
   2912 
   2913 	/* TRACE sport, dport */
   2914 
   2915 
   2916 	/*
   2917 	 * If the matching rule has IPN_STICKY set, then we want to have the
   2918 	 * same rule kick in as before.  Why would this happen?  If you have
   2919 	 * a collection of rdr rules with "round-robin sticky", the current
   2920 	 * packet might match a different one to the previous connection but
   2921 	 * we want the same destination to be used.
   2922 	 */
   2923 	if (((np->in_flags & (IPN_ROUNDR|IPN_SPLIT)) != 0) &&
   2924 	    ((np->in_flags & IPN_STICKY) != 0)) {
   2925 		hm = ipf_nat_hostmap(softn, NULL, fin->fin_src, fin->fin_dst,
   2926 				     in, (u_32_t)dport);
   2927 		if (hm != NULL) {
   2928 			in.s_addr = ntohl(hm->hm_ndstip.s_addr);
   2929 			np = hm->hm_ipnat;
   2930 			ni->nai_np = np;
   2931 			move = 0;
   2932 			ipf_nat_hostmapdel(softc, &hm);
   2933 		}
   2934 	}
   2935 
   2936 	/*
   2937 	 * Otherwise, it's an inbound packet. Most likely, we don't
   2938 	 * want to rewrite source ports and source addresses. Instead,
   2939 	 * we want to rewrite to a fixed internal address and fixed
   2940 	 * internal port.
   2941 	 */
   2942 	if (np->in_flags & IPN_SPLIT) {
   2943 		in.s_addr = np->in_dnip;
   2944 
   2945 		if ((np->in_flags & (IPN_ROUNDR|IPN_STICKY)) == IPN_STICKY) {
   2946 			hm = ipf_nat_hostmap(softn, NULL, fin->fin_src,
   2947 					     fin->fin_dst, in, (u_32_t)dport);
   2948 			if (hm != NULL) {
   2949 				in.s_addr = hm->hm_ndstip.s_addr;
   2950 				move = 0;
   2951 			}
   2952 		}
   2953 
   2954 		if (hm == NULL || hm->hm_ref == 1) {
   2955 			if (np->in_ndstaddr == htonl(in.s_addr)) {
   2956 				np->in_dnip = ntohl(np->in_ndstmsk);
   2957 				move = 0;
   2958 			} else {
   2959 				np->in_dnip = ntohl(np->in_ndstaddr);
   2960 			}
   2961 		}
   2962 		if (hm != NULL)
   2963 			ipf_nat_hostmapdel(softc, &hm);
   2964 
   2965 	} else if ((np->in_ndstaddr == 0) && (np->in_ndstmsk == 0xffffffff)) {
   2966 		i6addr_t in6;
   2967 
   2968 		/*
   2969 		 * 0/32 - use the interface's IP address.
   2970 		 */
   2971 		if (ipf_ifpaddr(softc, 4, FRI_NORMAL, fin->fin_ifp,
   2972 			       &in6, NULL) == -1) {
   2973 			NBUMPSIDEX(0, ns_new_ifpaddr, ns_new_ifpaddr_2);
   2974 			return -1;
   2975 		}
   2976 		in.s_addr = ntohl(in6.in4.s_addr);
   2977 
   2978 	} else if ((np->in_ndstaddr == 0) && (np->in_ndstmsk== 0)) {
   2979 		/*
   2980 		 * 0/0 - use the original destination address/port.
   2981 		 */
   2982 		in.s_addr = ntohl(fin->fin_daddr);
   2983 
   2984 	} else if (np->in_redir == NAT_BIMAP &&
   2985 		   np->in_ndstmsk == np->in_odstmsk) {
   2986 		/*
   2987 		 * map the address block in a 1:1 fashion
   2988 		 */
   2989 		in.s_addr = np->in_ndstaddr;
   2990 		in.s_addr |= fin->fin_daddr & ~np->in_ndstmsk;
   2991 		in.s_addr = ntohl(in.s_addr);
   2992 	} else {
   2993 		in.s_addr = ntohl(np->in_ndstaddr);
   2994 	}
   2995 
   2996 	if ((np->in_dpnext == 0) || ((flags & NAT_NOTRULEPORT) != 0))
   2997 		nport = dport;
   2998 	else {
   2999 		/*
   3000 		 * Whilst not optimized for the case where
   3001 		 * pmin == pmax, the gain is not significant.
   3002 		 */
   3003 		if (((np->in_flags & IPN_FIXEDDPORT) == 0) &&
   3004 		    (np->in_odport != np->in_dtop)) {
   3005 			nport = ntohs(dport) - np->in_odport + np->in_dpmax;
   3006 			nport = htons(nport);
   3007 		} else {
   3008 			nport = htons(np->in_dpnext);
   3009 			np->in_dpnext++;
   3010 			if (np->in_dpnext > np->in_dpmax)
   3011 				np->in_dpnext = np->in_dpmin;
   3012 		}
   3013 	}
   3014 
   3015 	/*
   3016 	 * When the redirect-to address is set to 0.0.0.0, just
   3017 	 * assume a blank `forwarding' of the packet.  We don't
   3018 	 * setup any translation for this either.
   3019 	 */
   3020 	if (in.s_addr == 0) {
   3021 		if (nport == dport) {
   3022 			NBUMPSIDED(0, ns_xlate_null);
   3023 			return -1;
   3024 		}
   3025 		in.s_addr = ntohl(fin->fin_daddr);
   3026 	}
   3027 
   3028 	/*
   3029 	 * Check to see if this redirect mapping already exists and if
   3030 	 * it does, return "failure" (allowing it to be created will just
   3031 	 * cause one or both of these "connections" to stop working.)
   3032 	 */
   3033 	inb.s_addr = htonl(in.s_addr);
   3034 	sp = fin->fin_data[0];
   3035 	dp = fin->fin_data[1];
   3036 	fin->fin_data[1] = fin->fin_data[0];
   3037 	fin->fin_data[0] = ntohs(nport);
   3038 	natl = ipf_nat_outlookup(fin, flags & ~(SI_WILDP|NAT_SEARCH),
   3039 			     (u_int)fin->fin_p, inb, fin->fin_src);
   3040 	fin->fin_data[0] = sp;
   3041 	fin->fin_data[1] = dp;
   3042 	if (natl != NULL) {
   3043 		DT2(ns_new_xlate_exists, fr_info_t *, fin, nat_t *, natl);
   3044 		NBUMPSIDE(0, ns_xlate_exists);
   3045 		return -1;
   3046 	}
   3047 
   3048 	nat->nat_ndstaddr = htonl(in.s_addr);
   3049 	nat->nat_odstip = fin->fin_dst;
   3050 	nat->nat_nsrcip = fin->fin_src;
   3051 	nat->nat_osrcip = fin->fin_src;
   3052 	if ((nat->nat_hm == NULL) && ((np->in_flags & IPN_STICKY) != 0))
   3053 		nat->nat_hm = ipf_nat_hostmap(softn, np, fin->fin_src,
   3054 					      fin->fin_dst, in, (u_32_t)dport);
   3055 
   3056 	if (flags & IPN_TCPUDP) {
   3057 		nat->nat_odport = dport;
   3058 		nat->nat_ndport = nport;
   3059 		nat->nat_osport = sport;
   3060 		nat->nat_nsport = sport;
   3061 		((tcphdr_t *)fin->fin_dp)->th_dport = nport;
   3062 	} else if (flags & IPN_ICMPQUERY) {
   3063 		nat->nat_oicmpid = fin->fin_data[1];
   3064 		((icmphdr_t *)fin->fin_dp)->icmp_id = nport;
   3065 		nat->nat_nicmpid = nport;
   3066 	}
   3067 
   3068 	return move;
   3069 }
   3070 
   3071 /* ------------------------------------------------------------------------ */
   3072 /* Function:    ipf_nat_add                                                 */
   3073 /* Returns:     nat_t* - NULL == failure to create new NAT structure,       */
   3074 /*                       else pointer to new NAT structure                  */
   3075 /* Parameters:  fin(I)       - pointer to packet information                */
   3076 /*              np(I)        - pointer to NAT rule                          */
   3077 /*              natsave(I)   - pointer to where to store NAT struct pointer */
   3078 /*              flags(I)     - flags describing the current packet          */
   3079 /*              direction(I) - direction of packet (in/out)                 */
   3080 /* Write Lock:  ipf_nat                                                     */
   3081 /*                                                                          */
   3082 /* Attempts to create a new NAT entry.  Does not actually change the packet */
   3083 /* in any way.                                                              */
   3084 /*                                                                          */
   3085 /* This fucntion is in three main parts: (1) deal with creating a new NAT   */
   3086 /* structure for a "MAP" rule (outgoing NAT translation); (2) deal with     */
   3087 /* creating a new NAT structure for a "RDR" rule (incoming NAT translation) */
   3088 /* and (3) building that structure and putting it into the NAT table(s).    */
   3089 /*                                                                          */
   3090 /* NOTE: natsave should NOT be used top point back to an ipstate_t struct   */
   3091 /*       as it can result in memory being corrupted.                        */
   3092 /* ------------------------------------------------------------------------ */
   3093 nat_t *
   3094 ipf_nat_add(fin, np, natsave, flags, direction)
   3095 	fr_info_t *fin;
   3096 	ipnat_t *np;
   3097 	nat_t **natsave;
   3098 	u_int flags;
   3099 	int direction;
   3100 {
   3101 	ipf_main_softc_t *softc = fin->fin_main_soft;
   3102 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   3103 	hostmap_t *hm = NULL;
   3104 	nat_t *nat, *natl;
   3105 	natstat_t *nsp;
   3106 	u_int nflags;
   3107 	natinfo_t ni;
   3108 	int move;
   3109 
   3110 	nsp = &softn->ipf_nat_stats;
   3111 
   3112 	if ((nsp->ns_active * 100 / softn->ipf_nat_table_max) >
   3113 	    softn->ipf_nat_table_wm_high) {
   3114 		softn->ipf_nat_doflush = 1;
   3115 	}
   3116 
   3117 	if (nsp->ns_active >= softn->ipf_nat_table_max) {
   3118 		NBUMPSIDED(fin->fin_out, ns_table_max);
   3119 		return NULL;
   3120 	}
   3121 
   3122 	move = 1;
   3123 	nflags = np->in_flags & flags;
   3124 	nflags &= NAT_FROMRULE;
   3125 
   3126 	ni.nai_np = np;
   3127 	ni.nai_dport = 0;
   3128 	ni.nai_sport = 0;
   3129 
   3130 	/* Give me a new nat */
   3131 	KMALLOC(nat, nat_t *);
   3132 	if (nat == NULL) {
   3133 		NBUMPSIDED(fin->fin_out, ns_memfail);
   3134 		/*
   3135 		 * Try to automatically tune the max # of entries in the
   3136 		 * table allowed to be less than what will cause kmem_alloc()
   3137 		 * to fail and try to eliminate panics due to out of memory
   3138 		 * conditions arising.
   3139 		 */
   3140 		if ((softn->ipf_nat_table_max > softn->ipf_nat_table_sz) &&
   3141 		    (nsp->ns_active > 100)) {
   3142 			softn->ipf_nat_table_max = nsp->ns_active - 100;
   3143 			printf("table_max reduced to %d\n",
   3144 				softn->ipf_nat_table_max);
   3145 		}
   3146 		return NULL;
   3147 	}
   3148 
   3149 	if (flags & IPN_ICMPQUERY) {
   3150 		/*
   3151 		 * In the ICMP query NAT code, we translate the ICMP id fields
   3152 		 * to make them unique. This is indepedent of the ICMP type
   3153 		 * (e.g. in the unlikely event that a host sends an echo and
   3154 		 * an tstamp request with the same id, both packets will have
   3155 		 * their ip address/id field changed in the same way).
   3156 		 */
   3157 		/* The icmp_id field is used by the sender to identify the
   3158 		 * process making the icmp request. (the receiver justs
   3159 		 * copies it back in its response). So, it closely matches
   3160 		 * the concept of source port. We overlay sport, so we can
   3161 		 * maximally reuse the existing code.
   3162 		 */
   3163 		ni.nai_sport = fin->fin_data[1];
   3164 		ni.nai_dport = 0;
   3165 	}
   3166 
   3167 	bzero((char *)nat, sizeof(*nat));
   3168 	nat->nat_flags = flags;
   3169 	nat->nat_redir = np->in_redir;
   3170 	nat->nat_dir = direction;
   3171 	nat->nat_pr[0] = fin->fin_p;
   3172 	nat->nat_pr[1] = fin->fin_p;
   3173 
   3174 	/*
   3175 	 * Search the current table for a match and create a new mapping
   3176 	 * if there is none found.
   3177 	 */
   3178 	if (np->in_redir & NAT_DIVERTUDP) {
   3179 		move = ipf_nat_newdivert(fin, nat, &ni);
   3180 
   3181 	} else if (np->in_redir & NAT_REWRITE) {
   3182 		move = ipf_nat_newrewrite(fin, nat, &ni);
   3183 
   3184 	} else if (direction == NAT_OUTBOUND) {
   3185 		/*
   3186 		 * We can now arrange to call this for the same connection
   3187 		 * because ipf_nat_new doesn't protect the code path into
   3188 		 * this function.
   3189 		 */
   3190 		natl = ipf_nat_outlookup(fin, nflags, (u_int)fin->fin_p,
   3191 				     fin->fin_src, fin->fin_dst);
   3192 		if (natl != NULL) {
   3193 			KFREE(nat);
   3194 			nat = natl;
   3195 			goto done;
   3196 		}
   3197 
   3198 		move = ipf_nat_newmap(fin, nat, &ni);
   3199 	} else {
   3200 		/*
   3201 		 * NAT_INBOUND is used for redirects rules
   3202 		 */
   3203 		natl = ipf_nat_inlookup(fin, nflags, (u_int)fin->fin_p,
   3204 					fin->fin_src, fin->fin_dst);
   3205 		if (natl != NULL) {
   3206 			KFREE(nat);
   3207 			nat = natl;
   3208 			goto done;
   3209 		}
   3210 
   3211 		move = ipf_nat_newrdr(fin, nat, &ni);
   3212 	}
   3213 	if (move == -1)
   3214 		goto badnat;
   3215 
   3216 	np = ni.nai_np;
   3217 
   3218 	nat->nat_mssclamp = np->in_mssclamp;
   3219 	nat->nat_me = natsave;
   3220 	nat->nat_fr = fin->fin_fr;
   3221 	nat->nat_rev = fin->fin_rev;
   3222 	nat->nat_ptr = np;
   3223 	nat->nat_dlocal = np->in_dlocal;
   3224 
   3225 	if ((np->in_apr != NULL) && ((nat->nat_flags & NAT_SLAVE) == 0)) {
   3226 		if (ipf_proxy_new(fin, nat) == -1) {
   3227 			NBUMPSIDED(fin->fin_out, ns_appr_fail);
   3228 			goto badnat;
   3229 		}
   3230 	}
   3231 
   3232 	nat->nat_ifps[0] = np->in_ifps[0];
   3233 	if (np->in_ifps[0] != NULL) {
   3234 		COPYIFNAME(np->in_v[0], np->in_ifps[0], nat->nat_ifnames[0]);
   3235 	}
   3236 
   3237 	nat->nat_ifps[1] = np->in_ifps[1];
   3238 	if (np->in_ifps[1] != NULL) {
   3239 		COPYIFNAME(np->in_v[1], np->in_ifps[1], nat->nat_ifnames[1]);
   3240 	}
   3241 
   3242 	if (ipf_nat_finalise(fin, nat) == -1) {
   3243 		goto badnat;
   3244 	}
   3245 
   3246 	np->in_use++;
   3247 
   3248 	if ((move == 1) && (np->in_flags & IPN_ROUNDR)) {
   3249 		if ((np->in_redir & (NAT_REDIRECT|NAT_MAP)) == NAT_REDIRECT) {
   3250 			ipf_nat_delrdr(softn, np);
   3251 			ipf_nat_addrdr(softn, np);
   3252 		} else if ((np->in_redir & (NAT_REDIRECT|NAT_MAP)) == NAT_MAP) {
   3253 			ipf_nat_delmap(softn, np);
   3254 			ipf_nat_addmap(softn, np);
   3255 		}
   3256 	}
   3257 
   3258 	if (flags & SI_WILDP)
   3259 		nsp->ns_wilds++;
   3260 	nsp->ns_proto[nat->nat_pr[0]]++;
   3261 
   3262 	goto done;
   3263 badnat:
   3264 	DT2(ns_badnatnew, fr_info_t *, fin, nat_t *, nat);
   3265 	NBUMPSIDE(fin->fin_out, ns_badnatnew);
   3266 	if ((hm = nat->nat_hm) != NULL)
   3267 		ipf_nat_hostmapdel(softc, &hm);
   3268 	KFREE(nat);
   3269 	nat = NULL;
   3270 done:
   3271 	if (nat != NULL && np != NULL)
   3272 		np->in_hits++;
   3273 	if (natsave != NULL)
   3274 		*natsave = nat;
   3275 	return nat;
   3276 }
   3277 
   3278 
   3279 /* ------------------------------------------------------------------------ */
   3280 /* Function:    ipf_nat_finalise                                            */
   3281 /* Returns:     int - 0 == sucess, -1 == failure                            */
   3282 /* Parameters:  fin(I) - pointer to packet information                      */
   3283 /*              nat(I) - pointer to NAT entry                               */
   3284 /* Write Lock:  ipf_nat                                                     */
   3285 /*                                                                          */
   3286 /* This is the tail end of constructing a new NAT entry and is the same     */
   3287 /* for both IPv4 and IPv6.                                                  */
   3288 /* ------------------------------------------------------------------------ */
   3289 /*ARGSUSED*/
   3290 static int
   3291 ipf_nat_finalise(fin, nat)
   3292 	fr_info_t *fin;
   3293 	nat_t *nat;
   3294 {
   3295 	ipf_main_softc_t *softc = fin->fin_main_soft;
   3296 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   3297 	u_32_t sum1, sum2, sumd;
   3298 	frentry_t *fr;
   3299 	u_32_t flags;
   3300 #if SOLARIS && defined(_KERNEL) && (SOLARIS2 >= 6) && defined(ICK_M_CTL_MAGIC)
   3301 	qpktinfo_t *qpi = fin->fin_qpi;
   3302 #endif
   3303 
   3304 	flags = nat->nat_flags;
   3305 
   3306 	switch (nat->nat_pr[0])
   3307 	{
   3308 	case IPPROTO_ICMP :
   3309 		sum1 = LONG_SUM(ntohs(nat->nat_oicmpid));
   3310 		sum2 = LONG_SUM(ntohs(nat->nat_nicmpid));
   3311 		CALC_SUMD(sum1, sum2, sumd);
   3312 		nat->nat_sumd[0] = (sumd & 0xffff) + (sumd >> 16);
   3313 
   3314 		break;
   3315 
   3316 	default :
   3317 		sum1 = LONG_SUM(ntohl(nat->nat_osrcaddr) + \
   3318 				ntohs(nat->nat_osport));
   3319 		sum2 = LONG_SUM(ntohl(nat->nat_nsrcaddr) + \
   3320 				ntohs(nat->nat_nsport));
   3321 		CALC_SUMD(sum1, sum2, sumd);
   3322 		nat->nat_sumd[0] = (sumd & 0xffff) + (sumd >> 16);
   3323 
   3324 		sum1 = LONG_SUM(ntohl(nat->nat_odstaddr) + \
   3325 				ntohs(nat->nat_odport));
   3326 		sum2 = LONG_SUM(ntohl(nat->nat_ndstaddr) + \
   3327 				ntohs(nat->nat_ndport));
   3328 		CALC_SUMD(sum1, sum2, sumd);
   3329 		nat->nat_sumd[0] += (sumd & 0xffff) + (sumd >> 16);
   3330 		break;
   3331 	}
   3332 
   3333 	/*
   3334 	 * Compute the partial checksum, just in case.
   3335 	 * This is only ever placed into outbound packets so care needs
   3336 	 * to be taken over which pair of addresses are used.
   3337 	 */
   3338 	if (nat->nat_dir == NAT_OUTBOUND) {
   3339 		sum1 = LONG_SUM(ntohl(nat->nat_nsrcaddr));
   3340 		sum1 += LONG_SUM(ntohl(nat->nat_ndstaddr));
   3341 	} else {
   3342 		sum1 = LONG_SUM(ntohl(nat->nat_osrcaddr));
   3343 		sum1 += LONG_SUM(ntohl(nat->nat_odstaddr));
   3344 	}
   3345 	sum1 += nat->nat_pr[1];
   3346 	nat->nat_sumd[1] = (sum1 & 0xffff) + (sum1 >> 16);
   3347 
   3348 	sum1 = LONG_SUM(ntohl(nat->nat_osrcaddr));
   3349 	sum2 = LONG_SUM(ntohl(nat->nat_nsrcaddr));
   3350 	CALC_SUMD(sum1, sum2, sumd);
   3351 	nat->nat_ipsumd = (sumd & 0xffff) + (sumd >> 16);
   3352 
   3353 	sum1 = LONG_SUM(ntohl(nat->nat_odstaddr));
   3354 	sum2 = LONG_SUM(ntohl(nat->nat_ndstaddr));
   3355 	CALC_SUMD(sum1, sum2, sumd);
   3356 	nat->nat_ipsumd += (sumd & 0xffff) + (sumd >> 16);
   3357 
   3358 	nat->nat_v[0] = 4;
   3359 	nat->nat_v[1] = 4;
   3360 
   3361 	if ((nat->nat_ifps[0] != NULL) && (nat->nat_ifps[0] != (void *)-1)) {
   3362 		nat->nat_mtu[0] = GETIFMTU_4(nat->nat_ifps[0]);
   3363 	}
   3364 
   3365 	if ((nat->nat_ifps[1] != NULL) && (nat->nat_ifps[1] != (void *)-1)) {
   3366 		nat->nat_mtu[1] = GETIFMTU_4(nat->nat_ifps[1]);
   3367 	}
   3368 
   3369 	if ((nat->nat_flags & SI_CLONE) == 0)
   3370 		nat->nat_sync = ipf_sync_new(softc, SMC_NAT, fin, nat);
   3371 
   3372 	if (ipf_nat_insert(softc, softn, nat) == 0) {
   3373 		if (softn->ipf_nat_logging)
   3374 			ipf_nat_log(softc, softn, nat, NL_NEW);
   3375 		fr = nat->nat_fr;
   3376 		if (fr != NULL) {
   3377 			MUTEX_ENTER(&fr->fr_lock);
   3378 			fr->fr_ref++;
   3379 			MUTEX_EXIT(&fr->fr_lock);
   3380 		}
   3381 		return 0;
   3382 	}
   3383 
   3384 	NBUMPSIDED(fin->fin_out, ns_unfinalised);
   3385 	/*
   3386 	 * nat_insert failed, so cleanup time...
   3387 	 */
   3388 	if (nat->nat_sync != NULL)
   3389 		ipf_sync_del_nat(softc->ipf_sync_soft, nat->nat_sync);
   3390 	return -1;
   3391 }
   3392 
   3393 
   3394 /* ------------------------------------------------------------------------ */
   3395 /* Function:    ipf_nat_insert                                              */
   3396 /* Returns:     int - 0 == sucess, -1 == failure                            */
   3397 /* Parameters:  softc(I) - pointer to soft context main structure           */
   3398 /*              softn(I) - pointer to NAT context structure                 */
   3399 /*              nat(I) - pointer to NAT structure                           */
   3400 /* Write Lock:  ipf_nat                                                     */
   3401 /*                                                                          */
   3402 /* Insert a NAT entry into the hash tables for searching and add it to the  */
   3403 /* list of active NAT entries.  Adjust global counters when complete.       */
   3404 /* ------------------------------------------------------------------------ */
   3405 int
   3406 ipf_nat_insert(softc, softn, nat)
   3407 	ipf_main_softc_t *softc;
   3408 	ipf_nat_softc_t *softn;
   3409 	nat_t *nat;
   3410 {
   3411 	u_int hv0, hv1;
   3412 	u_int sp, dp;
   3413 	ipnat_t *in;
   3414 
   3415 	/*
   3416 	 * Try and return an error as early as possible, so calculate the hash
   3417 	 * entry numbers first and then proceed.
   3418 	 */
   3419 	if ((nat->nat_flags & (SI_W_SPORT|SI_W_DPORT)) == 0) {
   3420 		if ((nat->nat_flags & IPN_TCPUDP) != 0) {
   3421 			sp = nat->nat_osport;
   3422 			dp = nat->nat_odport;
   3423 		} else if ((nat->nat_flags & IPN_ICMPQUERY) != 0) {
   3424 			sp = 0;
   3425 			dp = nat->nat_oicmpid;
   3426 		} else {
   3427 			sp = 0;
   3428 			dp = 0;
   3429 		}
   3430 		hv0 = NAT_HASH_FN(nat->nat_osrcaddr, sp, 0xffffffff);
   3431 		hv0 = NAT_HASH_FN(nat->nat_odstaddr, hv0 + dp, 0xffffffff);
   3432 		/*
   3433 		 * TRACE nat_osrcaddr, nat_osport, nat_odstaddr,
   3434 		 * nat_odport, hv0
   3435 		 */
   3436 
   3437 		if ((nat->nat_flags & IPN_TCPUDP) != 0) {
   3438 			sp = nat->nat_nsport;
   3439 			dp = nat->nat_ndport;
   3440 		} else if ((nat->nat_flags & IPN_ICMPQUERY) != 0) {
   3441 			sp = 0;
   3442 			dp = nat->nat_nicmpid;
   3443 		} else {
   3444 			sp = 0;
   3445 			dp = 0;
   3446 		}
   3447 		hv1 = NAT_HASH_FN(nat->nat_nsrcaddr, sp, 0xffffffff);
   3448 		hv1 = NAT_HASH_FN(nat->nat_ndstaddr, hv1 + dp, 0xffffffff);
   3449 		/*
   3450 		 * TRACE nat_nsrcaddr, nat_nsport, nat_ndstaddr,
   3451 		 * nat_ndport, hv1
   3452 		 */
   3453 	} else {
   3454 		hv0 = NAT_HASH_FN(nat->nat_osrcaddr, 0, 0xffffffff);
   3455 		hv0 = NAT_HASH_FN(nat->nat_odstaddr, hv0, 0xffffffff);
   3456 		/* TRACE nat_osrcaddr, nat_odstaddr, hv0 */
   3457 
   3458 		hv1 = NAT_HASH_FN(nat->nat_nsrcaddr, 0, 0xffffffff);
   3459 		hv1 = NAT_HASH_FN(nat->nat_ndstaddr, hv1, 0xffffffff);
   3460 		/* TRACE nat_nsrcaddr, nat_ndstaddr, hv1 */
   3461 	}
   3462 
   3463 	nat->nat_hv[0] = hv0;
   3464 	nat->nat_hv[1] = hv1;
   3465 
   3466 	MUTEX_INIT(&nat->nat_lock, "nat entry lock");
   3467 
   3468 	in = nat->nat_ptr;
   3469 	nat->nat_ref = nat->nat_me ? 2 : 1;
   3470 
   3471 	nat->nat_ifnames[0][LIFNAMSIZ - 1] = '\0';
   3472 	nat->nat_ifps[0] = ipf_resolvenic(softc, nat->nat_ifnames[0], 4);
   3473 
   3474 	if (nat->nat_ifnames[1][0] != '\0') {
   3475 		nat->nat_ifnames[1][LIFNAMSIZ - 1] = '\0';
   3476 		nat->nat_ifps[1] = ipf_resolvenic(softc,
   3477 						  nat->nat_ifnames[1], 4);
   3478 	} else if (in->in_ifnames[1] != -1) {
   3479 		char *name;
   3480 
   3481 		name = in->in_names + in->in_ifnames[1];
   3482 		if (name[1] != '\0' && name[0] != '-' && name[0] != '*') {
   3483 			(void) strncpy(nat->nat_ifnames[1],
   3484 				       nat->nat_ifnames[0], LIFNAMSIZ);
   3485 			nat->nat_ifnames[1][LIFNAMSIZ - 1] = '\0';
   3486 			nat->nat_ifps[1] = nat->nat_ifps[0];
   3487 		}
   3488 	}
   3489 	if ((nat->nat_ifps[0] != NULL) && (nat->nat_ifps[0] != (void *)-1)) {
   3490 		nat->nat_mtu[0] = GETIFMTU_4(nat->nat_ifps[0]);
   3491 	}
   3492 	if ((nat->nat_ifps[1] != NULL) && (nat->nat_ifps[1] != (void *)-1)) {
   3493 		nat->nat_mtu[1] = GETIFMTU_4(nat->nat_ifps[1]);
   3494 	}
   3495 
   3496 	return ipf_nat_hashtab_add(softc, softn, nat);
   3497 }
   3498 
   3499 
   3500 /* ------------------------------------------------------------------------ */
   3501 /* Function:    ipf_nat_hashtab_add                                         */
   3502 /* Parameters:  softc(I) - pointer to soft context main structure           */
   3503 /*              softn(I) - pointer to NAT context structure                 */
   3504 /*              nat(I) - pointer to NAT structure                           */
   3505 /*                                                                          */
   3506 /* Handle the insertion of a NAT entry into the table/list.                 */
   3507 /* ------------------------------------------------------------------------ */
   3508 int
   3509 ipf_nat_hashtab_add(softc, softn, nat)
   3510 	ipf_main_softc_t *softc;
   3511 	ipf_nat_softc_t *softn;
   3512 	nat_t *nat;
   3513 {
   3514 	nat_t **natp;
   3515 	u_int hv0;
   3516 	u_int hv1;
   3517 
   3518 	hv0 = nat->nat_hv[0] % softn->ipf_nat_table_sz;
   3519 	hv1 = nat->nat_hv[1] % softn->ipf_nat_table_sz;
   3520 
   3521 	if (nat->nat_dir == NAT_INBOUND || nat->nat_dir == NAT_DIVERTIN) {
   3522 		u_int swap;
   3523 
   3524 		swap = hv0;
   3525 		hv0 = hv1;
   3526 		hv1 = swap;
   3527 	}
   3528 
   3529 	if (softn->ipf_nat_stats.ns_side[0].ns_bucketlen[hv0] >=
   3530 	    softn->ipf_nat_maxbucket) {
   3531 		DT1(ns_bucket_max_0, int,
   3532 		    softn->ipf_nat_stats.ns_side[0].ns_bucketlen[hv0]);
   3533 		NBUMPSIDE(0, ns_bucket_max);
   3534 		return -1;
   3535 	}
   3536 
   3537 	if (softn->ipf_nat_stats.ns_side[1].ns_bucketlen[hv1] >=
   3538 	    softn->ipf_nat_maxbucket) {
   3539 		DT1(ns_bucket_max_1, int,
   3540 		    softn->ipf_nat_stats.ns_side[1].ns_bucketlen[hv1]);
   3541 		NBUMPSIDE(1, ns_bucket_max);
   3542 		return -1;
   3543 	}
   3544 
   3545 	/*
   3546 	 * The ordering of operations in the list and hash table insertion
   3547 	 * is very important.  The last operation for each task should be
   3548 	 * to update the top of the list, after all the "nexts" have been
   3549 	 * done so that walking the list while it is being done does not
   3550 	 * find strange pointers.
   3551 	 *
   3552 	 * Global list of NAT instances
   3553 	 */
   3554 	nat->nat_next = softn->ipf_nat_instances;
   3555 	nat->nat_pnext = &softn->ipf_nat_instances;
   3556 	if (softn->ipf_nat_instances)
   3557 		softn->ipf_nat_instances->nat_pnext = &nat->nat_next;
   3558 	softn->ipf_nat_instances = nat;
   3559 
   3560 	/*
   3561 	 * Inbound hash table.
   3562 	 */
   3563 	natp = &softn->ipf_nat_table[0][hv0];
   3564 	nat->nat_phnext[0] = natp;
   3565 	nat->nat_hnext[0] = *natp;
   3566 	if (*natp) {
   3567 		(*natp)->nat_phnext[0] = &nat->nat_hnext[0];
   3568 	} else {
   3569 		NBUMPSIDE(0, ns_inuse);
   3570 	}
   3571 	*natp = nat;
   3572 	NBUMPSIDE(0, ns_bucketlen[hv0]);
   3573 
   3574 	/*
   3575 	 * Outbound hash table.
   3576 	 */
   3577 	natp = &softn->ipf_nat_table[1][hv1];
   3578 	nat->nat_phnext[1] = natp;
   3579 	nat->nat_hnext[1] = *natp;
   3580 	if (*natp)
   3581 		(*natp)->nat_phnext[1] = &nat->nat_hnext[1];
   3582 	else {
   3583 		NBUMPSIDE(1, ns_inuse);
   3584 	}
   3585 	*natp = nat;
   3586 	NBUMPSIDE(1, ns_bucketlen[hv1]);
   3587 
   3588 	ipf_nat_setqueue(softc, softn, nat);
   3589 
   3590 	if (nat->nat_dir & NAT_OUTBOUND) {
   3591 		NBUMPSIDE(1, ns_added);
   3592 	} else {
   3593 		NBUMPSIDE(0, ns_added);
   3594 	}
   3595 	softn->ipf_nat_stats.ns_active++;
   3596 	return 0;
   3597 }
   3598 
   3599 
   3600 /* ------------------------------------------------------------------------ */
   3601 /* Function:    ipf_nat_icmperrorlookup                                     */
   3602 /* Returns:     nat_t* - point to matching NAT structure                    */
   3603 /* Parameters:  fin(I) - pointer to packet information                      */
   3604 /*              dir(I) - direction of packet (in/out)                       */
   3605 /*                                                                          */
   3606 /* Check if the ICMP error message is related to an existing TCP, UDP or    */
   3607 /* ICMP query nat entry.  It is assumed that the packet is already of the   */
   3608 /* the required length.                                                     */
   3609 /* ------------------------------------------------------------------------ */
   3610 nat_t *
   3611 ipf_nat_icmperrorlookup(fin, dir)
   3612 	fr_info_t *fin;
   3613 	int dir;
   3614 {
   3615 	ipf_main_softc_t *softc = fin->fin_main_soft;
   3616 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   3617 	int flags = 0, type, minlen;
   3618 	icmphdr_t *icmp, *orgicmp;
   3619 	nat_stat_side_t *nside;
   3620 	tcphdr_t *tcp = NULL;
   3621 	u_short data[2];
   3622 	nat_t *nat;
   3623 	ip_t *oip;
   3624 	u_int p;
   3625 
   3626 	icmp = fin->fin_dp;
   3627 	type = icmp->icmp_type;
   3628 	nside = &softn->ipf_nat_stats.ns_side[fin->fin_out];
   3629 	/*
   3630 	 * Does it at least have the return (basic) IP header ?
   3631 	 * Only a basic IP header (no options) should be with an ICMP error
   3632 	 * header.  Also, if it's not an error type, then return.
   3633 	 */
   3634 	if ((fin->fin_hlen != sizeof(ip_t)) || !(fin->fin_flx & FI_ICMPERR)) {
   3635 		ATOMIC_INCL(nside->ns_icmp_basic);
   3636 		return NULL;
   3637 	}
   3638 
   3639 	/*
   3640 	 * Check packet size
   3641 	 */
   3642 	oip = (ip_t *)((char *)fin->fin_dp + 8);
   3643 	minlen = IP_HL(oip) << 2;
   3644 	if ((minlen < sizeof(ip_t)) ||
   3645 	    (fin->fin_plen < ICMPERR_IPICMPHLEN + minlen)) {
   3646 		ATOMIC_INCL(nside->ns_icmp_size);
   3647 		return NULL;
   3648 	}
   3649 
   3650 	/*
   3651 	 * Is the buffer big enough for all of it ?  It's the size of the IP
   3652 	 * header claimed in the encapsulated part which is of concern.  It
   3653 	 * may be too big to be in this buffer but not so big that it's
   3654 	 * outside the ICMP packet, leading to TCP deref's causing problems.
   3655 	 * This is possible because we don't know how big oip_hl is when we
   3656 	 * do the pullup early in ipf_check() and thus can't gaurantee it is
   3657 	 * all here now.
   3658 	 */
   3659 #ifdef  ipf_nat_KERNEL
   3660 	{
   3661 	mb_t *m;
   3662 
   3663 	m = fin->fin_m;
   3664 # if defined(MENTAT)
   3665 	if ((char *)oip + fin->fin_dlen - ICMPERR_ICMPHLEN >
   3666 	    (char *)m->b_wptr) {
   3667 		ATOMIC_INCL(nside->ns_icmp_mbuf);
   3668 		return NULL;
   3669 	}
   3670 # else
   3671 	if ((char *)oip + fin->fin_dlen - ICMPERR_ICMPHLEN >
   3672 	    (char *)fin->fin_ip + M_LEN(m)) {
   3673 		ATOMIC_INCL(nside->ns_icmp_mbuf);
   3674 		return NULL;
   3675 	}
   3676 # endif
   3677 	}
   3678 #endif
   3679 
   3680 	if (fin->fin_daddr != oip->ip_src.s_addr) {
   3681 		ATOMIC_INCL(nside->ns_icmp_address);
   3682 		return NULL;
   3683 	}
   3684 
   3685 	p = oip->ip_p;
   3686 	if (p == IPPROTO_TCP)
   3687 		flags = IPN_TCP;
   3688 	else if (p == IPPROTO_UDP)
   3689 		flags = IPN_UDP;
   3690 	else if (p == IPPROTO_ICMP) {
   3691 		orgicmp = (icmphdr_t *)((char *)oip + (IP_HL(oip) << 2));
   3692 
   3693 		/* see if this is related to an ICMP query */
   3694 		if (ipf_nat_icmpquerytype(orgicmp->icmp_type)) {
   3695 			data[0] = fin->fin_data[0];
   3696 			data[1] = fin->fin_data[1];
   3697 			fin->fin_data[0] = 0;
   3698 			fin->fin_data[1] = orgicmp->icmp_id;
   3699 
   3700 			flags = IPN_ICMPERR|IPN_ICMPQUERY;
   3701 			/*
   3702 			 * NOTE : dir refers to the direction of the original
   3703 			 *        ip packet. By definition the icmp error
   3704 			 *        message flows in the opposite direction.
   3705 			 */
   3706 			if (dir == NAT_INBOUND)
   3707 				nat = ipf_nat_inlookup(fin, flags, p,
   3708 						       oip->ip_dst,
   3709 						       oip->ip_src);
   3710 			else
   3711 				nat = ipf_nat_outlookup(fin, flags, p,
   3712 							oip->ip_dst,
   3713 							oip->ip_src);
   3714 			fin->fin_data[0] = data[0];
   3715 			fin->fin_data[1] = data[1];
   3716 			return nat;
   3717 		}
   3718 	}
   3719 
   3720 	if (flags & IPN_TCPUDP) {
   3721 		minlen += 8;		/* + 64bits of data to get ports */
   3722 		/* TRACE (fin,minlen) */
   3723 		if (fin->fin_plen < ICMPERR_IPICMPHLEN + minlen) {
   3724 			ATOMIC_INCL(nside->ns_icmp_short);
   3725 			return NULL;
   3726 		}
   3727 
   3728 		data[0] = fin->fin_data[0];
   3729 		data[1] = fin->fin_data[1];
   3730 		tcp = (tcphdr_t *)((char *)oip + (IP_HL(oip) << 2));
   3731 		fin->fin_data[0] = ntohs(tcp->th_dport);
   3732 		fin->fin_data[1] = ntohs(tcp->th_sport);
   3733 
   3734 		if (dir == NAT_INBOUND) {
   3735 			nat = ipf_nat_inlookup(fin, flags, p, oip->ip_dst,
   3736 					       oip->ip_src);
   3737 		} else {
   3738 			nat = ipf_nat_outlookup(fin, flags, p, oip->ip_dst,
   3739 					    oip->ip_src);
   3740 		}
   3741 		fin->fin_data[0] = data[0];
   3742 		fin->fin_data[1] = data[1];
   3743 		return nat;
   3744 	}
   3745 	if (dir == NAT_INBOUND)
   3746 		nat = ipf_nat_inlookup(fin, 0, p, oip->ip_dst, oip->ip_src);
   3747 	else
   3748 		nat = ipf_nat_outlookup(fin, 0, p, oip->ip_dst, oip->ip_src);
   3749 
   3750 	return nat;
   3751 }
   3752 
   3753 
   3754 /* ------------------------------------------------------------------------ */
   3755 /* Function:    ipf_nat_icmperror                                           */
   3756 /* Returns:     nat_t* - point to matching NAT structure                    */
   3757 /* Parameters:  fin(I)    - pointer to packet information                   */
   3758 /*              nflags(I) - NAT flags for this packet                       */
   3759 /*              dir(I)    - direction of packet (in/out)                    */
   3760 /*                                                                          */
   3761 /* Fix up an ICMP packet which is an error message for an existing NAT      */
   3762 /* session.  This will correct both packet header data and checksums.       */
   3763 /*                                                                          */
   3764 /* This should *ONLY* be used for incoming ICMP error packets to make sure  */
   3765 /* a NAT'd ICMP packet gets correctly recognised.                           */
   3766 /* ------------------------------------------------------------------------ */
   3767 nat_t *
   3768 ipf_nat_icmperror(fin, nflags, dir)
   3769 	fr_info_t *fin;
   3770 	u_int *nflags;
   3771 	int dir;
   3772 {
   3773 	ipf_main_softc_t *softc = fin->fin_main_soft;
   3774 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   3775 	u_32_t sum1, sum2, sumd, sumd2;
   3776 	struct in_addr a1, a2, a3, a4;
   3777 	int flags, dlen, odst;
   3778 	icmphdr_t *icmp;
   3779 	u_short *csump;
   3780 	tcphdr_t *tcp;
   3781 	nat_t *nat;
   3782 	ip_t *oip;
   3783 	void *dp;
   3784 
   3785 	if ((fin->fin_flx & (FI_SHORT|FI_FRAGBODY))) {
   3786 		NBUMPSIDED(fin->fin_out, ns_icmp_short);
   3787 		return NULL;
   3788 	}
   3789 
   3790 	/*
   3791 	 * ipf_nat_icmperrorlookup() will return NULL for `defective' packets.
   3792 	 */
   3793 	if ((fin->fin_v != 4) || !(nat = ipf_nat_icmperrorlookup(fin, dir))) {
   3794 		NBUMPSIDED(fin->fin_out, ns_icmp_notfound);
   3795 		return NULL;
   3796 	}
   3797 
   3798 	tcp = NULL;
   3799 	csump = NULL;
   3800 	flags = 0;
   3801 	sumd2 = 0;
   3802 	*nflags = IPN_ICMPERR;
   3803 	icmp = fin->fin_dp;
   3804 	oip = (ip_t *)&icmp->icmp_ip;
   3805 	dp = (((char *)oip) + (IP_HL(oip) << 2));
   3806 	if (oip->ip_p == IPPROTO_TCP) {
   3807 		tcp = (tcphdr_t *)dp;
   3808 		csump = (u_short *)&tcp->th_sum;
   3809 		flags = IPN_TCP;
   3810 	} else if (oip->ip_p == IPPROTO_UDP) {
   3811 		udphdr_t *udp;
   3812 
   3813 		udp = (udphdr_t *)dp;
   3814 		tcp = (tcphdr_t *)dp;
   3815 		csump = (u_short *)&udp->uh_sum;
   3816 		flags = IPN_UDP;
   3817 	} else if (oip->ip_p == IPPROTO_ICMP)
   3818 		flags = IPN_ICMPQUERY;
   3819 	dlen = fin->fin_plen - ((char *)dp - (char *)fin->fin_ip);
   3820 
   3821 	/*
   3822 	 * Need to adjust ICMP header to include the real IP#'s and
   3823 	 * port #'s.  Only apply a checksum change relative to the
   3824 	 * IP address change as it will be modified again in ipf_nat_checkout
   3825 	 * for both address and port.  Two checksum changes are
   3826 	 * necessary for the two header address changes.  Be careful
   3827 	 * to only modify the checksum once for the port # and twice
   3828 	 * for the IP#.
   3829 	 */
   3830 
   3831 	/*
   3832 	 * Step 1
   3833 	 * Fix the IP addresses in the offending IP packet. You also need
   3834 	 * to adjust the IP header checksum of that offending IP packet.
   3835 	 *
   3836 	 * Normally, you would expect that the ICMP checksum of the
   3837 	 * ICMP error message needs to be adjusted as well for the
   3838 	 * IP address change in oip.
   3839 	 * However, this is a NOP, because the ICMP checksum is
   3840 	 * calculated over the complete ICMP packet, which includes the
   3841 	 * changed oip IP addresses and oip->ip_sum. However, these
   3842 	 * two changes cancel each other out (if the delta for
   3843 	 * the IP address is x, then the delta for ip_sum is minus x),
   3844 	 * so no change in the icmp_cksum is necessary.
   3845 	 *
   3846 	 * Inbound ICMP
   3847 	 * ------------
   3848 	 * MAP rule, SRC=a,DST=b -> SRC=c,DST=b
   3849 	 * - response to outgoing packet (a,b)=>(c,b) (OIP_SRC=c,OIP_DST=b)
   3850 	 * - OIP_SRC(c)=nat_newsrcip,          OIP_DST(b)=nat_newdstip
   3851 	 *=> OIP_SRC(c)=nat_oldsrcip,          OIP_DST(b)=nat_olddstip
   3852 	 *
   3853 	 * RDR rule, SRC=a,DST=b -> SRC=a,DST=c
   3854 	 * - response to outgoing packet (c,a)=>(b,a) (OIP_SRC=b,OIP_DST=a)
   3855 	 * - OIP_SRC(b)=nat_olddstip,          OIP_DST(a)=nat_oldsrcip
   3856 	 *=> OIP_SRC(b)=nat_newdstip,          OIP_DST(a)=nat_newsrcip
   3857 	 *
   3858 	 * REWRITE out rule, SRC=a,DST=b -> SRC=c,DST=d
   3859 	 * - response to outgoing packet (a,b)=>(c,d) (OIP_SRC=c,OIP_DST=d)
   3860 	 * - OIP_SRC(c)=nat_newsrcip,          OIP_DST(d)=nat_newdstip
   3861 	 *=> OIP_SRC(c)=nat_oldsrcip,          OIP_DST(d)=nat_olddstip
   3862 	 *
   3863 	 * REWRITE in rule, SRC=a,DST=b -> SRC=c,DST=d
   3864 	 * - response to outgoing packet (d,c)=>(b,a) (OIP_SRC=b,OIP_DST=a)
   3865 	 * - OIP_SRC(b)=nat_olddstip,          OIP_DST(a)=nat_oldsrcip
   3866 	 *=> OIP_SRC(b)=nat_newdstip,          OIP_DST(a)=nat_newsrcip
   3867 	 *
   3868 	 * Outbound ICMP
   3869 	 * -------------
   3870 	 * MAP rule, SRC=a,DST=b -> SRC=c,DST=b
   3871 	 * - response to incoming packet (b,c)=>(b,a) (OIP_SRC=b,OIP_DST=a)
   3872 	 * - OIP_SRC(b)=nat_olddstip,          OIP_DST(a)=nat_oldsrcip
   3873 	 *=> OIP_SRC(b)=nat_newdstip,          OIP_DST(a)=nat_newsrcip
   3874 	 *
   3875 	 * RDR rule, SRC=a,DST=b -> SRC=a,DST=c
   3876 	 * - response to incoming packet (a,b)=>(a,c) (OIP_SRC=a,OIP_DST=c)
   3877 	 * - OIP_SRC(a)=nat_newsrcip,          OIP_DST(c)=nat_newdstip
   3878 	 *=> OIP_SRC(a)=nat_oldsrcip,          OIP_DST(c)=nat_olddstip
   3879 	 *
   3880 	 * REWRITE out rule, SRC=a,DST=b -> SRC=c,DST=d
   3881 	 * - response to incoming packet (d,c)=>(b,a) (OIP_SRC=c,OIP_DST=d)
   3882 	 * - OIP_SRC(c)=nat_olddstip,          OIP_DST(d)=nat_oldsrcip
   3883 	 *=> OIP_SRC(b)=nat_newdstip,          OIP_DST(a)=nat_newsrcip
   3884 	 *
   3885 	 * REWRITE in rule, SRC=a,DST=b -> SRC=c,DST=d
   3886 	 * - response to incoming packet (a,b)=>(c,d) (OIP_SRC=b,OIP_DST=a)
   3887 	 * - OIP_SRC(b)=nat_newsrcip,          OIP_DST(a)=nat_newdstip
   3888 	 *=> OIP_SRC(a)=nat_oldsrcip,          OIP_DST(c)=nat_olddstip
   3889 	 */
   3890 
   3891 	if (((fin->fin_out == 0) && ((nat->nat_redir & NAT_MAP) != 0)) ||
   3892 	    ((fin->fin_out == 1) && ((nat->nat_redir & NAT_REDIRECT) != 0))) {
   3893 		a1.s_addr = ntohl(nat->nat_osrcaddr);
   3894 		a4.s_addr = ntohl(oip->ip_src.s_addr);
   3895 		a3.s_addr = ntohl(nat->nat_odstaddr);
   3896 		a2.s_addr = ntohl(oip->ip_dst.s_addr);
   3897 		oip->ip_src.s_addr = htonl(a1.s_addr);
   3898 		oip->ip_dst.s_addr = htonl(a3.s_addr);
   3899 		odst = 1;
   3900 	} else {
   3901 		a1.s_addr = ntohl(nat->nat_ndstaddr);
   3902 		a2.s_addr = ntohl(oip->ip_dst.s_addr);
   3903 		a3.s_addr = ntohl(nat->nat_nsrcaddr);
   3904 		a4.s_addr = ntohl(oip->ip_src.s_addr);
   3905 		oip->ip_dst.s_addr = htonl(a3.s_addr);
   3906 		oip->ip_src.s_addr = htonl(a1.s_addr);
   3907 		odst = 0;
   3908 	}
   3909 	sum1 = 0;
   3910 	sum2 = 0;
   3911 	sumd = 0;
   3912 	CALC_SUMD(a2.s_addr, a3.s_addr, sum1);
   3913 	CALC_SUMD(a4.s_addr, a1.s_addr, sum2);
   3914 	sumd = sum2 + sum1;
   3915 	if (sumd != 0)
   3916 		ipf_fix_datacksum(&oip->ip_sum, sumd);
   3917 
   3918 	sumd2 = sumd;
   3919 	sum1 = 0;
   3920 	sum2 = 0;
   3921 
   3922 	/*
   3923 	 * Fix UDP pseudo header checksum to compensate for the
   3924 	 * IP address change.
   3925 	 */
   3926 	if (((flags & IPN_TCPUDP) != 0) && (dlen >= 4)) {
   3927 		u_32_t sum3, sum4, sumt;
   3928 
   3929 		/*
   3930 		 * Step 2 :
   3931 		 * For offending TCP/UDP IP packets, translate the ports as
   3932 		 * well, based on the NAT specification. Of course such
   3933 		 * a change may be reflected in the ICMP checksum as well.
   3934 		 *
   3935 		 * Since the port fields are part of the TCP/UDP checksum
   3936 		 * of the offending IP packet, you need to adjust that checksum
   3937 		 * as well... except that the change in the port numbers should
   3938 		 * be offset by the checksum change.  However, the TCP/UDP
   3939 		 * checksum will also need to change if there has been an
   3940 		 * IP address change.
   3941 		 */
   3942 		if (odst == 1) {
   3943 			sum1 = ntohs(nat->nat_osport);
   3944 			sum4 = ntohs(tcp->th_sport);
   3945 			sum3 = ntohs(nat->nat_odport);
   3946 			sum2 = ntohs(tcp->th_dport);
   3947 
   3948 			tcp->th_sport = htons(sum1);
   3949 			tcp->th_dport = htons(sum3);
   3950 		} else {
   3951 			sum1 = ntohs(nat->nat_ndport);
   3952 			sum2 = ntohs(tcp->th_dport);
   3953 			sum3 = ntohs(nat->nat_nsport);
   3954 			sum4 = ntohs(tcp->th_sport);
   3955 
   3956 			tcp->th_dport = htons(sum3);
   3957 			tcp->th_sport = htons(sum1);
   3958 		}
   3959 		CALC_SUMD(sum4, sum1, sumt);
   3960 		sumd += sumt;
   3961 		CALC_SUMD(sum2, sum3, sumt);
   3962 		sumd += sumt;
   3963 
   3964 		if (sumd != 0 || sumd2 != 0) {
   3965 			/*
   3966 			 * At this point, sumd is the delta to apply to the
   3967 			 * TCP/UDP header, given the changes in both the IP
   3968 			 * address and the ports and sumd2 is the delta to
   3969 			 * apply to the ICMP header, given the IP address
   3970 			 * change delta that may need to be applied to the
   3971 			 * TCP/UDP checksum instead.
   3972 			 *
   3973 			 * If we will both the IP and TCP/UDP checksums
   3974 			 * then the ICMP checksum changes by the address
   3975 			 * delta applied to the TCP/UDP checksum.  If we
   3976 			 * do not change the TCP/UDP checksum them we
   3977 			 * apply the delta in ports to the ICMP checksum.
   3978 			 */
   3979 			if (oip->ip_p == IPPROTO_UDP) {
   3980 				if ((dlen >= 8) && (*csump != 0)) {
   3981 					ipf_fix_datacksum(csump, sumd);
   3982 				} else {
   3983 					CALC_SUMD(sum1, sum4, sumd2);
   3984 					CALC_SUMD(sum3, sum2, sumt);
   3985 					sumd2 += sumt;
   3986 				}
   3987 			} else if (oip->ip_p == IPPROTO_TCP) {
   3988 				if (dlen >= 18) {
   3989 					ipf_fix_datacksum(csump, sumd);
   3990 				} else {
   3991 					CALC_SUMD(sum1, sum4, sumd2);
   3992 					CALC_SUMD(sum3, sum2, sumt);
   3993 					sumd2 += sumt;
   3994 				}
   3995 			}
   3996 			if (sumd2 != 0) {
   3997 				sumd2 = (sumd2 & 0xffff) + (sumd2 >> 16);
   3998 				sumd2 = (sumd2 & 0xffff) + (sumd2 >> 16);
   3999 				sumd2 = (sumd2 & 0xffff) + (sumd2 >> 16);
   4000 				ipf_fix_incksum(0, &icmp->icmp_cksum, sumd2, 0);
   4001 			}
   4002 		}
   4003 	} else if (((flags & IPN_ICMPQUERY) != 0) && (dlen >= 8)) {
   4004 		icmphdr_t *orgicmp;
   4005 
   4006 		/*
   4007 		 * XXX - what if this is bogus hl and we go off the end ?
   4008 		 * In this case, ipf_nat_icmperrorlookup() will have
   4009 		 * returned NULL.
   4010 		 */
   4011 		orgicmp = (icmphdr_t *)dp;
   4012 
   4013 		if (odst == 1) {
   4014 			if (orgicmp->icmp_id != nat->nat_osport) {
   4015 
   4016 				/*
   4017 				 * Fix ICMP checksum (of the offening ICMP
   4018 				 * query packet) to compensate the change
   4019 				 * in the ICMP id of the offending ICMP
   4020 				 * packet.
   4021 				 *
   4022 				 * Since you modify orgicmp->icmp_id with
   4023 				 * a delta (say x) and you compensate that
   4024 				 * in origicmp->icmp_cksum with a delta
   4025 				 * minus x, you don't have to adjust the
   4026 				 * overall icmp->icmp_cksum
   4027 				 */
   4028 				sum1 = ntohs(orgicmp->icmp_id);
   4029 				sum2 = ntohs(nat->nat_oicmpid);
   4030 				CALC_SUMD(sum1, sum2, sumd);
   4031 				orgicmp->icmp_id = nat->nat_oicmpid;
   4032 				ipf_fix_datacksum(&orgicmp->icmp_cksum, sumd);
   4033 			}
   4034 		} /* nat_dir == NAT_INBOUND is impossible for icmp queries */
   4035 	}
   4036 	return nat;
   4037 }
   4038 
   4039 
   4040 /*
   4041  *       MAP-IN    MAP-OUT   RDR-IN   RDR-OUT
   4042  * osrc    X       == src    == src      X
   4043  * odst    X       == dst    == dst      X
   4044  * nsrc  == dst      X         X      == dst
   4045  * ndst  == src      X         X      == src
   4046  * MAP = NAT_OUTBOUND, RDR = NAT_INBOUND
   4047  */
   4048 /*
   4049  * NB: these lookups don't lock access to the list, it assumed that it has
   4050  * already been done!
   4051  */
   4052 /* ------------------------------------------------------------------------ */
   4053 /* Function:    ipf_nat_inlookup                                            */
   4054 /* Returns:     nat_t* - NULL == no match,                                  */
   4055 /*                       else pointer to matching NAT entry                 */
   4056 /* Parameters:  fin(I)    - pointer to packet information                   */
   4057 /*              flags(I)  - NAT flags for this packet                       */
   4058 /*              p(I)      - protocol for this packet                        */
   4059 /*              src(I)    - source IP address                               */
   4060 /*              mapdst(I) - destination IP address                          */
   4061 /*                                                                          */
   4062 /* Lookup a nat entry based on the mapped destination ip address/port and   */
   4063 /* real source address/port.  We use this lookup when receiving a packet,   */
   4064 /* we're looking for a table entry, based on the destination address.       */
   4065 /*                                                                          */
   4066 /* NOTE: THE PACKET BEING CHECKED (IF FOUND) HAS A MAPPING ALREADY.         */
   4067 /*                                                                          */
   4068 /* NOTE: IT IS ASSUMED THAT  IS ONLY HELD WITH A READ LOCK WHEN             */
   4069 /*       THIS FUNCTION IS CALLED WITH NAT_SEARCH SET IN nflags.             */
   4070 /*                                                                          */
   4071 /* flags   -> relevant are IPN_UDP/IPN_TCP/IPN_ICMPQUERY that indicate if   */
   4072 /*            the packet is of said protocol                                */
   4073 /* ------------------------------------------------------------------------ */
   4074 nat_t *
   4075 ipf_nat_inlookup(fin, flags, p, src, mapdst)
   4076 	fr_info_t *fin;
   4077 	u_int flags, p;
   4078 	struct in_addr src , mapdst;
   4079 {
   4080 	ipf_main_softc_t *softc = fin->fin_main_soft;
   4081 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   4082 	u_short sport, dport;
   4083 	grehdr_t *gre;
   4084 	ipnat_t *ipn;
   4085 	u_int sflags;
   4086 	nat_t *nat;
   4087 	int nflags;
   4088 	u_32_t dst;
   4089 	void *ifp;
   4090 	u_int hv, rhv;
   4091 
   4092 	ifp = fin->fin_ifp;
   4093 	gre = NULL;
   4094 	dst = mapdst.s_addr;
   4095 	sflags = flags & NAT_TCPUDPICMP;
   4096 
   4097 	switch (p)
   4098 	{
   4099 	case IPPROTO_TCP :
   4100 	case IPPROTO_UDP :
   4101 		sport = htons(fin->fin_data[0]);
   4102 		dport = htons(fin->fin_data[1]);
   4103 		break;
   4104 	case IPPROTO_ICMP :
   4105 		if (flags & IPN_ICMPERR) {
   4106 			sport = fin->fin_data[1];
   4107 			dport = 0;
   4108 		} else {
   4109 			dport = fin->fin_data[1];
   4110 			sport = 0;
   4111 		}
   4112 		break;
   4113 	default :
   4114 		sport = 0;
   4115 		dport = 0;
   4116 		break;
   4117 	}
   4118 
   4119 
   4120 	if ((flags & SI_WILDP) != 0)
   4121 		goto find_in_wild_ports;
   4122 
   4123 	rhv = NAT_HASH_FN(dst, dport, 0xffffffff);
   4124 	rhv = NAT_HASH_FN(src.s_addr, rhv + sport, 0xffffffff);
   4125 	hv = rhv % softn->ipf_nat_table_sz;
   4126 	nat = softn->ipf_nat_table[1][hv];
   4127 	/* TRACE dst, dport, src, sport, hv, nat */
   4128 
   4129 	for (; nat; nat = nat->nat_hnext[1]) {
   4130 		if (nat->nat_ifps[0] != NULL) {
   4131 			if ((ifp != NULL) && (ifp != nat->nat_ifps[0]))
   4132 				continue;
   4133 		}
   4134 
   4135 		if (nat->nat_pr[0] != p)
   4136 			continue;
   4137 
   4138 		switch (nat->nat_dir)
   4139 		{
   4140 		case NAT_INBOUND :
   4141 		case NAT_DIVERTIN :
   4142 			if (nat->nat_v[0] != 4)
   4143 				continue;
   4144 			if (nat->nat_osrcaddr != src.s_addr ||
   4145 			    nat->nat_odstaddr != dst)
   4146 				continue;
   4147 			if ((nat->nat_flags & IPN_TCPUDP) != 0) {
   4148 				if (nat->nat_osport != sport)
   4149 					continue;
   4150 				if (nat->nat_odport != dport)
   4151 					continue;
   4152 
   4153 			} else if (p == IPPROTO_ICMP) {
   4154 				if (nat->nat_osport != dport) {
   4155 					continue;
   4156 				}
   4157 			}
   4158 			break;
   4159 		case NAT_DIVERTOUT :
   4160 			if (nat->nat_dlocal)
   4161 				continue;
   4162 		case NAT_OUTBOUND :
   4163 			if (nat->nat_v[1] != 4)
   4164 				continue;
   4165 			if (nat->nat_dlocal)
   4166 				continue;
   4167 			if (nat->nat_dlocal)
   4168 				continue;
   4169 			if (nat->nat_ndstaddr != src.s_addr ||
   4170 			    nat->nat_nsrcaddr != dst)
   4171 				continue;
   4172 			if ((nat->nat_flags & IPN_TCPUDP) != 0) {
   4173 				if (nat->nat_ndport != sport)
   4174 					continue;
   4175 				if (nat->nat_nsport != dport)
   4176 					continue;
   4177 
   4178 			} else if (p == IPPROTO_ICMP) {
   4179 				if (nat->nat_osport != dport) {
   4180 					continue;
   4181 				}
   4182 			}
   4183 			break;
   4184 		}
   4185 
   4186 
   4187 		if ((nat->nat_flags & IPN_TCPUDP) != 0) {
   4188 			ipn = nat->nat_ptr;
   4189 			if ((ipn != NULL) && (nat->nat_aps != NULL))
   4190 				if (ipf_proxy_match(fin, nat) != 0)
   4191 					continue;
   4192 		}
   4193 		if ((nat->nat_ifps[0] == NULL) && (ifp != NULL)) {
   4194 			nat->nat_ifps[0] = ifp;
   4195 			nat->nat_mtu[0] = GETIFMTU_4(ifp);
   4196 		}
   4197 		return nat;
   4198 	}
   4199 
   4200 	/*
   4201 	 * So if we didn't find it but there are wildcard members in the hash
   4202 	 * table, go back and look for them.  We do this search and update here
   4203 	 * because it is modifying the NAT table and we want to do this only
   4204 	 * for the first packet that matches.  The exception, of course, is
   4205 	 * for "dummy" (FI_IGNORE) lookups.
   4206 	 */
   4207 find_in_wild_ports:
   4208 	if (!(flags & NAT_TCPUDP) || !(flags & NAT_SEARCH)) {
   4209 		NBUMPSIDEX(0, ns_lookup_miss, ns_lookup_miss_0);
   4210 		return NULL;
   4211 	}
   4212 	if (softn->ipf_nat_stats.ns_wilds == 0 || (fin->fin_flx & FI_NOWILD)) {
   4213 		NBUMPSIDEX(0, ns_lookup_nowild, ns_lookup_nowild_0);
   4214 		return NULL;
   4215 	}
   4216 
   4217 	RWLOCK_EXIT(&softc->ipf_nat);
   4218 
   4219 	hv = NAT_HASH_FN(dst, 0, 0xffffffff);
   4220 	hv = NAT_HASH_FN(src.s_addr, hv, softn->ipf_nat_table_sz);
   4221 	WRITE_ENTER(&softc->ipf_nat);
   4222 
   4223 	nat = softn->ipf_nat_table[1][hv];
   4224 	/* TRACE dst, src, hv, nat */
   4225 	for (; nat; nat = nat->nat_hnext[1]) {
   4226 		if (nat->nat_ifps[0] != NULL) {
   4227 			if ((ifp != NULL) && (ifp != nat->nat_ifps[0]))
   4228 				continue;
   4229 		}
   4230 
   4231 		if (nat->nat_pr[0] != fin->fin_p)
   4232 			continue;
   4233 
   4234 		switch (nat->nat_dir & (NAT_INBOUND|NAT_OUTBOUND))
   4235 		{
   4236 		case NAT_INBOUND :
   4237 			if (nat->nat_v[0] != 4)
   4238 				continue;
   4239 			if (nat->nat_osrcaddr != src.s_addr ||
   4240 			    nat->nat_odstaddr != dst)
   4241 				continue;
   4242 			break;
   4243 		case NAT_OUTBOUND :
   4244 			if (nat->nat_v[1] != 4)
   4245 				continue;
   4246 			if (nat->nat_ndstaddr != src.s_addr ||
   4247 			    nat->nat_nsrcaddr != dst)
   4248 				continue;
   4249 			break;
   4250 		}
   4251 
   4252 		nflags = nat->nat_flags;
   4253 		if (!(nflags & (NAT_TCPUDP|SI_WILDP)))
   4254 			continue;
   4255 
   4256 		if (ipf_nat_wildok(nat, (int)sport, (int)dport, nflags,
   4257 				   NAT_INBOUND) == 1) {
   4258 			if ((fin->fin_flx & FI_IGNORE) != 0)
   4259 				break;
   4260 			if ((nflags & SI_CLONE) != 0) {
   4261 				nat = ipf_nat_clone(fin, nat);
   4262 				if (nat == NULL)
   4263 					break;
   4264 			} else {
   4265 				MUTEX_ENTER(&softn->ipf_nat_new);
   4266 				softn->ipf_nat_stats.ns_wilds--;
   4267 				MUTEX_EXIT(&softn->ipf_nat_new);
   4268 			}
   4269 
   4270 			if (nat->nat_dir == NAT_INBOUND) {
   4271 				if (nat->nat_osport == 0) {
   4272 					nat->nat_osport = sport;
   4273 					nat->nat_nsport = sport;
   4274 				}
   4275 				if (nat->nat_odport == 0) {
   4276 					nat->nat_odport = dport;
   4277 					nat->nat_ndport = dport;
   4278 				}
   4279 			} else if (nat->nat_dir == NAT_OUTBOUND) {
   4280 				if (nat->nat_osport == 0) {
   4281 					nat->nat_osport = dport;
   4282 					nat->nat_nsport = dport;
   4283 				}
   4284 				if (nat->nat_odport == 0) {
   4285 					nat->nat_odport = sport;
   4286 					nat->nat_ndport = sport;
   4287 				}
   4288 			}
   4289 			if ((nat->nat_ifps[0] == NULL) && (ifp != NULL)) {
   4290 				nat->nat_ifps[0] = ifp;
   4291 				nat->nat_mtu[0] = GETIFMTU_4(ifp);
   4292 			}
   4293 			nat->nat_flags &= ~(SI_W_DPORT|SI_W_SPORT);
   4294 			ipf_nat_tabmove(softn, nat);
   4295 			break;
   4296 		}
   4297 	}
   4298 
   4299 	MUTEX_DOWNGRADE(&softc->ipf_nat);
   4300 
   4301 	if (nat == NULL) {
   4302 		NBUMPSIDE(0, ns_lookup_miss);
   4303 	}
   4304 	return nat;
   4305 }
   4306 
   4307 
   4308 /* ------------------------------------------------------------------------ */
   4309 /* Function:    ipf_nat_tabmove                                             */
   4310 /* Returns:     Nil                                                         */
   4311 /* Parameters:  softn(I) - pointer to NAT context structure                 */
   4312 /*              nat(I)   - pointer to NAT structure                         */
   4313 /* Write Lock:  ipf_nat                                                     */
   4314 /*                                                                          */
   4315 /* This function is only called for TCP/UDP NAT table entries where the     */
   4316 /* original was placed in the table without hashing on the ports and we now */
   4317 /* want to include hashing on port numbers.                                 */
   4318 /* ------------------------------------------------------------------------ */
   4319 static void
   4320 ipf_nat_tabmove(softn, nat)
   4321 	ipf_nat_softc_t *softn;
   4322 	nat_t *nat;
   4323 {
   4324 	u_int hv0, hv1, rhv0, rhv1;
   4325 	natstat_t *nsp;
   4326 	nat_t **natp;
   4327 
   4328 	if (nat->nat_flags & SI_CLONE)
   4329 		return;
   4330 
   4331 	nsp = &softn->ipf_nat_stats;
   4332 	/*
   4333 	 * Remove the NAT entry from the old location
   4334 	 */
   4335 	if (nat->nat_hnext[0])
   4336 		nat->nat_hnext[0]->nat_phnext[0] = nat->nat_phnext[0];
   4337 	*nat->nat_phnext[0] = nat->nat_hnext[0];
   4338 	nsp->ns_side[0].ns_bucketlen[nat->nat_hv[0] %
   4339 				     softn->ipf_nat_table_sz]--;
   4340 
   4341 	if (nat->nat_hnext[1])
   4342 		nat->nat_hnext[1]->nat_phnext[1] = nat->nat_phnext[1];
   4343 	*nat->nat_phnext[1] = nat->nat_hnext[1];
   4344 	nsp->ns_side[1].ns_bucketlen[nat->nat_hv[1] %
   4345 				     softn->ipf_nat_table_sz]--;
   4346 
   4347 	/*
   4348 	 * Add into the NAT table in the new position
   4349 	 */
   4350 	rhv0 = NAT_HASH_FN(nat->nat_osrcaddr, nat->nat_osport, 0xffffffff);
   4351 	rhv0 = NAT_HASH_FN(nat->nat_odstaddr, rhv0 + nat->nat_odport,
   4352 			   0xffffffff);
   4353 	rhv1 = NAT_HASH_FN(nat->nat_nsrcaddr, nat->nat_nsport, 0xffffffff);
   4354 	rhv1 = NAT_HASH_FN(nat->nat_ndstaddr, rhv1 + nat->nat_ndport,
   4355 			   0xffffffff);
   4356 
   4357 	hv0 = rhv0 % softn->ipf_nat_table_sz;
   4358 	hv1 = rhv1 % softn->ipf_nat_table_sz;
   4359 
   4360 	if (nat->nat_dir == NAT_INBOUND || nat->nat_dir == NAT_DIVERTIN) {
   4361 		u_int swap;
   4362 
   4363 		swap = hv0;
   4364 		hv0 = hv1;
   4365 		hv1 = swap;
   4366 	}
   4367 
   4368 	/* TRACE nat_osrcaddr, nat_osport, nat_odstaddr, nat_odport, hv0 */
   4369 	/* TRACE nat_nsrcaddr, nat_nsport, nat_ndstaddr, nat_ndport, hv1 */
   4370 
   4371 	nat->nat_hv[0] = rhv0;
   4372 	natp = &softn->ipf_nat_table[0][hv0];
   4373 	if (*natp)
   4374 		(*natp)->nat_phnext[0] = &nat->nat_hnext[0];
   4375 	nat->nat_phnext[0] = natp;
   4376 	nat->nat_hnext[0] = *natp;
   4377 	*natp = nat;
   4378 	nsp->ns_side[0].ns_bucketlen[hv0]++;
   4379 
   4380 	nat->nat_hv[1] = rhv1;
   4381 	natp = &softn->ipf_nat_table[1][hv1];
   4382 	if (*natp)
   4383 		(*natp)->nat_phnext[1] = &nat->nat_hnext[1];
   4384 	nat->nat_phnext[1] = natp;
   4385 	nat->nat_hnext[1] = *natp;
   4386 	*natp = nat;
   4387 	nsp->ns_side[1].ns_bucketlen[hv1]++;
   4388 }
   4389 
   4390 
   4391 /* ------------------------------------------------------------------------ */
   4392 /* Function:    ipf_nat_outlookup                                           */
   4393 /* Returns:     nat_t* - NULL == no match,                                  */
   4394 /*                       else pointer to matching NAT entry                 */
   4395 /* Parameters:  fin(I)   - pointer to packet information                    */
   4396 /*              flags(I) - NAT flags for this packet                        */
   4397 /*              p(I)     - protocol for this packet                         */
   4398 /*              src(I)   - source IP address                                */
   4399 /*              dst(I)   - destination IP address                           */
   4400 /*              rw(I)    - 1 == write lock on  held, 0 == read lock.        */
   4401 /*                                                                          */
   4402 /* Lookup a nat entry based on the source 'real' ip address/port and        */
   4403 /* destination address/port.  We use this lookup when sending a packet out, */
   4404 /* we're looking for a table entry, based on the source address.            */
   4405 /*                                                                          */
   4406 /* NOTE: THE PACKET BEING CHECKED (IF FOUND) HAS A MAPPING ALREADY.         */
   4407 /*                                                                          */
   4408 /* NOTE: IT IS ASSUMED THAT  IS ONLY HELD WITH A READ LOCK WHEN             */
   4409 /*       THIS FUNCTION IS CALLED WITH NAT_SEARCH SET IN nflags.             */
   4410 /*                                                                          */
   4411 /* flags   -> relevant are IPN_UDP/IPN_TCP/IPN_ICMPQUERY that indicate if   */
   4412 /*            the packet is of said protocol                                */
   4413 /* ------------------------------------------------------------------------ */
   4414 nat_t *
   4415 ipf_nat_outlookup(fin, flags, p, src, dst)
   4416 	fr_info_t *fin;
   4417 	u_int flags, p;
   4418 	struct in_addr src , dst;
   4419 {
   4420 	ipf_main_softc_t *softc = fin->fin_main_soft;
   4421 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   4422 	u_short sport, dport;
   4423 	u_int sflags;
   4424 	ipnat_t *ipn;
   4425 	nat_t *nat;
   4426 	void *ifp;
   4427 	u_int hv;
   4428 
   4429 	ifp = fin->fin_ifp;
   4430 	sflags = flags & IPN_TCPUDPICMP;
   4431 	sport = 0;
   4432 	dport = 0;
   4433 
   4434 	switch (p)
   4435 	{
   4436 	case IPPROTO_TCP :
   4437 	case IPPROTO_UDP :
   4438 		sport = htons(fin->fin_data[0]);
   4439 		dport = htons(fin->fin_data[1]);
   4440 		break;
   4441 	case IPPROTO_ICMP :
   4442 		if (flags & IPN_ICMPERR)
   4443 			sport = fin->fin_data[1];
   4444 		else
   4445 			dport = fin->fin_data[1];
   4446 		break;
   4447 	default :
   4448 		break;
   4449 	}
   4450 
   4451 	if ((flags & SI_WILDP) != 0)
   4452 		goto find_out_wild_ports;
   4453 
   4454 	hv = NAT_HASH_FN(src.s_addr, sport, 0xffffffff);
   4455 	hv = NAT_HASH_FN(dst.s_addr, hv + dport, softn->ipf_nat_table_sz);
   4456 	nat = softn->ipf_nat_table[0][hv];
   4457 
   4458 	/* TRACE src, sport, dst, dport, hv, nat */
   4459 
   4460 	for (; nat; nat = nat->nat_hnext[0]) {
   4461 		if (nat->nat_ifps[1] != NULL) {
   4462 			if ((ifp != NULL) && (ifp != nat->nat_ifps[1]))
   4463 				continue;
   4464 		}
   4465 
   4466 		if (nat->nat_pr[1] != p)
   4467 			continue;
   4468 
   4469 		switch (nat->nat_dir)
   4470 		{
   4471 		case NAT_INBOUND :
   4472 		case NAT_DIVERTIN :
   4473 			if (nat->nat_v[1] != 4)
   4474 				continue;
   4475 			if (nat->nat_ndstaddr != src.s_addr ||
   4476 			    nat->nat_nsrcaddr != dst.s_addr)
   4477 				continue;
   4478 
   4479 			if ((nat->nat_flags & IPN_TCPUDP) != 0) {
   4480 				if (nat->nat_ndport != sport)
   4481 					continue;
   4482 				if (nat->nat_nsport != dport)
   4483 					continue;
   4484 
   4485 			} else if (p == IPPROTO_ICMP) {
   4486 				if (nat->nat_osport != dport) {
   4487 					continue;
   4488 				}
   4489 			}
   4490 			break;
   4491 		case NAT_OUTBOUND :
   4492 		case NAT_DIVERTOUT :
   4493 			if (nat->nat_v[0] != 4)
   4494 				continue;
   4495 			if (nat->nat_osrcaddr != src.s_addr ||
   4496 			    nat->nat_odstaddr != dst.s_addr)
   4497 				continue;
   4498 
   4499 			if ((nat->nat_flags & IPN_TCPUDP) != 0) {
   4500 				if (nat->nat_odport != dport)
   4501 					continue;
   4502 				if (nat->nat_osport != sport)
   4503 					continue;
   4504 
   4505 			} else if (p == IPPROTO_ICMP) {
   4506 				if (nat->nat_osport != dport) {
   4507 					continue;
   4508 				}
   4509 			}
   4510 			break;
   4511 		}
   4512 
   4513 		ipn = nat->nat_ptr;
   4514 		if ((ipn != NULL) && (nat->nat_aps != NULL))
   4515 			if (ipf_proxy_match(fin, nat) != 0)
   4516 				continue;
   4517 
   4518 		if ((nat->nat_ifps[1] == NULL) && (ifp != NULL)) {
   4519 			nat->nat_ifps[1] = ifp;
   4520 			nat->nat_mtu[1] = GETIFMTU_4(ifp);
   4521 		}
   4522 		return nat;
   4523 	}
   4524 
   4525 	/*
   4526 	 * So if we didn't find it but there are wildcard members in the hash
   4527 	 * table, go back and look for them.  We do this search and update here
   4528 	 * because it is modifying the NAT table and we want to do this only
   4529 	 * for the first packet that matches.  The exception, of course, is
   4530 	 * for "dummy" (FI_IGNORE) lookups.
   4531 	 */
   4532 find_out_wild_ports:
   4533 	if (!(flags & NAT_TCPUDP) || !(flags & NAT_SEARCH)) {
   4534 		NBUMPSIDEX(1, ns_lookup_miss, ns_lookup_miss_1);
   4535 		return NULL;
   4536 	}
   4537 	if (softn->ipf_nat_stats.ns_wilds == 0 || (fin->fin_flx & FI_NOWILD)) {
   4538 		NBUMPSIDEX(1, ns_lookup_nowild, ns_lookup_nowild_1);
   4539 		return NULL;
   4540 	}
   4541 
   4542 	RWLOCK_EXIT(&softc->ipf_nat);
   4543 
   4544 	hv = NAT_HASH_FN(src.s_addr, 0, 0xffffffff);
   4545 	hv = NAT_HASH_FN(dst.s_addr, hv, softn->ipf_nat_table_sz);
   4546 
   4547 	WRITE_ENTER(&softc->ipf_nat);
   4548 
   4549 	nat = softn->ipf_nat_table[0][hv];
   4550 	for (; nat; nat = nat->nat_hnext[0]) {
   4551 		if (nat->nat_ifps[1] != NULL) {
   4552 			if ((ifp != NULL) && (ifp != nat->nat_ifps[1]))
   4553 				continue;
   4554 		}
   4555 
   4556 		if (nat->nat_pr[1] != fin->fin_p)
   4557 			continue;
   4558 
   4559 		switch (nat->nat_dir & (NAT_INBOUND|NAT_OUTBOUND))
   4560 		{
   4561 		case NAT_INBOUND :
   4562 			if (nat->nat_v[1] != 4)
   4563 				continue;
   4564 			if (nat->nat_ndstaddr != src.s_addr ||
   4565 			    nat->nat_nsrcaddr != dst.s_addr)
   4566 				continue;
   4567 			break;
   4568 		case NAT_OUTBOUND :
   4569 			if (nat->nat_v[0] != 4)
   4570 				continue;
   4571 			if (nat->nat_osrcaddr != src.s_addr ||
   4572 			    nat->nat_odstaddr != dst.s_addr)
   4573 				continue;
   4574 			break;
   4575 		}
   4576 
   4577 		if (!(nat->nat_flags & (NAT_TCPUDP|SI_WILDP)))
   4578 			continue;
   4579 
   4580 		if (ipf_nat_wildok(nat, (int)sport, (int)dport, nat->nat_flags,
   4581 				   NAT_OUTBOUND) == 1) {
   4582 			if ((fin->fin_flx & FI_IGNORE) != 0)
   4583 				break;
   4584 			if ((nat->nat_flags & SI_CLONE) != 0) {
   4585 				nat = ipf_nat_clone(fin, nat);
   4586 				if (nat == NULL)
   4587 					break;
   4588 			} else {
   4589 				MUTEX_ENTER(&softn->ipf_nat_new);
   4590 				softn->ipf_nat_stats.ns_wilds--;
   4591 				MUTEX_EXIT(&softn->ipf_nat_new);
   4592 			}
   4593 
   4594 			if (nat->nat_dir == NAT_OUTBOUND) {
   4595 				if (nat->nat_osport == 0) {
   4596 					nat->nat_osport = sport;
   4597 					nat->nat_nsport = sport;
   4598 				}
   4599 				if (nat->nat_odport == 0) {
   4600 					nat->nat_odport = dport;
   4601 					nat->nat_ndport = dport;
   4602 				}
   4603 			} else if (nat->nat_dir == NAT_INBOUND) {
   4604 				if (nat->nat_osport == 0) {
   4605 					nat->nat_osport = dport;
   4606 					nat->nat_nsport = dport;
   4607 				}
   4608 				if (nat->nat_odport == 0) {
   4609 					nat->nat_odport = sport;
   4610 					nat->nat_ndport = sport;
   4611 				}
   4612 			}
   4613 			if ((nat->nat_ifps[1] == NULL) && (ifp != NULL)) {
   4614 				nat->nat_ifps[1] = ifp;
   4615 				nat->nat_mtu[1] = GETIFMTU_4(ifp);
   4616 			}
   4617 			nat->nat_flags &= ~(SI_W_DPORT|SI_W_SPORT);
   4618 			ipf_nat_tabmove(softn, nat);
   4619 			break;
   4620 		}
   4621 	}
   4622 
   4623 	MUTEX_DOWNGRADE(&softc->ipf_nat);
   4624 
   4625 	if (nat == NULL) {
   4626 		NBUMPSIDE(1, ns_lookup_miss);
   4627 	}
   4628 	return nat;
   4629 }
   4630 
   4631 
   4632 /* ------------------------------------------------------------------------ */
   4633 /* Function:    ipf_nat_lookupredir                                         */
   4634 /* Returns:     nat_t* - NULL == no match,                                  */
   4635 /*                       else pointer to matching NAT entry                 */
   4636 /* Parameters:  np(I) - pointer to description of packet to find NAT table  */
   4637 /*                      entry for.                                          */
   4638 /*                                                                          */
   4639 /* Lookup the NAT tables to search for a matching redirect                  */
   4640 /* The contents of natlookup_t should imitate those found in a packet that  */
   4641 /* would be translated - ie a packet coming in for RDR or going out for MAP.*/
   4642 /* We can do the lookup in one of two ways, imitating an inbound or         */
   4643 /* outbound  packet.  By default we assume outbound, unless IPN_IN is set.  */
   4644 /* For IN, the fields are set as follows:                                   */
   4645 /*     nl_real* = source information                                        */
   4646 /*     nl_out* = destination information (translated)                       */
   4647 /* For an out packet, the fields are set like this:                         */
   4648 /*     nl_in* = source information (untranslated)                           */
   4649 /*     nl_out* = destination information (translated)                       */
   4650 /* ------------------------------------------------------------------------ */
   4651 nat_t *
   4652 ipf_nat_lookupredir(np)
   4653 	natlookup_t *np;
   4654 {
   4655 	fr_info_t fi;
   4656 	nat_t *nat;
   4657 
   4658 	bzero((char *)&fi, sizeof(fi));
   4659 	if (np->nl_flags & IPN_IN) {
   4660 		fi.fin_data[0] = ntohs(np->nl_realport);
   4661 		fi.fin_data[1] = ntohs(np->nl_outport);
   4662 	} else {
   4663 		fi.fin_data[0] = ntohs(np->nl_inport);
   4664 		fi.fin_data[1] = ntohs(np->nl_outport);
   4665 	}
   4666 	if (np->nl_flags & IPN_TCP)
   4667 		fi.fin_p = IPPROTO_TCP;
   4668 	else if (np->nl_flags & IPN_UDP)
   4669 		fi.fin_p = IPPROTO_UDP;
   4670 	else if (np->nl_flags & (IPN_ICMPERR|IPN_ICMPQUERY))
   4671 		fi.fin_p = IPPROTO_ICMP;
   4672 
   4673 	/*
   4674 	 * We can do two sorts of lookups:
   4675 	 * - IPN_IN: we have the `real' and `out' address, look for `in'.
   4676 	 * - default: we have the `in' and `out' address, look for `real'.
   4677 	 */
   4678 	if (np->nl_flags & IPN_IN) {
   4679 		if ((nat = ipf_nat_inlookup(&fi, np->nl_flags, fi.fin_p,
   4680 					    np->nl_realip, np->nl_outip))) {
   4681 			np->nl_inip = nat->nat_odstip;
   4682 			np->nl_inport = nat->nat_odport;
   4683 		}
   4684 	} else {
   4685 		/*
   4686 		 * If nl_inip is non null, this is a lookup based on the real
   4687 		 * ip address. Else, we use the fake.
   4688 		 */
   4689 		if ((nat = ipf_nat_outlookup(&fi, np->nl_flags, fi.fin_p,
   4690 					 np->nl_inip, np->nl_outip))) {
   4691 
   4692 			if ((np->nl_flags & IPN_FINDFORWARD) != 0) {
   4693 				fr_info_t fin;
   4694 				bzero((char *)&fin, sizeof(fin));
   4695 				fin.fin_p = nat->nat_pr[0];
   4696 				fin.fin_data[0] = ntohs(nat->nat_ndport);
   4697 				fin.fin_data[1] = ntohs(nat->nat_nsport);
   4698 				if (ipf_nat_inlookup(&fin, np->nl_flags,
   4699 						     fin.fin_p, nat->nat_ndstip,
   4700 						     nat->nat_nsrcip) != NULL) {
   4701 					np->nl_flags &= ~IPN_FINDFORWARD;
   4702 				}
   4703 			}
   4704 
   4705 			np->nl_realip = nat->nat_ndstip;
   4706 			np->nl_realport = nat->nat_ndport;
   4707 		}
   4708  	}
   4709 
   4710 	return nat;
   4711 }
   4712 
   4713 
   4714 /* ------------------------------------------------------------------------ */
   4715 /* Function:    ipf_nat_match                                               */
   4716 /* Returns:     int - 0 == no match, 1 == match                             */
   4717 /* Parameters:  fin(I)   - pointer to packet information                    */
   4718 /*              np(I)    - pointer to NAT rule                              */
   4719 /*                                                                          */
   4720 /* Pull the matching of a packet against a NAT rule out of that complex     */
   4721 /* loop inside ipf_nat_checkin() and lay it out properly in its own function. */
   4722 /* ------------------------------------------------------------------------ */
   4723 static int
   4724 ipf_nat_match(fin, np)
   4725 	fr_info_t *fin;
   4726 	ipnat_t *np;
   4727 {
   4728 	ipf_main_softc_t *softc = fin->fin_main_soft;
   4729 	frtuc_t *ft;
   4730 	int match;
   4731 
   4732 	match = 0;
   4733 	switch (np->in_osrcatype)
   4734 	{
   4735 	case FRI_NORMAL :
   4736 		match = ((fin->fin_saddr & np->in_osrcmsk) != np->in_osrcaddr);
   4737 		break;
   4738 	case FRI_LOOKUP :
   4739 		match = (*np->in_osrcfunc)(softc, np->in_osrcptr,
   4740 					   4, &fin->fin_saddr, fin->fin_plen);
   4741 		break;
   4742 	}
   4743 	match ^= ((np->in_flags & IPN_NOTSRC) != 0);
   4744 	if (match)
   4745 		return 0;
   4746 
   4747 	match = 0;
   4748 	switch (np->in_odstatype)
   4749 	{
   4750 	case FRI_NORMAL :
   4751 		match = ((fin->fin_daddr & np->in_odstmsk) != np->in_odstaddr);
   4752 		break;
   4753 	case FRI_LOOKUP :
   4754 		match = (*np->in_odstfunc)(softc, np->in_odstptr,
   4755 					   4, &fin->fin_daddr, fin->fin_plen);
   4756 		break;
   4757 	}
   4758 
   4759 	match ^= ((np->in_flags & IPN_NOTDST) != 0);
   4760 	if (match)
   4761 		return 0;
   4762 
   4763 	ft = &np->in_tuc;
   4764 	if (!(fin->fin_flx & FI_TCPUDP) ||
   4765 	    (fin->fin_flx & (FI_SHORT|FI_FRAGBODY))) {
   4766 		if (ft->ftu_scmp || ft->ftu_dcmp)
   4767 			return 0;
   4768 		return 1;
   4769 	}
   4770 
   4771 	return ipf_tcpudpchk(&fin->fin_fi, ft);
   4772 }
   4773 
   4774 
   4775 /* ------------------------------------------------------------------------ */
   4776 /* Function:    ipf_nat_update                                              */
   4777 /* Returns:     Nil                                                         */
   4778 /* Parameters:  fin(I) - pointer to packet information                      */
   4779 /*              nat(I) - pointer to NAT structure                           */
   4780 /*                                                                          */
   4781 /* Updates the lifetime of a NAT table entry for non-TCP packets.  Must be  */
   4782 /* called with fin_rev updated - i.e. after calling ipf_nat_proto().        */
   4783 /*                                                                          */
   4784 /* This *MUST* be called after ipf_nat_proto() as it expects fin_rev to     */
   4785 /* already be set.                                                          */
   4786 /* ------------------------------------------------------------------------ */
   4787 void
   4788 ipf_nat_update(fin, nat)
   4789 	fr_info_t *fin;
   4790 	nat_t *nat;
   4791 {
   4792 	ipf_main_softc_t *softc = fin->fin_main_soft;
   4793 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   4794 	ipftq_t *ifq, *ifq2;
   4795 	ipftqent_t *tqe;
   4796 	ipnat_t *np = nat->nat_ptr;
   4797 
   4798 	tqe = &nat->nat_tqe;
   4799 	ifq = tqe->tqe_ifq;
   4800 
   4801 	/*
   4802 	 * We allow over-riding of NAT timeouts from NAT rules, even for
   4803 	 * TCP, however, if it is TCP and there is no rule timeout set,
   4804 	 * then do not update the timeout here.
   4805 	 */
   4806 	if (np != NULL) {
   4807 		np->in_bytes[fin->fin_rev] += fin->fin_plen;
   4808 		ifq2 = np->in_tqehead[fin->fin_rev];
   4809 	} else {
   4810 		ifq2 = NULL;
   4811 	}
   4812 
   4813 	if (nat->nat_pr[0] == IPPROTO_TCP && ifq2 == NULL) {
   4814 		(void) ipf_tcp_age(&nat->nat_tqe, fin, softn->ipf_nat_tcptq,
   4815 				   0, 2);
   4816 	} else {
   4817 		if (ifq2 == NULL) {
   4818 			if (nat->nat_pr[0] == IPPROTO_UDP)
   4819 				ifq2 = fin->fin_rev ? &softn->ipf_nat_udpacktq :
   4820 						      &softn->ipf_nat_udptq;
   4821 			else if (nat->nat_pr[0] == IPPROTO_ICMP ||
   4822 				 nat->nat_pr[0] == IPPROTO_ICMPV6)
   4823 				ifq2 = fin->fin_rev ? &softn->ipf_nat_icmpacktq:
   4824 						      &softn->ipf_nat_icmptq;
   4825 			else
   4826 				ifq2 = &softn->ipf_nat_iptq;
   4827 		}
   4828 
   4829 		ipf_movequeue(softc->ipf_ticks, tqe, ifq, ifq2);
   4830 	}
   4831 }
   4832 
   4833 
   4834 /* ------------------------------------------------------------------------ */
   4835 /* Function:    ipf_nat_checkout                                            */
   4836 /* Returns:     int - -1 == packet failed NAT checks so block it,           */
   4837 /*                     0 == no packet translation occurred,                 */
   4838 /*                     1 == packet was successfully translated.             */
   4839 /* Parameters:  fin(I)   - pointer to packet information                    */
   4840 /*              passp(I) - pointer to filtering result flags                */
   4841 /*                                                                          */
   4842 /* Check to see if an outcoming packet should be changed.  ICMP packets are */
   4843 /* first checked to see if they match an existing entry (if an error),      */
   4844 /* otherwise a search of the current NAT table is made.  If neither results */
   4845 /* in a match then a search for a matching NAT rule is made.  Create a new  */
   4846 /* NAT entry if a we matched a NAT rule.  Lastly, actually change the       */
   4847 /* packet header(s) as required.                                            */
   4848 /* ------------------------------------------------------------------------ */
   4849 int
   4850 ipf_nat_checkout(fin, passp)
   4851 	fr_info_t *fin;
   4852 	u_32_t *passp;
   4853 {
   4854 	ipnat_t *np = NULL, *npnext;
   4855 	struct ifnet *ifp, *sifp;
   4856 	ipf_main_softc_t *softc;
   4857 	ipf_nat_softc_t *softn;
   4858 	icmphdr_t *icmp = NULL;
   4859 	tcphdr_t *tcp = NULL;
   4860 	int rval, natfailed;
   4861 	u_int nflags = 0;
   4862 	u_32_t ipa, iph;
   4863 	int natadd = 1;
   4864 	frentry_t *fr;
   4865 	nat_t *nat;
   4866 
   4867 	if (fin->fin_v == 6) {
   4868 #ifdef USE_INET6
   4869 		return ipf_nat6_checkout(fin, passp);
   4870 #else
   4871 		return 0;
   4872 #endif
   4873 	}
   4874 
   4875 	softc = fin->fin_main_soft;
   4876 	softn = softc->ipf_nat_soft;
   4877 
   4878 	if (softn->ipf_nat_lock != 0)
   4879 		return 0;
   4880 	if (softn->ipf_nat_stats.ns_rules == 0 &&
   4881 	    softn->ipf_nat_instances == NULL)
   4882 		return 0;
   4883 
   4884 	natfailed = 0;
   4885 	fr = fin->fin_fr;
   4886 	sifp = fin->fin_ifp;
   4887 	if (fr != NULL) {
   4888 		ifp = fr->fr_tifs[fin->fin_rev].fd_ptr;
   4889 		if ((ifp != NULL) && (ifp != (void *)-1))
   4890 			fin->fin_ifp = ifp;
   4891 	}
   4892 	ifp = fin->fin_ifp;
   4893 
   4894 	if (!(fin->fin_flx & FI_SHORT) && (fin->fin_off == 0)) {
   4895 		switch (fin->fin_p)
   4896 		{
   4897 		case IPPROTO_TCP :
   4898 			nflags = IPN_TCP;
   4899 			break;
   4900 		case IPPROTO_UDP :
   4901 			nflags = IPN_UDP;
   4902 			break;
   4903 		case IPPROTO_ICMP :
   4904 			icmp = fin->fin_dp;
   4905 
   4906 			/*
   4907 			 * This is an incoming packet, so the destination is
   4908 			 * the icmp_id and the source port equals 0
   4909 			 */
   4910 			if ((fin->fin_flx & FI_ICMPQUERY) != 0)
   4911 				nflags = IPN_ICMPQUERY;
   4912 			break;
   4913 		default :
   4914 			break;
   4915 		}
   4916 
   4917 		if ((nflags & IPN_TCPUDP))
   4918 			tcp = fin->fin_dp;
   4919 	}
   4920 
   4921 	ipa = fin->fin_saddr;
   4922 
   4923 	READ_ENTER(&softc->ipf_nat);
   4924 
   4925 	if ((fin->fin_p == IPPROTO_ICMP) && !(nflags & IPN_ICMPQUERY) &&
   4926 	    (nat = ipf_nat_icmperror(fin, &nflags, NAT_OUTBOUND)))
   4927 		/*EMPTY*/;
   4928 	else if ((fin->fin_flx & FI_FRAG) && (nat = ipf_frag_natknown(fin)))
   4929 		natadd = 0;
   4930 	else if ((nat = ipf_nat_outlookup(fin, nflags|NAT_SEARCH,
   4931 				      (u_int)fin->fin_p, fin->fin_src,
   4932 				      fin->fin_dst))) {
   4933 		nflags = nat->nat_flags;
   4934 	} else if (fin->fin_off == 0) {
   4935 		u_32_t hv, msk, nmsk = 0;
   4936 
   4937 		/*
   4938 		 * If there is no current entry in the nat table for this IP#,
   4939 		 * create one for it (if there is a matching rule).
   4940 		 */
   4941 maskloop:
   4942 		msk = softn->ipf_nat_map_active_masks[nmsk];
   4943 		iph = ipa & msk;
   4944 		hv = NAT_HASH_FN(iph, 0, softn->ipf_nat_maprules_sz);
   4945 retry_roundrobin:
   4946 		for (np = softn->ipf_nat_map_rules[hv]; np; np = npnext) {
   4947 			npnext = np->in_mnext;
   4948 			if ((np->in_ifps[1] && (np->in_ifps[1] != ifp)))
   4949 				continue;
   4950 			if (np->in_v[0] != 4)
   4951 				continue;
   4952 			if (np->in_pr[1] && (np->in_pr[1] != fin->fin_p))
   4953 				continue;
   4954 			if ((np->in_flags & IPN_RF) &&
   4955 			    !(np->in_flags & nflags))
   4956 				continue;
   4957 			if (np->in_flags & IPN_FILTER) {
   4958 				switch (ipf_nat_match(fin, np))
   4959 				{
   4960 				case 0 :
   4961 					continue;
   4962 				case -1 :
   4963 					rval = -1;
   4964 					goto outmatchfail;
   4965 				case 1 :
   4966 				default :
   4967 					break;
   4968 				}
   4969 			} else if ((ipa & np->in_osrcmsk) != np->in_osrcaddr)
   4970 				continue;
   4971 
   4972 			if ((fr != NULL) &&
   4973 			    !ipf_matchtag(&np->in_tag, &fr->fr_nattag))
   4974 				continue;
   4975 
   4976 			if (np->in_plabel != -1) {
   4977 				if (((np->in_flags & IPN_FILTER) == 0) &&
   4978 				    (np->in_odport != fin->fin_data[1]))
   4979 					continue;
   4980 				if (ipf_proxy_ok(fin, tcp, np) == 0)
   4981 					continue;
   4982 			}
   4983 
   4984 			if (np->in_flags & IPN_NO) {
   4985 				np->in_hits++;
   4986 				break;
   4987 			}
   4988 			MUTEX_ENTER(&softn->ipf_nat_new);
   4989 			/*
   4990 			 * If we've matched a round-robin rule but it has
   4991 			 * moved in the list since we got it, start over as
   4992 			 * this is now no longer correct.
   4993 			 */
   4994 			if (npnext != np->in_mnext) {
   4995 				if ((np->in_flags & IPN_ROUNDR) != 0) {
   4996 					MUTEX_EXIT(&softn->ipf_nat_new);
   4997 					goto retry_roundrobin;
   4998 				}
   4999 				npnext = np->in_mnext;
   5000 			}
   5001 
   5002 			nat = ipf_nat_add(fin, np, NULL, nflags, NAT_OUTBOUND);
   5003 			MUTEX_EXIT(&softn->ipf_nat_new);
   5004 			if (nat != NULL) {
   5005 				natfailed = 0;
   5006 				break;
   5007 			}
   5008 			natfailed = -1;
   5009 		}
   5010 		if ((np == NULL) && (nmsk < softn->ipf_nat_map_max)) {
   5011 			nmsk++;
   5012 			goto maskloop;
   5013 		}
   5014 	}
   5015 
   5016 	if (nat != NULL) {
   5017 		rval = ipf_nat_out(fin, nat, natadd, nflags);
   5018 		if (rval == 1) {
   5019 			MUTEX_ENTER(&nat->nat_lock);
   5020 			ipf_nat_update(fin, nat);
   5021 			nat->nat_bytes[1] += fin->fin_plen;
   5022 			nat->nat_pkts[1]++;
   5023 			fin->fin_pktnum = nat->nat_pkts[1];
   5024 			MUTEX_EXIT(&nat->nat_lock);
   5025 		}
   5026 	} else
   5027 		rval = natfailed;
   5028 outmatchfail:
   5029 	RWLOCK_EXIT(&softc->ipf_nat);
   5030 
   5031 	switch (rval)
   5032 	{
   5033 	case -1 :
   5034 		if (passp != NULL) {
   5035 			DT1(frb_natv4out, fr_info_t *, fin);
   5036 			NBUMPSIDED(1, ns_drop);
   5037 			*passp = FR_BLOCK;
   5038 			fin->fin_reason = FRB_NATV4;
   5039 		}
   5040 		fin->fin_flx |= FI_BADNAT;
   5041 		NBUMPSIDED(1, ns_badnat);
   5042 		break;
   5043 	case 0 :
   5044 		NBUMPSIDE(1, ns_ignored);
   5045 		break;
   5046 	case 1 :
   5047 		NBUMPSIDE(1, ns_translated);
   5048 		break;
   5049 	}
   5050 	fin->fin_ifp = sifp;
   5051 	return rval;
   5052 }
   5053 
   5054 /* ------------------------------------------------------------------------ */
   5055 /* Function:    ipf_nat_out                                                 */
   5056 /* Returns:     int - -1 == packet failed NAT checks so block it,           */
   5057 /*                     1 == packet was successfully translated.             */
   5058 /* Parameters:  fin(I)    - pointer to packet information                   */
   5059 /*              nat(I)    - pointer to NAT structure                        */
   5060 /*              natadd(I) - flag indicating if it is safe to add frag cache */
   5061 /*              nflags(I) - NAT flags set for this packet                   */
   5062 /*                                                                          */
   5063 /* Translate a packet coming "out" on an interface.                         */
   5064 /* ------------------------------------------------------------------------ */
   5065 int
   5066 ipf_nat_out(fin, nat, natadd, nflags)
   5067 	fr_info_t *fin;
   5068 	nat_t *nat;
   5069 	int natadd;
   5070 	u_32_t nflags;
   5071 {
   5072 	ipf_main_softc_t *softc = fin->fin_main_soft;
   5073 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   5074 	icmphdr_t *icmp;
   5075 	tcphdr_t *tcp;
   5076 	ipnat_t *np;
   5077 	int skip;
   5078 	int i;
   5079 
   5080 	tcp = NULL;
   5081 	icmp = NULL;
   5082 	np = nat->nat_ptr;
   5083 
   5084 	if ((natadd != 0) && (fin->fin_flx & FI_FRAG) && (np != NULL))
   5085 		(void) ipf_frag_natnew(softc, fin, 0, nat);
   5086 
   5087 	/*
   5088 	 * Fix up checksums, not by recalculating them, but
   5089 	 * simply computing adjustments.
   5090 	 * This is only done for STREAMS based IP implementations where the
   5091 	 * checksum has already been calculated by IP.  In all other cases,
   5092 	 * IPFilter is called before the checksum needs calculating so there
   5093 	 * is no call to modify whatever is in the header now.
   5094 	 */
   5095 	if (nflags == IPN_ICMPERR) {
   5096 		u_32_t s1, s2, sumd, msumd;
   5097 
   5098 		s1 = LONG_SUM(ntohl(fin->fin_saddr));
   5099 		if (nat->nat_dir == NAT_OUTBOUND) {
   5100 			s2 = LONG_SUM(ntohl(nat->nat_nsrcaddr));
   5101 		} else {
   5102 			s2 = LONG_SUM(ntohl(nat->nat_odstaddr));
   5103 		}
   5104 		CALC_SUMD(s1, s2, sumd);
   5105 		msumd = sumd;
   5106 
   5107 		s1 = LONG_SUM(ntohl(fin->fin_daddr));
   5108 		if (nat->nat_dir == NAT_OUTBOUND) {
   5109 			s2 = LONG_SUM(ntohl(nat->nat_ndstaddr));
   5110 		} else {
   5111 			s2 = LONG_SUM(ntohl(nat->nat_osrcaddr));
   5112 		}
   5113 		CALC_SUMD(s1, s2, sumd);
   5114 		msumd += sumd;
   5115 
   5116 		ipf_fix_outcksum(0, &fin->fin_ip->ip_sum, msumd, 0);
   5117 	}
   5118 #if !defined(_KERNEL) || defined(MENTAT) || defined(__sgi) || \
   5119     defined(linux) || defined(BRIDGE_IPF)
   5120 	else {
   5121 		/*
   5122 		 * Strictly speaking, this isn't necessary on BSD
   5123 		 * kernels because they do checksum calculation after
   5124 		 * this code has run BUT if ipfilter is being used
   5125 		 * to do NAT as a bridge, that code doesn't exist.
   5126 		 */
   5127 		switch (nat->nat_dir)
   5128 		{
   5129 		case NAT_OUTBOUND :
   5130 			ipf_fix_outcksum(fin->fin_cksum & FI_CK_L4PART,
   5131 					 &fin->fin_ip->ip_sum,
   5132 					 nat->nat_ipsumd, 0);
   5133 			break;
   5134 
   5135 		case NAT_INBOUND :
   5136 			ipf_fix_incksum(fin->fin_cksum & FI_CK_L4PART,
   5137 					&fin->fin_ip->ip_sum,
   5138 					nat->nat_ipsumd, 0);
   5139 			break;
   5140 
   5141 		default :
   5142 			break;
   5143 		}
   5144 	}
   5145 #endif
   5146 
   5147 	/*
   5148 	 * Address assignment is after the checksum modification because
   5149 	 * we are using the address in the packet for determining the
   5150 	 * correct checksum offset (the ICMP error could be coming from
   5151 	 * anyone...)
   5152 	 */
   5153 	switch (nat->nat_dir)
   5154 	{
   5155 	case NAT_OUTBOUND :
   5156 		fin->fin_ip->ip_src = nat->nat_nsrcip;
   5157 		fin->fin_saddr = nat->nat_nsrcaddr;
   5158 		fin->fin_ip->ip_dst = nat->nat_ndstip;
   5159 		fin->fin_daddr = nat->nat_ndstaddr;
   5160 		break;
   5161 
   5162 	case NAT_INBOUND :
   5163 		fin->fin_ip->ip_src = nat->nat_odstip;
   5164 		fin->fin_saddr = nat->nat_ndstaddr;
   5165 		fin->fin_ip->ip_dst = nat->nat_osrcip;
   5166 		fin->fin_daddr = nat->nat_nsrcaddr;
   5167 		break;
   5168 
   5169 	case NAT_DIVERTIN :
   5170 	    {
   5171 		mb_t *m;
   5172 
   5173 		skip = ipf_nat_decap(fin, nat);
   5174 		if (skip <= 0) {
   5175 			NBUMPSIDED(1, ns_decap_fail);
   5176 			return -1;
   5177 		}
   5178 
   5179 		m = fin->fin_m;
   5180 
   5181 #if defined(MENTAT) && defined(_KERNEL)
   5182 		m->b_rptr += skip;
   5183 #else
   5184 		m->m_data += skip;
   5185 		m->m_len -= skip;
   5186 
   5187 # ifdef M_PKTHDR
   5188 		if (m->m_flags & M_PKTHDR)
   5189 			m->m_pkthdr.len -= skip;
   5190 # endif
   5191 #endif
   5192 
   5193 		MUTEX_ENTER(&nat->nat_lock);
   5194 		ipf_nat_update(fin, nat);
   5195 		MUTEX_EXIT(&nat->nat_lock);
   5196 		fin->fin_flx |= FI_NATED;
   5197 		if (np != NULL && np->in_tag.ipt_num[0] != 0)
   5198 			fin->fin_nattag = &np->in_tag;
   5199 		return 1;
   5200 		/* NOTREACHED */
   5201 	    }
   5202 
   5203 	case NAT_DIVERTOUT :
   5204 	    {
   5205 		u_32_t s1, s2, sumd;
   5206 		udphdr_t *uh;
   5207 		ip_t *ip;
   5208 		mb_t *m;
   5209 
   5210 		m = M_DUP(np->in_divmp);
   5211 		if (m == NULL) {
   5212 			NBUMPSIDED(1, ns_divert_dup);
   5213 			return -1;
   5214 		}
   5215 
   5216 		ip = MTOD(m, ip_t *);
   5217 		ip->ip_id = htons(ipf_nextipid(fin));
   5218 		s2 = ntohs(ip->ip_id);
   5219 
   5220 		s1 = ip->ip_len;
   5221 		ip->ip_len = ntohs(ip->ip_len);
   5222 		ip->ip_len += fin->fin_plen;
   5223 		ip->ip_len = htons(ip->ip_len);
   5224 		s2 += ntohs(ip->ip_len);
   5225 		CALC_SUMD(s1, s2, sumd);
   5226 
   5227 		uh = (udphdr_t *)(ip + 1);
   5228 		uh->uh_ulen += fin->fin_plen;
   5229 		uh->uh_ulen = htons(uh->uh_ulen);
   5230 #if !defined(_KERNEL) || defined(MENTAT) || defined(__sgi) || \
   5231     defined(linux) || defined(BRIDGE_IPF)
   5232 		ipf_fix_outcksum(0, &ip->ip_sum, sumd, 0);
   5233 #endif
   5234 
   5235 		PREP_MB_T(fin, m);
   5236 
   5237 		fin->fin_src = ip->ip_src;
   5238 		fin->fin_dst = ip->ip_dst;
   5239 		fin->fin_ip = ip;
   5240 		fin->fin_plen += sizeof(ip_t) + 8;	/* UDP + IPv4 hdr */
   5241 		fin->fin_dlen += sizeof(ip_t) + 8;	/* UDP + IPv4 hdr */
   5242 
   5243 		nflags &= ~IPN_TCPUDPICMP;
   5244 
   5245 		break;
   5246 	    }
   5247 
   5248 	default :
   5249 		break;
   5250 	}
   5251 
   5252 	if (!(fin->fin_flx & FI_SHORT) && (fin->fin_off == 0)) {
   5253 		u_short *csump;
   5254 
   5255 		if ((nat->nat_nsport != 0) && (nflags & IPN_TCPUDP)) {
   5256 			tcp = fin->fin_dp;
   5257 
   5258 			switch (nat->nat_dir)
   5259 			{
   5260 			case NAT_OUTBOUND :
   5261 				tcp->th_sport = nat->nat_nsport;
   5262 				fin->fin_data[0] = ntohs(nat->nat_nsport);
   5263 				tcp->th_dport = nat->nat_ndport;
   5264 				fin->fin_data[1] = ntohs(nat->nat_ndport);
   5265 				break;
   5266 
   5267 			case NAT_INBOUND :
   5268 				tcp->th_sport = nat->nat_odport;
   5269 				fin->fin_data[0] = ntohs(nat->nat_odport);
   5270 				tcp->th_dport = nat->nat_osport;
   5271 				fin->fin_data[1] = ntohs(nat->nat_osport);
   5272 				break;
   5273 			}
   5274 		}
   5275 
   5276 		if ((nat->nat_nsport != 0) && (nflags & IPN_ICMPQUERY)) {
   5277 			icmp = fin->fin_dp;
   5278 			icmp->icmp_id = nat->nat_nicmpid;
   5279 		}
   5280 
   5281 		csump = ipf_nat_proto(fin, nat, nflags);
   5282 
   5283 		/*
   5284 		 * The above comments do not hold for layer 4 (or higher)
   5285 		 * checksums...
   5286 		 */
   5287 		if (csump != NULL) {
   5288 			if (nat->nat_dir == NAT_OUTBOUND)
   5289 				ipf_fix_outcksum(fin->fin_cksum, csump,
   5290 						 nat->nat_sumd[0],
   5291 						 nat->nat_sumd[1] +
   5292 						 fin->fin_dlen);
   5293 			else
   5294 				ipf_fix_incksum(fin->fin_cksum, csump,
   5295 						nat->nat_sumd[0],
   5296 						nat->nat_sumd[1] +
   5297 						fin->fin_dlen);
   5298 		}
   5299 	}
   5300 
   5301 	ipf_sync_update(softc, SMC_NAT, fin, nat->nat_sync);
   5302 	/* ------------------------------------------------------------- */
   5303 	/* A few quick notes:                                            */
   5304 	/*      Following are test conditions prior to calling the       */
   5305 	/*      ipf_proxy_check routine.                                 */
   5306 	/*                                                               */
   5307 	/*      A NULL tcp indicates a non TCP/UDP packet.  When dealing */
   5308 	/*      with a redirect rule, we attempt to match the packet's   */
   5309 	/*      source port against in_dport, otherwise we'd compare the */
   5310 	/*      packet's destination.                                    */
   5311 	/* ------------------------------------------------------------- */
   5312 	if ((np != NULL) && (np->in_apr != NULL)) {
   5313 		i = ipf_proxy_check(fin, nat);
   5314 		if (i == 0) {
   5315 			i = 1;
   5316 		} else if (i == -1) {
   5317 			NBUMPSIDED(1, ns_ipf_proxy_fail);
   5318 		}
   5319 	} else {
   5320 		i = 1;
   5321 	}
   5322 	fin->fin_flx |= FI_NATED;
   5323 	return i;
   5324 }
   5325 
   5326 
   5327 /* ------------------------------------------------------------------------ */
   5328 /* Function:    ipf_nat_checkin                                             */
   5329 /* Returns:     int - -1 == packet failed NAT checks so block it,           */
   5330 /*                     0 == no packet translation occurred,                 */
   5331 /*                     1 == packet was successfully translated.             */
   5332 /* Parameters:  fin(I)   - pointer to packet information                    */
   5333 /*              passp(I) - pointer to filtering result flags                */
   5334 /*                                                                          */
   5335 /* Check to see if an incoming packet should be changed.  ICMP packets are  */
   5336 /* first checked to see if they match an existing entry (if an error),      */
   5337 /* otherwise a search of the current NAT table is made.  If neither results */
   5338 /* in a match then a search for a matching NAT rule is made.  Create a new  */
   5339 /* NAT entry if a we matched a NAT rule.  Lastly, actually change the       */
   5340 /* packet header(s) as required.                                            */
   5341 /* ------------------------------------------------------------------------ */
   5342 int
   5343 ipf_nat_checkin(fin, passp)
   5344 	fr_info_t *fin;
   5345 	u_32_t *passp;
   5346 {
   5347 	ipf_main_softc_t *softc;
   5348 	ipf_nat_softc_t *softn;
   5349 	u_int nflags, natadd;
   5350 	ipnat_t *np, *npnext;
   5351 	int rval, natfailed;
   5352 	struct ifnet *ifp;
   5353 	struct in_addr in;
   5354 	icmphdr_t *icmp;
   5355 	tcphdr_t *tcp;
   5356 	u_short dport;
   5357 	nat_t *nat;
   5358 	u_32_t iph;
   5359 
   5360 	softc = fin->fin_main_soft;
   5361 	softn = softc->ipf_nat_soft;
   5362 
   5363 	if (softn->ipf_nat_lock != 0)
   5364 		return 0;
   5365 	if (softn->ipf_nat_stats.ns_rules == 0 &&
   5366 	    softn->ipf_nat_instances == NULL)
   5367 		return 0;
   5368 
   5369 	tcp = NULL;
   5370 	icmp = NULL;
   5371 	dport = 0;
   5372 	natadd = 1;
   5373 	nflags = 0;
   5374 	natfailed = 0;
   5375 	ifp = fin->fin_ifp;
   5376 
   5377 	if (!(fin->fin_flx & FI_SHORT) && (fin->fin_off == 0)) {
   5378 		switch (fin->fin_p)
   5379 		{
   5380 		case IPPROTO_TCP :
   5381 			nflags = IPN_TCP;
   5382 			break;
   5383 		case IPPROTO_UDP :
   5384 			nflags = IPN_UDP;
   5385 			break;
   5386 		case IPPROTO_ICMP :
   5387 			icmp = fin->fin_dp;
   5388 
   5389 			/*
   5390 			 * This is an incoming packet, so the destination is
   5391 			 * the icmp_id and the source port equals 0
   5392 			 */
   5393 			if ((fin->fin_flx & FI_ICMPQUERY) != 0) {
   5394 				nflags = IPN_ICMPQUERY;
   5395 				dport = icmp->icmp_id;
   5396 			} break;
   5397 		default :
   5398 			break;
   5399 		}
   5400 
   5401 		if ((nflags & IPN_TCPUDP)) {
   5402 			tcp = fin->fin_dp;
   5403 			dport = fin->fin_data[1];
   5404 		}
   5405 	}
   5406 
   5407 	in = fin->fin_dst;
   5408 
   5409 	READ_ENTER(&softc->ipf_nat);
   5410 
   5411 	if ((fin->fin_p == IPPROTO_ICMP) && !(nflags & IPN_ICMPQUERY) &&
   5412 	    (nat = ipf_nat_icmperror(fin, &nflags, NAT_INBOUND)))
   5413 		/*EMPTY*/;
   5414 	else if ((fin->fin_flx & FI_FRAG) && (nat = ipf_frag_natknown(fin)))
   5415 		natadd = 0;
   5416 	else if ((nat = ipf_nat_inlookup(fin, nflags|NAT_SEARCH,
   5417 					 (u_int)fin->fin_p,
   5418 					 fin->fin_src, in))) {
   5419 		nflags = nat->nat_flags;
   5420 	} else if (fin->fin_off == 0) {
   5421 		u_32_t hv, msk, rmsk = 0;
   5422 
   5423 		/*
   5424 		 * If there is no current entry in the nat table for this IP#,
   5425 		 * create one for it (if there is a matching rule).
   5426 		 */
   5427 maskloop:
   5428 		msk = softn->ipf_nat_rdr_active_masks[rmsk];
   5429 		iph = in.s_addr & msk;
   5430 		hv = NAT_HASH_FN(iph, 0, softn->ipf_nat_rdrrules_sz);
   5431 retry_roundrobin:
   5432 		/* TRACE (iph,msk,rmsk,hv,softn->ipf_nat_rdrrules_sz) */
   5433 		for (np = softn->ipf_nat_rdr_rules[hv]; np; np = npnext) {
   5434 			npnext = np->in_rnext;
   5435 			if (np->in_ifps[0] && (np->in_ifps[0] != ifp))
   5436 				continue;
   5437 			if (np->in_v[0] != 4)
   5438 				continue;
   5439 			if (np->in_pr[0] && (np->in_pr[0] != fin->fin_p))
   5440 				continue;
   5441 			if ((np->in_flags & IPN_RF) && !(np->in_flags & nflags))
   5442 				continue;
   5443 			if (np->in_flags & IPN_FILTER) {
   5444 				switch (ipf_nat_match(fin, np))
   5445 				{
   5446 				case 0 :
   5447 					continue;
   5448 				case -1 :
   5449 					rval = -1;
   5450 					goto inmatchfail;
   5451 				case 1 :
   5452 				default :
   5453 					break;
   5454 				}
   5455 			} else {
   5456 				if ((in.s_addr & np->in_odstmsk) !=
   5457 				    np->in_odstaddr)
   5458 					continue;
   5459 				if (np->in_odport &&
   5460 				    ((np->in_dtop < dport) ||
   5461 				     (dport < np->in_odport)))
   5462 					continue;
   5463 			}
   5464 
   5465 			if (np->in_plabel != -1) {
   5466 				if (!ipf_proxy_ok(fin, tcp, np)) {
   5467 					continue;
   5468 				}
   5469 			}
   5470 
   5471 			if (np->in_flags & IPN_NO) {
   5472 				np->in_hits++;
   5473 				break;
   5474 			}
   5475 
   5476 			MUTEX_ENTER(&softn->ipf_nat_new);
   5477 			/*
   5478 			 * If we've matched a round-robin rule but it has
   5479 			 * moved in the list since we got it, start over as
   5480 			 * this is now no longer correct.
   5481 			 */
   5482 			if (npnext != np->in_rnext) {
   5483 				if ((np->in_flags & IPN_ROUNDR) != 0) {
   5484 					MUTEX_EXIT(&softn->ipf_nat_new);
   5485 					goto retry_roundrobin;
   5486 				}
   5487 				npnext = np->in_rnext;
   5488 			}
   5489 
   5490 			nat = ipf_nat_add(fin, np, NULL, nflags, NAT_INBOUND);
   5491 			MUTEX_EXIT(&softn->ipf_nat_new);
   5492 			if (nat != NULL) {
   5493 				natfailed = 0;
   5494 				break;
   5495 			}
   5496 			natfailed = -1;
   5497 		}
   5498 		if ((np == NULL) && (rmsk < softn->ipf_nat_rdr_max)) {
   5499 			rmsk++;
   5500 			goto maskloop;
   5501 		}
   5502 	}
   5503 
   5504 	if (nat != NULL) {
   5505 		rval = ipf_nat_in(fin, nat, natadd, nflags);
   5506 		if (rval == 1) {
   5507 			MUTEX_ENTER(&nat->nat_lock);
   5508 			ipf_nat_update(fin, nat);
   5509 			nat->nat_bytes[0] += fin->fin_plen;
   5510 			nat->nat_pkts[0]++;
   5511 			fin->fin_pktnum = nat->nat_pkts[0];
   5512 			MUTEX_EXIT(&nat->nat_lock);
   5513 		}
   5514 	} else
   5515 		rval = natfailed;
   5516 inmatchfail:
   5517 	RWLOCK_EXIT(&softc->ipf_nat);
   5518 
   5519 	switch (rval)
   5520 	{
   5521 	case -1 :
   5522 		if (passp != NULL) {
   5523 			DT1(frb_natv4in, fr_info_t *, fin);
   5524 			NBUMPSIDED(0, ns_drop);
   5525 			*passp = FR_BLOCK;
   5526 			fin->fin_reason = FRB_NATV4;
   5527 		}
   5528 		fin->fin_flx |= FI_BADNAT;
   5529 		NBUMPSIDED(0, ns_badnat);
   5530 		break;
   5531 	case 0 :
   5532 		NBUMPSIDE(0, ns_ignored);
   5533 		break;
   5534 	case 1 :
   5535 		NBUMPSIDE(0, ns_translated);
   5536 		break;
   5537 	}
   5538 	return rval;
   5539 }
   5540 
   5541 
   5542 /* ------------------------------------------------------------------------ */
   5543 /* Function:    ipf_nat_in                                                  */
   5544 /* Returns:     int - -1 == packet failed NAT checks so block it,           */
   5545 /*                     1 == packet was successfully translated.             */
   5546 /* Parameters:  fin(I)    - pointer to packet information                   */
   5547 /*              nat(I)    - pointer to NAT structure                        */
   5548 /*              natadd(I) - flag indicating if it is safe to add frag cache */
   5549 /*              nflags(I) - NAT flags set for this packet                   */
   5550 /* Locks Held:  ipf_nat(READ)                                               */
   5551 /*                                                                          */
   5552 /* Translate a packet coming "in" on an interface.                          */
   5553 /* ------------------------------------------------------------------------ */
   5554 int
   5555 ipf_nat_in(fin, nat, natadd, nflags)
   5556 	fr_info_t *fin;
   5557 	nat_t *nat;
   5558 	int natadd;
   5559 	u_32_t nflags;
   5560 {
   5561 	ipf_main_softc_t *softc = fin->fin_main_soft;
   5562 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   5563 	u_32_t sumd, ipsumd, sum1, sum2;
   5564 	icmphdr_t *icmp;
   5565 	tcphdr_t *tcp;
   5566 	ipnat_t *np;
   5567 	int skip;
   5568 	int i;
   5569 
   5570 	tcp = NULL;
   5571 	np = nat->nat_ptr;
   5572 	fin->fin_fr = nat->nat_fr;
   5573 
   5574 	if (np != NULL) {
   5575 		if ((natadd != 0) && (fin->fin_flx & FI_FRAG))
   5576 			(void) ipf_frag_natnew(softc, fin, 0, nat);
   5577 
   5578 	/* ------------------------------------------------------------- */
   5579 	/* A few quick notes:                                            */
   5580 	/*      Following are test conditions prior to calling the       */
   5581 	/*      ipf_proxy_check routine.                                 */
   5582 	/*                                                               */
   5583 	/*      A NULL tcp indicates a non TCP/UDP packet.  When dealing */
   5584 	/*      with a map rule, we attempt to match the packet's        */
   5585 	/*      source port against in_dport, otherwise we'd compare the */
   5586 	/*      packet's destination.                                    */
   5587 	/* ------------------------------------------------------------- */
   5588 		if (np->in_apr != NULL) {
   5589 			i = ipf_proxy_check(fin, nat);
   5590 			if (i == -1) {
   5591 				NBUMPSIDED(0, ns_ipf_proxy_fail);
   5592 				return -1;
   5593 			}
   5594 		}
   5595 	}
   5596 
   5597 	ipf_sync_update(softc, SMC_NAT, fin, nat->nat_sync);
   5598 
   5599 	ipsumd = nat->nat_ipsumd;
   5600 	/*
   5601 	 * Fix up checksums, not by recalculating them, but
   5602 	 * simply computing adjustments.
   5603 	 * Why only do this for some platforms on inbound packets ?
   5604 	 * Because for those that it is done, IP processing is yet to happen
   5605 	 * and so the IPv4 header checksum has not yet been evaluated.
   5606 	 * Perhaps it should always be done for the benefit of things like
   5607 	 * fast forwarding (so that it doesn't need to be recomputed) but with
   5608 	 * header checksum offloading, perhaps it is a moot point.
   5609 	 */
   5610 
   5611 	switch (nat->nat_dir)
   5612 	{
   5613 	case NAT_INBOUND :
   5614 		if ((fin->fin_flx & FI_ICMPERR) == 0) {
   5615 			fin->fin_ip->ip_src = nat->nat_nsrcip;
   5616 			fin->fin_saddr = nat->nat_nsrcaddr;
   5617 		} else {
   5618 			sum1 = nat->nat_osrcaddr;
   5619 			sum2 = nat->nat_nsrcaddr;
   5620 			CALC_SUMD(sum1, sum2, sumd);
   5621 			ipsumd -= sumd;
   5622 		}
   5623 		fin->fin_ip->ip_dst = nat->nat_ndstip;
   5624 		fin->fin_daddr = nat->nat_ndstaddr;
   5625 #if !defined(_KERNEL) || defined(MENTAT) || defined(__sgi) || \
   5626      defined(__osf__) || defined(linux)
   5627 		ipf_fix_outcksum(0, &fin->fin_ip->ip_sum, ipsumd, 0);
   5628 #endif
   5629 		break;
   5630 
   5631 	case NAT_OUTBOUND :
   5632 		if ((fin->fin_flx & FI_ICMPERR) == 0) {
   5633 			fin->fin_ip->ip_src = nat->nat_odstip;
   5634 			fin->fin_saddr = nat->nat_odstaddr;
   5635 		} else {
   5636 			sum1 = nat->nat_odstaddr;
   5637 			sum2 = nat->nat_ndstaddr;
   5638 			CALC_SUMD(sum1, sum2, sumd);
   5639 			ipsumd -= sumd;
   5640 		}
   5641 		fin->fin_ip->ip_dst = nat->nat_osrcip;
   5642 		fin->fin_daddr = nat->nat_osrcaddr;
   5643 #if !defined(_KERNEL) || defined(MENTAT) || defined(__sgi) || \
   5644      defined(__osf__) || defined(linux)
   5645 		ipf_fix_incksum(0, &fin->fin_ip->ip_sum, ipsumd, 0);
   5646 #endif
   5647 		break;
   5648 
   5649 	case NAT_DIVERTIN :
   5650 	    {
   5651 		udphdr_t *uh;
   5652 		ip_t *ip;
   5653 		mb_t *m;
   5654 
   5655 		m = M_DUP(np->in_divmp);
   5656 		if (m == NULL) {
   5657 			NBUMPSIDED(0, ns_divert_dup);
   5658 			return -1;
   5659 		}
   5660 
   5661 		ip = MTOD(m, ip_t *);
   5662 		ip->ip_id = htons(ipf_nextipid(fin));
   5663 		sum1 = ntohs(ip->ip_len);
   5664 		ip->ip_len = ntohs(ip->ip_len);
   5665 		ip->ip_len += fin->fin_plen;
   5666 		ip->ip_len = htons(ip->ip_len);
   5667 
   5668 		uh = (udphdr_t *)(ip + 1);
   5669 		uh->uh_ulen += fin->fin_plen;
   5670 		uh->uh_ulen = htons(uh->uh_ulen);
   5671 
   5672 		sum2 = ntohs(ip->ip_id) + ntohs(ip->ip_len);
   5673 		sum2 += ntohs(ip->ip_off) & IP_DF;
   5674 		CALC_SUMD(sum1, sum2, sumd);
   5675 
   5676 #if !defined(_KERNEL) || defined(MENTAT) || defined(__sgi) || \
   5677      defined(__osf__) || defined(linux)
   5678 		ipf_fix_outcksum(0, &ip->ip_sum, sumd, 0);
   5679 #endif
   5680 		PREP_MB_T(fin, m);
   5681 
   5682 		fin->fin_ip = ip;
   5683 		fin->fin_plen += sizeof(ip_t) + 8;	/* UDP + new IPv4 hdr */
   5684 		fin->fin_dlen += sizeof(ip_t) + 8;	/* UDP + old IPv4 hdr */
   5685 
   5686 		nflags &= ~IPN_TCPUDPICMP;
   5687 
   5688 		break;
   5689 	    }
   5690 
   5691 	case NAT_DIVERTOUT :
   5692 	    {
   5693 		mb_t *m;
   5694 
   5695 		skip = ipf_nat_decap(fin, nat);
   5696 		if (skip <= 0) {
   5697 			NBUMPSIDED(0, ns_decap_fail);
   5698 			return -1;
   5699 		}
   5700 
   5701 		m = fin->fin_m;
   5702 
   5703 #if defined(MENTAT) && defined(_KERNEL)
   5704 		m->b_rptr += skip;
   5705 #else
   5706 		m->m_data += skip;
   5707 		m->m_len -= skip;
   5708 
   5709 # ifdef M_PKTHDR
   5710 		if (m->m_flags & M_PKTHDR)
   5711 			m->m_pkthdr.len -= skip;
   5712 # endif
   5713 #endif
   5714 
   5715 		ipf_nat_update(fin, nat);
   5716 		nflags &= ~IPN_TCPUDPICMP;
   5717 		fin->fin_flx |= FI_NATED;
   5718 		if (np != NULL && np->in_tag.ipt_num[0] != 0)
   5719 			fin->fin_nattag = &np->in_tag;
   5720 		return 1;
   5721 		/* NOTREACHED */
   5722 	    }
   5723 	}
   5724 	if (nflags & IPN_TCPUDP)
   5725 		tcp = fin->fin_dp;
   5726 
   5727 	if (!(fin->fin_flx & FI_SHORT) && (fin->fin_off == 0)) {
   5728 		u_short *csump;
   5729 
   5730 		if ((nat->nat_odport != 0) && (nflags & IPN_TCPUDP)) {
   5731 			switch (nat->nat_dir)
   5732 			{
   5733 			case NAT_INBOUND :
   5734 				tcp->th_sport = nat->nat_nsport;
   5735 				fin->fin_data[0] = ntohs(nat->nat_nsport);
   5736 				tcp->th_dport = nat->nat_ndport;
   5737 				fin->fin_data[1] = ntohs(nat->nat_ndport);
   5738 				break;
   5739 
   5740 			case NAT_OUTBOUND :
   5741 				tcp->th_sport = nat->nat_odport;
   5742 				fin->fin_data[0] = ntohs(nat->nat_odport);
   5743 				tcp->th_dport = nat->nat_osport;
   5744 				fin->fin_data[1] = ntohs(nat->nat_osport);
   5745 				break;
   5746 			}
   5747 		}
   5748 
   5749 
   5750 		if ((nat->nat_odport != 0) && (nflags & IPN_ICMPQUERY)) {
   5751 			icmp = fin->fin_dp;
   5752 
   5753 			icmp->icmp_id = nat->nat_nicmpid;
   5754 		}
   5755 
   5756 		csump = ipf_nat_proto(fin, nat, nflags);
   5757 
   5758 		/*
   5759 		 * The above comments do not hold for layer 4 (or higher)
   5760 		 * checksums...
   5761 		 */
   5762 		if (csump != NULL) {
   5763 			if (nat->nat_dir == NAT_OUTBOUND)
   5764 				ipf_fix_incksum(0, csump, nat->nat_sumd[0], 0);
   5765 			else
   5766 				ipf_fix_outcksum(0, csump, nat->nat_sumd[0], 0);
   5767 		}
   5768 	}
   5769 
   5770 	fin->fin_flx |= FI_NATED;
   5771 	if (np != NULL && np->in_tag.ipt_num[0] != 0)
   5772 		fin->fin_nattag = &np->in_tag;
   5773 	return 1;
   5774 }
   5775 
   5776 
   5777 /* ------------------------------------------------------------------------ */
   5778 /* Function:    ipf_nat_proto                                               */
   5779 /* Returns:     u_short* - pointer to transport header checksum to update,  */
   5780 /*                         NULL if the transport protocol is not recognised */
   5781 /*                         as needing a checksum update.                    */
   5782 /* Parameters:  fin(I)    - pointer to packet information                   */
   5783 /*              nat(I)    - pointer to NAT structure                        */
   5784 /*              nflags(I) - NAT flags set for this packet                   */
   5785 /*                                                                          */
   5786 /* Return the pointer to the checksum field for each protocol so understood.*/
   5787 /* If support for making other changes to a protocol header is required,    */
   5788 /* that is not strictly 'address' translation, such as clamping the MSS in  */
   5789 /* TCP down to a specific value, then do it from here.                      */
   5790 /* ------------------------------------------------------------------------ */
   5791 u_short *
   5792 ipf_nat_proto(fin, nat, nflags)
   5793 	fr_info_t *fin;
   5794 	nat_t *nat;
   5795 	u_int nflags;
   5796 {
   5797 	icmphdr_t *icmp;
   5798 	u_short *csump;
   5799 	tcphdr_t *tcp;
   5800 	udphdr_t *udp;
   5801 
   5802 	csump = NULL;
   5803 	if (fin->fin_out == 0) {
   5804 		fin->fin_rev = (nat->nat_dir & NAT_OUTBOUND);
   5805 	} else {
   5806 		fin->fin_rev = ((nat->nat_dir & NAT_OUTBOUND) == 0);
   5807 	}
   5808 
   5809 	switch (fin->fin_p)
   5810 	{
   5811 	case IPPROTO_TCP :
   5812 		tcp = fin->fin_dp;
   5813 
   5814 		if ((nflags & IPN_TCP) != 0)
   5815 			csump = &tcp->th_sum;
   5816 
   5817 		/*
   5818 		 * Do a MSS CLAMPING on a SYN packet,
   5819 		 * only deal IPv4 for now.
   5820 		 */
   5821 		if ((nat->nat_mssclamp != 0) && (tcp->th_flags & TH_SYN) != 0)
   5822 			ipf_nat_mssclamp(tcp, nat->nat_mssclamp, fin, csump);
   5823 
   5824 		break;
   5825 
   5826 	case IPPROTO_UDP :
   5827 		udp = fin->fin_dp;
   5828 
   5829 		if ((nflags & IPN_UDP) != 0) {
   5830 			if (udp->uh_sum != 0)
   5831 				csump = &udp->uh_sum;
   5832 		}
   5833 		break;
   5834 
   5835 	case IPPROTO_ICMP :
   5836 		icmp = fin->fin_dp;
   5837 
   5838 		if ((nflags & IPN_ICMPQUERY) != 0) {
   5839 			if (icmp->icmp_cksum != 0)
   5840 				csump = &icmp->icmp_cksum;
   5841 		}
   5842 		break;
   5843 
   5844 #ifdef USE_INET6
   5845 	case IPPROTO_ICMPV6 :
   5846 	    {
   5847 		struct icmp6_hdr *icmp6 = (struct icmp6_hdr *)fin->fin_dp;
   5848 
   5849 		icmp6 = fin->fin_dp;
   5850 
   5851 		if ((nflags & IPN_ICMPQUERY) != 0) {
   5852 			if (icmp6->icmp6_cksum != 0)
   5853 				csump = &icmp6->icmp6_cksum;
   5854 		}
   5855 		break;
   5856 	    }
   5857 #endif
   5858 	}
   5859 	return csump;
   5860 }
   5861 
   5862 
   5863 /* ------------------------------------------------------------------------ */
   5864 /* Function:    ipf_nat_expire                                              */
   5865 /* Returns:     Nil                                                         */
   5866 /* Parameters:  softc(I) - pointer to soft context main structure           */
   5867 /*                                                                          */
   5868 /* Check all of the timeout queues for entries at the top which need to be  */
   5869 /* expired.                                                                 */
   5870 /* ------------------------------------------------------------------------ */
   5871 void
   5872 ipf_nat_expire(softc)
   5873 	ipf_main_softc_t *softc;
   5874 {
   5875 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   5876 	ipftq_t *ifq, *ifqnext;
   5877 	ipftqent_t *tqe, *tqn;
   5878 	int i;
   5879 	SPL_INT(s);
   5880 
   5881 	SPL_NET(s);
   5882 	WRITE_ENTER(&softc->ipf_nat);
   5883 	for (ifq = softn->ipf_nat_tcptq, i = 0; ifq != NULL;
   5884 	     ifq = ifq->ifq_next) {
   5885 		for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); i++) {
   5886 			if (tqe->tqe_die > softc->ipf_ticks)
   5887 				break;
   5888 			tqn = tqe->tqe_next;
   5889 			ipf_nat_delete(softc, tqe->tqe_parent, NL_EXPIRE);
   5890 		}
   5891 	}
   5892 
   5893 	for (ifq = softn->ipf_nat_utqe; ifq != NULL; ifq = ifq->ifq_next) {
   5894 		for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); i++) {
   5895 			if (tqe->tqe_die > softc->ipf_ticks)
   5896 				break;
   5897 			tqn = tqe->tqe_next;
   5898 			ipf_nat_delete(softc, tqe->tqe_parent, NL_EXPIRE);
   5899 		}
   5900 	}
   5901 
   5902 	for (ifq = softn->ipf_nat_utqe; ifq != NULL; ifq = ifqnext) {
   5903 		ifqnext = ifq->ifq_next;
   5904 
   5905 		if (((ifq->ifq_flags & IFQF_DELETE) != 0) &&
   5906 		    (ifq->ifq_ref == 0)) {
   5907 			ipf_freetimeoutqueue(softc, ifq);
   5908 		}
   5909 	}
   5910 
   5911 	if (softn->ipf_nat_doflush != 0) {
   5912 		ipf_nat_extraflush(softc, softn, 2);
   5913 		softn->ipf_nat_doflush = 0;
   5914 	}
   5915 
   5916 	RWLOCK_EXIT(&softc->ipf_nat);
   5917 	SPL_X(s);
   5918 }
   5919 
   5920 
   5921 /* ------------------------------------------------------------------------ */
   5922 /* Function:    ipf_nat_sync                                                */
   5923 /* Returns:     Nil                                                         */
   5924 /* Parameters:  softc(I) - pointer to soft context main structure           */
   5925 /*              ifp(I) - pointer to network interface                       */
   5926 /*                                                                          */
   5927 /* Walk through all of the currently active NAT sessions, looking for those */
   5928 /* which need to have their translated address updated.                     */
   5929 /* ------------------------------------------------------------------------ */
   5930 void
   5931 ipf_nat_sync(softc, ifp)
   5932 	ipf_main_softc_t *softc;
   5933 	void *ifp;
   5934 {
   5935 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   5936 	u_32_t sum1, sum2, sumd;
   5937 	i6addr_t in;
   5938 	ipnat_t *n;
   5939 	nat_t *nat;
   5940 	void *ifp2;
   5941 	int idx;
   5942 	SPL_INT(s);
   5943 
   5944 	if (softc->ipf_running <= 0)
   5945 		return;
   5946 
   5947 	/*
   5948 	 * Change IP addresses for NAT sessions for any protocol except TCP
   5949 	 * since it will break the TCP connection anyway.  The only rules
   5950 	 * which will get changed are those which are "map ... -> 0/32",
   5951 	 * where the rule specifies the address is taken from the interface.
   5952 	 */
   5953 	SPL_NET(s);
   5954 	WRITE_ENTER(&softc->ipf_nat);
   5955 
   5956 	if (softc->ipf_running <= 0) {
   5957 		RWLOCK_EXIT(&softc->ipf_nat);
   5958 		return;
   5959 	}
   5960 
   5961 	for (nat = softn->ipf_nat_instances; nat; nat = nat->nat_next) {
   5962 		if ((nat->nat_flags & IPN_TCP) != 0)
   5963 			continue;
   5964 
   5965 		n = nat->nat_ptr;
   5966 		if (n != NULL) {
   5967 			if (n->in_v[1] == 4) {
   5968 				if (n->in_redir & NAT_MAP) {
   5969 					if ((n->in_nsrcaddr != 0) ||
   5970 					    (n->in_nsrcmsk != 0xffffffff))
   5971 						continue;
   5972 				} else if (n->in_redir & NAT_REDIRECT) {
   5973 					if ((n->in_ndstaddr != 0) ||
   5974 					    (n->in_ndstmsk != 0xffffffff))
   5975 						continue;
   5976 				}
   5977 			}
   5978 #ifdef USE_INET6
   5979 			if (n->in_v[1] == 4) {
   5980 				if (n->in_redir & NAT_MAP) {
   5981 					if (!IP6_ISZERO(&n->in_nsrcaddr) ||
   5982 					    !IP6_ISONES(&n->in_nsrcmsk))
   5983 						continue;
   5984 				} else if (n->in_redir & NAT_REDIRECT) {
   5985 					if (!IP6_ISZERO(&n->in_ndstaddr) ||
   5986 					    !IP6_ISONES(&n->in_ndstmsk))
   5987 						continue;
   5988 				}
   5989 			}
   5990 #endif
   5991 		}
   5992 
   5993 		if (((ifp == NULL) || (ifp == nat->nat_ifps[0]) ||
   5994 		     (ifp == nat->nat_ifps[1]))) {
   5995 			nat->nat_ifps[0] = GETIFP(nat->nat_ifnames[0],
   5996 						  nat->nat_v[0]);
   5997 			if ((nat->nat_ifps[0] != NULL) &&
   5998 			    (nat->nat_ifps[0] != (void *)-1)) {
   5999 				nat->nat_mtu[0] = GETIFMTU_4(nat->nat_ifps[0]);
   6000 			}
   6001 			if (nat->nat_ifnames[1][0] != '\0') {
   6002 				nat->nat_ifps[1] = GETIFP(nat->nat_ifnames[1],
   6003 							  nat->nat_v[1]);
   6004 			} else {
   6005 				nat->nat_ifps[1] = nat->nat_ifps[0];
   6006 			}
   6007 			if ((nat->nat_ifps[1] != NULL) &&
   6008 			    (nat->nat_ifps[1] != (void *)-1)) {
   6009 				nat->nat_mtu[1] = GETIFMTU_4(nat->nat_ifps[1]);
   6010 			}
   6011 			ifp2 = nat->nat_ifps[0];
   6012 			if (ifp2 == NULL)
   6013 				continue;
   6014 
   6015 			/*
   6016 			 * Change the map-to address to be the same as the
   6017 			 * new one.
   6018 			 */
   6019 			sum1 = NATFSUM(nat, nat->nat_v[1], nat_nsrc6);
   6020 			if (ipf_ifpaddr(softc, nat->nat_v[0], FRI_NORMAL, ifp2,
   6021 				       &in, NULL) != -1) {
   6022 				if (nat->nat_v[0] == 4)
   6023 					nat->nat_nsrcip = in.in4;
   6024 			}
   6025 			sum2 = NATFSUM(nat, nat->nat_v[1], nat_nsrc6);
   6026 
   6027 			if (sum1 == sum2)
   6028 				continue;
   6029 			/*
   6030 			 * Readjust the checksum adjustment to take into
   6031 			 * account the new IP#.
   6032 			 */
   6033 			CALC_SUMD(sum1, sum2, sumd);
   6034 			/* XXX - dont change for TCP when solaris does
   6035 			 * hardware checksumming.
   6036 			 */
   6037 			sumd += nat->nat_sumd[0];
   6038 			nat->nat_sumd[0] = (sumd & 0xffff) + (sumd >> 16);
   6039 			nat->nat_sumd[1] = nat->nat_sumd[0];
   6040 		}
   6041 	}
   6042 
   6043 	for (n = softn->ipf_nat_list; (n != NULL); n = n->in_next) {
   6044 		char *base = n->in_names;
   6045 
   6046 		if ((ifp == NULL) || (n->in_ifps[0] == ifp))
   6047 			n->in_ifps[0] = ipf_resolvenic(softc,
   6048 						       base + n->in_ifnames[0],
   6049 						       n->in_v[0]);
   6050 		if ((ifp == NULL) || (n->in_ifps[1] == ifp))
   6051 			n->in_ifps[1] = ipf_resolvenic(softc,
   6052 						       base + n->in_ifnames[1],
   6053 						       n->in_v[1]);
   6054 
   6055 		if (n->in_redir & NAT_REDIRECT)
   6056 			idx = 1;
   6057 		else
   6058 			idx = 0;
   6059 
   6060 		if (((ifp == NULL) || (n->in_ifps[idx] == ifp)) &&
   6061 		    (n->in_ifps[idx] != NULL &&
   6062 		     n->in_ifps[idx] != (void *)-1)) {
   6063 
   6064 			ipf_nat_nextaddrinit(softc, n->in_names, &n->in_osrc,
   6065 					     0, n->in_ifps[idx]);
   6066 			ipf_nat_nextaddrinit(softc, n->in_names, &n->in_odst,
   6067 					     0, n->in_ifps[idx]);
   6068 			ipf_nat_nextaddrinit(softc, n->in_names, &n->in_nsrc,
   6069 					     0, n->in_ifps[idx]);
   6070 			ipf_nat_nextaddrinit(softc, n->in_names, &n->in_ndst,
   6071 					     0, n->in_ifps[idx]);
   6072 		}
   6073 	}
   6074 	RWLOCK_EXIT(&softc->ipf_nat);
   6075 	SPL_X(s);
   6076 }
   6077 
   6078 
   6079 /* ------------------------------------------------------------------------ */
   6080 /* Function:    ipf_nat_icmpquerytype                                       */
   6081 /* Returns:     int - 1 == success, 0 == failure                            */
   6082 /* Parameters:  icmptype(I) - ICMP type number                              */
   6083 /*                                                                          */
   6084 /* Tests to see if the ICMP type number passed is a query/response type or  */
   6085 /* not.                                                                     */
   6086 /* ------------------------------------------------------------------------ */
   6087 static int
   6088 ipf_nat_icmpquerytype(icmptype)
   6089 	int icmptype;
   6090 {
   6091 
   6092 	/*
   6093 	 * For the ICMP query NAT code, it is essential that both the query
   6094 	 * and the reply match on the NAT rule. Because the NAT structure
   6095 	 * does not keep track of the icmptype, and a single NAT structure
   6096 	 * is used for all icmp types with the same src, dest and id, we
   6097 	 * simply define the replies as queries as well. The funny thing is,
   6098 	 * altough it seems silly to call a reply a query, this is exactly
   6099 	 * as it is defined in the IPv4 specification
   6100 	 */
   6101 	switch (icmptype)
   6102 	{
   6103 	case ICMP_ECHOREPLY:
   6104 	case ICMP_ECHO:
   6105 	/* route aedvertisement/solliciation is currently unsupported: */
   6106 	/* it would require rewriting the ICMP data section            */
   6107 	case ICMP_TSTAMP:
   6108 	case ICMP_TSTAMPREPLY:
   6109 	case ICMP_IREQ:
   6110 	case ICMP_IREQREPLY:
   6111 	case ICMP_MASKREQ:
   6112 	case ICMP_MASKREPLY:
   6113 		return 1;
   6114 	default:
   6115 		return 0;
   6116 	}
   6117 }
   6118 
   6119 
   6120 /* ------------------------------------------------------------------------ */
   6121 /* Function:    nat_log                                                     */
   6122 /* Returns:     Nil                                                         */
   6123 /* Parameters:  softc(I) - pointer to soft context main structure           */
   6124 /*              softn(I) - pointer to NAT context structure                 */
   6125 /*              nat(I)    - pointer to NAT structure                        */
   6126 /*              action(I) - action related to NAT structure being performed */
   6127 /*                                                                          */
   6128 /* Creates a NAT log entry.                                                 */
   6129 /* ------------------------------------------------------------------------ */
   6130 void
   6131 ipf_nat_log(softc, softn, nat, action)
   6132 	ipf_main_softc_t *softc;
   6133 	ipf_nat_softc_t *softn;
   6134 	struct nat *nat;
   6135 	u_int action;
   6136 {
   6137 #ifdef	IPFILTER_LOG
   6138 # ifndef LARGE_NAT
   6139 	struct ipnat *np;
   6140 	int rulen;
   6141 # endif
   6142 	struct natlog natl;
   6143 	void *items[1];
   6144 	size_t sizes[1];
   6145 	int types[1];
   6146 
   6147 	bcopy((char *)&nat->nat_osrc6, (char *)&natl.nl_osrcip,
   6148 	      sizeof(natl.nl_osrcip));
   6149 	bcopy((char *)&nat->nat_nsrc6, (char *)&natl.nl_nsrcip,
   6150 	      sizeof(natl.nl_nsrcip));
   6151 	bcopy((char *)&nat->nat_odst6, (char *)&natl.nl_odstip,
   6152 	      sizeof(natl.nl_odstip));
   6153 	bcopy((char *)&nat->nat_ndst6, (char *)&natl.nl_ndstip,
   6154 	      sizeof(natl.nl_ndstip));
   6155 
   6156 	natl.nl_bytes[0] = nat->nat_bytes[0];
   6157 	natl.nl_bytes[1] = nat->nat_bytes[1];
   6158 	natl.nl_pkts[0] = nat->nat_pkts[0];
   6159 	natl.nl_pkts[1] = nat->nat_pkts[1];
   6160 	natl.nl_odstport = nat->nat_odport;
   6161 	natl.nl_osrcport = nat->nat_osport;
   6162 	natl.nl_nsrcport = nat->nat_nsport;
   6163 	natl.nl_ndstport = nat->nat_ndport;
   6164 	natl.nl_p[0] = nat->nat_pr[0];
   6165 	natl.nl_p[1] = nat->nat_pr[1];
   6166 	natl.nl_v[0] = nat->nat_v[0];
   6167 	natl.nl_v[1] = nat->nat_v[1];
   6168 	natl.nl_type = nat->nat_redir;
   6169 	natl.nl_action = action;
   6170 	natl.nl_rule = -1;
   6171 
   6172 	bcopy(nat->nat_ifnames[0], natl.nl_ifnames[0],
   6173 	      sizeof(nat->nat_ifnames[0]));
   6174 	bcopy(nat->nat_ifnames[1], natl.nl_ifnames[1],
   6175 	      sizeof(nat->nat_ifnames[1]));
   6176 
   6177 # ifndef LARGE_NAT
   6178 	if (nat->nat_ptr != NULL) {
   6179 		for (rulen = 0, np = softn->ipf_nat_list; np != NULL;
   6180 		     np = np->in_next, rulen++)
   6181 			if (np == nat->nat_ptr) {
   6182 				natl.nl_rule = rulen;
   6183 				break;
   6184 			}
   6185 	}
   6186 # endif
   6187 	items[0] = &natl;
   6188 	sizes[0] = sizeof(natl);
   6189 	types[0] = 0;
   6190 
   6191 	(void) ipf_log_items(softc, IPL_LOGNAT, NULL, items, sizes, types, 1);
   6192 #endif
   6193 }
   6194 
   6195 
   6196 #if defined(__OpenBSD__)
   6197 /* ------------------------------------------------------------------------ */
   6198 /* Function:    ipf_nat_ifdetach                                            */
   6199 /* Returns:     Nil                                                         */
   6200 /* Parameters:  ifp(I) - pointer to network interface                       */
   6201 /*                                                                          */
   6202 /* Compatibility interface for OpenBSD to trigger the correct updating of   */
   6203 /* interface references within IPFilter.                                    */
   6204 /* ------------------------------------------------------------------------ */
   6205 void
   6206 ipf_nat_ifdetach(ifp)
   6207 	void *ifp;
   6208 {
   6209 	ipf_main_softc_t *softc;
   6210 
   6211 	softc = ipf_get_softc(0);
   6212 
   6213 	ipf_sync(ifp);
   6214 	return;
   6215 }
   6216 #endif
   6217 
   6218 
   6219 /* ------------------------------------------------------------------------ */
   6220 /* Function:    ipf_nat_rule_deref                                          */
   6221 /* Returns:     Nil                                                         */
   6222 /* Parameters:  softc(I) - pointer to soft context main structure           */
   6223 /*              inp(I)   - pointer to pointer to NAT rule                   */
   6224 /* Write Locks: ipf_nat                                                     */
   6225 /*                                                                          */
   6226 /* Dropping the refernce count for a rule means that whatever held the      */
   6227 /* pointer to this rule (*inp) is no longer interested in it and when the   */
   6228 /* reference count drops to zero, any resources allocated for the rule can  */
   6229 /* be released and the rule itself free'd.                                  */
   6230 /* ------------------------------------------------------------------------ */
   6231 void
   6232 ipf_nat_rule_deref(softc, inp)
   6233 	ipf_main_softc_t *softc;
   6234 	ipnat_t **inp;
   6235 {
   6236 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   6237 	ipnat_t *n;
   6238 
   6239 	n = *inp;
   6240 	*inp = NULL;
   6241 	n->in_use--;
   6242 	if (n->in_use > 0)
   6243 		return;
   6244 
   6245 	if (n->in_apr != NULL)
   6246 		ipf_proxy_deref(n->in_apr);
   6247 
   6248 	ipf_nat_rule_fini(softc, n);
   6249 
   6250 	if (n->in_redir & NAT_REDIRECT) {
   6251 		if ((n->in_flags & IPN_PROXYRULE) == 0) {
   6252 			ATOMIC_DEC32(softn->ipf_nat_stats.ns_rules_rdr);
   6253 		}
   6254 	}
   6255 	if (n->in_redir & (NAT_MAP|NAT_MAPBLK)) {
   6256 		if ((n->in_flags & IPN_PROXYRULE) == 0) {
   6257 			ATOMIC_DEC32(softn->ipf_nat_stats.ns_rules_map);
   6258 		}
   6259 	}
   6260 
   6261 	if (n->in_tqehead[0] != NULL) {
   6262 		if (ipf_deletetimeoutqueue(n->in_tqehead[0]) == 0) {
   6263 			ipf_freetimeoutqueue(softc, n->in_tqehead[1]);
   6264 		}
   6265 	}
   6266 
   6267 	if (n->in_tqehead[1] != NULL) {
   6268 		if (ipf_deletetimeoutqueue(n->in_tqehead[1]) == 0) {
   6269 			ipf_freetimeoutqueue(softc, n->in_tqehead[1]);
   6270 		}
   6271 	}
   6272 
   6273 	if ((n->in_flags & IPN_PROXYRULE) == 0) {
   6274 		ATOMIC_DEC32(softn->ipf_nat_stats.ns_rules);
   6275 	}
   6276 
   6277 	MUTEX_DESTROY(&n->in_lock);
   6278 
   6279 	KFREES(n, n->in_size);
   6280 
   6281 #if SOLARIS && !defined(INSTANCES)
   6282 	if (softn->ipf_nat_stats.ns_rules == 0)
   6283 		pfil_delayed_copy = 1;
   6284 #endif
   6285 }
   6286 
   6287 
   6288 /* ------------------------------------------------------------------------ */
   6289 /* Function:    ipf_nat_deref                                               */
   6290 /* Returns:     Nil                                                         */
   6291 /* Parameters:  softc(I) - pointer to soft context main structure           */
   6292 /*              natp(I)  - pointer to pointer to NAT table entry            */
   6293 /*                                                                          */
   6294 /* Decrement the reference counter for this NAT table entry and free it if  */
   6295 /* there are no more things using it.                                       */
   6296 /*                                                                          */
   6297 /* IF nat_ref == 1 when this function is called, then we have an orphan nat */
   6298 /* structure *because* it only gets called on paths _after_ nat_ref has been*/
   6299 /* incremented.  If nat_ref == 1 then we shouldn't decrement it here        */
   6300 /* because nat_delete() will do that and send nat_ref to -1.                */
   6301 /*                                                                          */
   6302 /* Holding the lock on nat_lock is required to serialise nat_delete() being */
   6303 /* called from a NAT flush ioctl with a deref happening because of a packet.*/
   6304 /* ------------------------------------------------------------------------ */
   6305 void
   6306 ipf_nat_deref(softc, natp)
   6307 	ipf_main_softc_t *softc;
   6308 	nat_t **natp;
   6309 {
   6310 	nat_t *nat;
   6311 
   6312 	nat = *natp;
   6313 	*natp = NULL;
   6314 
   6315 	MUTEX_ENTER(&nat->nat_lock);
   6316 	if (nat->nat_ref > 1) {
   6317 		nat->nat_ref--;
   6318 		ASSERT(nat->nat_ref >= 0);
   6319 		MUTEX_EXIT(&nat->nat_lock);
   6320 		return;
   6321 	}
   6322 	MUTEX_EXIT(&nat->nat_lock);
   6323 
   6324 	WRITE_ENTER(&softc->ipf_nat);
   6325 	ipf_nat_delete(softc, nat, NL_EXPIRE);
   6326 	RWLOCK_EXIT(&softc->ipf_nat);
   6327 }
   6328 
   6329 
   6330 /* ------------------------------------------------------------------------ */
   6331 /* Function:    ipf_nat_clone                                               */
   6332 /* Returns:     ipstate_t* - NULL == cloning failed,                        */
   6333 /*                           else pointer to new state structure            */
   6334 /* Parameters:  fin(I) - pointer to packet information                      */
   6335 /*              is(I)  - pointer to master state structure                  */
   6336 /* Write Lock:  ipf_nat                                                     */
   6337 /*                                                                          */
   6338 /* Create a "duplcate" state table entry from the master.                   */
   6339 /* ------------------------------------------------------------------------ */
   6340 nat_t *
   6341 ipf_nat_clone(fin, nat)
   6342 	fr_info_t *fin;
   6343 	nat_t *nat;
   6344 {
   6345 	ipf_main_softc_t *softc = fin->fin_main_soft;
   6346 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   6347 	frentry_t *fr;
   6348 	nat_t *clone;
   6349 	ipnat_t *np;
   6350 
   6351 	KMALLOC(clone, nat_t *);
   6352 	if (clone == NULL) {
   6353 		NBUMPSIDED(fin->fin_out, ns_clone_nomem);
   6354 		return NULL;
   6355 	}
   6356 	bcopy((char *)nat, (char *)clone, sizeof(*clone));
   6357 
   6358 	MUTEX_NUKE(&clone->nat_lock);
   6359 
   6360 	clone->nat_rev = fin->fin_rev;
   6361 	clone->nat_aps = NULL;
   6362 	/*
   6363 	 * Initialize all these so that ipf_nat_delete() doesn't cause a crash.
   6364 	 */
   6365 	clone->nat_tqe.tqe_pnext = NULL;
   6366 	clone->nat_tqe.tqe_next = NULL;
   6367 	clone->nat_tqe.tqe_ifq = NULL;
   6368 	clone->nat_tqe.tqe_parent = clone;
   6369 
   6370 	clone->nat_flags &= ~SI_CLONE;
   6371 	clone->nat_flags |= SI_CLONED;
   6372 
   6373 	if (clone->nat_hm)
   6374 		clone->nat_hm->hm_ref++;
   6375 
   6376 	if (ipf_nat_insert(softc, softn, clone) == -1) {
   6377 		KFREE(clone);
   6378 		NBUMPSIDED(fin->fin_out, ns_insert_fail);
   6379 		return NULL;
   6380 	}
   6381 
   6382 	np = clone->nat_ptr;
   6383 	if (np != NULL) {
   6384 		if (softn->ipf_nat_logging)
   6385 			ipf_nat_log(softc, softn, clone, NL_CLONE);
   6386 		np->in_use++;
   6387 	}
   6388 	fr = clone->nat_fr;
   6389 	if (fr != NULL) {
   6390 		MUTEX_ENTER(&fr->fr_lock);
   6391 		fr->fr_ref++;
   6392 		MUTEX_EXIT(&fr->fr_lock);
   6393 	}
   6394 
   6395 
   6396 	/*
   6397 	 * Because the clone is created outside the normal loop of things and
   6398 	 * TCP has special needs in terms of state, initialise the timeout
   6399 	 * state of the new NAT from here.
   6400 	 */
   6401 	if (clone->nat_pr[0] == IPPROTO_TCP) {
   6402 		(void) ipf_tcp_age(&clone->nat_tqe, fin, softn->ipf_nat_tcptq,
   6403 				   clone->nat_flags, 2);
   6404 	}
   6405 	clone->nat_sync = ipf_sync_new(softc, SMC_NAT, fin, clone);
   6406 	if (softn->ipf_nat_logging)
   6407 		ipf_nat_log(softc, softn, clone, NL_CLONE);
   6408 	return clone;
   6409 }
   6410 
   6411 
   6412 /* ------------------------------------------------------------------------ */
   6413 /* Function:   ipf_nat_wildok                                               */
   6414 /* Returns:    int - 1 == packet's ports match wildcards                    */
   6415 /*                   0 == packet's ports don't match wildcards              */
   6416 /* Parameters: nat(I)   - NAT entry                                         */
   6417 /*             sport(I) - source port                                       */
   6418 /*             dport(I) - destination port                                  */
   6419 /*             flags(I) - wildcard flags                                    */
   6420 /*             dir(I)   - packet direction                                  */
   6421 /*                                                                          */
   6422 /* Use NAT entry and packet direction to determine which combination of     */
   6423 /* wildcard flags should be used.                                           */
   6424 /* ------------------------------------------------------------------------ */
   6425 int
   6426 ipf_nat_wildok(nat, sport, dport, flags, dir)
   6427 	nat_t *nat;
   6428 	int sport, dport, flags, dir;
   6429 {
   6430 	/*
   6431 	 * When called by       dir is set to
   6432 	 * nat_inlookup         NAT_INBOUND (0)
   6433 	 * nat_outlookup        NAT_OUTBOUND (1)
   6434 	 *
   6435 	 * We simply combine the packet's direction in dir with the original
   6436 	 * "intended" direction of that NAT entry in nat->nat_dir to decide
   6437 	 * which combination of wildcard flags to allow.
   6438 	 */
   6439 	switch ((dir << 1) | (nat->nat_dir & (NAT_INBOUND|NAT_OUTBOUND)))
   6440 	{
   6441 	case 3: /* outbound packet / outbound entry */
   6442 		if (((nat->nat_osport == sport) ||
   6443 		    (flags & SI_W_SPORT)) &&
   6444 		    ((nat->nat_odport == dport) ||
   6445 		    (flags & SI_W_DPORT)))
   6446 			return 1;
   6447 		break;
   6448 	case 2: /* outbound packet / inbound entry */
   6449 		if (((nat->nat_osport == dport) ||
   6450 		    (flags & SI_W_SPORT)) &&
   6451 		    ((nat->nat_odport == sport) ||
   6452 		    (flags & SI_W_DPORT)))
   6453 			return 1;
   6454 		break;
   6455 	case 1: /* inbound packet / outbound entry */
   6456 		if (((nat->nat_osport == dport) ||
   6457 		    (flags & SI_W_SPORT)) &&
   6458 		    ((nat->nat_odport == sport) ||
   6459 		    (flags & SI_W_DPORT)))
   6460 			return 1;
   6461 		break;
   6462 	case 0: /* inbound packet / inbound entry */
   6463 		if (((nat->nat_osport == sport) ||
   6464 		    (flags & SI_W_SPORT)) &&
   6465 		    ((nat->nat_odport == dport) ||
   6466 		    (flags & SI_W_DPORT)))
   6467 			return 1;
   6468 		break;
   6469 	default:
   6470 		break;
   6471 	}
   6472 
   6473 	return(0);
   6474 }
   6475 
   6476 
   6477 /* ------------------------------------------------------------------------ */
   6478 /* Function:    nat_mssclamp                                                */
   6479 /* Returns:     Nil                                                         */
   6480 /* Parameters:  tcp(I)    - pointer to TCP header                           */
   6481 /*              maxmss(I) - value to clamp the TCP MSS to                   */
   6482 /*              fin(I)    - pointer to packet information                   */
   6483 /*              csump(I)  - pointer to TCP checksum                         */
   6484 /*                                                                          */
   6485 /* Check for MSS option and clamp it if necessary.  If found and changed,   */
   6486 /* then the TCP header checksum will be updated to reflect the change in    */
   6487 /* the MSS.                                                                 */
   6488 /* ------------------------------------------------------------------------ */
   6489 static void
   6490 ipf_nat_mssclamp(tcp, maxmss, fin, csump)
   6491 	tcphdr_t *tcp;
   6492 	u_32_t maxmss;
   6493 	fr_info_t *fin;
   6494 	u_short *csump;
   6495 {
   6496 	u_char *cp, *ep, opt;
   6497 	int hlen, advance;
   6498 	u_32_t mss, sumd;
   6499 
   6500 	hlen = TCP_OFF(tcp) << 2;
   6501 	if (hlen > sizeof(*tcp)) {
   6502 		cp = (u_char *)tcp + sizeof(*tcp);
   6503 		ep = (u_char *)tcp + hlen;
   6504 
   6505 		while (cp < ep) {
   6506 			opt = cp[0];
   6507 			if (opt == TCPOPT_EOL)
   6508 				break;
   6509 			else if (opt == TCPOPT_NOP) {
   6510 				cp++;
   6511 				continue;
   6512 			}
   6513 
   6514 			if (cp + 1 >= ep)
   6515 				break;
   6516 			advance = cp[1];
   6517 			if ((cp + advance > ep) || (advance <= 0))
   6518 				break;
   6519 			switch (opt)
   6520 			{
   6521 			case TCPOPT_MAXSEG:
   6522 				if (advance != 4)
   6523 					break;
   6524 				mss = cp[2] * 256 + cp[3];
   6525 				if (mss > maxmss) {
   6526 					cp[2] = maxmss / 256;
   6527 					cp[3] = maxmss & 0xff;
   6528 					CALC_SUMD(mss, maxmss, sumd);
   6529 					ipf_fix_outcksum(0, csump, sumd, 0);
   6530 				}
   6531 				break;
   6532 			default:
   6533 				/* ignore unknown options */
   6534 				break;
   6535 			}
   6536 
   6537 			cp += advance;
   6538 		}
   6539 	}
   6540 }
   6541 
   6542 
   6543 /* ------------------------------------------------------------------------ */
   6544 /* Function:    ipf_nat_setqueue                                            */
   6545 /* Returns:     Nil                                                         */
   6546 /* Parameters:  softc(I) - pointer to soft context main structure           */
   6547 /*              softn(I) - pointer to NAT context structure                 */
   6548 /*              nat(I)- pointer to NAT structure                            */
   6549 /* Locks:       ipf_nat (read or write)                                     */
   6550 /*                                                                          */
   6551 /* Put the NAT entry on its default queue entry, using rev as a helped in   */
   6552 /* determining which queue it should be placed on.                          */
   6553 /* ------------------------------------------------------------------------ */
   6554 void
   6555 ipf_nat_setqueue(softc, softn, nat)
   6556 	ipf_main_softc_t *softc;
   6557 	ipf_nat_softc_t *softn;
   6558 	nat_t *nat;
   6559 {
   6560 	ipftq_t *oifq, *nifq;
   6561 	int rev = nat->nat_rev;
   6562 
   6563 	if (nat->nat_ptr != NULL)
   6564 		nifq = nat->nat_ptr->in_tqehead[rev];
   6565 	else
   6566 		nifq = NULL;
   6567 
   6568 	if (nifq == NULL) {
   6569 		switch (nat->nat_pr[0])
   6570 		{
   6571 		case IPPROTO_UDP :
   6572 			nifq = &softn->ipf_nat_udptq;
   6573 			break;
   6574 		case IPPROTO_ICMP :
   6575 			nifq = &softn->ipf_nat_icmptq;
   6576 			break;
   6577 		case IPPROTO_TCP :
   6578 			nifq = softn->ipf_nat_tcptq +
   6579 			       nat->nat_tqe.tqe_state[rev];
   6580 			break;
   6581 		default :
   6582 			nifq = &softn->ipf_nat_iptq;
   6583 			break;
   6584 		}
   6585 	}
   6586 
   6587 	oifq = nat->nat_tqe.tqe_ifq;
   6588 	/*
   6589 	 * If it's currently on a timeout queue, move it from one queue to
   6590 	 * another, else put it on the end of the newly determined queue.
   6591 	 */
   6592 	if (oifq != NULL)
   6593 		ipf_movequeue(softc->ipf_ticks, &nat->nat_tqe, oifq, nifq);
   6594 	else
   6595 		ipf_queueappend(softc->ipf_ticks, &nat->nat_tqe, nifq, nat);
   6596 	return;
   6597 }
   6598 
   6599 
   6600 /* ------------------------------------------------------------------------ */
   6601 /* Function:    nat_getnext                                                 */
   6602 /* Returns:     int - 0 == ok, else error                                   */
   6603 /* Parameters:  softc(I) - pointer to soft context main structure           */
   6604 /*              t(I)   - pointer to ipftoken structure                      */
   6605 /*              itp(I) - pointer to ipfgeniter_t structure                  */
   6606 /*                                                                          */
   6607 /* Fetch the next nat/ipnat structure pointer from the linked list and      */
   6608 /* copy it out to the storage space pointed to by itp_data.  The next item  */
   6609 /* in the list to look at is put back in the ipftoken struture.             */
   6610 /* ------------------------------------------------------------------------ */
   6611 static int
   6612 ipf_nat_getnext(softc, t, itp, objp)
   6613 	ipf_main_softc_t *softc;
   6614 	ipftoken_t *t;
   6615 	ipfgeniter_t *itp;
   6616 	ipfobj_t *objp;
   6617 {
   6618 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   6619 	hostmap_t *hm, *nexthm = NULL, zerohm;
   6620 	ipnat_t *ipn, *nextipnat = NULL, zeroipn;
   6621 	nat_t *nat, *nextnat = NULL, zeronat;
   6622 	int error = 0;
   6623 	void *nnext;
   6624 
   6625 	if (itp->igi_nitems != 1) {
   6626 		IPFERROR(60075);
   6627 		return ENOSPC;
   6628 	}
   6629 
   6630 	READ_ENTER(&softc->ipf_nat);
   6631 
   6632 	switch (itp->igi_type)
   6633 	{
   6634 	case IPFGENITER_HOSTMAP :
   6635 		hm = t->ipt_data;
   6636 		if (hm == NULL) {
   6637 			nexthm = softn->ipf_hm_maplist;
   6638 		} else {
   6639 			nexthm = hm->hm_next;
   6640 		}
   6641 		if (nexthm != NULL) {
   6642 			ATOMIC_INC32(nexthm->hm_ref);
   6643 			t->ipt_data = nexthm;
   6644 		} else {
   6645 			bzero(&zerohm, sizeof(zerohm));
   6646 			nexthm = &zerohm;
   6647 			t->ipt_data = NULL;
   6648 		}
   6649 		nnext = nexthm->hm_next;
   6650 		break;
   6651 
   6652 	case IPFGENITER_IPNAT :
   6653 		ipn = t->ipt_data;
   6654 		if (ipn == NULL) {
   6655 			nextipnat = softn->ipf_nat_list;
   6656 		} else {
   6657 			nextipnat = ipn->in_next;
   6658 		}
   6659 		if (nextipnat != NULL) {
   6660 			ATOMIC_INC32(nextipnat->in_use);
   6661 			t->ipt_data = nextipnat;
   6662 		} else {
   6663 			bzero(&zeroipn, sizeof(zeroipn));
   6664 			nextipnat = &zeroipn;
   6665 			t->ipt_data = NULL;
   6666 		}
   6667 		nnext = nextipnat->in_next;
   6668 		break;
   6669 
   6670 	case IPFGENITER_NAT :
   6671 		nat = t->ipt_data;
   6672 		if (nat == NULL) {
   6673 			nextnat = softn->ipf_nat_instances;
   6674 		} else {
   6675 			nextnat = nat->nat_next;
   6676 		}
   6677 		if (nextnat != NULL) {
   6678 			MUTEX_ENTER(&nextnat->nat_lock);
   6679 			nextnat->nat_ref++;
   6680 			MUTEX_EXIT(&nextnat->nat_lock);
   6681 			t->ipt_data = nextnat;
   6682 		} else {
   6683 			bzero(&zeronat, sizeof(zeronat));
   6684 			nextnat = &zeronat;
   6685 			t->ipt_data = NULL;
   6686 		}
   6687 		nnext = nextnat->nat_next;
   6688 		break;
   6689 
   6690 	default :
   6691 		RWLOCK_EXIT(&softc->ipf_nat);
   6692 		IPFERROR(60055);
   6693 		return EINVAL;
   6694 	}
   6695 
   6696 	RWLOCK_EXIT(&softc->ipf_nat);
   6697 
   6698 	objp->ipfo_ptr = itp->igi_data;
   6699 
   6700 	switch (itp->igi_type)
   6701 	{
   6702 	case IPFGENITER_HOSTMAP :
   6703 		error = COPYOUT(nexthm, objp->ipfo_ptr, sizeof(*nexthm));
   6704 		if (error != 0) {
   6705 			IPFERROR(60049);
   6706 			error = EFAULT;
   6707 		}
   6708 		if (hm != NULL) {
   6709 			WRITE_ENTER(&softc->ipf_nat);
   6710 			ipf_nat_hostmapdel(softc, &hm);
   6711 			RWLOCK_EXIT(&softc->ipf_nat);
   6712 		}
   6713 		break;
   6714 
   6715 	case IPFGENITER_IPNAT :
   6716 		objp->ipfo_size = nextipnat->in_size;
   6717 		objp->ipfo_type = IPFOBJ_IPNAT;
   6718 		error = ipf_outobjk(softc, objp, nextipnat);
   6719 		if (ipn != NULL) {
   6720 			WRITE_ENTER(&softc->ipf_nat);
   6721 			ipf_nat_rule_deref(softc, &ipn);
   6722 			RWLOCK_EXIT(&softc->ipf_nat);
   6723 		}
   6724 		break;
   6725 
   6726 	case IPFGENITER_NAT :
   6727 		objp->ipfo_size = sizeof(nat_t);
   6728 		objp->ipfo_type = IPFOBJ_NAT;
   6729 		error = ipf_outobjk(softc, objp, nextnat);
   6730 		if (nat != NULL)
   6731 			ipf_nat_deref(softc, &nat);
   6732 
   6733 		break;
   6734 	}
   6735 
   6736 	if (nnext == NULL)
   6737 		ipf_token_mark_complete(t);
   6738 
   6739 	return error;
   6740 }
   6741 
   6742 
   6743 /* ------------------------------------------------------------------------ */
   6744 /* Function:    nat_extraflush                                              */
   6745 /* Returns:     int - 0 == success, -1 == failure                           */
   6746 /* Parameters:  softc(I) - pointer to soft context main structure           */
   6747 /*              softn(I) - pointer to NAT context structure                 */
   6748 /*              which(I) - how to flush the active NAT table                */
   6749 /* Write Locks: ipf_nat                                                     */
   6750 /*                                                                          */
   6751 /* Flush nat tables.  Three actions currently defined:                      */
   6752 /* which == 0 : flush all nat table entries                                 */
   6753 /* which == 1 : flush TCP connections which have started to close but are   */
   6754 /*	      stuck for some reason.                                        */
   6755 /* which == 2 : flush TCP connections which have been idle for a long time, */
   6756 /*	      starting at > 4 days idle and working back in successive half-*/
   6757 /*	      days to at most 12 hours old.  If this fails to free enough   */
   6758 /*            slots then work backwards in half hour slots to 30 minutes.   */
   6759 /*            If that too fails, then work backwards in 30 second intervals */
   6760 /*            for the last 30 minutes to at worst 30 seconds idle.          */
   6761 /* ------------------------------------------------------------------------ */
   6762 static int
   6763 ipf_nat_extraflush(softc, softn, which)
   6764 	ipf_main_softc_t *softc;
   6765 	ipf_nat_softc_t *softn;
   6766 	int which;
   6767 {
   6768 	nat_t *nat, **natp;
   6769 	ipftqent_t *tqn;
   6770 	ipftq_t *ifq;
   6771 	int removed;
   6772 	SPL_INT(s);
   6773 
   6774 	removed = 0;
   6775 
   6776 	SPL_NET(s);
   6777 	switch (which)
   6778 	{
   6779 	case 0 :
   6780 		softn->ipf_nat_stats.ns_flush_all++;
   6781 		/*
   6782 		 * Style 0 flush removes everything...
   6783 		 */
   6784 		for (natp = &softn->ipf_nat_instances;
   6785 		     ((nat = *natp) != NULL); ) {
   6786 			ipf_nat_delete(softc, nat, NL_FLUSH);
   6787 			removed++;
   6788 		}
   6789 		break;
   6790 
   6791 	case 1 :
   6792 		softn->ipf_nat_stats.ns_flush_closing++;
   6793 		/*
   6794 		 * Since we're only interested in things that are closing,
   6795 		 * we can start with the appropriate timeout queue.
   6796 		 */
   6797 		for (ifq = softn->ipf_nat_tcptq + IPF_TCPS_CLOSE_WAIT;
   6798 		     ifq != NULL; ifq = ifq->ifq_next) {
   6799 
   6800 			for (tqn = ifq->ifq_head; tqn != NULL; ) {
   6801 				nat = tqn->tqe_parent;
   6802 				tqn = tqn->tqe_next;
   6803 				if (nat->nat_pr[0] != IPPROTO_TCP ||
   6804 				    nat->nat_pr[1] != IPPROTO_TCP)
   6805 					break;
   6806 				ipf_nat_delete(softc, nat, NL_EXPIRE);
   6807 				removed++;
   6808 			}
   6809 		}
   6810 
   6811 		/*
   6812 		 * Also need to look through the user defined queues.
   6813 		 */
   6814 		for (ifq = softn->ipf_nat_utqe; ifq != NULL;
   6815 		     ifq = ifq->ifq_next) {
   6816 			for (tqn = ifq->ifq_head; tqn != NULL; ) {
   6817 				nat = tqn->tqe_parent;
   6818 				tqn = tqn->tqe_next;
   6819 				if (nat->nat_pr[0] != IPPROTO_TCP ||
   6820 				    nat->nat_pr[1] != IPPROTO_TCP)
   6821 					continue;
   6822 
   6823 				if ((nat->nat_tcpstate[0] >
   6824 				     IPF_TCPS_ESTABLISHED) &&
   6825 				    (nat->nat_tcpstate[1] >
   6826 				     IPF_TCPS_ESTABLISHED)) {
   6827 					ipf_nat_delete(softc, nat, NL_EXPIRE);
   6828 					removed++;
   6829 				}
   6830 			}
   6831 		}
   6832 		break;
   6833 
   6834 		/*
   6835 		 * Args 5-11 correspond to flushing those particular states
   6836 		 * for TCP connections.
   6837 		 */
   6838 	case IPF_TCPS_CLOSE_WAIT :
   6839 	case IPF_TCPS_FIN_WAIT_1 :
   6840 	case IPF_TCPS_CLOSING :
   6841 	case IPF_TCPS_LAST_ACK :
   6842 	case IPF_TCPS_FIN_WAIT_2 :
   6843 	case IPF_TCPS_TIME_WAIT :
   6844 	case IPF_TCPS_CLOSED :
   6845 		softn->ipf_nat_stats.ns_flush_state++;
   6846 		tqn = softn->ipf_nat_tcptq[which].ifq_head;
   6847 		while (tqn != NULL) {
   6848 			nat = tqn->tqe_parent;
   6849 			tqn = tqn->tqe_next;
   6850 			ipf_nat_delete(softc, nat, NL_FLUSH);
   6851 			removed++;
   6852 		}
   6853 		break;
   6854 
   6855 	default :
   6856 		if (which < 30)
   6857 			break;
   6858 
   6859 		softn->ipf_nat_stats.ns_flush_timeout++;
   6860 		/*
   6861 		 * Take a large arbitrary number to mean the number of seconds
   6862 		 * for which which consider to be the maximum value we'll allow
   6863 		 * the expiration to be.
   6864 		 */
   6865 		which = IPF_TTLVAL(which);
   6866 		for (natp = &softn->ipf_nat_instances;
   6867 		     ((nat = *natp) != NULL); ) {
   6868 			if (softc->ipf_ticks - nat->nat_touched > which) {
   6869 				ipf_nat_delete(softc, nat, NL_FLUSH);
   6870 				removed++;
   6871 			} else
   6872 				natp = &nat->nat_next;
   6873 		}
   6874 		break;
   6875 	}
   6876 
   6877 	if (which != 2) {
   6878 		SPL_X(s);
   6879 		return removed;
   6880 	}
   6881 
   6882 	softn->ipf_nat_stats.ns_flush_queue++;
   6883 
   6884 	/*
   6885 	 * Asked to remove inactive entries because the table is full, try
   6886 	 * again, 3 times, if first attempt failed with a different criteria
   6887 	 * each time.  The order tried in must be in decreasing age.
   6888 	 * Another alternative is to implement random drop and drop N entries
   6889 	 * at random until N have been freed up.
   6890 	 */
   6891 	if (softc->ipf_ticks - softn->ipf_nat_last_force_flush >
   6892 	    IPF_TTLVAL(5)) {
   6893 		softn->ipf_nat_last_force_flush = softc->ipf_ticks;
   6894 
   6895 		removed = ipf_queueflush(softc, ipf_nat_flush_entry,
   6896 					 softn->ipf_nat_tcptq,
   6897 					 softn->ipf_nat_utqe,
   6898 					 &softn->ipf_nat_stats.ns_active,
   6899 					 softn->ipf_nat_table_sz,
   6900 					 softn->ipf_nat_table_wm_low);
   6901 	}
   6902 
   6903 	SPL_X(s);
   6904 	return removed;
   6905 }
   6906 
   6907 
   6908 /* ------------------------------------------------------------------------ */
   6909 /* Function:    ipf_nat_flush_entry                                         */
   6910 /* Returns:     0 - always succeeds                                         */
   6911 /* Parameters:  softc(I) - pointer to soft context main structure           */
   6912 /*              entry(I) - pointer to NAT entry                             */
   6913 /* Write Locks: ipf_nat                                                     */
   6914 /*                                                                          */
   6915 /* This function is a stepping stone between ipf_queueflush() and           */
   6916 /* nat_dlete().  It is used so we can provide a uniform interface via the   */
   6917 /* ipf_queueflush() function.  Since the nat_delete() function returns void */
   6918 /* we translate that to mean it always succeeds in deleting something.      */
   6919 /* ------------------------------------------------------------------------ */
   6920 static int
   6921 ipf_nat_flush_entry(softc, entry)
   6922 	ipf_main_softc_t *softc;
   6923 	void *entry;
   6924 {
   6925 	ipf_nat_delete(softc, entry, NL_FLUSH);
   6926 	return 0;
   6927 }
   6928 
   6929 
   6930 /* ------------------------------------------------------------------------ */
   6931 /* Function:    ipf_nat_iterator                                            */
   6932 /* Returns:     int - 0 == ok, else error                                   */
   6933 /* Parameters:  softc(I) - pointer to soft context main structure           */
   6934 /*              token(I) - pointer to ipftoken structure                    */
   6935 /*              itp(I)   - pointer to ipfgeniter_t structure                */
   6936 /*              obj(I)   - pointer to data description structure            */
   6937 /*                                                                          */
   6938 /* This function acts as a handler for the SIOCGENITER ioctls that use a    */
   6939 /* generic structure to iterate through a list.  There are three different  */
   6940 /* linked lists of NAT related information to go through: NAT rules, active */
   6941 /* NAT mappings and the NAT fragment cache.                                 */
   6942 /* ------------------------------------------------------------------------ */
   6943 static int
   6944 ipf_nat_iterator(softc, token, itp, obj)
   6945 	ipf_main_softc_t *softc;
   6946 	ipftoken_t *token;
   6947 	ipfgeniter_t *itp;
   6948 	ipfobj_t *obj;
   6949 {
   6950 	int error;
   6951 
   6952 	if (itp->igi_data == NULL) {
   6953 		IPFERROR(60052);
   6954 		return EFAULT;
   6955 	}
   6956 
   6957 	switch (itp->igi_type)
   6958 	{
   6959 	case IPFGENITER_HOSTMAP :
   6960 	case IPFGENITER_IPNAT :
   6961 	case IPFGENITER_NAT :
   6962 		error = ipf_nat_getnext(softc, token, itp, obj);
   6963 		break;
   6964 
   6965 	case IPFGENITER_NATFRAG :
   6966 		error = ipf_frag_nat_next(softc, token, itp);
   6967 		break;
   6968 	default :
   6969 		IPFERROR(60053);
   6970 		error = EINVAL;
   6971 		break;
   6972 	}
   6973 
   6974 	return error;
   6975 }
   6976 
   6977 
   6978 /* ------------------------------------------------------------------------ */
   6979 /* Function:    ipf_nat_setpending                                          */
   6980 /* Returns:     Nil                                                         */
   6981 /* Parameters:  softc(I) - pointer to soft context main structure           */
   6982 /*              nat(I)   - pointer to NAT structure                         */
   6983 /* Locks:       ipf_nat (read or write)                                     */
   6984 /*                                                                          */
   6985 /* Put the NAT entry on to the pending queue - this queue has a very short  */
   6986 /* lifetime where items are put that can't be deleted straight away because */
   6987 /* of locking issues but we want to delete them ASAP, anyway.  In calling   */
   6988 /* this function, it is assumed that the owner (if there is one, as shown   */
   6989 /* by nat_me) is no longer interested in it.                                */
   6990 /* ------------------------------------------------------------------------ */
   6991 void
   6992 ipf_nat_setpending(softc, nat)
   6993 	ipf_main_softc_t *softc;
   6994 	nat_t *nat;
   6995 {
   6996 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   6997 	ipftq_t *oifq;
   6998 
   6999 	oifq = nat->nat_tqe.tqe_ifq;
   7000 	if (oifq != NULL)
   7001 		ipf_movequeue(softc->ipf_ticks, &nat->nat_tqe, oifq,
   7002 			      &softn->ipf_nat_pending);
   7003 	else
   7004 		ipf_queueappend(softc->ipf_ticks, &nat->nat_tqe,
   7005 				&softn->ipf_nat_pending, nat);
   7006 
   7007 	if (nat->nat_me != NULL) {
   7008 		*nat->nat_me = NULL;
   7009 		nat->nat_me = NULL;
   7010 		nat->nat_ref--;
   7011 		ASSERT(nat->nat_ref >= 0);
   7012 	}
   7013 }
   7014 
   7015 
   7016 /* ------------------------------------------------------------------------ */
   7017 /* Function:    nat_newrewrite                                              */
   7018 /* Returns:     int - -1 == error, 0 == success (no move), 1 == success and */
   7019 /*                    allow rule to be moved if IPN_ROUNDR is set.          */
   7020 /* Parameters:  fin(I) - pointer to packet information                      */
   7021 /*              nat(I) - pointer to NAT entry                               */
   7022 /*              ni(I)  - pointer to structure with misc. information needed */
   7023 /*                       to create new NAT entry.                           */
   7024 /* Write Lock:  ipf_nat                                                     */
   7025 /*                                                                          */
   7026 /* This function is responsible for setting up an active NAT session where  */
   7027 /* we are changing both the source and destination parameters at the same   */
   7028 /* time.  The loop in here works differently to elsewhere - each iteration  */
   7029 /* is responsible for changing a single parameter that can be incremented.  */
   7030 /* So one pass may increase the source IP#, next source port, next dest. IP#*/
   7031 /* and the last destination port for a total of 4 iterations to try each.   */
   7032 /* This is done to try and exhaustively use the translation space available.*/
   7033 /* ------------------------------------------------------------------------ */
   7034 static int
   7035 ipf_nat_newrewrite(fin, nat, nai)
   7036 	fr_info_t *fin;
   7037 	nat_t *nat;
   7038 	natinfo_t *nai;
   7039 {
   7040 	int src_search = 1;
   7041 	int dst_search = 1;
   7042 	fr_info_t frnat;
   7043 	u_32_t flags;
   7044 	u_short swap;
   7045 	ipnat_t *np;
   7046 	nat_t *natl;
   7047 	int l = 0;
   7048 	int changed;
   7049 
   7050 	natl = NULL;
   7051 	changed = -1;
   7052 	np = nai->nai_np;
   7053 	flags = nat->nat_flags;
   7054 	bcopy((char *)fin, (char *)&frnat, sizeof(*fin));
   7055 
   7056 	nat->nat_hm = NULL;
   7057 
   7058 	do {
   7059 		changed = -1;
   7060 		/* TRACE (l, src_search, dst_search, np) */
   7061 
   7062 		if ((src_search == 0) && (np->in_spnext == 0) &&
   7063 		    (dst_search == 0) && (np->in_dpnext == 0)) {
   7064 			if (l > 0)
   7065 				return -1;
   7066 		}
   7067 
   7068 		/*
   7069 		 * Find a new source address
   7070 		 */
   7071 		if (ipf_nat_nextaddr(fin, &np->in_nsrc, &frnat.fin_saddr,
   7072 				     &frnat.fin_saddr) == -1) {
   7073 			return -1;
   7074 		}
   7075 
   7076 		if ((np->in_nsrcaddr == 0) && (np->in_nsrcmsk == 0xffffffff)) {
   7077 			src_search = 0;
   7078 			if (np->in_stepnext == 0)
   7079 				np->in_stepnext = 1;
   7080 
   7081 		} else if ((np->in_nsrcaddr == 0) && (np->in_nsrcmsk == 0)) {
   7082 			src_search = 0;
   7083 			if (np->in_stepnext == 0)
   7084 				np->in_stepnext = 1;
   7085 
   7086 		} else if (np->in_nsrcmsk == 0xffffffff) {
   7087 			src_search = 0;
   7088 			if (np->in_stepnext == 0)
   7089 				np->in_stepnext = 1;
   7090 
   7091 		} else if (np->in_nsrcmsk != 0xffffffff) {
   7092 			if (np->in_stepnext == 0 && changed == -1) {
   7093 				np->in_snip++;
   7094 				np->in_stepnext++;
   7095 				changed = 0;
   7096 			}
   7097 		}
   7098 
   7099 		if ((flags & IPN_TCPUDPICMP) != 0) {
   7100 			if (np->in_spnext != 0)
   7101 				frnat.fin_data[0] = np->in_spnext;
   7102 
   7103 			/*
   7104 			 * Standard port translation.  Select next port.
   7105 			 */
   7106 			if ((flags & IPN_FIXEDSPORT) != 0) {
   7107 				np->in_stepnext = 2;
   7108 			} else if ((np->in_stepnext == 1) &&
   7109 				   (changed == -1) && (natl != NULL)) {
   7110 				np->in_spnext++;
   7111 				np->in_stepnext++;
   7112 				changed = 1;
   7113 				if (np->in_spnext > np->in_spmax)
   7114 					np->in_spnext = np->in_spmin;
   7115 			}
   7116 		} else {
   7117 			np->in_stepnext = 2;
   7118 		}
   7119 		np->in_stepnext &= 0x3;
   7120 
   7121 		/*
   7122 		 * Find a new destination address
   7123 		 */
   7124 		/* TRACE (fin, np, l, frnat) */
   7125 
   7126 		if (ipf_nat_nextaddr(fin, &np->in_ndst, &frnat.fin_daddr,
   7127 				     &frnat.fin_daddr) == -1)
   7128 			return -1;
   7129 		if ((np->in_ndstaddr == 0) && (np->in_ndstmsk == 0xffffffff)) {
   7130 			dst_search = 0;
   7131 			if (np->in_stepnext == 2)
   7132 				np->in_stepnext = 3;
   7133 
   7134 		} else if ((np->in_ndstaddr == 0) && (np->in_ndstmsk == 0)) {
   7135 			dst_search = 0;
   7136 			if (np->in_stepnext == 2)
   7137 				np->in_stepnext = 3;
   7138 
   7139 		} else if (np->in_ndstmsk == 0xffffffff) {
   7140 			dst_search = 0;
   7141 			if (np->in_stepnext == 2)
   7142 				np->in_stepnext = 3;
   7143 
   7144 		} else if (np->in_ndstmsk != 0xffffffff) {
   7145 			if ((np->in_stepnext == 2) && (changed == -1) &&
   7146 			    (natl != NULL)) {
   7147 				changed = 2;
   7148 				np->in_stepnext++;
   7149 				np->in_dnip++;
   7150 			}
   7151 		}
   7152 
   7153 		if ((flags & IPN_TCPUDPICMP) != 0) {
   7154 			if (np->in_dpnext != 0)
   7155 				frnat.fin_data[1] = np->in_dpnext;
   7156 
   7157 			/*
   7158 			 * Standard port translation.  Select next port.
   7159 			 */
   7160 			if ((flags & IPN_FIXEDDPORT) != 0) {
   7161 				np->in_stepnext = 0;
   7162 			} else if (np->in_stepnext == 3 && changed == -1) {
   7163 				np->in_dpnext++;
   7164 				np->in_stepnext++;
   7165 				changed = 3;
   7166 				if (np->in_dpnext > np->in_dpmax)
   7167 					np->in_dpnext = np->in_dpmin;
   7168 			}
   7169 		} else {
   7170 			if (np->in_stepnext == 3)
   7171 				np->in_stepnext = 0;
   7172 		}
   7173 
   7174 		/* TRACE (frnat) */
   7175 
   7176 		/*
   7177 		 * Here we do a lookup of the connection as seen from
   7178 		 * the outside.  If an IP# pair already exists, try
   7179 		 * again.  So if you have A->B becomes C->B, you can
   7180 		 * also have D->E become C->E but not D->B causing
   7181 		 * another C->B.  Also take protocol and ports into
   7182 		 * account when determining whether a pre-existing
   7183 		 * NAT setup will cause an external conflict where
   7184 		 * this is appropriate.
   7185 		 *
   7186 		 * fin_data[] is swapped around because we are doing a
   7187 		 * lookup of the packet is if it were moving in the opposite
   7188 		 * direction of the one we are working with now.
   7189 		 */
   7190 		if (flags & IPN_TCPUDP) {
   7191 			swap = frnat.fin_data[0];
   7192 			frnat.fin_data[0] = frnat.fin_data[1];
   7193 			frnat.fin_data[1] = swap;
   7194 		}
   7195 		if (fin->fin_out == 1) {
   7196 			natl = ipf_nat_inlookup(&frnat,
   7197 						flags & ~(SI_WILDP|NAT_SEARCH),
   7198 						(u_int)frnat.fin_p,
   7199 						frnat.fin_dst, frnat.fin_src);
   7200 
   7201 		} else {
   7202 			natl = ipf_nat_outlookup(&frnat,
   7203 						 flags & ~(SI_WILDP|NAT_SEARCH),
   7204 						 (u_int)frnat.fin_p,
   7205 						 frnat.fin_dst, frnat.fin_src);
   7206 		}
   7207 		if (flags & IPN_TCPUDP) {
   7208 			swap = frnat.fin_data[0];
   7209 			frnat.fin_data[0] = frnat.fin_data[1];
   7210 			frnat.fin_data[1] = swap;
   7211 		}
   7212 
   7213 		/* TRACE natl, in_stepnext, l */
   7214 
   7215 		if ((natl != NULL) && (l > 8))	/* XXX 8 is arbitrary */
   7216 			return -1;
   7217 
   7218 		np->in_stepnext &= 0x3;
   7219 
   7220 		l++;
   7221 		changed = -1;
   7222 	} while (natl != NULL);
   7223 
   7224 	nat->nat_osrcip = fin->fin_src;
   7225 	nat->nat_odstip = fin->fin_dst;
   7226 	nat->nat_nsrcip = frnat.fin_src;
   7227 	nat->nat_ndstip = frnat.fin_dst;
   7228 
   7229 	if ((flags & IPN_TCPUDP) != 0) {
   7230 		nat->nat_osport = htons(fin->fin_data[0]);
   7231 		nat->nat_odport = htons(fin->fin_data[1]);
   7232 		nat->nat_nsport = htons(frnat.fin_data[0]);
   7233 		nat->nat_ndport = htons(frnat.fin_data[1]);
   7234 	} else if ((flags & IPN_ICMPQUERY) != 0) {
   7235 		nat->nat_oicmpid = fin->fin_data[1];
   7236 		nat->nat_nicmpid = frnat.fin_data[1];
   7237 	}
   7238 
   7239 	return 0;
   7240 }
   7241 
   7242 
   7243 /* ------------------------------------------------------------------------ */
   7244 /* Function:    nat_newdivert                                               */
   7245 /* Returns:     int - -1 == error, 0 == success                             */
   7246 /* Parameters:  fin(I) - pointer to packet information                      */
   7247 /*              nat(I) - pointer to NAT entry                               */
   7248 /*              ni(I)  - pointer to structure with misc. information needed */
   7249 /*                       to create new NAT entry.                           */
   7250 /* Write Lock:  ipf_nat                                                     */
   7251 /*                                                                          */
   7252 /* Create a new NAT  divert session as defined by the NAT rule.  This is    */
   7253 /* somewhat different to other NAT session creation routines because we     */
   7254 /* do not iterate through either port numbers or IP addresses, searching    */
   7255 /* for a unique mapping, however, a complimentary duplicate check is made.  */
   7256 /* ------------------------------------------------------------------------ */
   7257 static int
   7258 ipf_nat_newdivert(fin, nat, nai)
   7259 	fr_info_t *fin;
   7260 	nat_t *nat;
   7261 	natinfo_t *nai;
   7262 {
   7263 	ipf_main_softc_t *softc = fin->fin_main_soft;
   7264 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   7265 	fr_info_t frnat;
   7266 	ipnat_t *np;
   7267 	nat_t *natl;
   7268 	int p;
   7269 
   7270 	np = nai->nai_np;
   7271 	bcopy((char *)fin, (char *)&frnat, sizeof(*fin));
   7272 
   7273 	nat->nat_pr[0] = 0;
   7274 	nat->nat_osrcaddr = fin->fin_saddr;
   7275 	nat->nat_odstaddr = fin->fin_daddr;
   7276 	frnat.fin_saddr = htonl(np->in_snip);
   7277 	frnat.fin_daddr = htonl(np->in_dnip);
   7278 	if ((nat->nat_flags & IPN_TCPUDP) != 0) {
   7279 		nat->nat_osport = htons(fin->fin_data[0]);
   7280 		nat->nat_odport = htons(fin->fin_data[1]);
   7281 	} else if ((nat->nat_flags & IPN_ICMPQUERY) != 0) {
   7282 		nat->nat_oicmpid = fin->fin_data[1];
   7283 	}
   7284 
   7285 	if (np->in_redir & NAT_DIVERTUDP) {
   7286 		frnat.fin_data[0] = np->in_spnext;
   7287 		frnat.fin_data[1] = np->in_dpnext;
   7288 		frnat.fin_flx |= FI_TCPUDP;
   7289 		p = IPPROTO_UDP;
   7290 	} else {
   7291 		frnat.fin_flx &= ~FI_TCPUDP;
   7292 		p = IPPROTO_IPIP;
   7293 	}
   7294 
   7295 	if (fin->fin_out == 1) {
   7296 		natl = ipf_nat_inlookup(&frnat, 0, p,
   7297 					frnat.fin_dst, frnat.fin_src);
   7298 
   7299 	} else {
   7300 		natl = ipf_nat_outlookup(&frnat, 0, p,
   7301 					 frnat.fin_dst, frnat.fin_src);
   7302 	}
   7303 
   7304 	if (natl != NULL) {
   7305 		NBUMPSIDED(fin->fin_out, ns_divert_exist);
   7306 		return -1;
   7307 	}
   7308 
   7309 	nat->nat_nsrcaddr = frnat.fin_saddr;
   7310 	nat->nat_ndstaddr = frnat.fin_daddr;
   7311 	if ((nat->nat_flags & IPN_TCPUDP) != 0) {
   7312 		nat->nat_nsport = htons(frnat.fin_data[0]);
   7313 		nat->nat_ndport = htons(frnat.fin_data[1]);
   7314 	} else if ((nat->nat_flags & IPN_ICMPQUERY) != 0) {
   7315 		nat->nat_nicmpid = frnat.fin_data[1];
   7316 	}
   7317 
   7318 	nat->nat_pr[fin->fin_out] = fin->fin_p;
   7319 	nat->nat_pr[1 - fin->fin_out] = p;
   7320 
   7321 	if (np->in_redir & NAT_REDIRECT)
   7322 		nat->nat_dir = NAT_DIVERTIN;
   7323 	else
   7324 		nat->nat_dir = NAT_DIVERTOUT;
   7325 
   7326 	return 0;
   7327 }
   7328 
   7329 
   7330 /* ------------------------------------------------------------------------ */
   7331 /* Function:    nat_builddivertmp                                           */
   7332 /* Returns:     int - -1 == error, 0 == success                             */
   7333 /* Parameters:  softn(I) - pointer to NAT context structure                 */
   7334 /*              np(I)    - pointer to a NAT rule                            */
   7335 /*                                                                          */
   7336 /* For divert rules, a skeleton packet representing what will be prepended  */
   7337 /* to the real packet is created.  Even though we don't have the full       */
   7338 /* packet here, a checksum is calculated that we update later when we       */
   7339 /* fill in the final details.  At present a 0 checksum for UDP is being set */
   7340 /* here because it is expected that divert will be used for localhost.      */
   7341 /* ------------------------------------------------------------------------ */
   7342 static int
   7343 ipf_nat_builddivertmp(softn, np)
   7344 	ipf_nat_softc_t *softn;
   7345 	ipnat_t *np;
   7346 {
   7347 	udphdr_t *uh;
   7348 	size_t len;
   7349 	ip_t *ip;
   7350 
   7351 	if ((np->in_redir & NAT_DIVERTUDP) != 0)
   7352 		len = sizeof(ip_t) + sizeof(udphdr_t);
   7353 	else
   7354 		len = sizeof(ip_t);
   7355 
   7356 	ALLOC_MB_T(np->in_divmp, len);
   7357 	if (np->in_divmp == NULL) {
   7358 		NBUMPD(ipf_nat_stats, ns_divert_build);
   7359 		return -1;
   7360 	}
   7361 
   7362 	/*
   7363 	 * First, the header to get the packet diverted to the new destination
   7364 	 */
   7365 	ip = MTOD(np->in_divmp, ip_t *);
   7366 	IP_V_A(ip, 4);
   7367 	IP_HL_A(ip, 5);
   7368 	ip->ip_tos = 0;
   7369 	if ((np->in_redir & NAT_DIVERTUDP) != 0)
   7370 		ip->ip_p = IPPROTO_UDP;
   7371 	else
   7372 		ip->ip_p = IPPROTO_IPIP;
   7373 	ip->ip_ttl = 255;
   7374 	ip->ip_off = 0;
   7375 	ip->ip_sum = 0;
   7376 	ip->ip_len = htons(len);
   7377 	ip->ip_id = 0;
   7378 	ip->ip_src.s_addr = htonl(np->in_snip);
   7379 	ip->ip_dst.s_addr = htonl(np->in_dnip);
   7380 	ip->ip_sum = ipf_cksum((u_short *)ip, sizeof(*ip));
   7381 
   7382 	if (np->in_redir & NAT_DIVERTUDP) {
   7383 		uh = (udphdr_t *)(ip + 1);
   7384 		uh->uh_sum = 0;
   7385 		uh->uh_ulen = 8;
   7386 		uh->uh_sport = htons(np->in_spnext);
   7387 		uh->uh_dport = htons(np->in_dpnext);
   7388 	}
   7389 
   7390 	return 0;
   7391 }
   7392 
   7393 
   7394 #define	MINDECAP	(sizeof(ip_t) + sizeof(udphdr_t) + sizeof(ip_t))
   7395 
   7396 /* ------------------------------------------------------------------------ */
   7397 /* Function:    nat_decap                                                   */
   7398 /* Returns:     int - -1 == error, 0 == success                             */
   7399 /* Parameters:  fin(I) - pointer to packet information                      */
   7400 /*              nat(I) - pointer to current NAT session                     */
   7401 /*                                                                          */
   7402 /* This function is responsible for undoing a packet's encapsulation in the */
   7403 /* reverse of an encap/divert rule.  After removing the outer encapsulation */
   7404 /* it is necessary to call ipf_makefrip() again so that the contents of 'fin'*/
   7405 /* match the "new" packet as it may still be used by IPFilter elsewhere.    */
   7406 /* We use "dir" here as the basis for some of the expectations about the    */
   7407 /* outer header.  If we return an error, the goal is to leave the original  */
   7408 /* packet information undisturbed - this falls short at the end where we'd  */
   7409 /* need to back a backup copy of "fin" - expensive.                         */
   7410 /* ------------------------------------------------------------------------ */
   7411 static int
   7412 ipf_nat_decap(fin, nat)
   7413 	fr_info_t *fin;
   7414 	nat_t *nat;
   7415 {
   7416 	ipf_main_softc_t *softc = fin->fin_main_soft;
   7417 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   7418 	char *hdr;
   7419 	int hlen;
   7420 	int skip;
   7421 	mb_t *m;
   7422 
   7423 	if ((fin->fin_flx & FI_ICMPERR) != 0) {
   7424 		/*
   7425 		 * ICMP packets don't get decapsulated, instead what we need
   7426 		 * to do is change the ICMP reply from including (in the data
   7427 		 * portion for errors) the encapsulated packet that we sent
   7428 		 * out to something that resembles the original packet prior
   7429 		 * to encapsulation.  This isn't done here - all we're doing
   7430 		 * here is changing the outer address to ensure that it gets
   7431 		 * targetted back to the correct system.
   7432 		 */
   7433 
   7434 		if (nat->nat_dir & NAT_OUTBOUND) {
   7435 			u_32_t sum1, sum2, sumd;
   7436 
   7437 			sum1 = ntohl(fin->fin_daddr);
   7438 			sum2 = ntohl(nat->nat_osrcaddr);
   7439 			CALC_SUMD(sum1, sum2, sumd);
   7440 			fin->fin_ip->ip_dst = nat->nat_osrcip;
   7441 			fin->fin_daddr = nat->nat_osrcaddr;
   7442 #if !defined(_KERNEL) || defined(MENTAT) || defined(__sgi) || \
   7443      defined(__osf__) || defined(linux)
   7444 			ipf_fix_outcksum(0, &fin->fin_ip->ip_sum, sumd, 0);
   7445 #endif
   7446 		}
   7447 		return 0;
   7448 	}
   7449 
   7450 	m = fin->fin_m;
   7451 	skip = fin->fin_hlen;
   7452 
   7453 	switch (nat->nat_dir)
   7454 	{
   7455 	case NAT_DIVERTIN :
   7456 	case NAT_DIVERTOUT :
   7457 		if (fin->fin_plen < MINDECAP)
   7458 			return -1;
   7459 		skip += sizeof(udphdr_t);
   7460 		break;
   7461 
   7462 	case NAT_ENCAPIN :
   7463 	case NAT_ENCAPOUT :
   7464 		if (fin->fin_plen < (skip + sizeof(ip_t)))
   7465 			return -1;
   7466 		break;
   7467 	default :
   7468 		return -1;
   7469 		/* NOTREACHED */
   7470 	}
   7471 
   7472 	/*
   7473 	 * The aim here is to keep the original packet details in "fin" for
   7474 	 * as long as possible so that returning with an error is for the
   7475 	 * original packet and there is little undoing work to do.
   7476 	 */
   7477 	if (M_LEN(m) < skip + sizeof(ip_t)) {
   7478 		if (ipf_pr_pullup(fin, skip + sizeof(ip_t)) == -1)
   7479 			return -1;
   7480 	}
   7481 
   7482 	hdr = MTOD(fin->fin_m, char *);
   7483 	fin->fin_ip = (ip_t *)(hdr + skip);
   7484 	hlen = IP_HL(fin->fin_ip) << 2;
   7485 
   7486 	if (ipf_pr_pullup(fin, skip + hlen) == -1) {
   7487 		NBUMPSIDED(fin->fin_out, ns_decap_pullup);
   7488 		return -1;
   7489 	}
   7490 
   7491 	fin->fin_hlen = hlen;
   7492 	fin->fin_dlen -= skip;
   7493 	fin->fin_plen -= skip;
   7494 	fin->fin_ipoff += skip;
   7495 
   7496 	if (ipf_makefrip(hlen, (ip_t *)hdr, fin) == -1) {
   7497 		NBUMPSIDED(fin->fin_out, ns_decap_bad);
   7498 		return -1;
   7499 	}
   7500 
   7501 	return skip;
   7502 }
   7503 
   7504 
   7505 /* ------------------------------------------------------------------------ */
   7506 /* Function:    nat_nextaddr                                                */
   7507 /* Returns:     int - -1 == bad input (no new address),                     */
   7508 /*                     0 == success and dst has new address                 */
   7509 /* Parameters:  fin(I) - pointer to packet information                      */
   7510 /*              na(I)  - how to generate new address                        */
   7511 /*              old(I) - original address being replaced                    */
   7512 /*              dst(O) - where to put the new address                       */
   7513 /* Write Lock:  ipf_nat                                                     */
   7514 /*                                                                          */
   7515 /* This function uses the contents of the "na" structure, in combination    */
   7516 /* with "old" to produce a new address to store in "dst".  Not all of the   */
   7517 /* possible uses of "na" will result in a new address.                      */
   7518 /* ------------------------------------------------------------------------ */
   7519 static int
   7520 ipf_nat_nextaddr(fin, na, old, dst)
   7521 	fr_info_t *fin;
   7522 	nat_addr_t *na;
   7523 	u_32_t *old, *dst;
   7524 {
   7525 	ipf_main_softc_t *softc = fin->fin_main_soft;
   7526 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   7527 	u_32_t amin, amax, new;
   7528 	i6addr_t newip;
   7529 	int error;
   7530 
   7531 	new = 0;
   7532 	amin = na->na_addr[0].in4.s_addr;
   7533 
   7534 	switch (na->na_atype)
   7535 	{
   7536 	case FRI_RANGE :
   7537 		amax = na->na_addr[1].in4.s_addr;
   7538 		break;
   7539 
   7540 	case FRI_NETMASKED :
   7541 	case FRI_DYNAMIC :
   7542 	case FRI_NORMAL :
   7543 		/*
   7544 		 * Compute the maximum address by adding the inverse of the
   7545 		 * netmask to the minimum address.
   7546 		 */
   7547 		amax = ~na->na_addr[1].in4.s_addr;
   7548 		amax |= amin;
   7549 		break;
   7550 
   7551 	case FRI_LOOKUP :
   7552 		break;
   7553 
   7554 	case FRI_BROADCAST :
   7555 	case FRI_PEERADDR :
   7556 	case FRI_NETWORK :
   7557 	default :
   7558 		return -1;
   7559 	}
   7560 
   7561 	error = -1;
   7562 
   7563 	if (na->na_atype == FRI_LOOKUP) {
   7564 		if (na->na_type == IPLT_DSTLIST) {
   7565 			error = ipf_dstlist_select_node(fin, na->na_ptr, dst,
   7566 							NULL);
   7567 		} else {
   7568 			NBUMPSIDE(fin->fin_out, ns_badnextaddr);
   7569 		}
   7570 
   7571 	} else if (na->na_atype == IPLT_NONE) {
   7572 		/*
   7573 		 * 0/0 as the new address means leave it alone.
   7574 		 */
   7575 		if (na->na_addr[0].in4.s_addr == 0 &&
   7576 		    na->na_addr[1].in4.s_addr == 0) {
   7577 			new = *old;
   7578 
   7579 		/*
   7580 		 * 0/32 means get the interface's address
   7581 		 */
   7582 		} else if (na->na_addr[0].in4.s_addr == 0 &&
   7583 			   na->na_addr[1].in4.s_addr == 0xffffffff) {
   7584 			if (ipf_ifpaddr(softc, 4, na->na_atype,
   7585 					fin->fin_ifp, &newip, NULL) == -1) {
   7586 				NBUMPSIDED(fin->fin_out, ns_ifpaddrfail);
   7587 				return -1;
   7588 			}
   7589 			new = newip.in4.s_addr;
   7590 		} else {
   7591 			new = htonl(na->na_nextip);
   7592 		}
   7593 		*dst = new;
   7594 		error = 0;
   7595 
   7596 	} else {
   7597 		NBUMPSIDE(fin->fin_out, ns_badnextaddr);
   7598 	}
   7599 
   7600 	return error;
   7601 }
   7602 
   7603 
   7604 /* ------------------------------------------------------------------------ */
   7605 /* Function:    nat_nextaddrinit                                            */
   7606 /* Returns:     int - 0 == success, else error number                       */
   7607 /* Parameters:  softc(I) - pointer to soft context main structure           */
   7608 /*              na(I)      - NAT address information for generating new addr*/
   7609 /*              initial(I) - flag indicating if it is the first call for    */
   7610 /*                           this "na" structure.                           */
   7611 /*              ifp(I)     - network interface to derive address            */
   7612 /*                           information from.                              */
   7613 /*                                                                          */
   7614 /* This function is expected to be called in two scenarious: when a new NAT */
   7615 /* rule is loaded into the kernel and when the list of NAT rules is sync'd  */
   7616 /* up with the valid network interfaces (possibly due to them changing.)    */
   7617 /* To distinguish between these, the "initial" parameter is used.  If it is */
   7618 /* 1 then this indicates the rule has just been reloaded and 0 for when we  */
   7619 /* are updating information.  This difference is important because in       */
   7620 /* instances where we are not updating address information associated with  */
   7621 /* a network interface, we don't want to disturb what the "next" address to */
   7622 /* come out of ipf_nat_nextaddr() will be.                                  */
   7623 /* ------------------------------------------------------------------------ */
   7624 static int
   7625 ipf_nat_nextaddrinit(softc, base, na, initial, ifp)
   7626 	ipf_main_softc_t *softc;
   7627 	char *base;
   7628 	nat_addr_t *na;
   7629 	int initial;
   7630 	void *ifp;
   7631 {
   7632 
   7633 	switch (na->na_atype)
   7634 	{
   7635 	case FRI_LOOKUP :
   7636 		if (na->na_subtype == 0) {
   7637 			na->na_ptr = ipf_lookup_res_num(softc, IPL_LOGNAT,
   7638 							na->na_type,
   7639 							na->na_num,
   7640 							&na->na_func);
   7641 		} else if (na->na_subtype == 1) {
   7642 			na->na_ptr = ipf_lookup_res_name(softc, IPL_LOGNAT,
   7643 							 na->na_type,
   7644 							 base + na->na_num,
   7645 							 &na->na_func);
   7646 		}
   7647 		if (na->na_func == NULL) {
   7648 			IPFERROR(60060);
   7649 			return ESRCH;
   7650 		}
   7651 		if (na->na_ptr == NULL) {
   7652 			IPFERROR(60056);
   7653 			return ESRCH;
   7654 		}
   7655 		break;
   7656 
   7657 	case FRI_DYNAMIC :
   7658 	case FRI_BROADCAST :
   7659 	case FRI_NETWORK :
   7660 	case FRI_NETMASKED :
   7661 	case FRI_PEERADDR :
   7662 		if (ifp != NULL)
   7663 			(void )ipf_ifpaddr(softc, 4, na->na_atype, ifp,
   7664 					   &na->na_addr[0], &na->na_addr[1]);
   7665 		break;
   7666 
   7667 	case FRI_SPLIT :
   7668 	case FRI_RANGE :
   7669 		if (initial)
   7670 			na->na_nextip = ntohl(na->na_addr[0].in4.s_addr);
   7671 		break;
   7672 
   7673 	case FRI_NONE :
   7674 		na->na_addr[0].in4.s_addr &= na->na_addr[1].in4.s_addr;
   7675 		return 0;
   7676 
   7677 	case FRI_NORMAL :
   7678 		na->na_addr[0].in4.s_addr &= na->na_addr[1].in4.s_addr;
   7679 		break;
   7680 
   7681 	default :
   7682 		IPFERROR(60054);
   7683 		return EINVAL;
   7684 	}
   7685 
   7686 	if (initial && (na->na_atype == FRI_NORMAL)) {
   7687 		if (na->na_addr[0].in4.s_addr == 0) {
   7688 			if ((na->na_addr[1].in4.s_addr == 0xffffffff) ||
   7689 			    (na->na_addr[1].in4.s_addr == 0)) {
   7690 				return 0;
   7691 			}
   7692 		}
   7693 
   7694 		if (na->na_addr[1].in4.s_addr == 0xffffffff) {
   7695 			na->na_nextip = ntohl(na->na_addr[0].in4.s_addr);
   7696 		} else {
   7697 			na->na_nextip = ntohl(na->na_addr[0].in4.s_addr) + 1;
   7698 		}
   7699 	}
   7700 
   7701 	return 0;
   7702 }
   7703 
   7704 
   7705 /* ------------------------------------------------------------------------ */
   7706 /* Function:    ipf_nat_matchflush                                          */
   7707 /* Returns:     int - -1 == error, 0 == success                             */
   7708 /* Parameters:  softc(I) - pointer to soft context main structure           */
   7709 /*              softn(I) - pointer to NAT context structure                 */
   7710 /*              nat(I)   - pointer to current NAT session                   */
   7711 /*                                                                          */
   7712 /* ------------------------------------------------------------------------ */
   7713 static int
   7714 ipf_nat_matchflush(softc, softn, data)
   7715 	ipf_main_softc_t *softc;
   7716 	ipf_nat_softc_t *softn;
   7717 	caddr_t data;
   7718 {
   7719 	int *array, flushed, error;
   7720 	nat_t *nat, *natnext;
   7721 	ipfobj_t obj;
   7722 
   7723 	error = ipf_matcharray_load(softc, data, &obj, &array);
   7724 	if (error != 0)
   7725 		return error;
   7726 
   7727 	flushed = 0;
   7728 
   7729 	for (nat = softn->ipf_nat_instances; nat != NULL; nat = natnext) {
   7730 		natnext = nat->nat_next;
   7731 		if (ipf_nat_matcharray(nat, array, softc->ipf_ticks) == 0) {
   7732 			ipf_nat_delete(softc, nat, NL_FLUSH);
   7733 			flushed++;
   7734 		}
   7735 	}
   7736 
   7737 	obj.ipfo_retval = flushed;
   7738 	error = BCOPYOUT(&obj, data, sizeof(obj));
   7739 
   7740 	KFREES(array, array[0] * sizeof(*array));
   7741 
   7742 	return error;
   7743 }
   7744 
   7745 
   7746 /* ------------------------------------------------------------------------ */
   7747 /* Function:    ipf_nat_matcharray                                          */
   7748 /* Returns:     int - -1 == error, 0 == success                             */
   7749 /* Parameters:  fin(I) - pointer to packet information                      */
   7750 /*              nat(I) - pointer to current NAT session                     */
   7751 /*                                                                          */
   7752 /* ------------------------------------------------------------------------ */
   7753 static int
   7754 ipf_nat_matcharray(nat, array, ticks)
   7755 	nat_t *nat;
   7756 	int *array;
   7757 	u_long ticks;
   7758 {
   7759 	int i, n, *x, e, p;
   7760 
   7761 	e = 0;
   7762 	n = array[0];
   7763 	x = array + 1;
   7764 
   7765 	for (; n > 0; x += 3 + x[2]) {
   7766 		if (x[0] == IPF_EXP_END)
   7767 			break;
   7768 		e = 0;
   7769 
   7770 		n -= x[2] + 3;
   7771 		if (n < 0)
   7772 			break;
   7773 
   7774 		p = x[0] >> 16;
   7775 		if (p != 0 && p != nat->nat_pr[1])
   7776 			break;
   7777 
   7778 		switch (x[0])
   7779 		{
   7780 		case IPF_EXP_IP_PR :
   7781 			for (i = 0; !e && i < x[2]; i++) {
   7782 				e |= (nat->nat_pr[1] == x[i + 3]);
   7783 			}
   7784 			break;
   7785 
   7786 		case IPF_EXP_IP_SRCADDR :
   7787 			if (nat->nat_v[0] == 4) {
   7788 				for (i = 0; !e && i < x[2]; i++) {
   7789 					e |= ((nat->nat_osrcaddr & x[i + 4]) ==
   7790 					      x[i + 3]);
   7791 				}
   7792 			}
   7793 			if (nat->nat_v[1] == 4) {
   7794 				for (i = 0; !e && i < x[2]; i++) {
   7795 					e |= ((nat->nat_nsrcaddr & x[i + 4]) ==
   7796 					      x[i + 3]);
   7797 				}
   7798 			}
   7799 			break;
   7800 
   7801 		case IPF_EXP_IP_DSTADDR :
   7802 			if (nat->nat_v[0] == 4) {
   7803 				for (i = 0; !e && i < x[2]; i++) {
   7804 					e |= ((nat->nat_odstaddr & x[i + 4]) ==
   7805 					      x[i + 3]);
   7806 				}
   7807 			}
   7808 			if (nat->nat_v[1] == 4) {
   7809 				for (i = 0; !e && i < x[2]; i++) {
   7810 					e |= ((nat->nat_ndstaddr & x[i + 4]) ==
   7811 					      x[i + 3]);
   7812 				}
   7813 			}
   7814 			break;
   7815 
   7816 		case IPF_EXP_IP_ADDR :
   7817 			for (i = 0; !e && i < x[2]; i++) {
   7818 				if (nat->nat_v[0] == 4) {
   7819 					e |= ((nat->nat_osrcaddr & x[i + 4]) ==
   7820 					      x[i + 3]);
   7821 				}
   7822 				if (nat->nat_v[1] == 4) {
   7823 					e |= ((nat->nat_nsrcaddr & x[i + 4]) ==
   7824 					      x[i + 3]);
   7825 				}
   7826 				if (nat->nat_v[0] == 4) {
   7827 					e |= ((nat->nat_odstaddr & x[i + 4]) ==
   7828 					      x[i + 3]);
   7829 				}
   7830 				if (nat->nat_v[1] == 4) {
   7831 					e |= ((nat->nat_ndstaddr & x[i + 4]) ==
   7832 					      x[i + 3]);
   7833 				}
   7834 			}
   7835 			break;
   7836 
   7837 #ifdef USE_INET6
   7838 		case IPF_EXP_IP6_SRCADDR :
   7839 			if (nat->nat_v[0] == 6) {
   7840 				for (i = 0; !e && i < x[3]; i++) {
   7841 					e |= IP6_MASKEQ(&nat->nat_osrc6,
   7842 							x + i + 7, x + i + 3);
   7843 				}
   7844 			}
   7845 			if (nat->nat_v[1] == 6) {
   7846 				for (i = 0; !e && i < x[3]; i++) {
   7847 					e |= IP6_MASKEQ(&nat->nat_nsrc6,
   7848 							x + i + 7, x + i + 3);
   7849 				}
   7850 			}
   7851 			break;
   7852 
   7853 		case IPF_EXP_IP6_DSTADDR :
   7854 			if (nat->nat_v[0] == 6) {
   7855 				for (i = 0; !e && i < x[3]; i++) {
   7856 					e |= IP6_MASKEQ(&nat->nat_odst6,
   7857 							x + i + 7,
   7858 							x + i + 3);
   7859 				}
   7860 			}
   7861 			if (nat->nat_v[1] == 6) {
   7862 				for (i = 0; !e && i < x[3]; i++) {
   7863 					e |= IP6_MASKEQ(&nat->nat_ndst6,
   7864 							x + i + 7,
   7865 							x + i + 3);
   7866 				}
   7867 			}
   7868 			break;
   7869 
   7870 		case IPF_EXP_IP6_ADDR :
   7871 			for (i = 0; !e && i < x[3]; i++) {
   7872 				if (nat->nat_v[0] == 6) {
   7873 					e |= IP6_MASKEQ(&nat->nat_osrc6,
   7874 							x + i + 7,
   7875 							x + i + 3);
   7876 				}
   7877 				if (nat->nat_v[0] == 6) {
   7878 					e |= IP6_MASKEQ(&nat->nat_odst6,
   7879 							x + i + 7,
   7880 							x + i + 3);
   7881 				}
   7882 				if (nat->nat_v[1] == 6) {
   7883 					e |= IP6_MASKEQ(&nat->nat_nsrc6,
   7884 							x + i + 7,
   7885 							x + i + 3);
   7886 				}
   7887 				if (nat->nat_v[1] == 6) {
   7888 					e |= IP6_MASKEQ(&nat->nat_ndst6,
   7889 							x + i + 7,
   7890 							x + i + 3);
   7891 				}
   7892 			}
   7893 			break;
   7894 #endif
   7895 
   7896 		case IPF_EXP_UDP_PORT :
   7897 		case IPF_EXP_TCP_PORT :
   7898 			for (i = 0; !e && i < x[2]; i++) {
   7899 				e |= (nat->nat_nsport == x[i + 3]) ||
   7900 				     (nat->nat_ndport == x[i + 3]);
   7901 			}
   7902 			break;
   7903 
   7904 		case IPF_EXP_UDP_SPORT :
   7905 		case IPF_EXP_TCP_SPORT :
   7906 			for (i = 0; !e && i < x[2]; i++) {
   7907 				e |= (nat->nat_nsport == x[i + 3]);
   7908 			}
   7909 			break;
   7910 
   7911 		case IPF_EXP_UDP_DPORT :
   7912 		case IPF_EXP_TCP_DPORT :
   7913 			for (i = 0; !e && i < x[2]; i++) {
   7914 				e |= (nat->nat_ndport == x[i + 3]);
   7915 			}
   7916 			break;
   7917 
   7918 		case IPF_EXP_TCP_STATE :
   7919 			for (i = 0; !e && i < x[2]; i++) {
   7920 				e |= (nat->nat_tcpstate[0] == x[i + 3]) ||
   7921 				     (nat->nat_tcpstate[1] == x[i + 3]);
   7922 			}
   7923 			break;
   7924 
   7925 		case IPF_EXP_IDLE_GT :
   7926 			e |= (ticks - nat->nat_touched > x[3]);
   7927 			break;
   7928 		}
   7929 		e ^= x[1];
   7930 
   7931 		if (!e)
   7932 			break;
   7933 	}
   7934 
   7935 	return e;
   7936 }
   7937 
   7938 
   7939 /* ------------------------------------------------------------------------ */
   7940 /* Function:    ipf_nat_gettable                                            */
   7941 /* Returns:     int     - 0 = success, else error                           */
   7942 /* Parameters:  softc(I) - pointer to soft context main structure           */
   7943 /*              softn(I) - pointer to NAT context structure                 */
   7944 /*              data(I)  - pointer to ioctl data                            */
   7945 /*                                                                          */
   7946 /* This function handles ioctl requests for tables of nat information.      */
   7947 /* At present the only table it deals with is the hash bucket statistics.   */
   7948 /* ------------------------------------------------------------------------ */
   7949 static int
   7950 ipf_nat_gettable(softc, softn, data)
   7951 	ipf_main_softc_t *softc;
   7952 	ipf_nat_softc_t *softn;
   7953 	char *data;
   7954 {
   7955 	ipftable_t table;
   7956 	int error;
   7957 
   7958 	error = ipf_inobj(softc, data, NULL, &table, IPFOBJ_GTABLE);
   7959 	if (error != 0)
   7960 		return error;
   7961 
   7962 	switch (table.ita_type)
   7963 	{
   7964 	case IPFTABLE_BUCKETS_NATIN :
   7965 		error = COPYOUT(softn->ipf_nat_stats.ns_side[0].ns_bucketlen,
   7966 				table.ita_table,
   7967 				softn->ipf_nat_table_sz * sizeof(u_int));
   7968 		break;
   7969 
   7970 	case IPFTABLE_BUCKETS_NATOUT :
   7971 		error = COPYOUT(softn->ipf_nat_stats.ns_side[1].ns_bucketlen,
   7972 				table.ita_table,
   7973 				softn->ipf_nat_table_sz * sizeof(u_int));
   7974 		break;
   7975 
   7976 	default :
   7977 		IPFERROR(60058);
   7978 		return EINVAL;
   7979 	}
   7980 
   7981 	if (error != 0) {
   7982 		IPFERROR(60059);
   7983 		error = EFAULT;
   7984 	}
   7985 	return error;
   7986 }
   7987 
   7988 
   7989 /* ------------------------------------------------------------------------ */
   7990 /* Function:    ipf_nat_settimeout                                          */
   7991 /* Returns:     int  - 0 = success, else failure			    */
   7992 /* Parameters:  softc(I) - pointer to soft context main structure           */
   7993 /*              t(I) - pointer to tunable                                   */
   7994 /*              p(I) - pointer to new tuning data                           */
   7995 /*                                                                          */
   7996 /* Apply the timeout change to the NAT timeout queues.                      */
   7997 /* ------------------------------------------------------------------------ */
   7998 int
   7999 ipf_nat_settimeout(softc, t, p)
   8000 	struct ipf_main_softc_s *softc;
   8001 	ipftuneable_t *t;
   8002 	ipftuneval_t *p;
   8003 {
   8004 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   8005 
   8006 	if (!strncmp(t->ipft_name, "tcp_", 4))
   8007 		return ipf_settimeout_tcp(t, p, softn->ipf_nat_tcptq);
   8008 
   8009 	if (!strcmp(t->ipft_name, "udp_timeout")) {
   8010 		ipf_apply_timeout(&softn->ipf_nat_udptq, p->ipftu_int);
   8011 	} else if (!strcmp(t->ipft_name, "udp_ack_timeout")) {
   8012 		ipf_apply_timeout(&softn->ipf_nat_udpacktq, p->ipftu_int);
   8013 	} else if (!strcmp(t->ipft_name, "icmp_timeout")) {
   8014 		ipf_apply_timeout(&softn->ipf_nat_icmptq, p->ipftu_int);
   8015 	} else if (!strcmp(t->ipft_name, "icmp_ack_timeout")) {
   8016 		ipf_apply_timeout(&softn->ipf_nat_icmpacktq, p->ipftu_int);
   8017 	} else if (!strcmp(t->ipft_name, "ip_timeout")) {
   8018 		ipf_apply_timeout(&softn->ipf_nat_iptq, p->ipftu_int);
   8019 	} else {
   8020 		IPFERROR(60062);
   8021 		return ESRCH;
   8022 	}
   8023 	return 0;
   8024 }
   8025 
   8026 
   8027 /* ------------------------------------------------------------------------ */
   8028 /* Function:    ipf_nat_rehash                                              */
   8029 /* Returns:     int  - 0 = success, else failure			    */
   8030 /* Parameters:  softc(I) - pointer to soft context main structure           */
   8031 /*              t(I) - pointer to tunable                                   */
   8032 /*              p(I) - pointer to new tuning data                           */
   8033 /*                                                                          */
   8034 /* To change the size of the basic NAT table, we need to first allocate the */
   8035 /* new tables (lest it fails and we've got nowhere to store all of the NAT  */
   8036 /* sessions currently active) and then walk through the entire list and     */
   8037 /* insert them into the table.  There are two tables here: an inbound one   */
   8038 /* and an outbound one.  Each NAT entry goes into each table once.          */
   8039 /* ------------------------------------------------------------------------ */
   8040 int
   8041 ipf_nat_rehash(softc, t, p)
   8042 	ipf_main_softc_t *softc;
   8043 	ipftuneable_t *t;
   8044 	ipftuneval_t *p;
   8045 {
   8046 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   8047 	nat_t **newtab[2], *nat, **natp;
   8048 	u_int *bucketlens[2];
   8049 	u_int maxbucket;
   8050 	u_int newsize;
   8051 	int error;
   8052 	u_int hv;
   8053 	int i;
   8054 
   8055 	newsize = p->ipftu_int;
   8056 	/*
   8057 	 * In case there is nothing to do...
   8058 	 */
   8059 	if (newsize == softn->ipf_nat_table_sz)
   8060 		return 0;
   8061 
   8062 	newtab[0] = NULL;
   8063 	newtab[1] = NULL;
   8064 	bucketlens[0] = NULL;
   8065 	bucketlens[1] = NULL;
   8066 	/*
   8067 	 * 4 tables depend on the NAT table size: the inbound looking table,
   8068 	 * the outbound lookup table and the hash chain length for each.
   8069 	 */
   8070 	KMALLOCS(newtab[0], nat_t **, newsize * sizeof(nat_t *));
   8071 	if (newtab == NULL) {
   8072 		error = 60063;
   8073 		goto badrehash;
   8074 	}
   8075 
   8076 	KMALLOCS(newtab[1], nat_t **, newsize * sizeof(nat_t *));
   8077 	if (newtab == NULL) {
   8078 		error = 60064;
   8079 		goto badrehash;
   8080 	}
   8081 
   8082 	KMALLOCS(bucketlens[0], u_int *, newsize * sizeof(u_int));
   8083 	if (bucketlens[0] == NULL) {
   8084 		error = 60065;
   8085 		goto badrehash;
   8086 	}
   8087 
   8088 	KMALLOCS(bucketlens[1], u_int *, newsize * sizeof(u_int));
   8089 	if (bucketlens[1] == NULL) {
   8090 		error = 60066;
   8091 		goto badrehash;
   8092 	}
   8093 
   8094 	/*
   8095 	 * Recalculate the maximum length based on the new size.
   8096 	 */
   8097 	for (maxbucket = 0, i = newsize; i > 0; i >>= 1)
   8098 		maxbucket++;
   8099 	maxbucket *= 2;
   8100 
   8101 	bzero((char *)newtab[0], newsize * sizeof(nat_t *));
   8102 	bzero((char *)newtab[1], newsize * sizeof(nat_t *));
   8103 	bzero((char *)bucketlens[0], newsize * sizeof(u_int));
   8104 	bzero((char *)bucketlens[1], newsize * sizeof(u_int));
   8105 
   8106 	WRITE_ENTER(&softc->ipf_nat);
   8107 
   8108 	if (softn->ipf_nat_table[0] != NULL) {
   8109 		KFREES(softn->ipf_nat_table[0],
   8110 		       softn->ipf_nat_table_sz *
   8111 		       sizeof(*softn->ipf_nat_table[0]));
   8112 	}
   8113 	softn->ipf_nat_table[0] = newtab[0];
   8114 
   8115 	if (softn->ipf_nat_table[1] != NULL) {
   8116 		KFREES(softn->ipf_nat_table[1],
   8117 		       softn->ipf_nat_table_sz *
   8118 		       sizeof(*softn->ipf_nat_table[1]));
   8119 	}
   8120 	softn->ipf_nat_table[1] = newtab[1];
   8121 
   8122 	if (softn->ipf_nat_stats.ns_side[0].ns_bucketlen != NULL) {
   8123 		KFREES(softn->ipf_nat_stats.ns_side[0].ns_bucketlen,
   8124 		       softn->ipf_nat_table_sz * sizeof(u_int));
   8125 	}
   8126 	softn->ipf_nat_stats.ns_side[0].ns_bucketlen = bucketlens[0];
   8127 
   8128 	if (softn->ipf_nat_stats.ns_side[1].ns_bucketlen != NULL) {
   8129 		KFREES(softn->ipf_nat_stats.ns_side[1].ns_bucketlen,
   8130 		       softn->ipf_nat_table_sz * sizeof(u_int));
   8131 	}
   8132 	softn->ipf_nat_stats.ns_side[1].ns_bucketlen = bucketlens[1];
   8133 
   8134 	if (softn->ipf_nat_stats.ns_side6[0].ns_bucketlen != NULL) {
   8135 		KFREES(softn->ipf_nat_stats.ns_side6[0].ns_bucketlen,
   8136 		       softn->ipf_nat_table_sz * sizeof(u_int));
   8137 	}
   8138 	softn->ipf_nat_stats.ns_side6[0].ns_bucketlen = bucketlens[0];
   8139 
   8140 	if (softn->ipf_nat_stats.ns_side6[1].ns_bucketlen != NULL) {
   8141 		KFREES(softn->ipf_nat_stats.ns_side6[1].ns_bucketlen,
   8142 		       softn->ipf_nat_table_sz * sizeof(u_int));
   8143 	}
   8144 	softn->ipf_nat_stats.ns_side6[1].ns_bucketlen = bucketlens[1];
   8145 
   8146 	softn->ipf_nat_maxbucket = maxbucket;
   8147 	softn->ipf_nat_table_sz = newsize;
   8148 	/*
   8149 	 * Walk through the entire list of NAT table entries and put them
   8150 	 * in the new NAT table, somewhere.  Because we have a new table,
   8151 	 * we need to restart the counter of how many chains are in use.
   8152 	 */
   8153 	softn->ipf_nat_stats.ns_side[0].ns_inuse = 0;
   8154 	softn->ipf_nat_stats.ns_side[1].ns_inuse = 0;
   8155 	softn->ipf_nat_stats.ns_side6[0].ns_inuse = 0;
   8156 	softn->ipf_nat_stats.ns_side6[1].ns_inuse = 0;
   8157 
   8158 	for (nat = softn->ipf_nat_instances; nat != NULL; nat = nat->nat_next) {
   8159 		nat->nat_hnext[0] = NULL;
   8160 		nat->nat_phnext[0] = NULL;
   8161 		hv = nat->nat_hv[0] % softn->ipf_nat_table_sz;
   8162 
   8163 		natp = &softn->ipf_nat_table[0][hv];
   8164 		if (*natp) {
   8165 			(*natp)->nat_phnext[0] = &nat->nat_hnext[0];
   8166 		} else {
   8167 			NBUMPSIDE(0, ns_inuse);
   8168 		}
   8169 		nat->nat_phnext[0] = natp;
   8170 		nat->nat_hnext[0] = *natp;
   8171 		*natp = nat;
   8172 		NBUMPSIDE(0, ns_bucketlen[hv]);
   8173 
   8174 		nat->nat_hnext[1] = NULL;
   8175 		nat->nat_phnext[1] = NULL;
   8176 		hv = nat->nat_hv[1] % softn->ipf_nat_table_sz;
   8177 
   8178 		natp = &softn->ipf_nat_table[1][hv];
   8179 		if (*natp) {
   8180 			(*natp)->nat_phnext[1] = &nat->nat_hnext[1];
   8181 		} else {
   8182 			NBUMPSIDE(1, ns_inuse);
   8183 		}
   8184 		nat->nat_phnext[1] = natp;
   8185 		nat->nat_hnext[1] = *natp;
   8186 		*natp = nat;
   8187 		NBUMPSIDE(1, ns_bucketlen[hv]);
   8188 	}
   8189 	RWLOCK_EXIT(&softc->ipf_nat);
   8190 
   8191 	return 0;
   8192 
   8193 badrehash:
   8194 	if (bucketlens[1] != NULL) {
   8195 		KFREES(bucketlens[0], newsize * sizeof(u_int));
   8196 	}
   8197 	if (bucketlens[0] != NULL) {
   8198 		KFREES(bucketlens[0], newsize * sizeof(u_int));
   8199 	}
   8200 	if (newtab[0] != NULL) {
   8201 		KFREES(newtab[0], newsize * sizeof(nat_t *));
   8202 	}
   8203 	if (newtab[1] != NULL) {
   8204 		KFREES(newtab[1], newsize * sizeof(nat_t *));
   8205 	}
   8206 	IPFERROR(error);
   8207 	return ENOMEM;
   8208 }
   8209 
   8210 
   8211 /* ------------------------------------------------------------------------ */
   8212 /* Function:    ipf_nat_rehash_rules                                        */
   8213 /* Returns:     int  - 0 = success, else failure			    */
   8214 /* Parameters:  softc(I) - pointer to soft context main structure           */
   8215 /*              t(I) - pointer to tunable                                   */
   8216 /*              p(I) - pointer to new tuning data                           */
   8217 /*                                                                          */
   8218 /* All of the NAT rules hang off of a hash table that is searched with a    */
   8219 /* hash on address after the netmask is applied.  There is a different table*/
   8220 /* for both inbound rules (rdr) and outbound (map.)  The resizing will only */
   8221 /* affect one of these two tables.                                          */
   8222 /* ------------------------------------------------------------------------ */
   8223 int
   8224 ipf_nat_rehash_rules(softc, t, p)
   8225 	ipf_main_softc_t *softc;
   8226 	ipftuneable_t *t;
   8227 	ipftuneval_t *p;
   8228 {
   8229 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   8230 	ipnat_t **newtab, *np, ***old, **npp;
   8231 	u_int newsize;
   8232 	u_int mask;
   8233 	u_int hv;
   8234 
   8235 	newsize = p->ipftu_int;
   8236 	/*
   8237 	 * In case there is nothing to do...
   8238 	 */
   8239 	if (newsize == *t->ipft_pint)
   8240 		return 0;
   8241 
   8242 	/*
   8243 	 * All inbound rules have the NAT_REDIRECT bit set in in_redir and
   8244 	 * all outbound rules have either NAT_MAP or MAT_MAPBLK set.
   8245 	 * This if statement allows for some more generic code to be below,
   8246 	 * rather than two huge gobs of code that almost do the same thing.
   8247 	 */
   8248 	if (t->ipft_pint == &softn->ipf_nat_rdrrules_sz) {
   8249 		old = &softn->ipf_nat_rdr_rules;
   8250 		mask = NAT_REDIRECT;
   8251 	} else {
   8252 		old = &softn->ipf_nat_map_rules;
   8253 		mask = NAT_MAP|NAT_MAPBLK;
   8254 	}
   8255 
   8256 	KMALLOCS(newtab, ipnat_t **, newsize * sizeof(ipnat_t *));
   8257 	if (newtab == NULL) {
   8258 		IPFERROR(60067);
   8259 		return ENOMEM;
   8260 	}
   8261 
   8262 	bzero((char *)newtab, newsize * sizeof(ipnat_t *));
   8263 
   8264 	WRITE_ENTER(&softc->ipf_nat);
   8265 
   8266 	if (*old != NULL) {
   8267 		KFREES(*old, *t->ipft_pint * sizeof(ipnat_t **));
   8268 	}
   8269 	*old = newtab;
   8270 	*t->ipft_pint = newsize;
   8271 
   8272 	for (np = softn->ipf_nat_list; np != NULL; np = np->in_next) {
   8273 		if ((np->in_redir & mask) == 0)
   8274 			continue;
   8275 
   8276 		if (np->in_redir & NAT_REDIRECT) {
   8277 			np->in_rnext = NULL;
   8278 			hv = np->in_hv[0] % newsize;
   8279 			for (npp = newtab + hv; *npp != NULL; )
   8280 				npp = &(*npp)->in_rnext;
   8281 			np->in_prnext = npp;
   8282 			*npp = np;
   8283 		}
   8284 		if (np->in_redir & NAT_MAP) {
   8285 			np->in_mnext = NULL;
   8286 			hv = np->in_hv[1] % newsize;
   8287 			for (npp = newtab + hv; *npp != NULL; )
   8288 				npp = &(*npp)->in_mnext;
   8289 			np->in_pmnext = npp;
   8290 			*npp = np;
   8291 		}
   8292 
   8293 	}
   8294 	RWLOCK_EXIT(&softc->ipf_nat);
   8295 
   8296 	return 0;
   8297 }
   8298 
   8299 
   8300 /* ------------------------------------------------------------------------ */
   8301 /* Function:    ipf_nat_hostmap_rehash                                      */
   8302 /* Returns:     int  - 0 = success, else failure			    */
   8303 /* Parameters:  softc(I) - pointer to soft context main structure           */
   8304 /*              t(I) - pointer to tunable                                   */
   8305 /*              p(I) - pointer to new tuning data                           */
   8306 /*                                                                          */
   8307 /* Allocate and populate a new hash table that will contain a reference to  */
   8308 /* all of the active IP# translations currently in place.                   */
   8309 /* ------------------------------------------------------------------------ */
   8310 int
   8311 ipf_nat_hostmap_rehash(softc, t, p)
   8312 	ipf_main_softc_t *softc;
   8313 	ipftuneable_t *t;
   8314 	ipftuneval_t *p;
   8315 {
   8316 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   8317 	hostmap_t *hm, **newtab;
   8318 	u_int newsize;
   8319 	u_int hv;
   8320 
   8321 	newsize = p->ipftu_int;
   8322 	/*
   8323 	 * In case there is nothing to do...
   8324 	 */
   8325 	if (newsize == *t->ipft_pint)
   8326 		return 0;
   8327 
   8328 	KMALLOCS(newtab, hostmap_t **, newsize * sizeof(hostmap_t *));
   8329 	if (newtab == NULL) {
   8330 		IPFERROR(60068);
   8331 		return ENOMEM;
   8332 	}
   8333 
   8334 	bzero((char *)newtab, newsize * sizeof(hostmap_t *));
   8335 
   8336 	WRITE_ENTER(&softc->ipf_nat);
   8337 	if (softn->ipf_hm_maptable != NULL) {
   8338 		KFREES(softn->ipf_hm_maptable,
   8339 		       softn->ipf_nat_hostmap_sz * sizeof(hostmap_t *));
   8340 	}
   8341 	softn->ipf_hm_maptable = newtab;
   8342 	softn->ipf_nat_hostmap_sz = newsize;
   8343 
   8344 	for (hm = softn->ipf_hm_maplist; hm != NULL; hm = hm->hm_next) {
   8345 		hv = hm->hm_hv % softn->ipf_nat_hostmap_sz;
   8346 		hm->hm_hnext = softn->ipf_hm_maptable[hv];
   8347 		hm->hm_phnext = softn->ipf_hm_maptable + hv;
   8348 		if (softn->ipf_hm_maptable[hv] != NULL)
   8349 			softn->ipf_hm_maptable[hv]->hm_phnext = &hm->hm_hnext;
   8350 		softn->ipf_hm_maptable[hv] = hm;
   8351 	}
   8352 	RWLOCK_EXIT(&softc->ipf_nat);
   8353 
   8354 	return 0;
   8355 }
   8356 
   8357 
   8358 /* ------------------------------------------------------------------------ */
   8359 /* Function:    ipf_nat_add_tq                                              */
   8360 /* Parameters:  softc(I) - pointer to soft context main structure           */
   8361 /*                                                                          */
   8362 /* ------------------------------------------------------------------------ */
   8363 ipftq_t *
   8364 ipf_nat_add_tq(softc, ttl)
   8365 	ipf_main_softc_t *softc;
   8366 	int ttl;
   8367 {
   8368 	ipf_nat_softc_t *softs = softc->ipf_nat_soft;
   8369 
   8370 	return ipf_addtimeoutqueue(softc, &softs->ipf_nat_utqe, ttl);
   8371 }
   8372 
   8373 /* ------------------------------------------------------------------------ */
   8374 /* Function:    ipf_nat_uncreate                                            */
   8375 /* Returns:     Nil                                                         */
   8376 /* Parameters:  fin(I) - pointer to packet information                      */
   8377 /*                                                                          */
   8378 /* This function is used to remove a NAT entry from the NAT table when we   */
   8379 /* decide that the create was actually in error. It is thus assumed that    */
   8380 /* fin_flx will have both FI_NATED and FI_NATNEW set. Because we're dealing */
   8381 /* with the translated packet (not the original), we have to reverse the    */
   8382 /* lookup. Although doing the lookup is expensive (relatively speaking), it */
   8383 /* is not anticipated that this will be a frequent occurance for normal     */
   8384 /* traffic patterns.                                                        */
   8385 /* ------------------------------------------------------------------------ */
   8386 void
   8387 ipf_nat_uncreate(fin)
   8388 	fr_info_t *fin;
   8389 {
   8390 	ipf_main_softc_t *softc = fin->fin_main_soft;
   8391 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   8392 	int nflags;
   8393 	nat_t *nat;
   8394 
   8395 	switch (fin->fin_p)
   8396 	{
   8397 	case IPPROTO_TCP :
   8398 		nflags = IPN_TCP;
   8399 		break;
   8400 	case IPPROTO_UDP :
   8401 		nflags = IPN_UDP;
   8402 		break;
   8403 	default :
   8404 		nflags = 0;
   8405 		break;
   8406 	}
   8407 
   8408 	WRITE_ENTER(&softc->ipf_nat);
   8409 
   8410 	if (fin->fin_out == 0) {
   8411 		nat = ipf_nat_outlookup(fin, nflags, (u_int)fin->fin_p,
   8412 					fin->fin_dst, fin->fin_src);
   8413 	} else {
   8414 		nat = ipf_nat_inlookup(fin, nflags, (u_int)fin->fin_p,
   8415 				       fin->fin_src, fin->fin_dst);
   8416 	}
   8417 
   8418 	if (nat != NULL) {
   8419 		NBUMPSIDE(fin->fin_out, ns_uncreate[0]);
   8420 		ipf_nat_delete(softc, nat, NL_DESTROY);
   8421 	} else {
   8422 		NBUMPSIDE(fin->fin_out, ns_uncreate[1]);
   8423 	}
   8424 
   8425 	RWLOCK_EXIT(&softc->ipf_nat);
   8426 }
   8427 
   8428 
   8429 /* ------------------------------------------------------------------------ */
   8430 /* Function:    ipf_nat_cmp_rules                                           */
   8431 /* Returns:     int   - 0 == success, else rules do not match.              */
   8432 /* Parameters:  n1(I) - first rule to compare                               */
   8433 /*              n2(I) - first rule to compare                               */
   8434 /*                                                                          */
   8435 /* Compare two rules using pointers to each rule. A straight bcmp will not  */
   8436 /* work as some fields (such as in_dst, in_pkts) actually do change once    */
   8437 /* the rule has been loaded into the kernel. Whilst this function returns   */
   8438 /* various non-zero returns, they're strictly to aid in debugging. Use of   */
   8439 /* this function should simply care if the result is zero or not.           */
   8440 /* ------------------------------------------------------------------------ */
   8441 static int
   8442 ipf_nat_cmp_rules(n1, n2)
   8443 	ipnat_t *n1, *n2;
   8444 {
   8445 	if (n1->in_size != n2->in_size)
   8446 		return 1;
   8447 
   8448 	if (bcmp((char *)&n1->in_v, (char *)&n2->in_v,
   8449 		 offsetof(ipnat_t, in_ndst) - offsetof(ipnat_t, in_v)) != 0)
   8450 		return 2;
   8451 
   8452 	if (bcmp((char *)&n1->in_tuc, (char *)&n2->in_tuc,
   8453 		 n1->in_size - offsetof(ipnat_t, in_tuc)) != 0)
   8454 		return 3;
   8455 	if (n1->in_ndst.na_atype != n2->in_ndst.na_atype)
   8456 		return 5;
   8457 	if (n1->in_ndst.na_function != n2->in_ndst.na_function)
   8458 		return 6;
   8459 	if (bcmp((char *)&n1->in_ndst.na_addr, (char *)&n2->in_ndst.na_addr,
   8460 		 sizeof(n1->in_ndst.na_addr)))
   8461 		return 7;
   8462 	if (n1->in_nsrc.na_atype != n2->in_nsrc.na_atype)
   8463 		return 8;
   8464 	if (n1->in_nsrc.na_function != n2->in_nsrc.na_function)
   8465 		return 9;
   8466 	if (bcmp((char *)&n1->in_nsrc.na_addr, (char *)&n2->in_nsrc.na_addr,
   8467 		 sizeof(n1->in_nsrc.na_addr)))
   8468 		return 10;
   8469 	if (n1->in_odst.na_atype != n2->in_odst.na_atype)
   8470 		return 11;
   8471 	if (n1->in_odst.na_function != n2->in_odst.na_function)
   8472 		return 12;
   8473 	if (bcmp((char *)&n1->in_odst.na_addr, (char *)&n2->in_odst.na_addr,
   8474 		 sizeof(n1->in_odst.na_addr)))
   8475 		return 13;
   8476 	if (n1->in_osrc.na_atype != n2->in_osrc.na_atype)
   8477 		return 14;
   8478 	if (n1->in_osrc.na_function != n2->in_osrc.na_function)
   8479 		return 15;
   8480 	if (bcmp((char *)&n1->in_osrc.na_addr, (char *)&n2->in_osrc.na_addr,
   8481 		 sizeof(n1->in_osrc.na_addr)))
   8482 		return 16;
   8483 	return 0;
   8484 }
   8485 
   8486 
   8487 /* ------------------------------------------------------------------------ */
   8488 /* Function:    ipf_nat_rule_init                                           */
   8489 /* Returns:     int   - 0 == success, else rules do not match.              */
   8490 /* Parameters:  softc(I) - pointer to soft context main structure           */
   8491 /*              softn(I) - pointer to NAT context structure                 */
   8492 /*              n(I)     - first rule to compare                            */
   8493 /*                                                                          */
   8494 /* ------------------------------------------------------------------------ */
   8495 static int
   8496 ipf_nat_rule_init(softc, softn, n)
   8497 	ipf_main_softc_t *softc;
   8498 	ipf_nat_softc_t *softn;
   8499 	ipnat_t *n;
   8500 {
   8501 	int error = 0;
   8502 
   8503 	if ((n->in_flags & IPN_SIPRANGE) != 0)
   8504 		n->in_nsrcatype = FRI_RANGE;
   8505 
   8506 	if ((n->in_flags & IPN_DIPRANGE) != 0)
   8507 		n->in_ndstatype = FRI_RANGE;
   8508 
   8509 	if ((n->in_flags & IPN_SPLIT) != 0)
   8510 		n->in_ndstatype = FRI_SPLIT;
   8511 
   8512 	if ((n->in_redir & (NAT_MAP|NAT_REWRITE|NAT_DIVERTUDP)) != 0)
   8513 		n->in_spnext = n->in_spmin;
   8514 
   8515 	if ((n->in_redir & (NAT_REWRITE|NAT_DIVERTUDP)) != 0) {
   8516 		n->in_dpnext = n->in_dpmin;
   8517 	} else if (n->in_redir == NAT_REDIRECT) {
   8518 		n->in_dpnext = n->in_dpmin;
   8519 	}
   8520 
   8521 	n->in_stepnext = 0;
   8522 
   8523 	switch (n->in_v[0])
   8524 	{
   8525 	case 4 :
   8526 		error = ipf_nat_ruleaddrinit(softc, softn, n);
   8527 		if (error != 0)
   8528 			return error;
   8529 		break;
   8530 #ifdef USE_INET6
   8531 	case 6 :
   8532 		error = ipf_nat6_ruleaddrinit(softc, softn, n);
   8533 		if (error != 0)
   8534 			return error;
   8535 		break;
   8536 #endif
   8537 	default :
   8538 		break;
   8539 	}
   8540 
   8541 	if (n->in_redir == (NAT_DIVERTUDP|NAT_MAP)) {
   8542 		/*
   8543 		 * Prerecord whether or not the destination of the divert
   8544 		 * is local or not to the interface the packet is going
   8545 		 * to be sent out.
   8546 		 */
   8547 		n->in_dlocal = ipf_deliverlocal(softc, n->in_v[1],
   8548 						n->in_ifps[1], &n->in_ndstip6);
   8549 	}
   8550 
   8551 	return error;
   8552 }
   8553 
   8554 
   8555 /* ------------------------------------------------------------------------ */
   8556 /* Function:    ipf_nat_rule_fini                                           */
   8557 /* Returns:     int   - 0 == success, else rules do not match.              */
   8558 /* Parameters:  softc(I) - pointer to soft context main structure           */
   8559 /*              n(I)     - rule to work on                                  */
   8560 /*                                                                          */
   8561 /* This function is used to release any objects that were referenced during */
   8562 /* the rule initialisation. This is useful both when free'ing the rule and  */
   8563 /* when handling ioctls that need to initialise these fields but not        */
   8564 /* actually use them after the ioctl processing has finished.               */
   8565 /* ------------------------------------------------------------------------ */
   8566 static void
   8567 ipf_nat_rule_fini(softc, n)
   8568 	ipf_main_softc_t *softc;
   8569 	ipnat_t *n;
   8570 {
   8571 	if (n->in_odst.na_atype == FRI_LOOKUP && n->in_odst.na_ptr != NULL)
   8572 		ipf_lookup_deref(softc, n->in_odst.na_type, n->in_odst.na_ptr);
   8573 
   8574 	if (n->in_osrc.na_atype == FRI_LOOKUP && n->in_osrc.na_ptr != NULL)
   8575 		ipf_lookup_deref(softc, n->in_osrc.na_type, n->in_osrc.na_ptr);
   8576 
   8577 	if (n->in_ndst.na_atype == FRI_LOOKUP && n->in_ndst.na_ptr != NULL)
   8578 		ipf_lookup_deref(softc, n->in_ndst.na_type, n->in_ndst.na_ptr);
   8579 
   8580 	if (n->in_nsrc.na_atype == FRI_LOOKUP && n->in_nsrc.na_ptr != NULL)
   8581 		ipf_lookup_deref(softc, n->in_nsrc.na_type, n->in_nsrc.na_ptr);
   8582 
   8583 	if (n->in_divmp != NULL)
   8584 		FREE_MB_T(n->in_divmp);
   8585 }
   8586