Home | History | Annotate | Line # | Download | only in netipsec
key.c revision 1.208
      1 /*	$NetBSD: key.c,v 1.208 2017/08/07 03:21:58 ozaki-r Exp $	*/
      2 /*	$FreeBSD: src/sys/netipsec/key.c,v 1.3.2.3 2004/02/14 22:23:23 bms Exp $	*/
      3 /*	$KAME: key.c,v 1.191 2001/06/27 10:46:49 sakane Exp $	*/
      4 
      5 /*
      6  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
      7  * All rights reserved.
      8  *
      9  * Redistribution and use in source and binary forms, with or without
     10  * modification, are permitted provided that the following conditions
     11  * are met:
     12  * 1. Redistributions of source code must retain the above copyright
     13  *    notice, this list of conditions and the following disclaimer.
     14  * 2. Redistributions in binary form must reproduce the above copyright
     15  *    notice, this list of conditions and the following disclaimer in the
     16  *    documentation and/or other materials provided with the distribution.
     17  * 3. Neither the name of the project nor the names of its contributors
     18  *    may be used to endorse or promote products derived from this software
     19  *    without specific prior written permission.
     20  *
     21  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
     22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
     25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     31  * SUCH DAMAGE.
     32  */
     33 
     34 #include <sys/cdefs.h>
     35 __KERNEL_RCSID(0, "$NetBSD: key.c,v 1.208 2017/08/07 03:21:58 ozaki-r Exp $");
     36 
     37 /*
     38  * This code is referd to RFC 2367
     39  */
     40 
     41 #if defined(_KERNEL_OPT)
     42 #include "opt_inet.h"
     43 #include "opt_ipsec.h"
     44 #include "opt_gateway.h"
     45 #include "opt_net_mpsafe.h"
     46 #endif
     47 
     48 #include <sys/types.h>
     49 #include <sys/param.h>
     50 #include <sys/systm.h>
     51 #include <sys/callout.h>
     52 #include <sys/kernel.h>
     53 #include <sys/mbuf.h>
     54 #include <sys/domain.h>
     55 #include <sys/socket.h>
     56 #include <sys/socketvar.h>
     57 #include <sys/sysctl.h>
     58 #include <sys/errno.h>
     59 #include <sys/proc.h>
     60 #include <sys/queue.h>
     61 #include <sys/syslog.h>
     62 #include <sys/once.h>
     63 #include <sys/cprng.h>
     64 #include <sys/psref.h>
     65 #include <sys/lwp.h>
     66 #include <sys/workqueue.h>
     67 #include <sys/kmem.h>
     68 #include <sys/cpu.h>
     69 #include <sys/atomic.h>
     70 #include <sys/pslist.h>
     71 #include <sys/mutex.h>
     72 #include <sys/condvar.h>
     73 #include <sys/localcount.h>
     74 #include <sys/pserialize.h>
     75 
     76 #include <net/if.h>
     77 #include <net/route.h>
     78 
     79 #include <netinet/in.h>
     80 #include <netinet/in_systm.h>
     81 #include <netinet/ip.h>
     82 #include <netinet/in_var.h>
     83 #ifdef INET
     84 #include <netinet/ip_var.h>
     85 #endif
     86 
     87 #ifdef INET6
     88 #include <netinet/ip6.h>
     89 #include <netinet6/in6_var.h>
     90 #include <netinet6/ip6_var.h>
     91 #endif /* INET6 */
     92 
     93 #ifdef INET
     94 #include <netinet/in_pcb.h>
     95 #endif
     96 #ifdef INET6
     97 #include <netinet6/in6_pcb.h>
     98 #endif /* INET6 */
     99 
    100 #include <net/pfkeyv2.h>
    101 #include <netipsec/keydb.h>
    102 #include <netipsec/key.h>
    103 #include <netipsec/keysock.h>
    104 #include <netipsec/key_debug.h>
    105 
    106 #include <netipsec/ipsec.h>
    107 #ifdef INET6
    108 #include <netipsec/ipsec6.h>
    109 #endif
    110 #include <netipsec/ipsec_private.h>
    111 
    112 #include <netipsec/xform.h>
    113 #include <netipsec/ipcomp.h>
    114 
    115 
    116 #include <net/net_osdep.h>
    117 
    118 #define FULLMASK	0xff
    119 #define	_BITS(bytes)	((bytes) << 3)
    120 
    121 #define PORT_NONE	0
    122 #define PORT_LOOSE	1
    123 #define PORT_STRICT	2
    124 
    125 percpu_t *pfkeystat_percpu;
    126 
    127 /*
    128  * Note on SA reference counting:
    129  * - SAs that are not in DEAD state will have (total external reference + 1)
    130  *   following value in reference count field.  they cannot be freed and are
    131  *   referenced from SA header.
    132  * - SAs that are in DEAD state will have (total external reference)
    133  *   in reference count field.  they are ready to be freed.  reference from
    134  *   SA header will be removed in key_delsav(), when the reference count
    135  *   field hits 0 (= no external reference other than from SA header.
    136  */
    137 
    138 /*
    139  * Locking notes on SPD:
    140  * - Modifications to the key_spd.splist must be done with holding key_spd.lock
    141  *   which is a adaptive mutex
    142  * - Read accesses to the key_spd.splist must be in critical sections of pserialize(9)
    143  * - SP's lifetime is managed by localcount(9)
    144  * - An SP that has been inserted to the key_spd.splist is initially referenced by none,
    145  *   i.e., a reference from the key_spd.splist isn't counted
    146  * - When an SP is being destroyed, we change its state as DEAD, wait for
    147  *   references to the SP to be released, and then deallocate the SP
    148  *   (see key_unlink_sp)
    149  * - Getting an SP
    150  *   - Normally we get an SP from the key_spd.splist by incrementing the reference count
    151  *     of the SP
    152  *   - We can gain another reference from a held SP only if we check its state
    153  *     and take its reference in a critical section of pserialize
    154  *     (see esp_output for example)
    155  *   - We may get an SP from an SP cache. See below
    156  * - Updating member variables of an SP
    157  *   - Most member variables of an SP are immutable
    158  *   - Only sp->state and sp->lastused can be changed
    159  *   - sp->state of an SP is updated only when destroying it under key_spd.lock
    160  * - SP caches
    161  *   - SPs can be cached in PCBs
    162  *   - The lifetime of the caches is controlled by the global generation counter
    163  *     (ipsec_spdgen)
    164  *   - The global counter value is stored when an SP is cached
    165  *   - If the stored value is different from the global counter then the cache
    166  *     is considered invalidated
    167  *   - The counter is incremented when an SP is being destroyed
    168  *   - So checking the generation and taking a reference to an SP should be
    169  *     in a critical section of pserialize
    170  *   - Note that caching doesn't increment the reference counter of an SP
    171  * - SPs in sockets
    172  *   - Userland programs can set a policy to a socket by
    173  *     setsockopt(IP_IPSEC_POLICY)
    174  *   - Such policies (SPs) are set to a socket (PCB) and also inserted to
    175  *     the key_spd.socksplist list (not the key_spd.splist)
    176  *   - Such a policy is destroyed when a corresponding socket is destroed,
    177  *     however, a socket can be destroyed in softint so we cannot destroy
    178  *     it directly instead we just mark it DEAD and delay the destruction
    179  *     until GC by the timer
    180  */
    181 
    182 u_int32_t key_debug_level = 0;
    183 static u_int key_spi_trycnt = 1000;
    184 static u_int32_t key_spi_minval = 0x100;
    185 static u_int32_t key_spi_maxval = 0x0fffffff;	/* XXX */
    186 static u_int32_t policy_id = 0;
    187 static u_int key_int_random = 60;	/*interval to initialize randseed,1(m)*/
    188 static u_int key_larval_lifetime = 30;	/* interval to expire acquiring, 30(s)*/
    189 static int key_blockacq_count = 10;	/* counter for blocking SADB_ACQUIRE.*/
    190 static int key_blockacq_lifetime = 20;	/* lifetime for blocking SADB_ACQUIRE.*/
    191 static int key_prefered_oldsa = 0;	/* prefered old sa rather than new sa.*/
    192 
    193 static u_int32_t acq_seq = 0;
    194 
    195 static pserialize_t key_psz;
    196 
    197 /* SPD */
    198 static struct {
    199 	kmutex_t lock;
    200 	kcondvar_t cv;
    201 	struct pslist_head splist[IPSEC_DIR_MAX];
    202 	/*
    203 	 * The list has SPs that are set to a socket via
    204 	 * setsockopt(IP_IPSEC_POLICY) from userland. See ipsec_set_policy.
    205 	 */
    206 	struct pslist_head socksplist;
    207 } key_spd __cacheline_aligned;
    208 
    209 /* SAD */
    210 static struct {
    211 	kmutex_t lock;
    212 	struct pslist_head sahlist;
    213 } key_sad __cacheline_aligned;
    214 
    215 /* Misc data */
    216 static struct {
    217 	kmutex_t lock;
    218 	/* registed list */
    219 	LIST_HEAD(_reglist, secreg) reglist[SADB_SATYPE_MAX + 1];
    220 #ifndef IPSEC_NONBLOCK_ACQUIRE
    221 	/* acquiring list */
    222 	LIST_HEAD(_acqlist, secacq) acqlist;
    223 #endif
    224 #ifdef notyet
    225 	/* SP acquiring list */
    226 	LIST_HEAD(_spacqlist, secspacq) spacqlist;
    227 #endif
    228 } key_misc __cacheline_aligned;
    229 
    230 /* Macros for key_spd.splist */
    231 #define SPLIST_ENTRY_INIT(sp)						\
    232 	PSLIST_ENTRY_INIT((sp), pslist_entry)
    233 #define SPLIST_ENTRY_DESTROY(sp)					\
    234 	PSLIST_ENTRY_DESTROY((sp), pslist_entry)
    235 #define SPLIST_WRITER_REMOVE(sp)					\
    236 	PSLIST_WRITER_REMOVE((sp), pslist_entry)
    237 #define SPLIST_READER_EMPTY(dir)					\
    238 	(PSLIST_READER_FIRST(&key_spd.splist[(dir)], struct secpolicy,	\
    239 	                     pslist_entry) == NULL)
    240 #define SPLIST_READER_FOREACH(sp, dir)					\
    241 	PSLIST_READER_FOREACH((sp), &key_spd.splist[(dir)],		\
    242 	                      struct secpolicy, pslist_entry)
    243 #define SPLIST_WRITER_FOREACH(sp, dir)					\
    244 	PSLIST_WRITER_FOREACH((sp), &key_spd.splist[(dir)],		\
    245 	                      struct secpolicy, pslist_entry)
    246 #define SPLIST_WRITER_INSERT_AFTER(sp, new)				\
    247 	PSLIST_WRITER_INSERT_AFTER((sp), (new), pslist_entry)
    248 #define SPLIST_WRITER_EMPTY(dir)					\
    249 	(PSLIST_WRITER_FIRST(&key_spd.splist[(dir)], struct secpolicy,	\
    250 	                     pslist_entry) == NULL)
    251 #define SPLIST_WRITER_INSERT_HEAD(dir, sp)				\
    252 	PSLIST_WRITER_INSERT_HEAD(&key_spd.splist[(dir)], (sp),		\
    253 	                          pslist_entry)
    254 #define SPLIST_WRITER_NEXT(sp)						\
    255 	PSLIST_WRITER_NEXT((sp), struct secpolicy, pslist_entry)
    256 #define SPLIST_WRITER_INSERT_TAIL(dir, new)				\
    257 	do {								\
    258 		if (SPLIST_WRITER_EMPTY((dir))) {			\
    259 			SPLIST_WRITER_INSERT_HEAD((dir), (new));	\
    260 		} else {						\
    261 			struct secpolicy *__sp;				\
    262 			SPLIST_WRITER_FOREACH(__sp, (dir)) {		\
    263 				if (SPLIST_WRITER_NEXT(__sp) == NULL) {	\
    264 					SPLIST_WRITER_INSERT_AFTER(__sp,\
    265 					    (new));			\
    266 					break;				\
    267 				}					\
    268 			}						\
    269 		}							\
    270 	} while (0)
    271 
    272 /* Macros for key_spd.socksplist */
    273 #define SOCKSPLIST_WRITER_FOREACH(sp)					\
    274 	PSLIST_WRITER_FOREACH((sp), &key_spd.socksplist,		\
    275 	                      struct secpolicy,	pslist_entry)
    276 #define SOCKSPLIST_READER_EMPTY()					\
    277 	(PSLIST_READER_FIRST(&key_spd.socksplist, struct secpolicy,	\
    278 	                     pslist_entry) == NULL)
    279 
    280 /* Macros for key_sad.sahlist */
    281 #define SAHLIST_ENTRY_INIT(sah)						\
    282 	PSLIST_ENTRY_INIT((sah), pslist_entry)
    283 #define SAHLIST_ENTRY_DESTROY(sah)					\
    284 	PSLIST_ENTRY_DESTROY((sah), pslist_entry)
    285 #define SAHLIST_WRITER_REMOVE(sah)					\
    286 	PSLIST_WRITER_REMOVE((sah), pslist_entry)
    287 #define SAHLIST_READER_FOREACH(sah)					\
    288 	PSLIST_READER_FOREACH((sah), &key_sad.sahlist, struct secashead,\
    289 	                      pslist_entry)
    290 #define SAHLIST_WRITER_FOREACH(sah)					\
    291 	PSLIST_WRITER_FOREACH((sah), &key_sad.sahlist, struct secashead,\
    292 	                      pslist_entry)
    293 #define SAHLIST_WRITER_INSERT_HEAD(sah)					\
    294 	PSLIST_WRITER_INSERT_HEAD(&key_sad.sahlist, (sah), pslist_entry)
    295 
    296 /* Macros for key_sad.sahlist#savlist */
    297 #define SAVLIST_ENTRY_INIT(sav)						\
    298 	PSLIST_ENTRY_INIT((sav), pslist_entry)
    299 #define SAVLIST_ENTRY_DESTROY(sav)					\
    300 	PSLIST_ENTRY_DESTROY((sav), pslist_entry)
    301 #define SAVLIST_READER_FIRST(sah, state)				\
    302 	PSLIST_READER_FIRST(&(sah)->savlist[(state)], struct secasvar,	\
    303 	                    pslist_entry)
    304 #define SAVLIST_WRITER_REMOVE(sav)					\
    305 	PSLIST_WRITER_REMOVE((sav), pslist_entry)
    306 #define SAVLIST_READER_FOREACH(sav, sah, state)				\
    307 	PSLIST_READER_FOREACH((sav), &(sah)->savlist[(state)],		\
    308 	                      struct secasvar, pslist_entry)
    309 #define SAVLIST_WRITER_FOREACH(sav, sah, state)				\
    310 	PSLIST_WRITER_FOREACH((sav), &(sah)->savlist[(state)],		\
    311 	                      struct secasvar, pslist_entry)
    312 #define SAVLIST_WRITER_INSERT_BEFORE(sav, new)				\
    313 	PSLIST_WRITER_INSERT_BEFORE((sav), (new), pslist_entry)
    314 #define SAVLIST_WRITER_INSERT_AFTER(sav, new)				\
    315 	PSLIST_WRITER_INSERT_AFTER((sav), (new), pslist_entry)
    316 #define SAVLIST_WRITER_EMPTY(sah, state)				\
    317 	(PSLIST_WRITER_FIRST(&(sah)->savlist[(state)], struct secasvar,	\
    318 	                     pslist_entry) == NULL)
    319 #define SAVLIST_WRITER_INSERT_HEAD(sah, state, sav)			\
    320 	PSLIST_WRITER_INSERT_HEAD(&(sah)->savlist[(state)], (sav),	\
    321 	                          pslist_entry)
    322 #define SAVLIST_WRITER_NEXT(sav)					\
    323 	PSLIST_WRITER_NEXT((sav), struct secasvar, pslist_entry)
    324 #define SAVLIST_WRITER_INSERT_TAIL(sah, state, new)			\
    325 	do {								\
    326 		if (SAVLIST_WRITER_EMPTY((sah), (state))) {		\
    327 			SAVLIST_WRITER_INSERT_HEAD((sah), (state), (new));\
    328 		} else {						\
    329 			struct secasvar *__sav;				\
    330 			SAVLIST_WRITER_FOREACH(__sav, (sah), (state)) {	\
    331 				if (SAVLIST_WRITER_NEXT(__sav) == NULL) {\
    332 					SAVLIST_WRITER_INSERT_AFTER(__sav,\
    333 					    (new));			\
    334 					break;				\
    335 				}					\
    336 			}						\
    337 		}							\
    338 	} while (0)
    339 #define SAVLIST_READER_NEXT(sav)					\
    340 	PSLIST_READER_NEXT((sav), struct secasvar, pslist_entry)
    341 
    342 
    343 /* search order for SAs */
    344 	/*
    345 	 * This order is important because we must select the oldest SA
    346 	 * for outbound processing.  For inbound, This is not important.
    347 	 */
    348 static const u_int saorder_state_valid_prefer_old[] = {
    349 	SADB_SASTATE_DYING, SADB_SASTATE_MATURE,
    350 };
    351 static const u_int saorder_state_valid_prefer_new[] = {
    352 	SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
    353 };
    354 
    355 static const u_int saorder_state_alive[] = {
    356 	/* except DEAD */
    357 	SADB_SASTATE_MATURE, SADB_SASTATE_DYING, SADB_SASTATE_LARVAL
    358 };
    359 static const u_int saorder_state_any[] = {
    360 	SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
    361 	SADB_SASTATE_LARVAL, SADB_SASTATE_DEAD
    362 };
    363 
    364 #define SASTATE_ALIVE_FOREACH(s)				\
    365 	for (int _i = 0;					\
    366 	    _i < __arraycount(saorder_state_alive) ?		\
    367 	    (s) = saorder_state_alive[_i], true : false;	\
    368 	    _i++)
    369 #define SASTATE_ANY_FOREACH(s)					\
    370 	for (int _i = 0;					\
    371 	    _i < __arraycount(saorder_state_any) ?		\
    372 	    (s) = saorder_state_any[_i], true : false;		\
    373 	    _i++)
    374 
    375 static const int minsize[] = {
    376 	sizeof(struct sadb_msg),	/* SADB_EXT_RESERVED */
    377 	sizeof(struct sadb_sa),		/* SADB_EXT_SA */
    378 	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_CURRENT */
    379 	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_HARD */
    380 	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_SOFT */
    381 	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_SRC */
    382 	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_DST */
    383 	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_PROXY */
    384 	sizeof(struct sadb_key),	/* SADB_EXT_KEY_AUTH */
    385 	sizeof(struct sadb_key),	/* SADB_EXT_KEY_ENCRYPT */
    386 	sizeof(struct sadb_ident),	/* SADB_EXT_IDENTITY_SRC */
    387 	sizeof(struct sadb_ident),	/* SADB_EXT_IDENTITY_DST */
    388 	sizeof(struct sadb_sens),	/* SADB_EXT_SENSITIVITY */
    389 	sizeof(struct sadb_prop),	/* SADB_EXT_PROPOSAL */
    390 	sizeof(struct sadb_supported),	/* SADB_EXT_SUPPORTED_AUTH */
    391 	sizeof(struct sadb_supported),	/* SADB_EXT_SUPPORTED_ENCRYPT */
    392 	sizeof(struct sadb_spirange),	/* SADB_EXT_SPIRANGE */
    393 	0,				/* SADB_X_EXT_KMPRIVATE */
    394 	sizeof(struct sadb_x_policy),	/* SADB_X_EXT_POLICY */
    395 	sizeof(struct sadb_x_sa2),	/* SADB_X_SA2 */
    396 	sizeof(struct sadb_x_nat_t_type),	/* SADB_X_EXT_NAT_T_TYPE */
    397 	sizeof(struct sadb_x_nat_t_port),	/* SADB_X_EXT_NAT_T_SPORT */
    398 	sizeof(struct sadb_x_nat_t_port),	/* SADB_X_EXT_NAT_T_DPORT */
    399 	sizeof(struct sadb_address),		/* SADB_X_EXT_NAT_T_OAI */
    400 	sizeof(struct sadb_address),		/* SADB_X_EXT_NAT_T_OAR */
    401 	sizeof(struct sadb_x_nat_t_frag),	/* SADB_X_EXT_NAT_T_FRAG */
    402 };
    403 static const int maxsize[] = {
    404 	sizeof(struct sadb_msg),	/* SADB_EXT_RESERVED */
    405 	sizeof(struct sadb_sa),		/* SADB_EXT_SA */
    406 	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_CURRENT */
    407 	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_HARD */
    408 	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_SOFT */
    409 	0,				/* SADB_EXT_ADDRESS_SRC */
    410 	0,				/* SADB_EXT_ADDRESS_DST */
    411 	0,				/* SADB_EXT_ADDRESS_PROXY */
    412 	0,				/* SADB_EXT_KEY_AUTH */
    413 	0,				/* SADB_EXT_KEY_ENCRYPT */
    414 	0,				/* SADB_EXT_IDENTITY_SRC */
    415 	0,				/* SADB_EXT_IDENTITY_DST */
    416 	0,				/* SADB_EXT_SENSITIVITY */
    417 	0,				/* SADB_EXT_PROPOSAL */
    418 	0,				/* SADB_EXT_SUPPORTED_AUTH */
    419 	0,				/* SADB_EXT_SUPPORTED_ENCRYPT */
    420 	sizeof(struct sadb_spirange),	/* SADB_EXT_SPIRANGE */
    421 	0,				/* SADB_X_EXT_KMPRIVATE */
    422 	0,				/* SADB_X_EXT_POLICY */
    423 	sizeof(struct sadb_x_sa2),	/* SADB_X_SA2 */
    424 	sizeof(struct sadb_x_nat_t_type),	/* SADB_X_EXT_NAT_T_TYPE */
    425 	sizeof(struct sadb_x_nat_t_port),	/* SADB_X_EXT_NAT_T_SPORT */
    426 	sizeof(struct sadb_x_nat_t_port),	/* SADB_X_EXT_NAT_T_DPORT */
    427 	0,					/* SADB_X_EXT_NAT_T_OAI */
    428 	0,					/* SADB_X_EXT_NAT_T_OAR */
    429 	sizeof(struct sadb_x_nat_t_frag),	/* SADB_X_EXT_NAT_T_FRAG */
    430 };
    431 
    432 static int ipsec_esp_keymin = 256;
    433 static int ipsec_esp_auth = 0;
    434 static int ipsec_ah_keymin = 128;
    435 
    436 #ifdef SYSCTL_DECL
    437 SYSCTL_DECL(_net_key);
    438 #endif
    439 
    440 #ifdef SYSCTL_INT
    441 SYSCTL_INT(_net_key, KEYCTL_DEBUG_LEVEL,	debug,	CTLFLAG_RW, \
    442 	&key_debug_level,	0,	"");
    443 
    444 /* max count of trial for the decision of spi value */
    445 SYSCTL_INT(_net_key, KEYCTL_SPI_TRY,		spi_trycnt,	CTLFLAG_RW, \
    446 	&key_spi_trycnt,	0,	"");
    447 
    448 /* minimum spi value to allocate automatically. */
    449 SYSCTL_INT(_net_key, KEYCTL_SPI_MIN_VALUE,	spi_minval,	CTLFLAG_RW, \
    450 	&key_spi_minval,	0,	"");
    451 
    452 /* maximun spi value to allocate automatically. */
    453 SYSCTL_INT(_net_key, KEYCTL_SPI_MAX_VALUE,	spi_maxval,	CTLFLAG_RW, \
    454 	&key_spi_maxval,	0,	"");
    455 
    456 /* interval to initialize randseed */
    457 SYSCTL_INT(_net_key, KEYCTL_RANDOM_INT,	int_random,	CTLFLAG_RW, \
    458 	&key_int_random,	0,	"");
    459 
    460 /* lifetime for larval SA */
    461 SYSCTL_INT(_net_key, KEYCTL_LARVAL_LIFETIME,	larval_lifetime, CTLFLAG_RW, \
    462 	&key_larval_lifetime,	0,	"");
    463 
    464 /* counter for blocking to send SADB_ACQUIRE to IKEd */
    465 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_COUNT,	blockacq_count,	CTLFLAG_RW, \
    466 	&key_blockacq_count,	0,	"");
    467 
    468 /* lifetime for blocking to send SADB_ACQUIRE to IKEd */
    469 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_LIFETIME,	blockacq_lifetime, CTLFLAG_RW, \
    470 	&key_blockacq_lifetime,	0,	"");
    471 
    472 /* ESP auth */
    473 SYSCTL_INT(_net_key, KEYCTL_ESP_AUTH,	esp_auth, CTLFLAG_RW, \
    474 	&ipsec_esp_auth,	0,	"");
    475 
    476 /* minimum ESP key length */
    477 SYSCTL_INT(_net_key, KEYCTL_ESP_KEYMIN,	esp_keymin, CTLFLAG_RW, \
    478 	&ipsec_esp_keymin,	0,	"");
    479 
    480 /* minimum AH key length */
    481 SYSCTL_INT(_net_key, KEYCTL_AH_KEYMIN,	ah_keymin, CTLFLAG_RW, \
    482 	&ipsec_ah_keymin,	0,	"");
    483 
    484 /* perfered old SA rather than new SA */
    485 SYSCTL_INT(_net_key, KEYCTL_PREFERED_OLDSA,	prefered_oldsa, CTLFLAG_RW,\
    486 	&key_prefered_oldsa,	0,	"");
    487 #endif /* SYSCTL_INT */
    488 
    489 #define __LIST_CHAINED(elm) \
    490 	(!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
    491 #define LIST_INSERT_TAIL(head, elm, type, field) \
    492 do {\
    493 	struct type *curelm = LIST_FIRST(head); \
    494 	if (curelm == NULL) {\
    495 		LIST_INSERT_HEAD(head, elm, field); \
    496 	} else { \
    497 		while (LIST_NEXT(curelm, field)) \
    498 			curelm = LIST_NEXT(curelm, field);\
    499 		LIST_INSERT_AFTER(curelm, elm, field);\
    500 	}\
    501 } while (0)
    502 
    503 #define KEY_CHKSASTATE(head, sav) \
    504 /* do */ { \
    505 	if ((head) != (sav)) {						\
    506 		IPSECLOG(LOG_DEBUG,					\
    507 		    "state mismatched (TREE=%d SA=%d)\n",		\
    508 		    (head), (sav));					\
    509 		continue;						\
    510 	}								\
    511 } /* while (0) */
    512 
    513 #define KEY_CHKSPDIR(head, sp) \
    514 do { \
    515 	if ((head) != (sp)) {						\
    516 		IPSECLOG(LOG_DEBUG,					\
    517 		    "direction mismatched (TREE=%d SP=%d), anyway continue.\n",\
    518 		    (head), (sp));					\
    519 	}								\
    520 } while (0)
    521 
    522 /*
    523  * set parameters into secasindex buffer.
    524  * Must allocate secasindex buffer before calling this function.
    525  */
    526 static int
    527 key_setsecasidx(int, int, int, const struct sockaddr *,
    528     const struct sockaddr *, struct secasindex *);
    529 
    530 /* key statistics */
    531 struct _keystat {
    532 	u_long getspi_count; /* the avarage of count to try to get new SPI */
    533 } keystat;
    534 
    535 struct sadb_msghdr {
    536 	struct sadb_msg *msg;
    537 	struct sadb_ext *ext[SADB_EXT_MAX + 1];
    538 	int extoff[SADB_EXT_MAX + 1];
    539 	int extlen[SADB_EXT_MAX + 1];
    540 };
    541 
    542 static void
    543 key_init_spidx_bymsghdr(struct secpolicyindex *, const struct sadb_msghdr *);
    544 
    545 static const struct sockaddr *
    546 key_msghdr_get_sockaddr(const struct sadb_msghdr *mhp, int idx)
    547 {
    548 
    549 	return PFKEY_ADDR_SADDR((struct sadb_address *)mhp->ext[idx]);
    550 }
    551 
    552 static struct mbuf *
    553 key_fill_replymsg(struct mbuf *m, int seq)
    554 {
    555 	struct sadb_msg *msg;
    556 
    557 	if (m->m_len < sizeof(*msg)) {
    558 		m = m_pullup(m, sizeof(*msg));
    559 		if (m == NULL)
    560 			return NULL;
    561 	}
    562 	msg = mtod(m, struct sadb_msg *);
    563 	msg->sadb_msg_errno = 0;
    564 	msg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
    565 	if (seq != 0)
    566 		msg->sadb_msg_seq = seq;
    567 
    568 	return m;
    569 }
    570 
    571 static struct secasvar *key_lookup_sa_bysaidx(const struct secasindex *);
    572 #if 0
    573 static void key_freeso(struct socket *);
    574 static void key_freesp_so(struct secpolicy **);
    575 #endif
    576 static struct secpolicy *key_getsp (const struct secpolicyindex *);
    577 static struct secpolicy *key_getspbyid (u_int32_t);
    578 static struct secpolicy *key_lookup_and_remove_sp(const struct secpolicyindex *);
    579 static struct secpolicy *key_lookupbyid_and_remove_sp(u_int32_t);
    580 static void key_destroy_sp(struct secpolicy *);
    581 static u_int16_t key_newreqid (void);
    582 static struct mbuf *key_gather_mbuf (struct mbuf *,
    583 	const struct sadb_msghdr *, int, int, ...);
    584 static int key_api_spdadd(struct socket *, struct mbuf *,
    585 	const struct sadb_msghdr *);
    586 static u_int32_t key_getnewspid (void);
    587 static int key_api_spddelete(struct socket *, struct mbuf *,
    588 	const struct sadb_msghdr *);
    589 static int key_api_spddelete2(struct socket *, struct mbuf *,
    590 	const struct sadb_msghdr *);
    591 static int key_api_spdget(struct socket *, struct mbuf *,
    592 	const struct sadb_msghdr *);
    593 static int key_api_spdflush(struct socket *, struct mbuf *,
    594 	const struct sadb_msghdr *);
    595 static int key_api_spddump(struct socket *, struct mbuf *,
    596 	const struct sadb_msghdr *);
    597 static struct mbuf * key_setspddump (int *errorp, pid_t);
    598 static struct mbuf * key_setspddump_chain (int *errorp, int *lenp, pid_t pid);
    599 static int key_api_nat_map(struct socket *, struct mbuf *,
    600 	const struct sadb_msghdr *);
    601 static struct mbuf *key_setdumpsp (struct secpolicy *,
    602 	u_int8_t, u_int32_t, pid_t);
    603 static u_int key_getspreqmsglen (const struct secpolicy *);
    604 static int key_spdexpire (struct secpolicy *);
    605 static struct secashead *key_newsah (const struct secasindex *);
    606 static void key_delsah (struct secashead *);
    607 static struct secasvar *key_newsav(struct mbuf *,
    608 	const struct sadb_msghdr *, int *, const char*, int);
    609 #define	KEY_NEWSAV(m, sadb, e)				\
    610 	key_newsav(m, sadb, e, __func__, __LINE__)
    611 static void key_delsav (struct secasvar *);
    612 static struct secashead *key_getsah(const struct secasindex *, int);
    613 static bool key_checkspidup(const struct secasindex *, u_int32_t);
    614 static struct secasvar *key_getsavbyspi (struct secashead *, u_int32_t);
    615 static int key_setsaval (struct secasvar *, struct mbuf *,
    616 	const struct sadb_msghdr *);
    617 static void key_freesaval(struct secasvar *);
    618 static int key_init_xform(struct secasvar *);
    619 static void key_clear_xform(struct secasvar *);
    620 static struct mbuf *key_setdumpsa (struct secasvar *, u_int8_t,
    621 	u_int8_t, u_int32_t, u_int32_t);
    622 static struct mbuf *key_setsadbxport (u_int16_t, u_int16_t);
    623 static struct mbuf *key_setsadbxtype (u_int16_t);
    624 static struct mbuf *key_setsadbxfrag (u_int16_t);
    625 static void key_porttosaddr (union sockaddr_union *, u_int16_t);
    626 static int key_checksalen (const union sockaddr_union *);
    627 static struct mbuf *key_setsadbmsg (u_int8_t, u_int16_t, u_int8_t,
    628 	u_int32_t, pid_t, u_int16_t);
    629 static struct mbuf *key_setsadbsa (struct secasvar *);
    630 static struct mbuf *key_setsadbaddr (u_int16_t,
    631 	const struct sockaddr *, u_int8_t, u_int16_t);
    632 #if 0
    633 static struct mbuf *key_setsadbident (u_int16_t, u_int16_t, void *,
    634 	int, u_int64_t);
    635 #endif
    636 static struct mbuf *key_setsadbxsa2 (u_int8_t, u_int32_t, u_int16_t);
    637 static struct mbuf *key_setsadbxpolicy (u_int16_t, u_int8_t,
    638 	u_int32_t);
    639 static void *key_newbuf (const void *, u_int);
    640 #ifdef INET6
    641 static int key_ismyaddr6 (const struct sockaddr_in6 *);
    642 #endif
    643 
    644 static void sysctl_net_keyv2_setup(struct sysctllog **);
    645 static void sysctl_net_key_compat_setup(struct sysctllog **);
    646 
    647 /* flags for key_saidx_match() */
    648 #define CMP_HEAD	1	/* protocol, addresses. */
    649 #define CMP_MODE_REQID	2	/* additionally HEAD, reqid, mode. */
    650 #define CMP_REQID	3	/* additionally HEAD, reaid. */
    651 #define CMP_EXACTLY	4	/* all elements. */
    652 static int key_saidx_match(const struct secasindex *,
    653     const struct secasindex *, int);
    654 
    655 static int key_sockaddr_match(const struct sockaddr *,
    656     const struct sockaddr *, int);
    657 static int key_bb_match_withmask(const void *, const void *, u_int);
    658 static u_int16_t key_satype2proto (u_int8_t);
    659 static u_int8_t key_proto2satype (u_int16_t);
    660 
    661 static int key_spidx_match_exactly(const struct secpolicyindex *,
    662     const struct secpolicyindex *);
    663 static int key_spidx_match_withmask(const struct secpolicyindex *,
    664     const struct secpolicyindex *);
    665 
    666 static int key_api_getspi(struct socket *, struct mbuf *,
    667 	const struct sadb_msghdr *);
    668 static u_int32_t key_do_getnewspi (const struct sadb_spirange *,
    669 					const struct secasindex *);
    670 static int key_handle_natt_info (struct secasvar *,
    671 				     const struct sadb_msghdr *);
    672 static int key_set_natt_ports (union sockaddr_union *,
    673 			 	union sockaddr_union *,
    674 				const struct sadb_msghdr *);
    675 static int key_api_update(struct socket *, struct mbuf *,
    676 	const struct sadb_msghdr *);
    677 #ifdef IPSEC_DOSEQCHECK
    678 static struct secasvar *key_getsavbyseq (struct secashead *, u_int32_t);
    679 #endif
    680 static int key_api_add(struct socket *, struct mbuf *,
    681 	const struct sadb_msghdr *);
    682 static int key_setident (struct secashead *, struct mbuf *,
    683 	const struct sadb_msghdr *);
    684 static struct mbuf *key_getmsgbuf_x1 (struct mbuf *,
    685 	const struct sadb_msghdr *);
    686 static int key_api_delete(struct socket *, struct mbuf *,
    687 	const struct sadb_msghdr *);
    688 static int key_api_get(struct socket *, struct mbuf *,
    689 	const struct sadb_msghdr *);
    690 
    691 static void key_getcomb_setlifetime (struct sadb_comb *);
    692 static struct mbuf *key_getcomb_esp (void);
    693 static struct mbuf *key_getcomb_ah (void);
    694 static struct mbuf *key_getcomb_ipcomp (void);
    695 static struct mbuf *key_getprop (const struct secasindex *);
    696 
    697 static int key_acquire (const struct secasindex *, struct secpolicy *);
    698 #ifndef IPSEC_NONBLOCK_ACQUIRE
    699 static struct secacq *key_newacq (const struct secasindex *);
    700 static struct secacq *key_getacq (const struct secasindex *);
    701 static struct secacq *key_getacqbyseq (u_int32_t);
    702 #endif
    703 #ifdef notyet
    704 static struct secspacq *key_newspacq (const struct secpolicyindex *);
    705 static struct secspacq *key_getspacq (const struct secpolicyindex *);
    706 #endif
    707 static int key_api_acquire(struct socket *, struct mbuf *,
    708 	const struct sadb_msghdr *);
    709 static int key_api_register(struct socket *, struct mbuf *,
    710 	const struct sadb_msghdr *);
    711 static int key_expire (struct secasvar *);
    712 static int key_api_flush(struct socket *, struct mbuf *,
    713 	const struct sadb_msghdr *);
    714 static struct mbuf *key_setdump_chain (u_int8_t req_satype, int *errorp,
    715 	int *lenp, pid_t pid);
    716 static int key_api_dump(struct socket *, struct mbuf *,
    717 	const struct sadb_msghdr *);
    718 static int key_api_promisc(struct socket *, struct mbuf *,
    719 	const struct sadb_msghdr *);
    720 static int key_senderror (struct socket *, struct mbuf *, int);
    721 static int key_validate_ext (const struct sadb_ext *, int);
    722 static int key_align (struct mbuf *, struct sadb_msghdr *);
    723 #if 0
    724 static const char *key_getfqdn (void);
    725 static const char *key_getuserfqdn (void);
    726 #endif
    727 static void key_sa_chgstate (struct secasvar *, u_int8_t);
    728 
    729 static struct mbuf *key_alloc_mbuf (int);
    730 
    731 static void key_timehandler(void *);
    732 static void key_timehandler_work(struct work *, void *);
    733 static struct callout	key_timehandler_ch;
    734 static struct workqueue	*key_timehandler_wq;
    735 static struct work	key_timehandler_wk;
    736 
    737 #ifdef IPSEC_REF_DEBUG
    738 #define REFLOG(label, p, where, tag)					\
    739 	log(LOG_DEBUG, "%s:%d: " label " : refcnt=%d (%p)\n.",		\
    740 	    (where), (tag), (p)->refcnt, (p))
    741 #else
    742 #define REFLOG(label, p, where, tag)	do {} while (0)
    743 #endif
    744 
    745 #define	SA_ADDREF(p) do {						\
    746 	atomic_inc_uint(&(p)->refcnt);					\
    747 	REFLOG("SA_ADDREF", (p), __func__, __LINE__);			\
    748 	KASSERTMSG((p)->refcnt != 0, "SA refcnt overflow");		\
    749 } while (0)
    750 #define	SA_ADDREF2(p, where, tag) do {					\
    751 	atomic_inc_uint(&(p)->refcnt);					\
    752 	REFLOG("SA_ADDREF", (p), (where), (tag));			\
    753 	KASSERTMSG((p)->refcnt != 0, "SA refcnt overflow");		\
    754 } while (0)
    755 #define	SA_DELREF(p) do {						\
    756 	KASSERTMSG((p)->refcnt > 0, "SA refcnt underflow");		\
    757 	atomic_dec_uint(&(p)->refcnt);					\
    758 	REFLOG("SA_DELREF", (p), __func__, __LINE__);			\
    759 } while (0)
    760 #define	SA_DELREF2(p, nv, where, tag) do {				\
    761 	KASSERTMSG((p)->refcnt > 0, "SA refcnt underflow");		\
    762 	nv = atomic_dec_uint_nv(&(p)->refcnt);				\
    763 	REFLOG("SA_DELREF", (p), (where), (tag));			\
    764 } while (0)
    765 
    766 u_int
    767 key_sp_refcnt(const struct secpolicy *sp)
    768 {
    769 
    770 	/* FIXME */
    771 	return 0;
    772 }
    773 
    774 /*
    775  * Remove the sp from the key_spd.splist and wait for references to the sp
    776  * to be released. key_spd.lock must be held.
    777  */
    778 static void
    779 key_unlink_sp(struct secpolicy *sp)
    780 {
    781 
    782 	KASSERT(mutex_owned(&key_spd.lock));
    783 
    784 	sp->state = IPSEC_SPSTATE_DEAD;
    785 	SPLIST_WRITER_REMOVE(sp);
    786 
    787 	/* Invalidate all cached SPD pointers in the PCBs. */
    788 	ipsec_invalpcbcacheall();
    789 
    790 #ifdef NET_MPSAFE
    791 	KASSERT(mutex_ownable(softnet_lock));
    792 	pserialize_perform(key_psz);
    793 #endif
    794 
    795 	localcount_drain(&sp->localcount, &key_spd.cv, &key_spd.lock);
    796 }
    797 
    798 /*
    799  * Return 0 when there are known to be no SP's for the specified
    800  * direction.  Otherwise return 1.  This is used by IPsec code
    801  * to optimize performance.
    802  */
    803 int
    804 key_havesp(u_int dir)
    805 {
    806 	return (dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND ?
    807 		!SPLIST_READER_EMPTY(dir) : 1);
    808 }
    809 
    810 /* %%% IPsec policy management */
    811 /*
    812  * allocating a SP for OUTBOUND or INBOUND packet.
    813  * Must call key_freesp() later.
    814  * OUT:	NULL:	not found
    815  *	others:	found and return the pointer.
    816  */
    817 struct secpolicy *
    818 key_lookup_sp_byspidx(const struct secpolicyindex *spidx,
    819     u_int dir, const char* where, int tag)
    820 {
    821 	struct secpolicy *sp;
    822 	int s;
    823 
    824 	KASSERT(spidx != NULL);
    825 	KASSERTMSG(IPSEC_DIR_IS_INOROUT(dir), "invalid direction %u", dir);
    826 
    827 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP, "DP from %s:%u\n", where, tag);
    828 
    829 	/* get a SP entry */
    830 	if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DATA)) {
    831 		printf("*** objects\n");
    832 		kdebug_secpolicyindex(spidx);
    833 	}
    834 
    835 	s = pserialize_read_enter();
    836 	SPLIST_READER_FOREACH(sp, dir) {
    837 		if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DATA)) {
    838 			printf("*** in SPD\n");
    839 			kdebug_secpolicyindex(&sp->spidx);
    840 		}
    841 
    842 		if (sp->state == IPSEC_SPSTATE_DEAD)
    843 			continue;
    844 		if (key_spidx_match_withmask(&sp->spidx, spidx))
    845 			goto found;
    846 	}
    847 	sp = NULL;
    848 found:
    849 	if (sp) {
    850 		/* sanity check */
    851 		KEY_CHKSPDIR(sp->spidx.dir, dir);
    852 
    853 		/* found a SPD entry */
    854 		sp->lastused = time_uptime;
    855 		key_sp_ref(sp, where, tag);
    856 	}
    857 	pserialize_read_exit(s);
    858 
    859 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
    860 	    "DP return SP:%p (ID=%u) refcnt %u\n",
    861 	    sp, sp ? sp->id : 0, key_sp_refcnt(sp));
    862 	return sp;
    863 }
    864 
    865 /*
    866  * return a policy that matches this particular inbound packet.
    867  * XXX slow
    868  */
    869 struct secpolicy *
    870 key_gettunnel(const struct sockaddr *osrc,
    871 	      const struct sockaddr *odst,
    872 	      const struct sockaddr *isrc,
    873 	      const struct sockaddr *idst,
    874 	      const char* where, int tag)
    875 {
    876 	struct secpolicy *sp;
    877 	const int dir = IPSEC_DIR_INBOUND;
    878 	int s;
    879 	struct ipsecrequest *r1, *r2, *p;
    880 	struct secpolicyindex spidx;
    881 
    882 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP, "DP from %s:%u\n", where, tag);
    883 
    884 	if (isrc->sa_family != idst->sa_family) {
    885 		IPSECLOG(LOG_ERR, "protocol family mismatched %d != %d\n.",
    886 		    isrc->sa_family, idst->sa_family);
    887 		sp = NULL;
    888 		goto done;
    889 	}
    890 
    891 	s = pserialize_read_enter();
    892 	SPLIST_READER_FOREACH(sp, dir) {
    893 		if (sp->state == IPSEC_SPSTATE_DEAD)
    894 			continue;
    895 
    896 		r1 = r2 = NULL;
    897 		for (p = sp->req; p; p = p->next) {
    898 			if (p->saidx.mode != IPSEC_MODE_TUNNEL)
    899 				continue;
    900 
    901 			r1 = r2;
    902 			r2 = p;
    903 
    904 			if (!r1) {
    905 				/* here we look at address matches only */
    906 				spidx = sp->spidx;
    907 				if (isrc->sa_len > sizeof(spidx.src) ||
    908 				    idst->sa_len > sizeof(spidx.dst))
    909 					continue;
    910 				memcpy(&spidx.src, isrc, isrc->sa_len);
    911 				memcpy(&spidx.dst, idst, idst->sa_len);
    912 				if (!key_spidx_match_withmask(&sp->spidx, &spidx))
    913 					continue;
    914 			} else {
    915 				if (!key_sockaddr_match(&r1->saidx.src.sa, isrc, PORT_NONE) ||
    916 				    !key_sockaddr_match(&r1->saidx.dst.sa, idst, PORT_NONE))
    917 					continue;
    918 			}
    919 
    920 			if (!key_sockaddr_match(&r2->saidx.src.sa, osrc, PORT_NONE) ||
    921 			    !key_sockaddr_match(&r2->saidx.dst.sa, odst, PORT_NONE))
    922 				continue;
    923 
    924 			goto found;
    925 		}
    926 	}
    927 	sp = NULL;
    928 found:
    929 	if (sp) {
    930 		sp->lastused = time_uptime;
    931 		key_sp_ref(sp, where, tag);
    932 	}
    933 	pserialize_read_exit(s);
    934 done:
    935 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
    936 	    "DP return SP:%p (ID=%u) refcnt %u\n",
    937 	    sp, sp ? sp->id : 0, key_sp_refcnt(sp));
    938 	return sp;
    939 }
    940 
    941 /*
    942  * allocating an SA entry for an *OUTBOUND* packet.
    943  * checking each request entries in SP, and acquire an SA if need.
    944  * OUT:	0: there are valid requests.
    945  *	ENOENT: policy may be valid, but SA with REQUIRE is on acquiring.
    946  */
    947 int
    948 key_checkrequest(struct ipsecrequest *isr, struct secasvar **ret)
    949 {
    950 	u_int level;
    951 	int error;
    952 	const struct secasindex *saidx = &isr->saidx;
    953 	struct secasvar *sav;
    954 
    955 	KASSERT(isr != NULL);
    956 	KASSERTMSG(saidx->mode == IPSEC_MODE_TRANSPORT ||
    957 	    saidx->mode == IPSEC_MODE_TUNNEL,
    958 	    "unexpected policy %u", saidx->mode);
    959 
    960 	/* get current level */
    961 	level = ipsec_get_reqlevel(isr);
    962 
    963 	/*
    964 	 * XXX guard against protocol callbacks from the crypto
    965 	 * thread as they reference ipsecrequest.sav which we
    966 	 * temporarily null out below.  Need to rethink how we
    967 	 * handle bundled SA's in the callback thread.
    968 	 */
    969 	IPSEC_SPLASSERT_SOFTNET("key_checkrequest");
    970 
    971 	sav = key_lookup_sa_bysaidx(saidx);
    972 	if (sav != NULL) {
    973 		*ret = sav;
    974 		return 0;
    975 	}
    976 
    977 	/* there is no SA */
    978 	error = key_acquire(saidx, isr->sp);
    979 	if (error != 0) {
    980 		/* XXX What should I do ? */
    981 		IPSECLOG(LOG_DEBUG, "error %d returned from key_acquire.\n",
    982 		    error);
    983 		return error;
    984 	}
    985 
    986 	if (level != IPSEC_LEVEL_REQUIRE) {
    987 		/* XXX sigh, the interface to this routine is botched */
    988 		*ret = NULL;
    989 		return 0;
    990 	} else {
    991 		return ENOENT;
    992 	}
    993 }
    994 
    995 /*
    996  * looking up a SA for policy entry from SAD.
    997  * NOTE: searching SAD of aliving state.
    998  * OUT:	NULL:	not found.
    999  *	others:	found and return the pointer.
   1000  */
   1001 static struct secasvar *
   1002 key_lookup_sa_bysaidx(const struct secasindex *saidx)
   1003 {
   1004 	struct secashead *sah;
   1005 	struct secasvar *sav = NULL;
   1006 	u_int stateidx, state;
   1007 	const u_int *saorder_state_valid;
   1008 	int arraysize;
   1009 	int s;
   1010 
   1011 	s = pserialize_read_enter();
   1012 	sah = key_getsah(saidx, CMP_MODE_REQID);
   1013 	if (sah == NULL)
   1014 		goto out;
   1015 
   1016 	/*
   1017 	 * search a valid state list for outbound packet.
   1018 	 * This search order is important.
   1019 	 */
   1020 	if (key_prefered_oldsa) {
   1021 		saorder_state_valid = saorder_state_valid_prefer_old;
   1022 		arraysize = _ARRAYLEN(saorder_state_valid_prefer_old);
   1023 	} else {
   1024 		saorder_state_valid = saorder_state_valid_prefer_new;
   1025 		arraysize = _ARRAYLEN(saorder_state_valid_prefer_new);
   1026 	}
   1027 
   1028 	/* search valid state */
   1029 	for (stateidx = 0;
   1030 	     stateidx < arraysize;
   1031 	     stateidx++) {
   1032 
   1033 		state = saorder_state_valid[stateidx];
   1034 
   1035 		if (key_prefered_oldsa)
   1036 			sav = SAVLIST_READER_FIRST(sah, state);
   1037 		else {
   1038 			/* XXX need O(1) lookup */
   1039 			struct secasvar *last = NULL;
   1040 
   1041 			SAVLIST_READER_FOREACH(sav, sah, state)
   1042 				last = sav;
   1043 			sav = last;
   1044 		}
   1045 		if (sav != NULL) {
   1046 			SA_ADDREF(sav);
   1047 			KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
   1048 			    "DP cause refcnt++:%d SA:%p\n",
   1049 			    sav->refcnt, sav);
   1050 			break;
   1051 		}
   1052 	}
   1053 out:
   1054 	pserialize_read_exit(s);
   1055 
   1056 	return sav;
   1057 }
   1058 
   1059 #if 0
   1060 static void
   1061 key_sendup_message_delete(struct secasvar *sav)
   1062 {
   1063 	struct mbuf *m, *result = 0;
   1064 	uint8_t satype;
   1065 
   1066 	satype = key_proto2satype(sav->sah->saidx.proto);
   1067 	if (satype == 0)
   1068 		goto msgfail;
   1069 
   1070 	m = key_setsadbmsg(SADB_DELETE, 0, satype, 0, 0, sav->refcnt - 1);
   1071 	if (m == NULL)
   1072 		goto msgfail;
   1073 	result = m;
   1074 
   1075 	/* set sadb_address for saidx's. */
   1076 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC, &sav->sah->saidx.src.sa,
   1077 	    sav->sah->saidx.src.sa.sa_len << 3, IPSEC_ULPROTO_ANY);
   1078 	if (m == NULL)
   1079 		goto msgfail;
   1080 	m_cat(result, m);
   1081 
   1082 	/* set sadb_address for saidx's. */
   1083 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST, &sav->sah->saidx.src.sa,
   1084 	    sav->sah->saidx.src.sa.sa_len << 3, IPSEC_ULPROTO_ANY);
   1085 	if (m == NULL)
   1086 		goto msgfail;
   1087 	m_cat(result, m);
   1088 
   1089 	/* create SA extension */
   1090 	m = key_setsadbsa(sav);
   1091 	if (m == NULL)
   1092 		goto msgfail;
   1093 	m_cat(result, m);
   1094 
   1095 	if (result->m_len < sizeof(struct sadb_msg)) {
   1096 		result = m_pullup(result, sizeof(struct sadb_msg));
   1097 		if (result == NULL)
   1098 			goto msgfail;
   1099 	}
   1100 
   1101 	result->m_pkthdr.len = 0;
   1102 	for (m = result; m; m = m->m_next)
   1103 		result->m_pkthdr.len += m->m_len;
   1104 	mtod(result, struct sadb_msg *)->sadb_msg_len =
   1105 	    PFKEY_UNIT64(result->m_pkthdr.len);
   1106 
   1107 	key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
   1108 	result = NULL;
   1109 msgfail:
   1110 	if (result)
   1111 		m_freem(result);
   1112 }
   1113 #endif
   1114 
   1115 /*
   1116  * allocating a usable SA entry for a *INBOUND* packet.
   1117  * Must call key_freesav() later.
   1118  * OUT: positive:	pointer to a usable sav (i.e. MATURE or DYING state).
   1119  *	NULL:		not found, or error occurred.
   1120  *
   1121  * In the comparison, no source address is used--for RFC2401 conformance.
   1122  * To quote, from section 4.1:
   1123  *	A security association is uniquely identified by a triple consisting
   1124  *	of a Security Parameter Index (SPI), an IP Destination Address, and a
   1125  *	security protocol (AH or ESP) identifier.
   1126  * Note that, however, we do need to keep source address in IPsec SA.
   1127  * IKE specification and PF_KEY specification do assume that we
   1128  * keep source address in IPsec SA.  We see a tricky situation here.
   1129  *
   1130  * sport and dport are used for NAT-T. network order is always used.
   1131  */
   1132 struct secasvar *
   1133 key_lookup_sa(
   1134 	const union sockaddr_union *dst,
   1135 	u_int proto,
   1136 	u_int32_t spi,
   1137 	u_int16_t sport,
   1138 	u_int16_t dport,
   1139 	const char* where, int tag)
   1140 {
   1141 	struct secashead *sah;
   1142 	struct secasvar *sav;
   1143 	u_int stateidx, state;
   1144 	const u_int *saorder_state_valid;
   1145 	int arraysize, chkport;
   1146 	int s;
   1147 
   1148 	int must_check_spi = 1;
   1149 	int must_check_alg = 0;
   1150 	u_int16_t cpi = 0;
   1151 	u_int8_t algo = 0;
   1152 
   1153 	if ((sport != 0) && (dport != 0))
   1154 		chkport = PORT_STRICT;
   1155 	else
   1156 		chkport = PORT_NONE;
   1157 
   1158 	KASSERT(dst != NULL);
   1159 
   1160 	/*
   1161 	 * XXX IPCOMP case
   1162 	 * We use cpi to define spi here. In the case where cpi <=
   1163 	 * IPCOMP_CPI_NEGOTIATE_MIN, cpi just define the algorithm used, not
   1164 	 * the real spi. In this case, don't check the spi but check the
   1165 	 * algorithm
   1166 	 */
   1167 
   1168 	if (proto == IPPROTO_IPCOMP) {
   1169 		u_int32_t tmp;
   1170 		tmp = ntohl(spi);
   1171 		cpi = (u_int16_t) tmp;
   1172 		if (cpi < IPCOMP_CPI_NEGOTIATE_MIN) {
   1173 			algo = (u_int8_t) cpi;
   1174 			must_check_spi = 0;
   1175 			must_check_alg = 1;
   1176 		}
   1177 	}
   1178 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
   1179 	    "DP from %s:%u check_spi=%d, check_alg=%d\n",
   1180 	    where, tag, must_check_spi, must_check_alg);
   1181 
   1182 
   1183 	/*
   1184 	 * searching SAD.
   1185 	 * XXX: to be checked internal IP header somewhere.  Also when
   1186 	 * IPsec tunnel packet is received.  But ESP tunnel mode is
   1187 	 * encrypted so we can't check internal IP header.
   1188 	 */
   1189 	if (key_prefered_oldsa) {
   1190 		saorder_state_valid = saorder_state_valid_prefer_old;
   1191 		arraysize = _ARRAYLEN(saorder_state_valid_prefer_old);
   1192 	} else {
   1193 		saorder_state_valid = saorder_state_valid_prefer_new;
   1194 		arraysize = _ARRAYLEN(saorder_state_valid_prefer_new);
   1195 	}
   1196 	s = pserialize_read_enter();
   1197 	SAHLIST_READER_FOREACH(sah) {
   1198 		/* search valid state */
   1199 		for (stateidx = 0; stateidx < arraysize; stateidx++) {
   1200 			state = saorder_state_valid[stateidx];
   1201 			SAVLIST_READER_FOREACH(sav, sah, state) {
   1202 				KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
   1203 				    "try match spi %#x, %#x\n",
   1204 				    ntohl(spi), ntohl(sav->spi));
   1205 				/* sanity check */
   1206 				KEY_CHKSASTATE(sav->state, state);
   1207 				/* do not return entries w/ unusable state */
   1208 				if (!SADB_SASTATE_USABLE_P(sav)) {
   1209 					KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
   1210 					    "bad state %d\n", sav->state);
   1211 					continue;
   1212 				}
   1213 				if (proto != sav->sah->saidx.proto) {
   1214 					KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
   1215 					    "proto fail %d != %d\n",
   1216 					    proto, sav->sah->saidx.proto);
   1217 					continue;
   1218 				}
   1219 				if (must_check_spi && spi != sav->spi) {
   1220 					KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
   1221 					    "spi fail %#x != %#x\n",
   1222 					    ntohl(spi), ntohl(sav->spi));
   1223 					continue;
   1224 				}
   1225 				/* XXX only on the ipcomp case */
   1226 				if (must_check_alg && algo != sav->alg_comp) {
   1227 					KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
   1228 					    "algo fail %d != %d\n",
   1229 					    algo, sav->alg_comp);
   1230 					continue;
   1231 				}
   1232 
   1233 #if 0	/* don't check src */
   1234 	/* Fix port in src->sa */
   1235 
   1236 				/* check src address */
   1237 				if (!key_sockaddr_match(&src->sa, &sav->sah->saidx.src.sa, PORT_NONE))
   1238 					continue;
   1239 #endif
   1240 				/* fix port of dst address XXX*/
   1241 				key_porttosaddr(__UNCONST(dst), dport);
   1242 				/* check dst address */
   1243 				if (!key_sockaddr_match(&dst->sa, &sav->sah->saidx.dst.sa, chkport))
   1244 					continue;
   1245 				SA_ADDREF2(sav, where, tag);
   1246 				goto done;
   1247 			}
   1248 		}
   1249 	}
   1250 	sav = NULL;
   1251 done:
   1252 	pserialize_read_exit(s);
   1253 
   1254 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
   1255 	    "DP return SA:%p; refcnt %u\n", sav, sav ? sav->refcnt : 0);
   1256 	return sav;
   1257 }
   1258 
   1259 static void
   1260 key_validate_savlist(const struct secashead *sah, const u_int state)
   1261 {
   1262 #ifdef DEBUG
   1263 	struct secasvar *sav, *next;
   1264 	int s;
   1265 
   1266 	/*
   1267 	 * The list should be sorted by lft_c->sadb_lifetime_addtime
   1268 	 * in ascending order.
   1269 	 */
   1270 	s = pserialize_read_enter();
   1271 	SAVLIST_READER_FOREACH(sav, sah, state) {
   1272 		next = SAVLIST_READER_NEXT(sav);
   1273 		if (next != NULL &&
   1274 		    sav->lft_c != NULL && next->lft_c != NULL) {
   1275 			KDASSERTMSG(sav->lft_c->sadb_lifetime_addtime <=
   1276 			    next->lft_c->sadb_lifetime_addtime,
   1277 			    "savlist is not sorted: sah=%p, state=%d, "
   1278 			    "sav=%" PRIu64 ", next=%" PRIu64, sah, state,
   1279 			    sav->lft_c->sadb_lifetime_addtime,
   1280 			    next->lft_c->sadb_lifetime_addtime);
   1281 		}
   1282 	}
   1283 	pserialize_read_exit(s);
   1284 #endif
   1285 }
   1286 
   1287 void
   1288 key_init_sp(struct secpolicy *sp)
   1289 {
   1290 
   1291 	ASSERT_SLEEPABLE();
   1292 
   1293 	sp->state = IPSEC_SPSTATE_ALIVE;
   1294 	if (sp->policy == IPSEC_POLICY_IPSEC)
   1295 		KASSERT(sp->req != NULL);
   1296 	localcount_init(&sp->localcount);
   1297 	SPLIST_ENTRY_INIT(sp);
   1298 }
   1299 
   1300 void
   1301 key_sp_ref(struct secpolicy *sp, const char* where, int tag)
   1302 {
   1303 
   1304 	localcount_acquire(&sp->localcount);
   1305 
   1306 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
   1307 	    "DP SP:%p (ID=%u) from %s:%u; refcnt++ now %u\n",
   1308 	    sp, sp->id, where, tag, key_sp_refcnt(sp));
   1309 }
   1310 
   1311 void
   1312 key_sp_unref(struct secpolicy *sp, const char* where, int tag)
   1313 {
   1314 
   1315 	KDASSERT(mutex_ownable(&key_spd.lock));
   1316 
   1317 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
   1318 	    "DP SP:%p (ID=%u) from %s:%u; refcnt-- now %u\n",
   1319 	    sp, sp->id, where, tag, key_sp_refcnt(sp));
   1320 
   1321 	localcount_release(&sp->localcount, &key_spd.cv, &key_spd.lock);
   1322 }
   1323 
   1324 void
   1325 key_sa_ref(struct secasvar *sav, const char* where, int tag)
   1326 {
   1327 
   1328 	SA_ADDREF2(sav, where, tag);
   1329 
   1330 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
   1331 	    "DP cause refcnt++:%d SA:%p from %s:%u\n",
   1332 	    sav->refcnt, sav, where, tag);
   1333 }
   1334 
   1335 #if 0
   1336 /*
   1337  * Must be called after calling key_lookup_sp*().
   1338  * For the packet with socket.
   1339  */
   1340 static void
   1341 key_freeso(struct socket *so)
   1342 {
   1343 	/* sanity check */
   1344 	KASSERT(so != NULL);
   1345 
   1346 	switch (so->so_proto->pr_domain->dom_family) {
   1347 #ifdef INET
   1348 	case PF_INET:
   1349 	    {
   1350 		struct inpcb *pcb = sotoinpcb(so);
   1351 
   1352 		/* Does it have a PCB ? */
   1353 		if (pcb == NULL)
   1354 			return;
   1355 
   1356 		struct inpcbpolicy *sp = pcb->inp_sp;
   1357 		key_freesp_so(&sp->sp_in);
   1358 		key_freesp_so(&sp->sp_out);
   1359 	    }
   1360 		break;
   1361 #endif
   1362 #ifdef INET6
   1363 	case PF_INET6:
   1364 	    {
   1365 #ifdef HAVE_NRL_INPCB
   1366 		struct inpcb *pcb  = sotoinpcb(so);
   1367 		struct inpcbpolicy *sp = pcb->inp_sp;
   1368 
   1369 		/* Does it have a PCB ? */
   1370 		if (pcb == NULL)
   1371 			return;
   1372 		key_freesp_so(&sp->sp_in);
   1373 		key_freesp_so(&sp->sp_out);
   1374 #else
   1375 		struct in6pcb *pcb  = sotoin6pcb(so);
   1376 
   1377 		/* Does it have a PCB ? */
   1378 		if (pcb == NULL)
   1379 			return;
   1380 		key_freesp_so(&pcb->in6p_sp->sp_in);
   1381 		key_freesp_so(&pcb->in6p_sp->sp_out);
   1382 #endif
   1383 	    }
   1384 		break;
   1385 #endif /* INET6 */
   1386 	default:
   1387 		IPSECLOG(LOG_DEBUG, "unknown address family=%d.\n",
   1388 		    so->so_proto->pr_domain->dom_family);
   1389 		return;
   1390 	}
   1391 }
   1392 
   1393 static void
   1394 key_freesp_so(struct secpolicy **sp)
   1395 {
   1396 
   1397 	KASSERT(sp != NULL);
   1398 	KASSERT(*sp != NULL);
   1399 
   1400 	if ((*sp)->policy == IPSEC_POLICY_ENTRUST ||
   1401 	    (*sp)->policy == IPSEC_POLICY_BYPASS)
   1402 		return;
   1403 
   1404 	KASSERTMSG((*sp)->policy == IPSEC_POLICY_IPSEC,
   1405 	    "invalid policy %u", (*sp)->policy);
   1406 	KEY_SP_UNREF(&sp);
   1407 }
   1408 #endif
   1409 
   1410 /*
   1411  * Must be called after calling key_lookup_sa().
   1412  * This function is called by key_freesp() to free some SA allocated
   1413  * for a policy.
   1414  */
   1415 void
   1416 key_freesav(struct secasvar **psav, const char* where, int tag)
   1417 {
   1418 	struct secasvar *sav = *psav;
   1419 	unsigned int nv;
   1420 
   1421 	KASSERT(sav != NULL);
   1422 
   1423 	SA_DELREF2(sav, nv, where, tag);
   1424 
   1425 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
   1426 	    "DP SA:%p (SPI %lu) from %s:%u; refcnt now %u\n",
   1427 	    sav, (u_long)ntohl(sav->spi), where, tag, nv);
   1428 
   1429 	if (nv == 0) {
   1430 		*psav = NULL;
   1431 
   1432 		/* remove from SA header */
   1433 		SAVLIST_WRITER_REMOVE(sav);
   1434 
   1435 		key_delsav(sav);
   1436 	}
   1437 }
   1438 
   1439 /* %%% SPD management */
   1440 /*
   1441  * free security policy entry.
   1442  */
   1443 static void
   1444 key_destroy_sp(struct secpolicy *sp)
   1445 {
   1446 
   1447 	SPLIST_ENTRY_DESTROY(sp);
   1448 	localcount_fini(&sp->localcount);
   1449 
   1450 	key_free_sp(sp);
   1451 
   1452 	key_update_used();
   1453 }
   1454 
   1455 void
   1456 key_free_sp(struct secpolicy *sp)
   1457 {
   1458 	struct ipsecrequest *isr = sp->req, *nextisr;
   1459 
   1460 	while (isr != NULL) {
   1461 		nextisr = isr->next;
   1462 		kmem_free(isr, sizeof(*isr));
   1463 		isr = nextisr;
   1464 	}
   1465 
   1466 	kmem_free(sp, sizeof(*sp));
   1467 }
   1468 
   1469 void
   1470 key_socksplist_add(struct secpolicy *sp)
   1471 {
   1472 
   1473 	mutex_enter(&key_spd.lock);
   1474 	PSLIST_WRITER_INSERT_HEAD(&key_spd.socksplist, sp, pslist_entry);
   1475 	mutex_exit(&key_spd.lock);
   1476 
   1477 	key_update_used();
   1478 }
   1479 
   1480 /*
   1481  * search SPD
   1482  * OUT:	NULL	: not found
   1483  *	others	: found, pointer to a SP.
   1484  */
   1485 static struct secpolicy *
   1486 key_getsp(const struct secpolicyindex *spidx)
   1487 {
   1488 	struct secpolicy *sp;
   1489 	int s;
   1490 
   1491 	KASSERT(spidx != NULL);
   1492 
   1493 	s = pserialize_read_enter();
   1494 	SPLIST_READER_FOREACH(sp, spidx->dir) {
   1495 		if (sp->state == IPSEC_SPSTATE_DEAD)
   1496 			continue;
   1497 		if (key_spidx_match_exactly(spidx, &sp->spidx)) {
   1498 			KEY_SP_REF(sp);
   1499 			pserialize_read_exit(s);
   1500 			return sp;
   1501 		}
   1502 	}
   1503 	pserialize_read_exit(s);
   1504 
   1505 	return NULL;
   1506 }
   1507 
   1508 /*
   1509  * search SPD and remove found SP
   1510  * OUT:	NULL	: not found
   1511  *	others	: found, pointer to a SP.
   1512  */
   1513 static struct secpolicy *
   1514 key_lookup_and_remove_sp(const struct secpolicyindex *spidx)
   1515 {
   1516 	struct secpolicy *sp = NULL;
   1517 
   1518 	mutex_enter(&key_spd.lock);
   1519 	SPLIST_WRITER_FOREACH(sp, spidx->dir) {
   1520 		KASSERT(sp->state != IPSEC_SPSTATE_DEAD);
   1521 
   1522 		if (key_spidx_match_exactly(spidx, &sp->spidx)) {
   1523 			key_unlink_sp(sp);
   1524 			goto out;
   1525 		}
   1526 	}
   1527 	sp = NULL;
   1528 out:
   1529 	mutex_exit(&key_spd.lock);
   1530 
   1531 	return sp;
   1532 }
   1533 
   1534 /*
   1535  * get SP by index.
   1536  * OUT:	NULL	: not found
   1537  *	others	: found, pointer to a SP.
   1538  */
   1539 static struct secpolicy *
   1540 key_getspbyid(u_int32_t id)
   1541 {
   1542 	struct secpolicy *sp;
   1543 	int s;
   1544 
   1545 	s = pserialize_read_enter();
   1546 	SPLIST_READER_FOREACH(sp, IPSEC_DIR_INBOUND) {
   1547 		if (sp->state == IPSEC_SPSTATE_DEAD)
   1548 			continue;
   1549 		if (sp->id == id) {
   1550 			KEY_SP_REF(sp);
   1551 			goto out;
   1552 		}
   1553 	}
   1554 
   1555 	SPLIST_READER_FOREACH(sp, IPSEC_DIR_OUTBOUND) {
   1556 		if (sp->state == IPSEC_SPSTATE_DEAD)
   1557 			continue;
   1558 		if (sp->id == id) {
   1559 			KEY_SP_REF(sp);
   1560 			goto out;
   1561 		}
   1562 	}
   1563 out:
   1564 	pserialize_read_exit(s);
   1565 	return sp;
   1566 }
   1567 
   1568 /*
   1569  * get SP by index, remove and return it.
   1570  * OUT:	NULL	: not found
   1571  *	others	: found, pointer to a SP.
   1572  */
   1573 static struct secpolicy *
   1574 key_lookupbyid_and_remove_sp(u_int32_t id)
   1575 {
   1576 	struct secpolicy *sp;
   1577 
   1578 	mutex_enter(&key_spd.lock);
   1579 	SPLIST_READER_FOREACH(sp, IPSEC_DIR_INBOUND) {
   1580 		KASSERT(sp->state != IPSEC_SPSTATE_DEAD);
   1581 		if (sp->id == id)
   1582 			goto out;
   1583 	}
   1584 
   1585 	SPLIST_READER_FOREACH(sp, IPSEC_DIR_OUTBOUND) {
   1586 		KASSERT(sp->state != IPSEC_SPSTATE_DEAD);
   1587 		if (sp->id == id)
   1588 			goto out;
   1589 	}
   1590 out:
   1591 	if (sp != NULL)
   1592 		key_unlink_sp(sp);
   1593 	mutex_exit(&key_spd.lock);
   1594 	return sp;
   1595 }
   1596 
   1597 struct secpolicy *
   1598 key_newsp(const char* where, int tag)
   1599 {
   1600 	struct secpolicy *newsp = NULL;
   1601 
   1602 	newsp = kmem_zalloc(sizeof(struct secpolicy), KM_SLEEP);
   1603 
   1604 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
   1605 	    "DP from %s:%u return SP:%p\n", where, tag, newsp);
   1606 	return newsp;
   1607 }
   1608 
   1609 /*
   1610  * create secpolicy structure from sadb_x_policy structure.
   1611  * NOTE: `state', `secpolicyindex' in secpolicy structure are not set,
   1612  * so must be set properly later.
   1613  */
   1614 struct secpolicy *
   1615 key_msg2sp(const struct sadb_x_policy *xpl0, size_t len, int *error)
   1616 {
   1617 	struct secpolicy *newsp;
   1618 
   1619 	KASSERT(!cpu_softintr_p());
   1620 	KASSERT(xpl0 != NULL);
   1621 	KASSERT(len >= sizeof(*xpl0));
   1622 
   1623 	if (len != PFKEY_EXTLEN(xpl0)) {
   1624 		IPSECLOG(LOG_DEBUG, "Invalid msg length.\n");
   1625 		*error = EINVAL;
   1626 		return NULL;
   1627 	}
   1628 
   1629 	newsp = KEY_NEWSP();
   1630 	if (newsp == NULL) {
   1631 		*error = ENOBUFS;
   1632 		return NULL;
   1633 	}
   1634 
   1635 	newsp->spidx.dir = xpl0->sadb_x_policy_dir;
   1636 	newsp->policy = xpl0->sadb_x_policy_type;
   1637 
   1638 	/* check policy */
   1639 	switch (xpl0->sadb_x_policy_type) {
   1640 	case IPSEC_POLICY_DISCARD:
   1641 	case IPSEC_POLICY_NONE:
   1642 	case IPSEC_POLICY_ENTRUST:
   1643 	case IPSEC_POLICY_BYPASS:
   1644 		newsp->req = NULL;
   1645 		*error = 0;
   1646 		return newsp;
   1647 
   1648 	case IPSEC_POLICY_IPSEC:
   1649 		/* Continued */
   1650 		break;
   1651 	default:
   1652 		IPSECLOG(LOG_DEBUG, "invalid policy type.\n");
   1653 		key_free_sp(newsp);
   1654 		*error = EINVAL;
   1655 		return NULL;
   1656 	}
   1657 
   1658 	/* IPSEC_POLICY_IPSEC */
   1659     {
   1660 	int tlen;
   1661 	const struct sadb_x_ipsecrequest *xisr;
   1662 	uint16_t xisr_reqid;
   1663 	struct ipsecrequest **p_isr = &newsp->req;
   1664 
   1665 	/* validity check */
   1666 	if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) {
   1667 		IPSECLOG(LOG_DEBUG, "Invalid msg length.\n");
   1668 		*error = EINVAL;
   1669 		goto free_exit;
   1670 	}
   1671 
   1672 	tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0);
   1673 	xisr = (const struct sadb_x_ipsecrequest *)(xpl0 + 1);
   1674 
   1675 	while (tlen > 0) {
   1676 		/* length check */
   1677 		if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) {
   1678 			IPSECLOG(LOG_DEBUG, "invalid ipsecrequest length.\n");
   1679 			*error = EINVAL;
   1680 			goto free_exit;
   1681 		}
   1682 
   1683 		/* allocate request buffer */
   1684 		*p_isr = kmem_zalloc(sizeof(**p_isr), KM_SLEEP);
   1685 
   1686 		/* set values */
   1687 		(*p_isr)->next = NULL;
   1688 
   1689 		switch (xisr->sadb_x_ipsecrequest_proto) {
   1690 		case IPPROTO_ESP:
   1691 		case IPPROTO_AH:
   1692 		case IPPROTO_IPCOMP:
   1693 			break;
   1694 		default:
   1695 			IPSECLOG(LOG_DEBUG, "invalid proto type=%u\n",
   1696 			    xisr->sadb_x_ipsecrequest_proto);
   1697 			*error = EPROTONOSUPPORT;
   1698 			goto free_exit;
   1699 		}
   1700 		(*p_isr)->saidx.proto = xisr->sadb_x_ipsecrequest_proto;
   1701 
   1702 		switch (xisr->sadb_x_ipsecrequest_mode) {
   1703 		case IPSEC_MODE_TRANSPORT:
   1704 		case IPSEC_MODE_TUNNEL:
   1705 			break;
   1706 		case IPSEC_MODE_ANY:
   1707 		default:
   1708 			IPSECLOG(LOG_DEBUG, "invalid mode=%u\n",
   1709 			    xisr->sadb_x_ipsecrequest_mode);
   1710 			*error = EINVAL;
   1711 			goto free_exit;
   1712 		}
   1713 		(*p_isr)->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
   1714 
   1715 		switch (xisr->sadb_x_ipsecrequest_level) {
   1716 		case IPSEC_LEVEL_DEFAULT:
   1717 		case IPSEC_LEVEL_USE:
   1718 		case IPSEC_LEVEL_REQUIRE:
   1719 			break;
   1720 		case IPSEC_LEVEL_UNIQUE:
   1721 			xisr_reqid = xisr->sadb_x_ipsecrequest_reqid;
   1722 			/* validity check */
   1723 			/*
   1724 			 * If range violation of reqid, kernel will
   1725 			 * update it, don't refuse it.
   1726 			 */
   1727 			if (xisr_reqid > IPSEC_MANUAL_REQID_MAX) {
   1728 				IPSECLOG(LOG_DEBUG,
   1729 				    "reqid=%d range "
   1730 				    "violation, updated by kernel.\n",
   1731 				    xisr_reqid);
   1732 				xisr_reqid = 0;
   1733 			}
   1734 
   1735 			/* allocate new reqid id if reqid is zero. */
   1736 			if (xisr_reqid == 0) {
   1737 				u_int16_t reqid = key_newreqid();
   1738 				if (reqid == 0) {
   1739 					*error = ENOBUFS;
   1740 					goto free_exit;
   1741 				}
   1742 				(*p_isr)->saidx.reqid = reqid;
   1743 			} else {
   1744 			/* set it for manual keying. */
   1745 				(*p_isr)->saidx.reqid = xisr_reqid;
   1746 			}
   1747 			break;
   1748 
   1749 		default:
   1750 			IPSECLOG(LOG_DEBUG, "invalid level=%u\n",
   1751 			    xisr->sadb_x_ipsecrequest_level);
   1752 			*error = EINVAL;
   1753 			goto free_exit;
   1754 		}
   1755 		(*p_isr)->level = xisr->sadb_x_ipsecrequest_level;
   1756 
   1757 		/* set IP addresses if there */
   1758 		if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
   1759 			const struct sockaddr *paddr;
   1760 
   1761 			paddr = (const struct sockaddr *)(xisr + 1);
   1762 
   1763 			/* validity check */
   1764 			if (paddr->sa_len > sizeof((*p_isr)->saidx.src)) {
   1765 				IPSECLOG(LOG_DEBUG, "invalid request "
   1766 				    "address length.\n");
   1767 				*error = EINVAL;
   1768 				goto free_exit;
   1769 			}
   1770 			memcpy(&(*p_isr)->saidx.src, paddr, paddr->sa_len);
   1771 
   1772 			paddr = (const struct sockaddr *)((const char *)paddr
   1773 			    + paddr->sa_len);
   1774 
   1775 			/* validity check */
   1776 			if (paddr->sa_len > sizeof((*p_isr)->saidx.dst)) {
   1777 				IPSECLOG(LOG_DEBUG, "invalid request "
   1778 				    "address length.\n");
   1779 				*error = EINVAL;
   1780 				goto free_exit;
   1781 			}
   1782 			memcpy(&(*p_isr)->saidx.dst, paddr, paddr->sa_len);
   1783 		}
   1784 
   1785 		(*p_isr)->sp = newsp;
   1786 
   1787 		/* initialization for the next. */
   1788 		p_isr = &(*p_isr)->next;
   1789 		tlen -= xisr->sadb_x_ipsecrequest_len;
   1790 
   1791 		/* validity check */
   1792 		if (tlen < 0) {
   1793 			IPSECLOG(LOG_DEBUG, "becoming tlen < 0.\n");
   1794 			*error = EINVAL;
   1795 			goto free_exit;
   1796 		}
   1797 
   1798 		xisr = (const struct sadb_x_ipsecrequest *)((const char *)xisr +
   1799 		    xisr->sadb_x_ipsecrequest_len);
   1800 	}
   1801     }
   1802 
   1803 	*error = 0;
   1804 	return newsp;
   1805 
   1806 free_exit:
   1807 	key_free_sp(newsp);
   1808 	return NULL;
   1809 }
   1810 
   1811 static u_int16_t
   1812 key_newreqid(void)
   1813 {
   1814 	static u_int16_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
   1815 
   1816 	auto_reqid = (auto_reqid == 0xffff ?
   1817 	    IPSEC_MANUAL_REQID_MAX + 1 : auto_reqid + 1);
   1818 
   1819 	/* XXX should be unique check */
   1820 
   1821 	return auto_reqid;
   1822 }
   1823 
   1824 /*
   1825  * copy secpolicy struct to sadb_x_policy structure indicated.
   1826  */
   1827 struct mbuf *
   1828 key_sp2msg(const struct secpolicy *sp)
   1829 {
   1830 	struct sadb_x_policy *xpl;
   1831 	int tlen;
   1832 	char *p;
   1833 	struct mbuf *m;
   1834 
   1835 	KASSERT(sp != NULL);
   1836 
   1837 	tlen = key_getspreqmsglen(sp);
   1838 
   1839 	m = key_alloc_mbuf(tlen);
   1840 	if (!m || m->m_next) {	/*XXX*/
   1841 		if (m)
   1842 			m_freem(m);
   1843 		return NULL;
   1844 	}
   1845 
   1846 	m->m_len = tlen;
   1847 	m->m_next = NULL;
   1848 	xpl = mtod(m, struct sadb_x_policy *);
   1849 	memset(xpl, 0, tlen);
   1850 
   1851 	xpl->sadb_x_policy_len = PFKEY_UNIT64(tlen);
   1852 	xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
   1853 	xpl->sadb_x_policy_type = sp->policy;
   1854 	xpl->sadb_x_policy_dir = sp->spidx.dir;
   1855 	xpl->sadb_x_policy_id = sp->id;
   1856 	p = (char *)xpl + sizeof(*xpl);
   1857 
   1858 	/* if is the policy for ipsec ? */
   1859 	if (sp->policy == IPSEC_POLICY_IPSEC) {
   1860 		struct sadb_x_ipsecrequest *xisr;
   1861 		struct ipsecrequest *isr;
   1862 
   1863 		for (isr = sp->req; isr != NULL; isr = isr->next) {
   1864 
   1865 			xisr = (struct sadb_x_ipsecrequest *)p;
   1866 
   1867 			xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto;
   1868 			xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode;
   1869 			xisr->sadb_x_ipsecrequest_level = isr->level;
   1870 			xisr->sadb_x_ipsecrequest_reqid = isr->saidx.reqid;
   1871 
   1872 			p += sizeof(*xisr);
   1873 			memcpy(p, &isr->saidx.src, isr->saidx.src.sa.sa_len);
   1874 			p += isr->saidx.src.sa.sa_len;
   1875 			memcpy(p, &isr->saidx.dst, isr->saidx.dst.sa.sa_len);
   1876 			p += isr->saidx.src.sa.sa_len;
   1877 
   1878 			xisr->sadb_x_ipsecrequest_len =
   1879 			    PFKEY_ALIGN8(sizeof(*xisr)
   1880 			    + isr->saidx.src.sa.sa_len
   1881 			    + isr->saidx.dst.sa.sa_len);
   1882 		}
   1883 	}
   1884 
   1885 	return m;
   1886 }
   1887 
   1888 /* m will not be freed nor modified */
   1889 static struct mbuf *
   1890 key_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp,
   1891 		int ndeep, int nitem, ...)
   1892 {
   1893 	va_list ap;
   1894 	int idx;
   1895 	int i;
   1896 	struct mbuf *result = NULL, *n;
   1897 	int len;
   1898 
   1899 	KASSERT(m != NULL);
   1900 	KASSERT(mhp != NULL);
   1901 
   1902 	va_start(ap, nitem);
   1903 	for (i = 0; i < nitem; i++) {
   1904 		idx = va_arg(ap, int);
   1905 		if (idx < 0 || idx > SADB_EXT_MAX)
   1906 			goto fail;
   1907 		/* don't attempt to pull empty extension */
   1908 		if (idx == SADB_EXT_RESERVED && mhp->msg == NULL)
   1909 			continue;
   1910 		if (idx != SADB_EXT_RESERVED &&
   1911 		    (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0))
   1912 			continue;
   1913 
   1914 		if (idx == SADB_EXT_RESERVED) {
   1915 			CTASSERT(PFKEY_ALIGN8(sizeof(struct sadb_msg)) <= MHLEN);
   1916 			len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
   1917 			MGETHDR(n, M_DONTWAIT, MT_DATA);
   1918 			if (!n)
   1919 				goto fail;
   1920 			n->m_len = len;
   1921 			n->m_next = NULL;
   1922 			m_copydata(m, 0, sizeof(struct sadb_msg),
   1923 			    mtod(n, void *));
   1924 		} else if (i < ndeep) {
   1925 			len = mhp->extlen[idx];
   1926 			n = key_alloc_mbuf(len);
   1927 			if (!n || n->m_next) {	/*XXX*/
   1928 				if (n)
   1929 					m_freem(n);
   1930 				goto fail;
   1931 			}
   1932 			m_copydata(m, mhp->extoff[idx], mhp->extlen[idx],
   1933 			    mtod(n, void *));
   1934 		} else {
   1935 			n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx],
   1936 			    M_DONTWAIT);
   1937 		}
   1938 		if (n == NULL)
   1939 			goto fail;
   1940 
   1941 		if (result)
   1942 			m_cat(result, n);
   1943 		else
   1944 			result = n;
   1945 	}
   1946 	va_end(ap);
   1947 
   1948 	if (result && (result->m_flags & M_PKTHDR) != 0) {
   1949 		result->m_pkthdr.len = 0;
   1950 		for (n = result; n; n = n->m_next)
   1951 			result->m_pkthdr.len += n->m_len;
   1952 	}
   1953 
   1954 	return result;
   1955 
   1956 fail:
   1957 	va_end(ap);
   1958 	m_freem(result);
   1959 	return NULL;
   1960 }
   1961 
   1962 /*
   1963  * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing
   1964  * add an entry to SP database, when received
   1965  *   <base, address(SD), (lifetime(H),) policy>
   1966  * from the user(?).
   1967  * Adding to SP database,
   1968  * and send
   1969  *   <base, address(SD), (lifetime(H),) policy>
   1970  * to the socket which was send.
   1971  *
   1972  * SPDADD set a unique policy entry.
   1973  * SPDSETIDX like SPDADD without a part of policy requests.
   1974  * SPDUPDATE replace a unique policy entry.
   1975  *
   1976  * m will always be freed.
   1977  */
   1978 static int
   1979 key_api_spdadd(struct socket *so, struct mbuf *m,
   1980 	   const struct sadb_msghdr *mhp)
   1981 {
   1982 	const struct sockaddr *src, *dst;
   1983 	const struct sadb_x_policy *xpl0;
   1984 	struct sadb_x_policy *xpl;
   1985 	const struct sadb_lifetime *lft = NULL;
   1986 	struct secpolicyindex spidx;
   1987 	struct secpolicy *newsp;
   1988 	int error;
   1989 
   1990 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   1991 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
   1992 	    mhp->ext[SADB_X_EXT_POLICY] == NULL) {
   1993 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   1994 		return key_senderror(so, m, EINVAL);
   1995 	}
   1996 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   1997 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
   1998 	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
   1999 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   2000 		return key_senderror(so, m, EINVAL);
   2001 	}
   2002 	if (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL) {
   2003 		if (mhp->extlen[SADB_EXT_LIFETIME_HARD] <
   2004 		    sizeof(struct sadb_lifetime)) {
   2005 			IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   2006 			return key_senderror(so, m, EINVAL);
   2007 		}
   2008 		lft = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
   2009 	}
   2010 
   2011 	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
   2012 
   2013 	/* checking the direciton. */
   2014 	switch (xpl0->sadb_x_policy_dir) {
   2015 	case IPSEC_DIR_INBOUND:
   2016 	case IPSEC_DIR_OUTBOUND:
   2017 		break;
   2018 	default:
   2019 		IPSECLOG(LOG_DEBUG, "Invalid SP direction.\n");
   2020 		return key_senderror(so, m, EINVAL);
   2021 	}
   2022 
   2023 	/* check policy */
   2024 	/* key_api_spdadd() accepts DISCARD, NONE and IPSEC. */
   2025 	if (xpl0->sadb_x_policy_type == IPSEC_POLICY_ENTRUST ||
   2026 	    xpl0->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
   2027 		IPSECLOG(LOG_DEBUG, "Invalid policy type.\n");
   2028 		return key_senderror(so, m, EINVAL);
   2029 	}
   2030 
   2031 	/* policy requests are mandatory when action is ipsec. */
   2032 	if (mhp->msg->sadb_msg_type != SADB_X_SPDSETIDX &&
   2033 	    xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC &&
   2034 	    mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) {
   2035 		IPSECLOG(LOG_DEBUG, "some policy requests part required.\n");
   2036 		return key_senderror(so, m, EINVAL);
   2037 	}
   2038 
   2039 	src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
   2040 	dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
   2041 
   2042 	/* sanity check on addr pair */
   2043 	if (src->sa_family != dst->sa_family)
   2044 		return key_senderror(so, m, EINVAL);
   2045 	if (src->sa_len != dst->sa_len)
   2046 		return key_senderror(so, m, EINVAL);
   2047 
   2048 	key_init_spidx_bymsghdr(&spidx, mhp);
   2049 
   2050 	/*
   2051 	 * checking there is SP already or not.
   2052 	 * SPDUPDATE doesn't depend on whether there is a SP or not.
   2053 	 * If the type is either SPDADD or SPDSETIDX AND a SP is found,
   2054 	 * then error.
   2055 	 */
   2056     {
   2057 	struct secpolicy *sp;
   2058 
   2059 	if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
   2060 		sp = key_lookup_and_remove_sp(&spidx);
   2061 		if (sp != NULL)
   2062 			key_destroy_sp(sp);
   2063 	} else {
   2064 		sp = key_getsp(&spidx);
   2065 		if (sp != NULL) {
   2066 			KEY_SP_UNREF(&sp);
   2067 			IPSECLOG(LOG_DEBUG, "a SP entry exists already.\n");
   2068 			return key_senderror(so, m, EEXIST);
   2069 		}
   2070 	}
   2071     }
   2072 
   2073 	/* allocation new SP entry */
   2074 	newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error);
   2075 	if (newsp == NULL) {
   2076 		return key_senderror(so, m, error);
   2077 	}
   2078 
   2079 	newsp->id = key_getnewspid();
   2080 	if (newsp->id == 0) {
   2081 		kmem_free(newsp, sizeof(*newsp));
   2082 		return key_senderror(so, m, ENOBUFS);
   2083 	}
   2084 
   2085 	newsp->spidx = spidx;
   2086 	newsp->created = time_uptime;
   2087 	newsp->lastused = newsp->created;
   2088 	newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
   2089 	newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
   2090 
   2091 	key_init_sp(newsp);
   2092 
   2093 	mutex_enter(&key_spd.lock);
   2094 	SPLIST_WRITER_INSERT_TAIL(newsp->spidx.dir, newsp);
   2095 	mutex_exit(&key_spd.lock);
   2096 
   2097 #ifdef notyet
   2098 	/* delete the entry in key_misc.spacqlist */
   2099 	if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
   2100 		struct secspacq *spacq = key_getspacq(&spidx);
   2101 		if (spacq != NULL) {
   2102 			/* reset counter in order to deletion by timehandler. */
   2103 			spacq->created = time_uptime;
   2104 			spacq->count = 0;
   2105 		}
   2106     	}
   2107 #endif
   2108 
   2109 	/* Invalidate all cached SPD pointers in the PCBs. */
   2110 	ipsec_invalpcbcacheall();
   2111 
   2112 #if defined(GATEWAY)
   2113 	/* Invalidate the ipflow cache, as well. */
   2114 	ipflow_invalidate_all(0);
   2115 #ifdef INET6
   2116 	if (in6_present)
   2117 		ip6flow_invalidate_all(0);
   2118 #endif /* INET6 */
   2119 #endif /* GATEWAY */
   2120 
   2121 	key_update_used();
   2122 
   2123     {
   2124 	struct mbuf *n, *mpolicy;
   2125 	int off;
   2126 
   2127 	/* create new sadb_msg to reply. */
   2128 	if (lft) {
   2129 		n = key_gather_mbuf(m, mhp, 2, 5, SADB_EXT_RESERVED,
   2130 		    SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD,
   2131 		    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
   2132 	} else {
   2133 		n = key_gather_mbuf(m, mhp, 2, 4, SADB_EXT_RESERVED,
   2134 		    SADB_X_EXT_POLICY,
   2135 		    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
   2136 	}
   2137 	if (!n)
   2138 		return key_senderror(so, m, ENOBUFS);
   2139 
   2140 	n = key_fill_replymsg(n, 0);
   2141 	if (n == NULL)
   2142 		return key_senderror(so, m, ENOBUFS);
   2143 
   2144 	off = 0;
   2145 	mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
   2146 	    sizeof(*xpl), &off);
   2147 	if (mpolicy == NULL) {
   2148 		/* n is already freed */
   2149 		return key_senderror(so, m, ENOBUFS);
   2150 	}
   2151 	xpl = (struct sadb_x_policy *)(mtod(mpolicy, char *) + off);
   2152 	if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
   2153 		m_freem(n);
   2154 		return key_senderror(so, m, EINVAL);
   2155 	}
   2156 	xpl->sadb_x_policy_id = newsp->id;
   2157 
   2158 	m_freem(m);
   2159 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
   2160     }
   2161 }
   2162 
   2163 /*
   2164  * get new policy id.
   2165  * OUT:
   2166  *	0:	failure.
   2167  *	others: success.
   2168  */
   2169 static u_int32_t
   2170 key_getnewspid(void)
   2171 {
   2172 	u_int32_t newid = 0;
   2173 	int count = key_spi_trycnt;	/* XXX */
   2174 	struct secpolicy *sp;
   2175 
   2176 	/* when requesting to allocate spi ranged */
   2177 	while (count--) {
   2178 		newid = (policy_id = (policy_id == ~0 ? 1 : policy_id + 1));
   2179 
   2180 		sp = key_getspbyid(newid);
   2181 		if (sp == NULL)
   2182 			break;
   2183 
   2184 		KEY_SP_UNREF(&sp);
   2185 	}
   2186 
   2187 	if (count == 0 || newid == 0) {
   2188 		IPSECLOG(LOG_DEBUG, "to allocate policy id is failed.\n");
   2189 		return 0;
   2190 	}
   2191 
   2192 	return newid;
   2193 }
   2194 
   2195 /*
   2196  * SADB_SPDDELETE processing
   2197  * receive
   2198  *   <base, address(SD), policy(*)>
   2199  * from the user(?), and set SADB_SASTATE_DEAD,
   2200  * and send,
   2201  *   <base, address(SD), policy(*)>
   2202  * to the ikmpd.
   2203  * policy(*) including direction of policy.
   2204  *
   2205  * m will always be freed.
   2206  */
   2207 static int
   2208 key_api_spddelete(struct socket *so, struct mbuf *m,
   2209               const struct sadb_msghdr *mhp)
   2210 {
   2211 	struct sadb_x_policy *xpl0;
   2212 	struct secpolicyindex spidx;
   2213 	struct secpolicy *sp;
   2214 
   2215 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   2216 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
   2217 	    mhp->ext[SADB_X_EXT_POLICY] == NULL) {
   2218 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   2219 		return key_senderror(so, m, EINVAL);
   2220 	}
   2221 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   2222 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
   2223 	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
   2224 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   2225 		return key_senderror(so, m, EINVAL);
   2226 	}
   2227 
   2228 	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
   2229 
   2230 	/* checking the direciton. */
   2231 	switch (xpl0->sadb_x_policy_dir) {
   2232 	case IPSEC_DIR_INBOUND:
   2233 	case IPSEC_DIR_OUTBOUND:
   2234 		break;
   2235 	default:
   2236 		IPSECLOG(LOG_DEBUG, "Invalid SP direction.\n");
   2237 		return key_senderror(so, m, EINVAL);
   2238 	}
   2239 
   2240 	/* make secindex */
   2241 	key_init_spidx_bymsghdr(&spidx, mhp);
   2242 
   2243 	/* Is there SP in SPD ? */
   2244 	sp = key_lookup_and_remove_sp(&spidx);
   2245 	if (sp == NULL) {
   2246 		IPSECLOG(LOG_DEBUG, "no SP found.\n");
   2247 		return key_senderror(so, m, EINVAL);
   2248 	}
   2249 
   2250 	/* save policy id to buffer to be returned. */
   2251 	xpl0->sadb_x_policy_id = sp->id;
   2252 
   2253 	key_destroy_sp(sp);
   2254 
   2255 	/* We're deleting policy; no need to invalidate the ipflow cache. */
   2256 
   2257     {
   2258 	struct mbuf *n;
   2259 
   2260 	/* create new sadb_msg to reply. */
   2261 	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
   2262 	    SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
   2263 	if (!n)
   2264 		return key_senderror(so, m, ENOBUFS);
   2265 
   2266 	n = key_fill_replymsg(n, 0);
   2267 	if (n == NULL)
   2268 		return key_senderror(so, m, ENOBUFS);
   2269 
   2270 	m_freem(m);
   2271 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
   2272     }
   2273 }
   2274 
   2275 /*
   2276  * SADB_SPDDELETE2 processing
   2277  * receive
   2278  *   <base, policy(*)>
   2279  * from the user(?), and set SADB_SASTATE_DEAD,
   2280  * and send,
   2281  *   <base, policy(*)>
   2282  * to the ikmpd.
   2283  * policy(*) including direction of policy.
   2284  *
   2285  * m will always be freed.
   2286  */
   2287 static int
   2288 key_api_spddelete2(struct socket *so, struct mbuf *m,
   2289 	       const struct sadb_msghdr *mhp)
   2290 {
   2291 	u_int32_t id;
   2292 	struct secpolicy *sp;
   2293 
   2294 	if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
   2295 	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
   2296 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   2297 		return key_senderror(so, m, EINVAL);
   2298 	}
   2299 
   2300 	id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
   2301 
   2302 	/* Is there SP in SPD ? */
   2303 	sp = key_lookupbyid_and_remove_sp(id);
   2304 	if (sp == NULL) {
   2305 		IPSECLOG(LOG_DEBUG, "no SP found id:%u.\n", id);
   2306 		return key_senderror(so, m, EINVAL);
   2307 	}
   2308 
   2309 	key_destroy_sp(sp);
   2310 
   2311 	/* We're deleting policy; no need to invalidate the ipflow cache. */
   2312 
   2313     {
   2314 	struct mbuf *n, *nn;
   2315 	int off, len;
   2316 
   2317 	CTASSERT(PFKEY_ALIGN8(sizeof(struct sadb_msg)) <= MCLBYTES);
   2318 
   2319 	/* create new sadb_msg to reply. */
   2320 	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
   2321 
   2322 	MGETHDR(n, M_DONTWAIT, MT_DATA);
   2323 	if (n && len > MHLEN) {
   2324 		MCLGET(n, M_DONTWAIT);
   2325 		if ((n->m_flags & M_EXT) == 0) {
   2326 			m_freem(n);
   2327 			n = NULL;
   2328 		}
   2329 	}
   2330 	if (!n)
   2331 		return key_senderror(so, m, ENOBUFS);
   2332 
   2333 	n->m_len = len;
   2334 	n->m_next = NULL;
   2335 	off = 0;
   2336 
   2337 	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, char *) + off);
   2338 	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
   2339 
   2340 	KASSERTMSG(off == len, "length inconsistency");
   2341 
   2342 	n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
   2343 	    mhp->extlen[SADB_X_EXT_POLICY], M_DONTWAIT);
   2344 	if (!n->m_next) {
   2345 		m_freem(n);
   2346 		return key_senderror(so, m, ENOBUFS);
   2347 	}
   2348 
   2349 	n->m_pkthdr.len = 0;
   2350 	for (nn = n; nn; nn = nn->m_next)
   2351 		n->m_pkthdr.len += nn->m_len;
   2352 
   2353 	n = key_fill_replymsg(n, 0);
   2354 	if (n == NULL)
   2355 		return key_senderror(so, m, ENOBUFS);
   2356 
   2357 	m_freem(m);
   2358 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
   2359     }
   2360 }
   2361 
   2362 /*
   2363  * SADB_X_GET processing
   2364  * receive
   2365  *   <base, policy(*)>
   2366  * from the user(?),
   2367  * and send,
   2368  *   <base, address(SD), policy>
   2369  * to the ikmpd.
   2370  * policy(*) including direction of policy.
   2371  *
   2372  * m will always be freed.
   2373  */
   2374 static int
   2375 key_api_spdget(struct socket *so, struct mbuf *m,
   2376 	   const struct sadb_msghdr *mhp)
   2377 {
   2378 	u_int32_t id;
   2379 	struct secpolicy *sp;
   2380 	struct mbuf *n;
   2381 
   2382 	if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
   2383 	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
   2384 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   2385 		return key_senderror(so, m, EINVAL);
   2386 	}
   2387 
   2388 	id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
   2389 
   2390 	/* Is there SP in SPD ? */
   2391 	sp = key_getspbyid(id);
   2392 	if (sp == NULL) {
   2393 		IPSECLOG(LOG_DEBUG, "no SP found id:%u.\n", id);
   2394 		return key_senderror(so, m, ENOENT);
   2395 	}
   2396 
   2397 	n = key_setdumpsp(sp, SADB_X_SPDGET, mhp->msg->sadb_msg_seq,
   2398 	    mhp->msg->sadb_msg_pid);
   2399 	KEY_SP_UNREF(&sp); /* ref gained by key_getspbyid */
   2400 	if (n != NULL) {
   2401 		m_freem(m);
   2402 		return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
   2403 	} else
   2404 		return key_senderror(so, m, ENOBUFS);
   2405 }
   2406 
   2407 #ifdef notyet
   2408 /*
   2409  * SADB_X_SPDACQUIRE processing.
   2410  * Acquire policy and SA(s) for a *OUTBOUND* packet.
   2411  * send
   2412  *   <base, policy(*)>
   2413  * to KMD, and expect to receive
   2414  *   <base> with SADB_X_SPDACQUIRE if error occurred,
   2415  * or
   2416  *   <base, policy>
   2417  * with SADB_X_SPDUPDATE from KMD by PF_KEY.
   2418  * policy(*) is without policy requests.
   2419  *
   2420  *    0     : succeed
   2421  *    others: error number
   2422  */
   2423 int
   2424 key_spdacquire(const struct secpolicy *sp)
   2425 {
   2426 	struct mbuf *result = NULL, *m;
   2427 	struct secspacq *newspacq;
   2428 	int error;
   2429 
   2430 	KASSERT(sp != NULL);
   2431 	KASSERTMSG(sp->req == NULL, "called but there is request");
   2432 	KASSERTMSG(sp->policy == IPSEC_POLICY_IPSEC,
   2433 	    "policy mismathed. IPsec is expected");
   2434 
   2435 	/* Get an entry to check whether sent message or not. */
   2436 	newspacq = key_getspacq(&sp->spidx);
   2437 	if (newspacq != NULL) {
   2438 		if (key_blockacq_count < newspacq->count) {
   2439 			/* reset counter and do send message. */
   2440 			newspacq->count = 0;
   2441 		} else {
   2442 			/* increment counter and do nothing. */
   2443 			newspacq->count++;
   2444 			return 0;
   2445 		}
   2446 	} else {
   2447 		/* make new entry for blocking to send SADB_ACQUIRE. */
   2448 		newspacq = key_newspacq(&sp->spidx);
   2449 		if (newspacq == NULL)
   2450 			return ENOBUFS;
   2451 
   2452 		/* add to key_misc.acqlist */
   2453 		LIST_INSERT_HEAD(&key_misc.spacqlist, newspacq, chain);
   2454 	}
   2455 
   2456 	/* create new sadb_msg to reply. */
   2457 	m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
   2458 	if (!m) {
   2459 		error = ENOBUFS;
   2460 		goto fail;
   2461 	}
   2462 	result = m;
   2463 
   2464 	result->m_pkthdr.len = 0;
   2465 	for (m = result; m; m = m->m_next)
   2466 		result->m_pkthdr.len += m->m_len;
   2467 
   2468 	mtod(result, struct sadb_msg *)->sadb_msg_len =
   2469 	    PFKEY_UNIT64(result->m_pkthdr.len);
   2470 
   2471 	return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
   2472 
   2473 fail:
   2474 	if (result)
   2475 		m_freem(result);
   2476 	return error;
   2477 }
   2478 #endif /* notyet */
   2479 
   2480 /*
   2481  * SADB_SPDFLUSH processing
   2482  * receive
   2483  *   <base>
   2484  * from the user, and free all entries in secpctree.
   2485  * and send,
   2486  *   <base>
   2487  * to the user.
   2488  * NOTE: what to do is only marking SADB_SASTATE_DEAD.
   2489  *
   2490  * m will always be freed.
   2491  */
   2492 static int
   2493 key_api_spdflush(struct socket *so, struct mbuf *m,
   2494 	     const struct sadb_msghdr *mhp)
   2495 {
   2496 	struct sadb_msg *newmsg;
   2497 	struct secpolicy *sp;
   2498 	u_int dir;
   2499 
   2500 	if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
   2501 		return key_senderror(so, m, EINVAL);
   2502 
   2503 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
   2504 	    retry:
   2505 		mutex_enter(&key_spd.lock);
   2506 		SPLIST_WRITER_FOREACH(sp, dir) {
   2507 			KASSERT(sp->state != IPSEC_SPSTATE_DEAD);
   2508 			key_unlink_sp(sp);
   2509 			mutex_exit(&key_spd.lock);
   2510 			key_destroy_sp(sp);
   2511 			goto retry;
   2512 		}
   2513 		mutex_exit(&key_spd.lock);
   2514 	}
   2515 
   2516 	/* We're deleting policy; no need to invalidate the ipflow cache. */
   2517 
   2518 	if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
   2519 		IPSECLOG(LOG_DEBUG, "No more memory.\n");
   2520 		return key_senderror(so, m, ENOBUFS);
   2521 	}
   2522 
   2523 	if (m->m_next)
   2524 		m_freem(m->m_next);
   2525 	m->m_next = NULL;
   2526 	m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
   2527 	newmsg = mtod(m, struct sadb_msg *);
   2528 	newmsg->sadb_msg_errno = 0;
   2529 	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
   2530 
   2531 	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
   2532 }
   2533 
   2534 static struct sockaddr key_src = {
   2535 	.sa_len = 2,
   2536 	.sa_family = PF_KEY,
   2537 };
   2538 
   2539 static struct mbuf *
   2540 key_setspddump_chain(int *errorp, int *lenp, pid_t pid)
   2541 {
   2542 	struct secpolicy *sp;
   2543 	int cnt;
   2544 	u_int dir;
   2545 	struct mbuf *m, *n, *prev;
   2546 	int totlen;
   2547 
   2548 	KASSERT(mutex_owned(&key_spd.lock));
   2549 
   2550 	*lenp = 0;
   2551 
   2552 	/* search SPD entry and get buffer size. */
   2553 	cnt = 0;
   2554 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
   2555 		SPLIST_WRITER_FOREACH(sp, dir) {
   2556 			cnt++;
   2557 		}
   2558 	}
   2559 
   2560 	if (cnt == 0) {
   2561 		*errorp = ENOENT;
   2562 		return (NULL);
   2563 	}
   2564 
   2565 	m = NULL;
   2566 	prev = m;
   2567 	totlen = 0;
   2568 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
   2569 		SPLIST_WRITER_FOREACH(sp, dir) {
   2570 			--cnt;
   2571 			n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt, pid);
   2572 
   2573 			if (!n) {
   2574 				*errorp = ENOBUFS;
   2575 				if (m)
   2576 					m_freem(m);
   2577 				return (NULL);
   2578 			}
   2579 
   2580 			totlen += n->m_pkthdr.len;
   2581 			if (!m) {
   2582 				m = n;
   2583 			} else {
   2584 				prev->m_nextpkt = n;
   2585 			}
   2586 			prev = n;
   2587 		}
   2588 	}
   2589 
   2590 	*lenp = totlen;
   2591 	*errorp = 0;
   2592 	return (m);
   2593 }
   2594 
   2595 /*
   2596  * SADB_SPDDUMP processing
   2597  * receive
   2598  *   <base>
   2599  * from the user, and dump all SP leaves
   2600  * and send,
   2601  *   <base> .....
   2602  * to the ikmpd.
   2603  *
   2604  * m will always be freed.
   2605  */
   2606 static int
   2607 key_api_spddump(struct socket *so, struct mbuf *m0,
   2608  	    const struct sadb_msghdr *mhp)
   2609 {
   2610 	struct mbuf *n;
   2611 	int error, len;
   2612 	int ok;
   2613 	pid_t pid;
   2614 
   2615 	pid = mhp->msg->sadb_msg_pid;
   2616 	/*
   2617 	 * If the requestor has insufficient socket-buffer space
   2618 	 * for the entire chain, nobody gets any response to the DUMP.
   2619 	 * XXX For now, only the requestor ever gets anything.
   2620 	 * Moreover, if the requestor has any space at all, they receive
   2621 	 * the entire chain, otherwise the request is refused with  ENOBUFS.
   2622 	 */
   2623 	if (sbspace(&so->so_rcv) <= 0) {
   2624 		return key_senderror(so, m0, ENOBUFS);
   2625 	}
   2626 
   2627 	mutex_enter(&key_spd.lock);
   2628 	n = key_setspddump_chain(&error, &len, pid);
   2629 	mutex_exit(&key_spd.lock);
   2630 
   2631 	if (n == NULL) {
   2632 		return key_senderror(so, m0, ENOENT);
   2633 	}
   2634 	{
   2635 		uint64_t *ps = PFKEY_STAT_GETREF();
   2636 		ps[PFKEY_STAT_IN_TOTAL]++;
   2637 		ps[PFKEY_STAT_IN_BYTES] += len;
   2638 		PFKEY_STAT_PUTREF();
   2639 	}
   2640 
   2641 	/*
   2642 	 * PF_KEY DUMP responses are no longer broadcast to all PF_KEY sockets.
   2643 	 * The requestor receives either the entire chain, or an
   2644 	 * error message with ENOBUFS.
   2645 	 */
   2646 
   2647 	/*
   2648 	 * sbappendchainwith record takes the chain of entries, one
   2649 	 * packet-record per SPD entry, prepends the key_src sockaddr
   2650 	 * to each packet-record, links the sockaddr mbufs into a new
   2651 	 * list of records, then   appends the entire resulting
   2652 	 * list to the requesting socket.
   2653 	 */
   2654 	ok = sbappendaddrchain(&so->so_rcv, (struct sockaddr *)&key_src, n,
   2655 	    SB_PRIO_ONESHOT_OVERFLOW);
   2656 
   2657 	if (!ok) {
   2658 		PFKEY_STATINC(PFKEY_STAT_IN_NOMEM);
   2659 		m_freem(n);
   2660 		return key_senderror(so, m0, ENOBUFS);
   2661 	}
   2662 
   2663 	m_freem(m0);
   2664 	return error;
   2665 }
   2666 
   2667 /*
   2668  * SADB_X_NAT_T_NEW_MAPPING. Unused by racoon as of 2005/04/23
   2669  */
   2670 static int
   2671 key_api_nat_map(struct socket *so, struct mbuf *m,
   2672 	    const struct sadb_msghdr *mhp)
   2673 {
   2674 	struct sadb_x_nat_t_type *type;
   2675 	struct sadb_x_nat_t_port *sport;
   2676 	struct sadb_x_nat_t_port *dport;
   2677 	struct sadb_address *iaddr, *raddr;
   2678 	struct sadb_x_nat_t_frag *frag;
   2679 
   2680 	if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] == NULL ||
   2681 	    mhp->ext[SADB_X_EXT_NAT_T_SPORT] == NULL ||
   2682 	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] == NULL) {
   2683 		IPSECLOG(LOG_DEBUG, "invalid message.\n");
   2684 		return key_senderror(so, m, EINVAL);
   2685 	}
   2686 	if ((mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type)) ||
   2687 	    (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport)) ||
   2688 	    (mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport))) {
   2689 		IPSECLOG(LOG_DEBUG, "invalid message.\n");
   2690 		return key_senderror(so, m, EINVAL);
   2691 	}
   2692 
   2693 	if ((mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL) &&
   2694 	    (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr))) {
   2695 		IPSECLOG(LOG_DEBUG, "invalid message\n");
   2696 		return key_senderror(so, m, EINVAL);
   2697 	}
   2698 
   2699 	if ((mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) &&
   2700 	    (mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr))) {
   2701 		IPSECLOG(LOG_DEBUG, "invalid message\n");
   2702 		return key_senderror(so, m, EINVAL);
   2703 	}
   2704 
   2705 	if ((mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) &&
   2706 	    (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag))) {
   2707 		IPSECLOG(LOG_DEBUG, "invalid message\n");
   2708 		return key_senderror(so, m, EINVAL);
   2709 	}
   2710 
   2711 	type = (struct sadb_x_nat_t_type *)mhp->ext[SADB_X_EXT_NAT_T_TYPE];
   2712 	sport = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_SPORT];
   2713 	dport = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_DPORT];
   2714 	iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
   2715 	raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
   2716 	frag = (struct sadb_x_nat_t_frag *) mhp->ext[SADB_X_EXT_NAT_T_FRAG];
   2717 
   2718 	/*
   2719 	 * XXX handle that, it should also contain a SA, or anything
   2720 	 * that enable to update the SA information.
   2721 	 */
   2722 
   2723 	return 0;
   2724 }
   2725 
   2726 static struct mbuf *
   2727 key_setdumpsp(struct secpolicy *sp, u_int8_t type, u_int32_t seq, pid_t pid)
   2728 {
   2729 	struct mbuf *result = NULL, *m;
   2730 
   2731 	m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid,
   2732 	    key_sp_refcnt(sp));
   2733 	if (!m)
   2734 		goto fail;
   2735 	result = m;
   2736 
   2737 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
   2738 	    &sp->spidx.src.sa, sp->spidx.prefs, sp->spidx.ul_proto);
   2739 	if (!m)
   2740 		goto fail;
   2741 	m_cat(result, m);
   2742 
   2743 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
   2744 	    &sp->spidx.dst.sa, sp->spidx.prefd, sp->spidx.ul_proto);
   2745 	if (!m)
   2746 		goto fail;
   2747 	m_cat(result, m);
   2748 
   2749 	m = key_sp2msg(sp);
   2750 	if (!m)
   2751 		goto fail;
   2752 	m_cat(result, m);
   2753 
   2754 	if ((result->m_flags & M_PKTHDR) == 0)
   2755 		goto fail;
   2756 
   2757 	if (result->m_len < sizeof(struct sadb_msg)) {
   2758 		result = m_pullup(result, sizeof(struct sadb_msg));
   2759 		if (result == NULL)
   2760 			goto fail;
   2761 	}
   2762 
   2763 	result->m_pkthdr.len = 0;
   2764 	for (m = result; m; m = m->m_next)
   2765 		result->m_pkthdr.len += m->m_len;
   2766 
   2767 	mtod(result, struct sadb_msg *)->sadb_msg_len =
   2768 	    PFKEY_UNIT64(result->m_pkthdr.len);
   2769 
   2770 	return result;
   2771 
   2772 fail:
   2773 	m_freem(result);
   2774 	return NULL;
   2775 }
   2776 
   2777 /*
   2778  * get PFKEY message length for security policy and request.
   2779  */
   2780 static u_int
   2781 key_getspreqmsglen(const struct secpolicy *sp)
   2782 {
   2783 	u_int tlen;
   2784 
   2785 	tlen = sizeof(struct sadb_x_policy);
   2786 
   2787 	/* if is the policy for ipsec ? */
   2788 	if (sp->policy != IPSEC_POLICY_IPSEC)
   2789 		return tlen;
   2790 
   2791 	/* get length of ipsec requests */
   2792     {
   2793 	const struct ipsecrequest *isr;
   2794 	int len;
   2795 
   2796 	for (isr = sp->req; isr != NULL; isr = isr->next) {
   2797 		len = sizeof(struct sadb_x_ipsecrequest)
   2798 		    + isr->saidx.src.sa.sa_len + isr->saidx.dst.sa.sa_len;
   2799 
   2800 		tlen += PFKEY_ALIGN8(len);
   2801 	}
   2802     }
   2803 
   2804 	return tlen;
   2805 }
   2806 
   2807 /*
   2808  * SADB_SPDEXPIRE processing
   2809  * send
   2810  *   <base, address(SD), lifetime(CH), policy>
   2811  * to KMD by PF_KEY.
   2812  *
   2813  * OUT:	0	: succeed
   2814  *	others	: error number
   2815  */
   2816 static int
   2817 key_spdexpire(struct secpolicy *sp)
   2818 {
   2819 	int s;
   2820 	struct mbuf *result = NULL, *m;
   2821 	int len;
   2822 	int error = -1;
   2823 	struct sadb_lifetime *lt;
   2824 
   2825 	/* XXX: Why do we lock ? */
   2826 	s = splsoftnet();	/*called from softclock()*/
   2827 
   2828 	KASSERT(sp != NULL);
   2829 
   2830 	/* set msg header */
   2831 	m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
   2832 	if (!m) {
   2833 		error = ENOBUFS;
   2834 		goto fail;
   2835 	}
   2836 	result = m;
   2837 
   2838 	/* create lifetime extension (current and hard) */
   2839 	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
   2840 	m = key_alloc_mbuf(len);
   2841 	if (!m || m->m_next) {	/*XXX*/
   2842 		if (m)
   2843 			m_freem(m);
   2844 		error = ENOBUFS;
   2845 		goto fail;
   2846 	}
   2847 	memset(mtod(m, void *), 0, len);
   2848 	lt = mtod(m, struct sadb_lifetime *);
   2849 	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
   2850 	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
   2851 	lt->sadb_lifetime_allocations = 0;
   2852 	lt->sadb_lifetime_bytes = 0;
   2853 	lt->sadb_lifetime_addtime = time_mono_to_wall(sp->created);
   2854 	lt->sadb_lifetime_usetime = time_mono_to_wall(sp->lastused);
   2855 	lt = (struct sadb_lifetime *)(mtod(m, char *) + len / 2);
   2856 	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
   2857 	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
   2858 	lt->sadb_lifetime_allocations = 0;
   2859 	lt->sadb_lifetime_bytes = 0;
   2860 	lt->sadb_lifetime_addtime = sp->lifetime;
   2861 	lt->sadb_lifetime_usetime = sp->validtime;
   2862 	m_cat(result, m);
   2863 
   2864 	/* set sadb_address for source */
   2865 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC, &sp->spidx.src.sa,
   2866 	    sp->spidx.prefs, sp->spidx.ul_proto);
   2867 	if (!m) {
   2868 		error = ENOBUFS;
   2869 		goto fail;
   2870 	}
   2871 	m_cat(result, m);
   2872 
   2873 	/* set sadb_address for destination */
   2874 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST, &sp->spidx.dst.sa,
   2875 	    sp->spidx.prefd, sp->spidx.ul_proto);
   2876 	if (!m) {
   2877 		error = ENOBUFS;
   2878 		goto fail;
   2879 	}
   2880 	m_cat(result, m);
   2881 
   2882 	/* set secpolicy */
   2883 	m = key_sp2msg(sp);
   2884 	if (!m) {
   2885 		error = ENOBUFS;
   2886 		goto fail;
   2887 	}
   2888 	m_cat(result, m);
   2889 
   2890 	if ((result->m_flags & M_PKTHDR) == 0) {
   2891 		error = EINVAL;
   2892 		goto fail;
   2893 	}
   2894 
   2895 	if (result->m_len < sizeof(struct sadb_msg)) {
   2896 		result = m_pullup(result, sizeof(struct sadb_msg));
   2897 		if (result == NULL) {
   2898 			error = ENOBUFS;
   2899 			goto fail;
   2900 		}
   2901 	}
   2902 
   2903 	result->m_pkthdr.len = 0;
   2904 	for (m = result; m; m = m->m_next)
   2905 		result->m_pkthdr.len += m->m_len;
   2906 
   2907 	mtod(result, struct sadb_msg *)->sadb_msg_len =
   2908 	    PFKEY_UNIT64(result->m_pkthdr.len);
   2909 
   2910 	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
   2911 
   2912  fail:
   2913 	if (result)
   2914 		m_freem(result);
   2915 	splx(s);
   2916 	return error;
   2917 }
   2918 
   2919 /* %%% SAD management */
   2920 /*
   2921  * allocating a memory for new SA head, and copy from the values of mhp.
   2922  * OUT:	NULL	: failure due to the lack of memory.
   2923  *	others	: pointer to new SA head.
   2924  */
   2925 static struct secashead *
   2926 key_newsah(const struct secasindex *saidx)
   2927 {
   2928 	struct secashead *newsah;
   2929 	int i;
   2930 
   2931 	KASSERT(saidx != NULL);
   2932 
   2933 	newsah = kmem_zalloc(sizeof(struct secashead), KM_SLEEP);
   2934 	for (i = 0; i < __arraycount(newsah->savlist); i++)
   2935 		PSLIST_INIT(&newsah->savlist[i]);
   2936 	newsah->saidx = *saidx;
   2937 
   2938 	/* add to saidxtree */
   2939 	newsah->state = SADB_SASTATE_MATURE;
   2940 	SAHLIST_ENTRY_INIT(newsah);
   2941 	mutex_enter(&key_sad.lock);
   2942 	SAHLIST_WRITER_INSERT_HEAD(newsah);
   2943 	mutex_exit(&key_sad.lock);
   2944 
   2945 	return newsah;
   2946 }
   2947 
   2948 /*
   2949  * delete SA index and all SA registerd.
   2950  */
   2951 static void
   2952 key_delsah(struct secashead *sah)
   2953 {
   2954 	struct secasvar *sav;
   2955 	u_int state;
   2956 	int s;
   2957 	int zombie = 0;
   2958 
   2959 	KASSERT(!cpu_softintr_p());
   2960 	KASSERT(sah != NULL);
   2961 
   2962 	s = splsoftnet();
   2963 
   2964 	/* searching all SA registerd in the secindex. */
   2965 	SASTATE_ANY_FOREACH(state) {
   2966 		SAVLIST_READER_FOREACH(sav, sah, state) {
   2967 			/* give up to delete this sa */
   2968 			zombie++;
   2969 		}
   2970 	}
   2971 
   2972 	/* don't delete sah only if there are savs. */
   2973 	if (zombie) {
   2974 		splx(s);
   2975 		return;
   2976 	}
   2977 
   2978 	rtcache_free(&sah->sa_route);
   2979 
   2980 	/* remove from tree of SA index */
   2981 	SAHLIST_WRITER_REMOVE(sah);
   2982 
   2983 	if (sah->idents != NULL)
   2984 		kmem_free(sah->idents, sah->idents_len);
   2985 	if (sah->identd != NULL)
   2986 		kmem_free(sah->identd, sah->identd_len);
   2987 
   2988 	SAHLIST_ENTRY_DESTROY(sah);
   2989 	kmem_free(sah, sizeof(*sah));
   2990 
   2991 	splx(s);
   2992 	return;
   2993 }
   2994 
   2995 /*
   2996  * allocating a new SA with LARVAL state.
   2997  * key_api_add() and key_api_getspi() call,
   2998  * and copy the values of mhp into new buffer.
   2999  * When SAD message type is GETSPI:
   3000  *	to set sequence number from acq_seq++,
   3001  *	to set zero to SPI.
   3002  *	not to call key_setsava().
   3003  * OUT:	NULL	: fail
   3004  *	others	: pointer to new secasvar.
   3005  *
   3006  * does not modify mbuf.  does not free mbuf on error.
   3007  */
   3008 static struct secasvar *
   3009 key_newsav(struct mbuf *m, const struct sadb_msghdr *mhp,
   3010     int *errp, const char* where, int tag)
   3011 {
   3012 	struct secasvar *newsav;
   3013 	const struct sadb_sa *xsa;
   3014 
   3015 	KASSERT(!cpu_softintr_p());
   3016 	KASSERT(m != NULL);
   3017 	KASSERT(mhp != NULL);
   3018 	KASSERT(mhp->msg != NULL);
   3019 
   3020 	newsav = kmem_zalloc(sizeof(struct secasvar), KM_SLEEP);
   3021 
   3022 	switch (mhp->msg->sadb_msg_type) {
   3023 	case SADB_GETSPI:
   3024 		newsav->spi = 0;
   3025 
   3026 #ifdef IPSEC_DOSEQCHECK
   3027 		/* sync sequence number */
   3028 		if (mhp->msg->sadb_msg_seq == 0)
   3029 			newsav->seq =
   3030 			    (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
   3031 		else
   3032 #endif
   3033 			newsav->seq = mhp->msg->sadb_msg_seq;
   3034 		break;
   3035 
   3036 	case SADB_ADD:
   3037 		/* sanity check */
   3038 		if (mhp->ext[SADB_EXT_SA] == NULL) {
   3039 			IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   3040 			*errp = EINVAL;
   3041 			goto error;
   3042 		}
   3043 		xsa = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
   3044 		newsav->spi = xsa->sadb_sa_spi;
   3045 		newsav->seq = mhp->msg->sadb_msg_seq;
   3046 		break;
   3047 	default:
   3048 		*errp = EINVAL;
   3049 		goto error;
   3050 	}
   3051 
   3052 	/* copy sav values */
   3053 	if (mhp->msg->sadb_msg_type != SADB_GETSPI) {
   3054 		*errp = key_setsaval(newsav, m, mhp);
   3055 		if (*errp)
   3056 			goto error;
   3057 	} else {
   3058 		/* We don't allow lft_c to be NULL */
   3059 		newsav->lft_c = kmem_zalloc(sizeof(struct sadb_lifetime),
   3060 		    KM_SLEEP);
   3061 	}
   3062 
   3063 	/* reset created */
   3064 	newsav->created = time_uptime;
   3065 	newsav->pid = mhp->msg->sadb_msg_pid;
   3066 
   3067 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
   3068 	    "DP from %s:%u return SA:%p\n", where, tag, newsav);
   3069 	return newsav;
   3070 
   3071 error:
   3072 	KASSERT(*errp != 0);
   3073 	kmem_free(newsav, sizeof(*newsav));
   3074 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
   3075 	    "DP from %s:%u return SA:NULL\n", where, tag);
   3076 	return NULL;
   3077 }
   3078 
   3079 
   3080 static void
   3081 key_clear_xform(struct secasvar *sav)
   3082 {
   3083 
   3084 	/*
   3085 	 * Cleanup xform state.  Note that zeroize'ing causes the
   3086 	 * keys to be cleared; otherwise we must do it ourself.
   3087 	 */
   3088 	if (sav->tdb_xform != NULL) {
   3089 		sav->tdb_xform->xf_zeroize(sav);
   3090 		sav->tdb_xform = NULL;
   3091 	} else {
   3092 		if (sav->key_auth != NULL)
   3093 			explicit_memset(_KEYBUF(sav->key_auth), 0,
   3094 			    _KEYLEN(sav->key_auth));
   3095 		if (sav->key_enc != NULL)
   3096 			explicit_memset(_KEYBUF(sav->key_enc), 0,
   3097 			    _KEYLEN(sav->key_enc));
   3098 	}
   3099 }
   3100 
   3101 /*
   3102  * free() SA variable entry.
   3103  */
   3104 static void
   3105 key_delsav(struct secasvar *sav)
   3106 {
   3107 
   3108 	KASSERT(sav != NULL);
   3109 	KASSERTMSG(sav->refcnt == 0, "reference count %u > 0", sav->refcnt);
   3110 
   3111 	key_clear_xform(sav);
   3112 	key_freesaval(sav);
   3113 	SAVLIST_ENTRY_DESTROY(sav);
   3114 	kmem_intr_free(sav, sizeof(*sav));
   3115 
   3116 	return;
   3117 }
   3118 
   3119 /*
   3120  * search SAD.
   3121  * OUT:
   3122  *	NULL	: not found
   3123  *	others	: found, pointer to a SA.
   3124  */
   3125 static struct secashead *
   3126 key_getsah(const struct secasindex *saidx, int flag)
   3127 {
   3128 	struct secashead *sah;
   3129 
   3130 	SAHLIST_READER_FOREACH(sah) {
   3131 		if (sah->state == SADB_SASTATE_DEAD)
   3132 			continue;
   3133 		if (key_saidx_match(&sah->saidx, saidx, flag))
   3134 			return sah;
   3135 	}
   3136 
   3137 	return NULL;
   3138 }
   3139 
   3140 /*
   3141  * check not to be duplicated SPI.
   3142  * NOTE: this function is too slow due to searching all SAD.
   3143  * OUT:
   3144  *	NULL	: not found
   3145  *	others	: found, pointer to a SA.
   3146  */
   3147 static bool
   3148 key_checkspidup(const struct secasindex *saidx, u_int32_t spi)
   3149 {
   3150 	struct secashead *sah;
   3151 	struct secasvar *sav;
   3152 
   3153 	/* check address family */
   3154 	if (saidx->src.sa.sa_family != saidx->dst.sa.sa_family) {
   3155 		IPSECLOG(LOG_DEBUG, "address family mismatched.\n");
   3156 		return false;
   3157 	}
   3158 
   3159 	/* check all SAD */
   3160 	SAHLIST_READER_FOREACH(sah) {
   3161 		if (!key_ismyaddr((struct sockaddr *)&sah->saidx.dst))
   3162 			continue;
   3163 		sav = key_getsavbyspi(sah, spi);
   3164 		if (sav != NULL) {
   3165 			KEY_SA_UNREF(&sav);
   3166 			return true;
   3167 		}
   3168 	}
   3169 
   3170 	return false;
   3171 }
   3172 
   3173 /*
   3174  * search SAD litmited alive SA, protocol, SPI.
   3175  * OUT:
   3176  *	NULL	: not found
   3177  *	others	: found, pointer to a SA.
   3178  */
   3179 static struct secasvar *
   3180 key_getsavbyspi(struct secashead *sah, u_int32_t spi)
   3181 {
   3182 	struct secasvar *sav = NULL;
   3183 	u_int state;
   3184 	int s;
   3185 
   3186 	/* search all status */
   3187 	s = pserialize_read_enter();
   3188 	SASTATE_ALIVE_FOREACH(state) {
   3189 		SAVLIST_READER_FOREACH(sav, sah, state) {
   3190 			/* sanity check */
   3191 			if (sav->state != state) {
   3192 				IPSECLOG(LOG_DEBUG,
   3193 				    "invalid sav->state (queue: %d SA: %d)\n",
   3194 				    state, sav->state);
   3195 				continue;
   3196 			}
   3197 
   3198 			if (sav->spi == spi) {
   3199 				SA_ADDREF(sav);
   3200 				goto out;
   3201 			}
   3202 		}
   3203 	}
   3204 out:
   3205 	pserialize_read_exit(s);
   3206 
   3207 	return sav;
   3208 }
   3209 
   3210 /*
   3211  * Free allocated data to member variables of sav:
   3212  * sav->replay, sav->key_* and sav->lft_*.
   3213  */
   3214 static void
   3215 key_freesaval(struct secasvar *sav)
   3216 {
   3217 
   3218 	KASSERT(sav->refcnt == 0);
   3219 
   3220 	if (sav->replay != NULL)
   3221 		kmem_intr_free(sav->replay, sav->replay_len);
   3222 	if (sav->key_auth != NULL)
   3223 		kmem_intr_free(sav->key_auth, sav->key_auth_len);
   3224 	if (sav->key_enc != NULL)
   3225 		kmem_intr_free(sav->key_enc, sav->key_enc_len);
   3226 	if (sav->lft_c != NULL)
   3227 		kmem_intr_free(sav->lft_c, sizeof(*(sav->lft_c)));
   3228 	if (sav->lft_h != NULL)
   3229 		kmem_intr_free(sav->lft_h, sizeof(*(sav->lft_h)));
   3230 	if (sav->lft_s != NULL)
   3231 		kmem_intr_free(sav->lft_s, sizeof(*(sav->lft_s)));
   3232 }
   3233 
   3234 /*
   3235  * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
   3236  * You must update these if need.
   3237  * OUT:	0:	success.
   3238  *	!0:	failure.
   3239  *
   3240  * does not modify mbuf.  does not free mbuf on error.
   3241  */
   3242 static int
   3243 key_setsaval(struct secasvar *sav, struct mbuf *m,
   3244 	     const struct sadb_msghdr *mhp)
   3245 {
   3246 	int error = 0;
   3247 
   3248 	KASSERT(!cpu_softintr_p());
   3249 	KASSERT(m != NULL);
   3250 	KASSERT(mhp != NULL);
   3251 	KASSERT(mhp->msg != NULL);
   3252 
   3253 	/* We shouldn't initialize sav variables while someone uses it. */
   3254 	KASSERT(sav->refcnt == 0);
   3255 
   3256 	/* SA */
   3257 	if (mhp->ext[SADB_EXT_SA] != NULL) {
   3258 		const struct sadb_sa *sa0;
   3259 
   3260 		sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
   3261 		if (mhp->extlen[SADB_EXT_SA] < sizeof(*sa0)) {
   3262 			error = EINVAL;
   3263 			goto fail;
   3264 		}
   3265 
   3266 		sav->alg_auth = sa0->sadb_sa_auth;
   3267 		sav->alg_enc = sa0->sadb_sa_encrypt;
   3268 		sav->flags = sa0->sadb_sa_flags;
   3269 
   3270 		/* replay window */
   3271 		if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) {
   3272 			size_t len = sizeof(struct secreplay) +
   3273 			    sa0->sadb_sa_replay;
   3274 			sav->replay = kmem_zalloc(len, KM_SLEEP);
   3275 			sav->replay_len = len;
   3276 			if (sa0->sadb_sa_replay != 0)
   3277 				sav->replay->bitmap = (char*)(sav->replay+1);
   3278 			sav->replay->wsize = sa0->sadb_sa_replay;
   3279 		}
   3280 	}
   3281 
   3282 	/* Authentication keys */
   3283 	if (mhp->ext[SADB_EXT_KEY_AUTH] != NULL) {
   3284 		const struct sadb_key *key0;
   3285 		int len;
   3286 
   3287 		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
   3288 		len = mhp->extlen[SADB_EXT_KEY_AUTH];
   3289 
   3290 		error = 0;
   3291 		if (len < sizeof(*key0)) {
   3292 			error = EINVAL;
   3293 			goto fail;
   3294 		}
   3295 		switch (mhp->msg->sadb_msg_satype) {
   3296 		case SADB_SATYPE_AH:
   3297 		case SADB_SATYPE_ESP:
   3298 		case SADB_X_SATYPE_TCPSIGNATURE:
   3299 			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
   3300 			    sav->alg_auth != SADB_X_AALG_NULL)
   3301 				error = EINVAL;
   3302 			break;
   3303 		case SADB_X_SATYPE_IPCOMP:
   3304 		default:
   3305 			error = EINVAL;
   3306 			break;
   3307 		}
   3308 		if (error) {
   3309 			IPSECLOG(LOG_DEBUG, "invalid key_auth values.\n");
   3310 			goto fail;
   3311 		}
   3312 
   3313 		sav->key_auth = key_newbuf(key0, len);
   3314 		sav->key_auth_len = len;
   3315 	}
   3316 
   3317 	/* Encryption key */
   3318 	if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) {
   3319 		const struct sadb_key *key0;
   3320 		int len;
   3321 
   3322 		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
   3323 		len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
   3324 
   3325 		error = 0;
   3326 		if (len < sizeof(*key0)) {
   3327 			error = EINVAL;
   3328 			goto fail;
   3329 		}
   3330 		switch (mhp->msg->sadb_msg_satype) {
   3331 		case SADB_SATYPE_ESP:
   3332 			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
   3333 			    sav->alg_enc != SADB_EALG_NULL) {
   3334 				error = EINVAL;
   3335 				break;
   3336 			}
   3337 			sav->key_enc = key_newbuf(key0, len);
   3338 			sav->key_enc_len = len;
   3339 			break;
   3340 		case SADB_X_SATYPE_IPCOMP:
   3341 			if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
   3342 				error = EINVAL;
   3343 			sav->key_enc = NULL;	/*just in case*/
   3344 			break;
   3345 		case SADB_SATYPE_AH:
   3346 		case SADB_X_SATYPE_TCPSIGNATURE:
   3347 		default:
   3348 			error = EINVAL;
   3349 			break;
   3350 		}
   3351 		if (error) {
   3352 			IPSECLOG(LOG_DEBUG, "invalid key_enc value.\n");
   3353 			goto fail;
   3354 		}
   3355 	}
   3356 
   3357 	/* set iv */
   3358 	sav->ivlen = 0;
   3359 
   3360 	switch (mhp->msg->sadb_msg_satype) {
   3361 	case SADB_SATYPE_AH:
   3362 		error = xform_init(sav, XF_AH);
   3363 		break;
   3364 	case SADB_SATYPE_ESP:
   3365 		error = xform_init(sav, XF_ESP);
   3366 		break;
   3367 	case SADB_X_SATYPE_IPCOMP:
   3368 		error = xform_init(sav, XF_IPCOMP);
   3369 		break;
   3370 	case SADB_X_SATYPE_TCPSIGNATURE:
   3371 		error = xform_init(sav, XF_TCPSIGNATURE);
   3372 		break;
   3373 	}
   3374 	if (error) {
   3375 		IPSECLOG(LOG_DEBUG, "unable to initialize SA type %u.\n",
   3376 		    mhp->msg->sadb_msg_satype);
   3377 		goto fail;
   3378 	}
   3379 
   3380 	/* reset created */
   3381 	sav->created = time_uptime;
   3382 
   3383 	/* make lifetime for CURRENT */
   3384 	sav->lft_c = kmem_alloc(sizeof(struct sadb_lifetime), KM_SLEEP);
   3385 
   3386 	sav->lft_c->sadb_lifetime_len =
   3387 	    PFKEY_UNIT64(sizeof(struct sadb_lifetime));
   3388 	sav->lft_c->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
   3389 	sav->lft_c->sadb_lifetime_allocations = 0;
   3390 	sav->lft_c->sadb_lifetime_bytes = 0;
   3391 	sav->lft_c->sadb_lifetime_addtime = time_uptime;
   3392 	sav->lft_c->sadb_lifetime_usetime = 0;
   3393 
   3394 	/* lifetimes for HARD and SOFT */
   3395     {
   3396 	const struct sadb_lifetime *lft0;
   3397 
   3398 	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
   3399 	if (lft0 != NULL) {
   3400 		if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) {
   3401 			error = EINVAL;
   3402 			goto fail;
   3403 		}
   3404 		sav->lft_h = key_newbuf(lft0, sizeof(*lft0));
   3405 	}
   3406 
   3407 	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_SOFT];
   3408 	if (lft0 != NULL) {
   3409 		if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) {
   3410 			error = EINVAL;
   3411 			goto fail;
   3412 		}
   3413 		sav->lft_s = key_newbuf(lft0, sizeof(*lft0));
   3414 		/* to be initialize ? */
   3415 	}
   3416     }
   3417 
   3418 	return 0;
   3419 
   3420  fail:
   3421 	key_clear_xform(sav);
   3422 	key_freesaval(sav);
   3423 
   3424 	return error;
   3425 }
   3426 
   3427 /*
   3428  * validation with a secasvar entry, and set SADB_SATYPE_MATURE.
   3429  * OUT:	0:	valid
   3430  *	other:	errno
   3431  */
   3432 static int
   3433 key_init_xform(struct secasvar *sav)
   3434 {
   3435 	int error;
   3436 
   3437 	/* We shouldn't initialize sav variables while someone uses it. */
   3438 	KASSERT(sav->refcnt == 0);
   3439 
   3440 	/* check SPI value */
   3441 	switch (sav->sah->saidx.proto) {
   3442 	case IPPROTO_ESP:
   3443 	case IPPROTO_AH:
   3444 		if (ntohl(sav->spi) <= 255) {
   3445 			IPSECLOG(LOG_DEBUG, "illegal range of SPI %u.\n",
   3446 			    (u_int32_t)ntohl(sav->spi));
   3447 			return EINVAL;
   3448 		}
   3449 		break;
   3450 	}
   3451 
   3452 	/* check satype */
   3453 	switch (sav->sah->saidx.proto) {
   3454 	case IPPROTO_ESP:
   3455 		/* check flags */
   3456 		if ((sav->flags & (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) ==
   3457 		    (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) {
   3458 			IPSECLOG(LOG_DEBUG,
   3459 			    "invalid flag (derived) given to old-esp.\n");
   3460 			return EINVAL;
   3461 		}
   3462 		error = xform_init(sav, XF_ESP);
   3463 		break;
   3464 	case IPPROTO_AH:
   3465 		/* check flags */
   3466 		if (sav->flags & SADB_X_EXT_DERIV) {
   3467 			IPSECLOG(LOG_DEBUG,
   3468 			    "invalid flag (derived) given to AH SA.\n");
   3469 			return EINVAL;
   3470 		}
   3471 		if (sav->alg_enc != SADB_EALG_NONE) {
   3472 			IPSECLOG(LOG_DEBUG,
   3473 			    "protocol and algorithm mismated.\n");
   3474 			return(EINVAL);
   3475 		}
   3476 		error = xform_init(sav, XF_AH);
   3477 		break;
   3478 	case IPPROTO_IPCOMP:
   3479 		if (sav->alg_auth != SADB_AALG_NONE) {
   3480 			IPSECLOG(LOG_DEBUG,
   3481 			    "protocol and algorithm mismated.\n");
   3482 			return(EINVAL);
   3483 		}
   3484 		if ((sav->flags & SADB_X_EXT_RAWCPI) == 0
   3485 		 && ntohl(sav->spi) >= 0x10000) {
   3486 			IPSECLOG(LOG_DEBUG, "invalid cpi for IPComp.\n");
   3487 			return(EINVAL);
   3488 		}
   3489 		error = xform_init(sav, XF_IPCOMP);
   3490 		break;
   3491 	case IPPROTO_TCP:
   3492 		if (sav->alg_enc != SADB_EALG_NONE) {
   3493 			IPSECLOG(LOG_DEBUG,
   3494 			    "protocol and algorithm mismated.\n");
   3495 			return(EINVAL);
   3496 		}
   3497 		error = xform_init(sav, XF_TCPSIGNATURE);
   3498 		break;
   3499 	default:
   3500 		IPSECLOG(LOG_DEBUG, "Invalid satype.\n");
   3501 		error = EPROTONOSUPPORT;
   3502 		break;
   3503 	}
   3504 
   3505 	return error;
   3506 }
   3507 
   3508 /*
   3509  * subroutine for SADB_GET and SADB_DUMP.
   3510  */
   3511 static struct mbuf *
   3512 key_setdumpsa(struct secasvar *sav, u_int8_t type, u_int8_t satype,
   3513 	      u_int32_t seq, u_int32_t pid)
   3514 {
   3515 	struct mbuf *result = NULL, *tres = NULL, *m;
   3516 	int l = 0;
   3517 	int i;
   3518 	void *p;
   3519 	struct sadb_lifetime lt;
   3520 	int dumporder[] = {
   3521 		SADB_EXT_SA, SADB_X_EXT_SA2,
   3522 		SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
   3523 		SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
   3524 		SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
   3525 		SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
   3526 		SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
   3527 		SADB_X_EXT_NAT_T_TYPE,
   3528 		SADB_X_EXT_NAT_T_SPORT, SADB_X_EXT_NAT_T_DPORT,
   3529 		SADB_X_EXT_NAT_T_OAI, SADB_X_EXT_NAT_T_OAR,
   3530 		SADB_X_EXT_NAT_T_FRAG,
   3531 
   3532 	};
   3533 
   3534 	m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
   3535 	if (m == NULL)
   3536 		goto fail;
   3537 	result = m;
   3538 
   3539 	for (i = __arraycount(dumporder) - 1; i >= 0; i--) {
   3540 		m = NULL;
   3541 		p = NULL;
   3542 		switch (dumporder[i]) {
   3543 		case SADB_EXT_SA:
   3544 			m = key_setsadbsa(sav);
   3545 			break;
   3546 
   3547 		case SADB_X_EXT_SA2:
   3548 			m = key_setsadbxsa2(sav->sah->saidx.mode,
   3549 			    sav->replay ? sav->replay->count : 0,
   3550 			    sav->sah->saidx.reqid);
   3551 			break;
   3552 
   3553 		case SADB_EXT_ADDRESS_SRC:
   3554 			m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
   3555 			    &sav->sah->saidx.src.sa,
   3556 			    FULLMASK, IPSEC_ULPROTO_ANY);
   3557 			break;
   3558 
   3559 		case SADB_EXT_ADDRESS_DST:
   3560 			m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
   3561 			    &sav->sah->saidx.dst.sa,
   3562 			    FULLMASK, IPSEC_ULPROTO_ANY);
   3563 			break;
   3564 
   3565 		case SADB_EXT_KEY_AUTH:
   3566 			if (!sav->key_auth)
   3567 				continue;
   3568 			l = PFKEY_UNUNIT64(sav->key_auth->sadb_key_len);
   3569 			p = sav->key_auth;
   3570 			break;
   3571 
   3572 		case SADB_EXT_KEY_ENCRYPT:
   3573 			if (!sav->key_enc)
   3574 				continue;
   3575 			l = PFKEY_UNUNIT64(sav->key_enc->sadb_key_len);
   3576 			p = sav->key_enc;
   3577 			break;
   3578 
   3579 		case SADB_EXT_LIFETIME_CURRENT:
   3580 			KASSERT(sav->lft_c != NULL);
   3581 			l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_c)->sadb_ext_len);
   3582 			memcpy(&lt, sav->lft_c, sizeof(struct sadb_lifetime));
   3583 			lt.sadb_lifetime_addtime =
   3584 			    time_mono_to_wall(lt.sadb_lifetime_addtime);
   3585 			lt.sadb_lifetime_usetime =
   3586 			    time_mono_to_wall(lt.sadb_lifetime_usetime);
   3587 			p = &lt;
   3588 			break;
   3589 
   3590 		case SADB_EXT_LIFETIME_HARD:
   3591 			if (!sav->lft_h)
   3592 				continue;
   3593 			l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_h)->sadb_ext_len);
   3594 			p = sav->lft_h;
   3595 			break;
   3596 
   3597 		case SADB_EXT_LIFETIME_SOFT:
   3598 			if (!sav->lft_s)
   3599 				continue;
   3600 			l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_s)->sadb_ext_len);
   3601 			p = sav->lft_s;
   3602 			break;
   3603 
   3604 		case SADB_X_EXT_NAT_T_TYPE:
   3605 			m = key_setsadbxtype(sav->natt_type);
   3606 			break;
   3607 
   3608 		case SADB_X_EXT_NAT_T_DPORT:
   3609 			if (sav->natt_type == 0)
   3610 				continue;
   3611 			m = key_setsadbxport(
   3612 			    key_portfromsaddr(&sav->sah->saidx.dst),
   3613 			    SADB_X_EXT_NAT_T_DPORT);
   3614 			break;
   3615 
   3616 		case SADB_X_EXT_NAT_T_SPORT:
   3617 			if (sav->natt_type == 0)
   3618 				continue;
   3619 			m = key_setsadbxport(
   3620 			    key_portfromsaddr(&sav->sah->saidx.src),
   3621 			    SADB_X_EXT_NAT_T_SPORT);
   3622 			break;
   3623 
   3624 		case SADB_X_EXT_NAT_T_FRAG:
   3625 			/* don't send frag info if not set */
   3626 			if (sav->natt_type == 0 || sav->esp_frag == IP_MAXPACKET)
   3627 				continue;
   3628 			m = key_setsadbxfrag(sav->esp_frag);
   3629 			break;
   3630 
   3631 		case SADB_X_EXT_NAT_T_OAI:
   3632 		case SADB_X_EXT_NAT_T_OAR:
   3633 			continue;
   3634 
   3635 		case SADB_EXT_ADDRESS_PROXY:
   3636 		case SADB_EXT_IDENTITY_SRC:
   3637 		case SADB_EXT_IDENTITY_DST:
   3638 			/* XXX: should we brought from SPD ? */
   3639 		case SADB_EXT_SENSITIVITY:
   3640 		default:
   3641 			continue;
   3642 		}
   3643 
   3644 		KASSERT(!(m && p));
   3645 		if (!m && !p)
   3646 			goto fail;
   3647 		if (p && tres) {
   3648 			M_PREPEND(tres, l, M_DONTWAIT);
   3649 			if (!tres)
   3650 				goto fail;
   3651 			memcpy(mtod(tres, void *), p, l);
   3652 			continue;
   3653 		}
   3654 		if (p) {
   3655 			m = key_alloc_mbuf(l);
   3656 			if (!m)
   3657 				goto fail;
   3658 			m_copyback(m, 0, l, p);
   3659 		}
   3660 
   3661 		if (tres)
   3662 			m_cat(m, tres);
   3663 		tres = m;
   3664 	}
   3665 
   3666 	m_cat(result, tres);
   3667 	tres = NULL; /* avoid free on error below */
   3668 
   3669 	if (result->m_len < sizeof(struct sadb_msg)) {
   3670 		result = m_pullup(result, sizeof(struct sadb_msg));
   3671 		if (result == NULL)
   3672 			goto fail;
   3673 	}
   3674 
   3675 	result->m_pkthdr.len = 0;
   3676 	for (m = result; m; m = m->m_next)
   3677 		result->m_pkthdr.len += m->m_len;
   3678 
   3679 	mtod(result, struct sadb_msg *)->sadb_msg_len =
   3680 	    PFKEY_UNIT64(result->m_pkthdr.len);
   3681 
   3682 	return result;
   3683 
   3684 fail:
   3685 	m_freem(result);
   3686 	m_freem(tres);
   3687 	return NULL;
   3688 }
   3689 
   3690 
   3691 /*
   3692  * set a type in sadb_x_nat_t_type
   3693  */
   3694 static struct mbuf *
   3695 key_setsadbxtype(u_int16_t type)
   3696 {
   3697 	struct mbuf *m;
   3698 	size_t len;
   3699 	struct sadb_x_nat_t_type *p;
   3700 
   3701 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_type));
   3702 
   3703 	m = key_alloc_mbuf(len);
   3704 	if (!m || m->m_next) {	/*XXX*/
   3705 		if (m)
   3706 			m_freem(m);
   3707 		return NULL;
   3708 	}
   3709 
   3710 	p = mtod(m, struct sadb_x_nat_t_type *);
   3711 
   3712 	memset(p, 0, len);
   3713 	p->sadb_x_nat_t_type_len = PFKEY_UNIT64(len);
   3714 	p->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE;
   3715 	p->sadb_x_nat_t_type_type = type;
   3716 
   3717 	return m;
   3718 }
   3719 /*
   3720  * set a port in sadb_x_nat_t_port. port is in network order
   3721  */
   3722 static struct mbuf *
   3723 key_setsadbxport(u_int16_t port, u_int16_t type)
   3724 {
   3725 	struct mbuf *m;
   3726 	size_t len;
   3727 	struct sadb_x_nat_t_port *p;
   3728 
   3729 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_port));
   3730 
   3731 	m = key_alloc_mbuf(len);
   3732 	if (!m || m->m_next) {	/*XXX*/
   3733 		if (m)
   3734 			m_freem(m);
   3735 		return NULL;
   3736 	}
   3737 
   3738 	p = mtod(m, struct sadb_x_nat_t_port *);
   3739 
   3740 	memset(p, 0, len);
   3741 	p->sadb_x_nat_t_port_len = PFKEY_UNIT64(len);
   3742 	p->sadb_x_nat_t_port_exttype = type;
   3743 	p->sadb_x_nat_t_port_port = port;
   3744 
   3745 	return m;
   3746 }
   3747 
   3748 /*
   3749  * set fragmentation info in sadb_x_nat_t_frag
   3750  */
   3751 static struct mbuf *
   3752 key_setsadbxfrag(u_int16_t flen)
   3753 {
   3754 	struct mbuf *m;
   3755 	size_t len;
   3756 	struct sadb_x_nat_t_frag *p;
   3757 
   3758 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_frag));
   3759 
   3760 	m = key_alloc_mbuf(len);
   3761 	if (!m || m->m_next) {  /*XXX*/
   3762 		if (m)
   3763 			m_freem(m);
   3764 		return NULL;
   3765 	}
   3766 
   3767 	p = mtod(m, struct sadb_x_nat_t_frag *);
   3768 
   3769 	memset(p, 0, len);
   3770 	p->sadb_x_nat_t_frag_len = PFKEY_UNIT64(len);
   3771 	p->sadb_x_nat_t_frag_exttype = SADB_X_EXT_NAT_T_FRAG;
   3772 	p->sadb_x_nat_t_frag_fraglen = flen;
   3773 
   3774 	return m;
   3775 }
   3776 
   3777 /*
   3778  * Get port from sockaddr, port is in network order
   3779  */
   3780 u_int16_t
   3781 key_portfromsaddr(const union sockaddr_union *saddr)
   3782 {
   3783 	u_int16_t port;
   3784 
   3785 	switch (saddr->sa.sa_family) {
   3786 	case AF_INET: {
   3787 		port = saddr->sin.sin_port;
   3788 		break;
   3789 	}
   3790 #ifdef INET6
   3791 	case AF_INET6: {
   3792 		port = saddr->sin6.sin6_port;
   3793 		break;
   3794 	}
   3795 #endif
   3796 	default:
   3797 		printf("%s: unexpected address family\n", __func__);
   3798 		port = 0;
   3799 		break;
   3800 	}
   3801 
   3802 	return port;
   3803 }
   3804 
   3805 
   3806 /*
   3807  * Set port is struct sockaddr. port is in network order
   3808  */
   3809 static void
   3810 key_porttosaddr(union sockaddr_union *saddr, u_int16_t port)
   3811 {
   3812 	switch (saddr->sa.sa_family) {
   3813 	case AF_INET: {
   3814 		saddr->sin.sin_port = port;
   3815 		break;
   3816 	}
   3817 #ifdef INET6
   3818 	case AF_INET6: {
   3819 		saddr->sin6.sin6_port = port;
   3820 		break;
   3821 	}
   3822 #endif
   3823 	default:
   3824 		printf("%s: unexpected address family %d\n", __func__,
   3825 		    saddr->sa.sa_family);
   3826 		break;
   3827 	}
   3828 
   3829 	return;
   3830 }
   3831 
   3832 /*
   3833  * Safety check sa_len
   3834  */
   3835 static int
   3836 key_checksalen(const union sockaddr_union *saddr)
   3837 {
   3838 	switch (saddr->sa.sa_family) {
   3839 	case AF_INET:
   3840 		if (saddr->sa.sa_len != sizeof(struct sockaddr_in))
   3841 			return -1;
   3842 		break;
   3843 #ifdef INET6
   3844 	case AF_INET6:
   3845 		if (saddr->sa.sa_len != sizeof(struct sockaddr_in6))
   3846 			return -1;
   3847 		break;
   3848 #endif
   3849 	default:
   3850 		printf("%s: unexpected sa_family %d\n", __func__,
   3851 		    saddr->sa.sa_family);
   3852 			return -1;
   3853 		break;
   3854 	}
   3855 	return 0;
   3856 }
   3857 
   3858 
   3859 /*
   3860  * set data into sadb_msg.
   3861  */
   3862 static struct mbuf *
   3863 key_setsadbmsg(u_int8_t type,  u_int16_t tlen, u_int8_t satype,
   3864 	       u_int32_t seq, pid_t pid, u_int16_t reserved)
   3865 {
   3866 	struct mbuf *m;
   3867 	struct sadb_msg *p;
   3868 	int len;
   3869 
   3870 	CTASSERT(PFKEY_ALIGN8(sizeof(struct sadb_msg)) <= MCLBYTES);
   3871 
   3872 	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
   3873 
   3874 	MGETHDR(m, M_DONTWAIT, MT_DATA);
   3875 	if (m && len > MHLEN) {
   3876 		MCLGET(m, M_DONTWAIT);
   3877 		if ((m->m_flags & M_EXT) == 0) {
   3878 			m_freem(m);
   3879 			m = NULL;
   3880 		}
   3881 	}
   3882 	if (!m)
   3883 		return NULL;
   3884 	m->m_pkthdr.len = m->m_len = len;
   3885 	m->m_next = NULL;
   3886 
   3887 	p = mtod(m, struct sadb_msg *);
   3888 
   3889 	memset(p, 0, len);
   3890 	p->sadb_msg_version = PF_KEY_V2;
   3891 	p->sadb_msg_type = type;
   3892 	p->sadb_msg_errno = 0;
   3893 	p->sadb_msg_satype = satype;
   3894 	p->sadb_msg_len = PFKEY_UNIT64(tlen);
   3895 	p->sadb_msg_reserved = reserved;
   3896 	p->sadb_msg_seq = seq;
   3897 	p->sadb_msg_pid = (u_int32_t)pid;
   3898 
   3899 	return m;
   3900 }
   3901 
   3902 /*
   3903  * copy secasvar data into sadb_address.
   3904  */
   3905 static struct mbuf *
   3906 key_setsadbsa(struct secasvar *sav)
   3907 {
   3908 	struct mbuf *m;
   3909 	struct sadb_sa *p;
   3910 	int len;
   3911 
   3912 	len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
   3913 	m = key_alloc_mbuf(len);
   3914 	if (!m || m->m_next) {	/*XXX*/
   3915 		if (m)
   3916 			m_freem(m);
   3917 		return NULL;
   3918 	}
   3919 
   3920 	p = mtod(m, struct sadb_sa *);
   3921 
   3922 	memset(p, 0, len);
   3923 	p->sadb_sa_len = PFKEY_UNIT64(len);
   3924 	p->sadb_sa_exttype = SADB_EXT_SA;
   3925 	p->sadb_sa_spi = sav->spi;
   3926 	p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
   3927 	p->sadb_sa_state = sav->state;
   3928 	p->sadb_sa_auth = sav->alg_auth;
   3929 	p->sadb_sa_encrypt = sav->alg_enc;
   3930 	p->sadb_sa_flags = sav->flags;
   3931 
   3932 	return m;
   3933 }
   3934 
   3935 /*
   3936  * set data into sadb_address.
   3937  */
   3938 static struct mbuf *
   3939 key_setsadbaddr(u_int16_t exttype, const struct sockaddr *saddr,
   3940 		u_int8_t prefixlen, u_int16_t ul_proto)
   3941 {
   3942 	struct mbuf *m;
   3943 	struct sadb_address *p;
   3944 	size_t len;
   3945 
   3946 	len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
   3947 	    PFKEY_ALIGN8(saddr->sa_len);
   3948 	m = key_alloc_mbuf(len);
   3949 	if (!m || m->m_next) {	/*XXX*/
   3950 		if (m)
   3951 			m_freem(m);
   3952 		return NULL;
   3953 	}
   3954 
   3955 	p = mtod(m, struct sadb_address *);
   3956 
   3957 	memset(p, 0, len);
   3958 	p->sadb_address_len = PFKEY_UNIT64(len);
   3959 	p->sadb_address_exttype = exttype;
   3960 	p->sadb_address_proto = ul_proto;
   3961 	if (prefixlen == FULLMASK) {
   3962 		switch (saddr->sa_family) {
   3963 		case AF_INET:
   3964 			prefixlen = sizeof(struct in_addr) << 3;
   3965 			break;
   3966 		case AF_INET6:
   3967 			prefixlen = sizeof(struct in6_addr) << 3;
   3968 			break;
   3969 		default:
   3970 			; /*XXX*/
   3971 		}
   3972 	}
   3973 	p->sadb_address_prefixlen = prefixlen;
   3974 	p->sadb_address_reserved = 0;
   3975 
   3976 	memcpy(mtod(m, char *) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
   3977 	    saddr, saddr->sa_len);
   3978 
   3979 	return m;
   3980 }
   3981 
   3982 #if 0
   3983 /*
   3984  * set data into sadb_ident.
   3985  */
   3986 static struct mbuf *
   3987 key_setsadbident(u_int16_t exttype, u_int16_t idtype,
   3988 		 void *string, int stringlen, u_int64_t id)
   3989 {
   3990 	struct mbuf *m;
   3991 	struct sadb_ident *p;
   3992 	size_t len;
   3993 
   3994 	len = PFKEY_ALIGN8(sizeof(struct sadb_ident)) + PFKEY_ALIGN8(stringlen);
   3995 	m = key_alloc_mbuf(len);
   3996 	if (!m || m->m_next) {	/*XXX*/
   3997 		if (m)
   3998 			m_freem(m);
   3999 		return NULL;
   4000 	}
   4001 
   4002 	p = mtod(m, struct sadb_ident *);
   4003 
   4004 	memset(p, 0, len);
   4005 	p->sadb_ident_len = PFKEY_UNIT64(len);
   4006 	p->sadb_ident_exttype = exttype;
   4007 	p->sadb_ident_type = idtype;
   4008 	p->sadb_ident_reserved = 0;
   4009 	p->sadb_ident_id = id;
   4010 
   4011 	memcpy(mtod(m, void *) + PFKEY_ALIGN8(sizeof(struct sadb_ident)),
   4012 	   	   string, stringlen);
   4013 
   4014 	return m;
   4015 }
   4016 #endif
   4017 
   4018 /*
   4019  * set data into sadb_x_sa2.
   4020  */
   4021 static struct mbuf *
   4022 key_setsadbxsa2(u_int8_t mode, u_int32_t seq, u_int16_t reqid)
   4023 {
   4024 	struct mbuf *m;
   4025 	struct sadb_x_sa2 *p;
   4026 	size_t len;
   4027 
   4028 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
   4029 	m = key_alloc_mbuf(len);
   4030 	if (!m || m->m_next) {	/*XXX*/
   4031 		if (m)
   4032 			m_freem(m);
   4033 		return NULL;
   4034 	}
   4035 
   4036 	p = mtod(m, struct sadb_x_sa2 *);
   4037 
   4038 	memset(p, 0, len);
   4039 	p->sadb_x_sa2_len = PFKEY_UNIT64(len);
   4040 	p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
   4041 	p->sadb_x_sa2_mode = mode;
   4042 	p->sadb_x_sa2_reserved1 = 0;
   4043 	p->sadb_x_sa2_reserved2 = 0;
   4044 	p->sadb_x_sa2_sequence = seq;
   4045 	p->sadb_x_sa2_reqid = reqid;
   4046 
   4047 	return m;
   4048 }
   4049 
   4050 /*
   4051  * set data into sadb_x_policy
   4052  */
   4053 static struct mbuf *
   4054 key_setsadbxpolicy(u_int16_t type, u_int8_t dir, u_int32_t id)
   4055 {
   4056 	struct mbuf *m;
   4057 	struct sadb_x_policy *p;
   4058 	size_t len;
   4059 
   4060 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
   4061 	m = key_alloc_mbuf(len);
   4062 	if (!m || m->m_next) {	/*XXX*/
   4063 		if (m)
   4064 			m_freem(m);
   4065 		return NULL;
   4066 	}
   4067 
   4068 	p = mtod(m, struct sadb_x_policy *);
   4069 
   4070 	memset(p, 0, len);
   4071 	p->sadb_x_policy_len = PFKEY_UNIT64(len);
   4072 	p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
   4073 	p->sadb_x_policy_type = type;
   4074 	p->sadb_x_policy_dir = dir;
   4075 	p->sadb_x_policy_id = id;
   4076 
   4077 	return m;
   4078 }
   4079 
   4080 /* %%% utilities */
   4081 /*
   4082  * copy a buffer into the new buffer allocated.
   4083  */
   4084 static void *
   4085 key_newbuf(const void *src, u_int len)
   4086 {
   4087 	void *new;
   4088 
   4089 	new = kmem_alloc(len, KM_SLEEP);
   4090 	memcpy(new, src, len);
   4091 
   4092 	return new;
   4093 }
   4094 
   4095 /* compare my own address
   4096  * OUT:	1: true, i.e. my address.
   4097  *	0: false
   4098  */
   4099 int
   4100 key_ismyaddr(const struct sockaddr *sa)
   4101 {
   4102 #ifdef INET
   4103 	const struct sockaddr_in *sin;
   4104 	const struct in_ifaddr *ia;
   4105 	int s;
   4106 #endif
   4107 
   4108 	KASSERT(sa != NULL);
   4109 
   4110 	switch (sa->sa_family) {
   4111 #ifdef INET
   4112 	case AF_INET:
   4113 		sin = (const struct sockaddr_in *)sa;
   4114 		s = pserialize_read_enter();
   4115 		IN_ADDRLIST_READER_FOREACH(ia) {
   4116 			if (sin->sin_family == ia->ia_addr.sin_family &&
   4117 			    sin->sin_len == ia->ia_addr.sin_len &&
   4118 			    sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
   4119 			{
   4120 				pserialize_read_exit(s);
   4121 				return 1;
   4122 			}
   4123 		}
   4124 		pserialize_read_exit(s);
   4125 		break;
   4126 #endif
   4127 #ifdef INET6
   4128 	case AF_INET6:
   4129 		return key_ismyaddr6((const struct sockaddr_in6 *)sa);
   4130 #endif
   4131 	}
   4132 
   4133 	return 0;
   4134 }
   4135 
   4136 #ifdef INET6
   4137 /*
   4138  * compare my own address for IPv6.
   4139  * 1: ours
   4140  * 0: other
   4141  * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
   4142  */
   4143 #include <netinet6/in6_var.h>
   4144 
   4145 static int
   4146 key_ismyaddr6(const struct sockaddr_in6 *sin6)
   4147 {
   4148 	struct in6_ifaddr *ia;
   4149 	int s;
   4150 	struct psref psref;
   4151 	int bound;
   4152 	int ours = 1;
   4153 
   4154 	bound = curlwp_bind();
   4155 	s = pserialize_read_enter();
   4156 	IN6_ADDRLIST_READER_FOREACH(ia) {
   4157 		bool ingroup;
   4158 
   4159 		if (key_sockaddr_match((const struct sockaddr *)&sin6,
   4160 		    (const struct sockaddr *)&ia->ia_addr, 0)) {
   4161 			pserialize_read_exit(s);
   4162 			goto ours;
   4163 		}
   4164 		ia6_acquire(ia, &psref);
   4165 		pserialize_read_exit(s);
   4166 
   4167 		/*
   4168 		 * XXX Multicast
   4169 		 * XXX why do we care about multlicast here while we don't care
   4170 		 * about IPv4 multicast??
   4171 		 * XXX scope
   4172 		 */
   4173 		ingroup = in6_multi_group(&sin6->sin6_addr, ia->ia_ifp);
   4174 		if (ingroup) {
   4175 			ia6_release(ia, &psref);
   4176 			goto ours;
   4177 		}
   4178 
   4179 		s = pserialize_read_enter();
   4180 		ia6_release(ia, &psref);
   4181 	}
   4182 	pserialize_read_exit(s);
   4183 
   4184 	/* loopback, just for safety */
   4185 	if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
   4186 		goto ours;
   4187 
   4188 	ours = 0;
   4189 ours:
   4190 	curlwp_bindx(bound);
   4191 
   4192 	return ours;
   4193 }
   4194 #endif /*INET6*/
   4195 
   4196 /*
   4197  * compare two secasindex structure.
   4198  * flag can specify to compare 2 saidxes.
   4199  * compare two secasindex structure without both mode and reqid.
   4200  * don't compare port.
   4201  * IN:
   4202  *      saidx0: source, it can be in SAD.
   4203  *      saidx1: object.
   4204  * OUT:
   4205  *      1 : equal
   4206  *      0 : not equal
   4207  */
   4208 static int
   4209 key_saidx_match(
   4210 	const struct secasindex *saidx0,
   4211 	const struct secasindex *saidx1,
   4212 	int flag)
   4213 {
   4214 	int chkport;
   4215 	const struct sockaddr *sa0src, *sa0dst, *sa1src, *sa1dst;
   4216 
   4217 	KASSERT(saidx0 != NULL);
   4218 	KASSERT(saidx1 != NULL);
   4219 
   4220 	/* sanity */
   4221 	if (saidx0->proto != saidx1->proto)
   4222 		return 0;
   4223 
   4224 	if (flag == CMP_EXACTLY) {
   4225 		if (saidx0->mode != saidx1->mode)
   4226 			return 0;
   4227 		if (saidx0->reqid != saidx1->reqid)
   4228 			return 0;
   4229 		if (memcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
   4230 		    memcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
   4231 			return 0;
   4232 	} else {
   4233 
   4234 		/* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
   4235 		if (flag == CMP_MODE_REQID ||flag == CMP_REQID) {
   4236 			/*
   4237 			 * If reqid of SPD is non-zero, unique SA is required.
   4238 			 * The result must be of same reqid in this case.
   4239 			 */
   4240 			if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
   4241 				return 0;
   4242 		}
   4243 
   4244 		if (flag == CMP_MODE_REQID) {
   4245 			if (saidx0->mode != IPSEC_MODE_ANY &&
   4246 			    saidx0->mode != saidx1->mode)
   4247 				return 0;
   4248 		}
   4249 
   4250 
   4251 		sa0src = &saidx0->src.sa;
   4252 		sa0dst = &saidx0->dst.sa;
   4253 		sa1src = &saidx1->src.sa;
   4254 		sa1dst = &saidx1->dst.sa;
   4255 		/*
   4256 		 * If NAT-T is enabled, check ports for tunnel mode.
   4257 		 * Don't do it for transport mode, as there is no
   4258 		 * port information available in the SP.
   4259 		 * Also don't check ports if they are set to zero
   4260 		 * in the SPD: This means we have a non-generated
   4261 		 * SPD which can't know UDP ports.
   4262 		 */
   4263 		if (saidx1->mode == IPSEC_MODE_TUNNEL)
   4264 			chkport = PORT_LOOSE;
   4265 		else
   4266 			chkport = PORT_NONE;
   4267 
   4268 		if (!key_sockaddr_match(sa0src, sa1src, chkport)) {
   4269 			return 0;
   4270 		}
   4271 		if (!key_sockaddr_match(sa0dst, sa1dst, chkport)) {
   4272 			return 0;
   4273 		}
   4274 	}
   4275 
   4276 	return 1;
   4277 }
   4278 
   4279 /*
   4280  * compare two secindex structure exactly.
   4281  * IN:
   4282  *	spidx0: source, it is often in SPD.
   4283  *	spidx1: object, it is often from PFKEY message.
   4284  * OUT:
   4285  *	1 : equal
   4286  *	0 : not equal
   4287  */
   4288 static int
   4289 key_spidx_match_exactly(
   4290 	const struct secpolicyindex *spidx0,
   4291 	const struct secpolicyindex *spidx1)
   4292 {
   4293 
   4294 	KASSERT(spidx0 != NULL);
   4295 	KASSERT(spidx1 != NULL);
   4296 
   4297 	/* sanity */
   4298 	if (spidx0->prefs != spidx1->prefs ||
   4299 	    spidx0->prefd != spidx1->prefd ||
   4300 	    spidx0->ul_proto != spidx1->ul_proto)
   4301 		return 0;
   4302 
   4303 	return key_sockaddr_match(&spidx0->src.sa, &spidx1->src.sa, PORT_STRICT) &&
   4304 	       key_sockaddr_match(&spidx0->dst.sa, &spidx1->dst.sa, PORT_STRICT);
   4305 }
   4306 
   4307 /*
   4308  * compare two secindex structure with mask.
   4309  * IN:
   4310  *	spidx0: source, it is often in SPD.
   4311  *	spidx1: object, it is often from IP header.
   4312  * OUT:
   4313  *	1 : equal
   4314  *	0 : not equal
   4315  */
   4316 static int
   4317 key_spidx_match_withmask(
   4318 	const struct secpolicyindex *spidx0,
   4319 	const struct secpolicyindex *spidx1)
   4320 {
   4321 
   4322 	KASSERT(spidx0 != NULL);
   4323 	KASSERT(spidx1 != NULL);
   4324 
   4325 	if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
   4326 	    spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
   4327 	    spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
   4328 	    spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
   4329 		return 0;
   4330 
   4331 	/* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
   4332 	if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY &&
   4333 	    spidx0->ul_proto != spidx1->ul_proto)
   4334 		return 0;
   4335 
   4336 	switch (spidx0->src.sa.sa_family) {
   4337 	case AF_INET:
   4338 		if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY &&
   4339 		    spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
   4340 			return 0;
   4341 		if (!key_bb_match_withmask(&spidx0->src.sin.sin_addr,
   4342 		    &spidx1->src.sin.sin_addr, spidx0->prefs))
   4343 			return 0;
   4344 		break;
   4345 	case AF_INET6:
   4346 		if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY &&
   4347 		    spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
   4348 			return 0;
   4349 		/*
   4350 		 * scope_id check. if sin6_scope_id is 0, we regard it
   4351 		 * as a wildcard scope, which matches any scope zone ID.
   4352 		 */
   4353 		if (spidx0->src.sin6.sin6_scope_id &&
   4354 		    spidx1->src.sin6.sin6_scope_id &&
   4355 		    spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
   4356 			return 0;
   4357 		if (!key_bb_match_withmask(&spidx0->src.sin6.sin6_addr,
   4358 		    &spidx1->src.sin6.sin6_addr, spidx0->prefs))
   4359 			return 0;
   4360 		break;
   4361 	default:
   4362 		/* XXX */
   4363 		if (memcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
   4364 			return 0;
   4365 		break;
   4366 	}
   4367 
   4368 	switch (spidx0->dst.sa.sa_family) {
   4369 	case AF_INET:
   4370 		if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY &&
   4371 		    spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
   4372 			return 0;
   4373 		if (!key_bb_match_withmask(&spidx0->dst.sin.sin_addr,
   4374 		    &spidx1->dst.sin.sin_addr, spidx0->prefd))
   4375 			return 0;
   4376 		break;
   4377 	case AF_INET6:
   4378 		if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY &&
   4379 		    spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
   4380 			return 0;
   4381 		/*
   4382 		 * scope_id check. if sin6_scope_id is 0, we regard it
   4383 		 * as a wildcard scope, which matches any scope zone ID.
   4384 		 */
   4385 		if (spidx0->src.sin6.sin6_scope_id &&
   4386 		    spidx1->src.sin6.sin6_scope_id &&
   4387 		    spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
   4388 			return 0;
   4389 		if (!key_bb_match_withmask(&spidx0->dst.sin6.sin6_addr,
   4390 		    &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
   4391 			return 0;
   4392 		break;
   4393 	default:
   4394 		/* XXX */
   4395 		if (memcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
   4396 			return 0;
   4397 		break;
   4398 	}
   4399 
   4400 	/* XXX Do we check other field ?  e.g. flowinfo */
   4401 
   4402 	return 1;
   4403 }
   4404 
   4405 /* returns 0 on match */
   4406 static int
   4407 key_portcomp(in_port_t port1, in_port_t port2, int howport)
   4408 {
   4409 	switch (howport) {
   4410 	case PORT_NONE:
   4411 		return 0;
   4412 	case PORT_LOOSE:
   4413 		if (port1 == 0 || port2 == 0)
   4414 			return 0;
   4415 		/*FALLTHROUGH*/
   4416 	case PORT_STRICT:
   4417 		if (port1 != port2) {
   4418 			KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
   4419 			    "port fail %d != %d\n", port1, port2);
   4420 			return 1;
   4421 		}
   4422 		return 0;
   4423 	default:
   4424 		KASSERT(0);
   4425 		return 1;
   4426 	}
   4427 }
   4428 
   4429 /* returns 1 on match */
   4430 static int
   4431 key_sockaddr_match(
   4432 	const struct sockaddr *sa1,
   4433 	const struct sockaddr *sa2,
   4434 	int howport)
   4435 {
   4436 	const struct sockaddr_in *sin1, *sin2;
   4437 	const struct sockaddr_in6 *sin61, *sin62;
   4438 
   4439 	if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len) {
   4440 		KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
   4441 		    "fam/len fail %d != %d || %d != %d\n",
   4442 			sa1->sa_family, sa2->sa_family, sa1->sa_len,
   4443 			sa2->sa_len);
   4444 		return 0;
   4445 	}
   4446 
   4447 	switch (sa1->sa_family) {
   4448 	case AF_INET:
   4449 		if (sa1->sa_len != sizeof(struct sockaddr_in)) {
   4450 			KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
   4451 			    "len fail %d != %zu\n",
   4452 			    sa1->sa_len, sizeof(struct sockaddr_in));
   4453 			return 0;
   4454 		}
   4455 		sin1 = (const struct sockaddr_in *)sa1;
   4456 		sin2 = (const struct sockaddr_in *)sa2;
   4457 		if (sin1->sin_addr.s_addr != sin2->sin_addr.s_addr) {
   4458 			KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
   4459 			    "addr fail %#x != %#x\n",
   4460 			    sin1->sin_addr.s_addr, sin2->sin_addr.s_addr);
   4461 			return 0;
   4462 		}
   4463 		if (key_portcomp(sin1->sin_port, sin2->sin_port, howport)) {
   4464 			return 0;
   4465 		}
   4466 		KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
   4467 		    "addr success %#x[%d] == %#x[%d]\n",
   4468 		    sin1->sin_addr.s_addr, sin1->sin_port,
   4469 		    sin2->sin_addr.s_addr, sin2->sin_port);
   4470 		break;
   4471 	case AF_INET6:
   4472 		sin61 = (const struct sockaddr_in6 *)sa1;
   4473 		sin62 = (const struct sockaddr_in6 *)sa2;
   4474 		if (sa1->sa_len != sizeof(struct sockaddr_in6))
   4475 			return 0;	/*EINVAL*/
   4476 
   4477 		if (sin61->sin6_scope_id != sin62->sin6_scope_id) {
   4478 			return 0;
   4479 		}
   4480 		if (!IN6_ARE_ADDR_EQUAL(&sin61->sin6_addr, &sin62->sin6_addr)) {
   4481 			return 0;
   4482 		}
   4483 		if (key_portcomp(sin61->sin6_port, sin62->sin6_port, howport)) {
   4484 			return 0;
   4485 		}
   4486 		break;
   4487 	default:
   4488 		if (memcmp(sa1, sa2, sa1->sa_len) != 0)
   4489 			return 0;
   4490 		break;
   4491 	}
   4492 
   4493 	return 1;
   4494 }
   4495 
   4496 /*
   4497  * compare two buffers with mask.
   4498  * IN:
   4499  *	addr1: source
   4500  *	addr2: object
   4501  *	bits:  Number of bits to compare
   4502  * OUT:
   4503  *	1 : equal
   4504  *	0 : not equal
   4505  */
   4506 static int
   4507 key_bb_match_withmask(const void *a1, const void *a2, u_int bits)
   4508 {
   4509 	const unsigned char *p1 = a1;
   4510 	const unsigned char *p2 = a2;
   4511 
   4512 	/* XXX: This could be considerably faster if we compare a word
   4513 	 * at a time, but it is complicated on LSB Endian machines */
   4514 
   4515 	/* Handle null pointers */
   4516 	if (p1 == NULL || p2 == NULL)
   4517 		return (p1 == p2);
   4518 
   4519 	while (bits >= 8) {
   4520 		if (*p1++ != *p2++)
   4521 			return 0;
   4522 		bits -= 8;
   4523 	}
   4524 
   4525 	if (bits > 0) {
   4526 		u_int8_t mask = ~((1<<(8-bits))-1);
   4527 		if ((*p1 & mask) != (*p2 & mask))
   4528 			return 0;
   4529 	}
   4530 	return 1;	/* Match! */
   4531 }
   4532 
   4533 static void
   4534 key_timehandler_spd(time_t now)
   4535 {
   4536 	u_int dir;
   4537 	struct secpolicy *sp;
   4538 
   4539 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
   4540 	    retry:
   4541 		mutex_enter(&key_spd.lock);
   4542 		SPLIST_WRITER_FOREACH(sp, dir) {
   4543 			KASSERT(sp->state != IPSEC_SPSTATE_DEAD);
   4544 
   4545 			if (sp->lifetime == 0 && sp->validtime == 0)
   4546 				continue;
   4547 
   4548 			if ((sp->lifetime && now - sp->created > sp->lifetime) ||
   4549 			    (sp->validtime && now - sp->lastused > sp->validtime)) {
   4550 				key_unlink_sp(sp);
   4551 				mutex_exit(&key_spd.lock);
   4552 				key_spdexpire(sp);
   4553 				key_destroy_sp(sp);
   4554 				goto retry;
   4555 			}
   4556 		}
   4557 		mutex_exit(&key_spd.lock);
   4558 	}
   4559 
   4560     retry_socksplist:
   4561 	mutex_enter(&key_spd.lock);
   4562 	SOCKSPLIST_WRITER_FOREACH(sp) {
   4563 		if (sp->state != IPSEC_SPSTATE_DEAD)
   4564 			continue;
   4565 
   4566 		key_unlink_sp(sp);
   4567 		mutex_exit(&key_spd.lock);
   4568 		key_destroy_sp(sp);
   4569 		goto retry_socksplist;
   4570 	}
   4571 	mutex_exit(&key_spd.lock);
   4572 }
   4573 
   4574 static void
   4575 key_timehandler_sad(time_t now)
   4576 {
   4577 	struct secashead *sah;
   4578 	struct secasvar *sav;
   4579 
   4580 restart:
   4581 	SAHLIST_WRITER_FOREACH(sah) {
   4582 		/* if sah has been dead, then delete it and process next sah. */
   4583 		if (sah->state == SADB_SASTATE_DEAD) {
   4584 			key_delsah(sah);
   4585 			goto restart;
   4586 		}
   4587 
   4588 		/* if LARVAL entry doesn't become MATURE, delete it. */
   4589 	restart_sav_LARVAL:
   4590 		SAVLIST_READER_FOREACH(sav, sah, SADB_SASTATE_LARVAL) {
   4591 			if (now - sav->created > key_larval_lifetime) {
   4592 				KEY_FREESAV(&sav);
   4593 				goto restart_sav_LARVAL;
   4594 			}
   4595 		}
   4596 
   4597 		/*
   4598 		 * check MATURE entry to start to send expire message
   4599 		 * whether or not.
   4600 		 */
   4601 	restart_sav_MATURE:
   4602 		SAVLIST_READER_FOREACH(sav, sah, SADB_SASTATE_MATURE) {
   4603 			/* we don't need to check. */
   4604 			if (sav->lft_s == NULL)
   4605 				continue;
   4606 
   4607 			/* sanity check */
   4608 			KASSERT(sav->lft_c != NULL);
   4609 
   4610 			/* check SOFT lifetime */
   4611 			if (sav->lft_s->sadb_lifetime_addtime != 0 &&
   4612 			    now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
   4613 				/*
   4614 				 * check SA to be used whether or not.
   4615 				 * when SA hasn't been used, delete it.
   4616 				 */
   4617 				if (sav->lft_c->sadb_lifetime_usetime == 0) {
   4618 					key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   4619 					KEY_FREESAV(&sav);
   4620 				} else {
   4621 					key_sa_chgstate(sav, SADB_SASTATE_DYING);
   4622 					/*
   4623 					 * XXX If we keep to send expire
   4624 					 * message in the status of
   4625 					 * DYING. Do remove below code.
   4626 					 */
   4627 					key_expire(sav);
   4628 				}
   4629 				goto restart_sav_MATURE;
   4630 			}
   4631 			/* check SOFT lifetime by bytes */
   4632 			/*
   4633 			 * XXX I don't know the way to delete this SA
   4634 			 * when new SA is installed.  Caution when it's
   4635 			 * installed too big lifetime by time.
   4636 			 */
   4637 			else if (sav->lft_s->sadb_lifetime_bytes != 0 &&
   4638 			         sav->lft_s->sadb_lifetime_bytes <
   4639 			         sav->lft_c->sadb_lifetime_bytes) {
   4640 
   4641 				key_sa_chgstate(sav, SADB_SASTATE_DYING);
   4642 				/*
   4643 				 * XXX If we keep to send expire
   4644 				 * message in the status of
   4645 				 * DYING. Do remove below code.
   4646 				 */
   4647 				key_expire(sav);
   4648 				goto restart_sav_MATURE;
   4649 			}
   4650 		}
   4651 
   4652 		/* check DYING entry to change status to DEAD. */
   4653 	restart_sav_DYING:
   4654 		SAVLIST_READER_FOREACH(sav, sah, SADB_SASTATE_DYING) {
   4655 			/* we don't need to check. */
   4656 			if (sav->lft_h == NULL)
   4657 				continue;
   4658 
   4659 			/* sanity check */
   4660 			KASSERT(sav->lft_c != NULL);
   4661 
   4662 			if (sav->lft_h->sadb_lifetime_addtime != 0 &&
   4663 			    now - sav->created > sav->lft_h->sadb_lifetime_addtime) {
   4664 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   4665 				KEY_FREESAV(&sav);
   4666 				goto restart_sav_DYING;
   4667 			}
   4668 #if 0	/* XXX Should we keep to send expire message until HARD lifetime ? */
   4669 			else if (sav->lft_s != NULL
   4670 			      && sav->lft_s->sadb_lifetime_addtime != 0
   4671 			      && now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
   4672 				/*
   4673 				 * XXX: should be checked to be
   4674 				 * installed the valid SA.
   4675 				 */
   4676 
   4677 				/*
   4678 				 * If there is no SA then sending
   4679 				 * expire message.
   4680 				 */
   4681 				key_expire(sav);
   4682 			}
   4683 #endif
   4684 			/* check HARD lifetime by bytes */
   4685 			else if (sav->lft_h->sadb_lifetime_bytes != 0 &&
   4686 			         sav->lft_h->sadb_lifetime_bytes <
   4687 			         sav->lft_c->sadb_lifetime_bytes) {
   4688 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   4689 				KEY_FREESAV(&sav);
   4690 				goto restart_sav_DYING;
   4691 			}
   4692 		}
   4693 
   4694 		/* delete entry in DEAD */
   4695 		SAVLIST_READER_FOREACH(sav, sah, SADB_SASTATE_DEAD) {
   4696 			/* sanity check */
   4697 			if (sav->state != SADB_SASTATE_DEAD) {
   4698 				IPSECLOG(LOG_DEBUG,
   4699 				    "invalid sav->state (queue: %d SA: %d): "
   4700 				    "kill it anyway\n",
   4701 				    SADB_SASTATE_DEAD, sav->state);
   4702 			}
   4703 
   4704 			/*
   4705 			 * do not call key_freesav() here.
   4706 			 * sav should already be freed, and sav->refcnt
   4707 			 * shows other references to sav
   4708 			 * (such as from SPD).
   4709 			 */
   4710 		}
   4711 	}
   4712 }
   4713 
   4714 static void
   4715 key_timehandler_acq(time_t now)
   4716 {
   4717 #ifndef IPSEC_NONBLOCK_ACQUIRE
   4718 	struct secacq *acq, *nextacq;
   4719 
   4720     restart:
   4721 	mutex_enter(&key_misc.lock);
   4722 	LIST_FOREACH_SAFE(acq, &key_misc.acqlist, chain, nextacq) {
   4723 		if (now - acq->created > key_blockacq_lifetime) {
   4724 			LIST_REMOVE(acq, chain);
   4725 			mutex_exit(&key_misc.lock);
   4726 			kmem_free(acq, sizeof(*acq));
   4727 			goto restart;
   4728 		}
   4729 	}
   4730 	mutex_exit(&key_misc.lock);
   4731 #endif
   4732 }
   4733 
   4734 static void
   4735 key_timehandler_spacq(time_t now)
   4736 {
   4737 #ifdef notyet
   4738 	struct secspacq *acq, *nextacq;
   4739 
   4740 	LIST_FOREACH_SAFE(acq, &key_misc.spacqlist, chain, nextacq) {
   4741 		if (now - acq->created > key_blockacq_lifetime) {
   4742 			KASSERT(__LIST_CHAINED(acq));
   4743 			LIST_REMOVE(acq, chain);
   4744 			kmem_free(acq, sizeof(*acq));
   4745 		}
   4746 	}
   4747 #endif
   4748 }
   4749 
   4750 /*
   4751  * time handler.
   4752  * scanning SPD and SAD to check status for each entries,
   4753  * and do to remove or to expire.
   4754  */
   4755 static void
   4756 key_timehandler_work(struct work *wk, void *arg)
   4757 {
   4758 	time_t now = time_uptime;
   4759 	IPSEC_DECLARE_LOCK_VARIABLE;
   4760 
   4761 	IPSEC_ACQUIRE_GLOBAL_LOCKS();
   4762 
   4763 	key_timehandler_spd(now);
   4764 	key_timehandler_sad(now);
   4765 	key_timehandler_acq(now);
   4766 	key_timehandler_spacq(now);
   4767 
   4768 	/* do exchange to tick time !! */
   4769 	callout_reset(&key_timehandler_ch, hz, key_timehandler, NULL);
   4770 
   4771 	IPSEC_RELEASE_GLOBAL_LOCKS();
   4772 	return;
   4773 }
   4774 
   4775 static void
   4776 key_timehandler(void *arg)
   4777 {
   4778 
   4779 	workqueue_enqueue(key_timehandler_wq, &key_timehandler_wk, NULL);
   4780 }
   4781 
   4782 u_long
   4783 key_random(void)
   4784 {
   4785 	u_long value;
   4786 
   4787 	key_randomfill(&value, sizeof(value));
   4788 	return value;
   4789 }
   4790 
   4791 void
   4792 key_randomfill(void *p, size_t l)
   4793 {
   4794 
   4795 	cprng_fast(p, l);
   4796 }
   4797 
   4798 /*
   4799  * map SADB_SATYPE_* to IPPROTO_*.
   4800  * if satype == SADB_SATYPE then satype is mapped to ~0.
   4801  * OUT:
   4802  *	0: invalid satype.
   4803  */
   4804 static u_int16_t
   4805 key_satype2proto(u_int8_t satype)
   4806 {
   4807 	switch (satype) {
   4808 	case SADB_SATYPE_UNSPEC:
   4809 		return IPSEC_PROTO_ANY;
   4810 	case SADB_SATYPE_AH:
   4811 		return IPPROTO_AH;
   4812 	case SADB_SATYPE_ESP:
   4813 		return IPPROTO_ESP;
   4814 	case SADB_X_SATYPE_IPCOMP:
   4815 		return IPPROTO_IPCOMP;
   4816 	case SADB_X_SATYPE_TCPSIGNATURE:
   4817 		return IPPROTO_TCP;
   4818 	default:
   4819 		return 0;
   4820 	}
   4821 	/* NOTREACHED */
   4822 }
   4823 
   4824 /*
   4825  * map IPPROTO_* to SADB_SATYPE_*
   4826  * OUT:
   4827  *	0: invalid protocol type.
   4828  */
   4829 static u_int8_t
   4830 key_proto2satype(u_int16_t proto)
   4831 {
   4832 	switch (proto) {
   4833 	case IPPROTO_AH:
   4834 		return SADB_SATYPE_AH;
   4835 	case IPPROTO_ESP:
   4836 		return SADB_SATYPE_ESP;
   4837 	case IPPROTO_IPCOMP:
   4838 		return SADB_X_SATYPE_IPCOMP;
   4839 	case IPPROTO_TCP:
   4840 		return SADB_X_SATYPE_TCPSIGNATURE;
   4841 	default:
   4842 		return 0;
   4843 	}
   4844 	/* NOTREACHED */
   4845 }
   4846 
   4847 static int
   4848 key_setsecasidx(int proto, int mode, int reqid,
   4849     const struct sockaddr *src, const struct sockaddr *dst,
   4850     struct secasindex * saidx)
   4851 {
   4852 	const union sockaddr_union *src_u = (const union sockaddr_union *)src;
   4853 	const union sockaddr_union *dst_u = (const union sockaddr_union *)dst;
   4854 
   4855 	/* sa len safety check */
   4856 	if (key_checksalen(src_u) != 0)
   4857 		return -1;
   4858 	if (key_checksalen(dst_u) != 0)
   4859 		return -1;
   4860 
   4861 	memset(saidx, 0, sizeof(*saidx));
   4862 	saidx->proto = proto;
   4863 	saidx->mode = mode;
   4864 	saidx->reqid = reqid;
   4865 	memcpy(&saidx->src, src_u, src_u->sa.sa_len);
   4866 	memcpy(&saidx->dst, dst_u, dst_u->sa.sa_len);
   4867 
   4868 	key_porttosaddr(&((saidx)->src), 0);
   4869 	key_porttosaddr(&((saidx)->dst), 0);
   4870 	return 0;
   4871 }
   4872 
   4873 static void
   4874 key_init_spidx_bymsghdr(struct secpolicyindex *spidx,
   4875     const struct sadb_msghdr *mhp)
   4876 {
   4877 	const struct sadb_address *src0, *dst0;
   4878 	const struct sockaddr *src, *dst;
   4879 	const struct sadb_x_policy *xpl0;
   4880 
   4881 	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
   4882 	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
   4883 	src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
   4884 	dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
   4885 	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
   4886 
   4887 	memset(spidx, 0, sizeof(*spidx));
   4888 	spidx->dir = xpl0->sadb_x_policy_dir;
   4889 	spidx->prefs = src0->sadb_address_prefixlen;
   4890 	spidx->prefd = dst0->sadb_address_prefixlen;
   4891 	spidx->ul_proto = src0->sadb_address_proto;
   4892 	/* XXX boundary check against sa_len */
   4893 	memcpy(&spidx->src, src, src->sa_len);
   4894 	memcpy(&spidx->dst, dst, dst->sa_len);
   4895 }
   4896 
   4897 /* %%% PF_KEY */
   4898 /*
   4899  * SADB_GETSPI processing is to receive
   4900  *	<base, (SA2), src address, dst address, (SPI range)>
   4901  * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
   4902  * tree with the status of LARVAL, and send
   4903  *	<base, SA(*), address(SD)>
   4904  * to the IKMPd.
   4905  *
   4906  * IN:	mhp: pointer to the pointer to each header.
   4907  * OUT:	NULL if fail.
   4908  *	other if success, return pointer to the message to send.
   4909  */
   4910 static int
   4911 key_api_getspi(struct socket *so, struct mbuf *m,
   4912 	   const struct sadb_msghdr *mhp)
   4913 {
   4914 	const struct sockaddr *src, *dst;
   4915 	struct secasindex saidx;
   4916 	struct secashead *sah;
   4917 	struct secasvar *newsav;
   4918 	u_int8_t proto;
   4919 	u_int32_t spi;
   4920 	u_int8_t mode;
   4921 	u_int16_t reqid;
   4922 	int error;
   4923 
   4924 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   4925 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
   4926 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   4927 		return key_senderror(so, m, EINVAL);
   4928 	}
   4929 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   4930 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
   4931 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   4932 		return key_senderror(so, m, EINVAL);
   4933 	}
   4934 	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
   4935 		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
   4936 		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
   4937 	} else {
   4938 		mode = IPSEC_MODE_ANY;
   4939 		reqid = 0;
   4940 	}
   4941 
   4942 	src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
   4943 	dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
   4944 
   4945 	/* map satype to proto */
   4946 	proto = key_satype2proto(mhp->msg->sadb_msg_satype);
   4947 	if (proto == 0) {
   4948 		IPSECLOG(LOG_DEBUG, "invalid satype is passed.\n");
   4949 		return key_senderror(so, m, EINVAL);
   4950 	}
   4951 
   4952 
   4953 	error = key_setsecasidx(proto, mode, reqid, src, dst, &saidx);
   4954 	if (error != 0)
   4955 		return key_senderror(so, m, EINVAL);
   4956 
   4957 	error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp);
   4958 	if (error != 0)
   4959 		return key_senderror(so, m, EINVAL);
   4960 
   4961 	/* SPI allocation */
   4962 	spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
   4963 	    &saidx);
   4964 	if (spi == 0)
   4965 		return key_senderror(so, m, EINVAL);
   4966 
   4967 	/* get a SA index */
   4968 	sah = key_getsah(&saidx, CMP_REQID);
   4969 	if (sah == NULL) {
   4970 		/* create a new SA index */
   4971 		sah = key_newsah(&saidx);
   4972 		if (sah == NULL) {
   4973 			IPSECLOG(LOG_DEBUG, "No more memory.\n");
   4974 			return key_senderror(so, m, ENOBUFS);
   4975 		}
   4976 	}
   4977 
   4978 	/* get a new SA */
   4979 	/* XXX rewrite */
   4980 	newsav = KEY_NEWSAV(m, mhp, &error);
   4981 	if (newsav == NULL) {
   4982 		/* XXX don't free new SA index allocated in above. */
   4983 		return key_senderror(so, m, error);
   4984 	}
   4985 
   4986 	/* set spi */
   4987 	newsav->spi = htonl(spi);
   4988 
   4989 	/* add to satree */
   4990 	newsav->refcnt = 1;
   4991 	newsav->sah = sah;
   4992 	newsav->state = SADB_SASTATE_LARVAL;
   4993 	SAVLIST_ENTRY_INIT(newsav);
   4994 	mutex_enter(&key_sad.lock);
   4995 	SAVLIST_WRITER_INSERT_TAIL(sah, SADB_SASTATE_LARVAL, newsav);
   4996 	mutex_exit(&key_sad.lock);
   4997 	key_validate_savlist(sah, SADB_SASTATE_LARVAL);
   4998 
   4999 #ifndef IPSEC_NONBLOCK_ACQUIRE
   5000 	/* delete the entry in key_misc.acqlist */
   5001 	if (mhp->msg->sadb_msg_seq != 0) {
   5002 		struct secacq *acq;
   5003 		mutex_enter(&key_misc.lock);
   5004 		acq = key_getacqbyseq(mhp->msg->sadb_msg_seq);
   5005 		if (acq != NULL) {
   5006 			/* reset counter in order to deletion by timehandler. */
   5007 			acq->created = time_uptime;
   5008 			acq->count = 0;
   5009 		}
   5010 		mutex_exit(&key_misc.lock);
   5011 	}
   5012 #endif
   5013 
   5014     {
   5015 	struct mbuf *n, *nn;
   5016 	struct sadb_sa *m_sa;
   5017 	int off, len;
   5018 
   5019 	CTASSERT(PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
   5020 	    PFKEY_ALIGN8(sizeof(struct sadb_sa)) <= MCLBYTES);
   5021 
   5022 	/* create new sadb_msg to reply. */
   5023 	len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
   5024 	    PFKEY_ALIGN8(sizeof(struct sadb_sa));
   5025 
   5026 	MGETHDR(n, M_DONTWAIT, MT_DATA);
   5027 	if (len > MHLEN) {
   5028 		MCLGET(n, M_DONTWAIT);
   5029 		if ((n->m_flags & M_EXT) == 0) {
   5030 			m_freem(n);
   5031 			n = NULL;
   5032 		}
   5033 	}
   5034 	if (!n)
   5035 		return key_senderror(so, m, ENOBUFS);
   5036 
   5037 	n->m_len = len;
   5038 	n->m_next = NULL;
   5039 	off = 0;
   5040 
   5041 	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, char *) + off);
   5042 	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
   5043 
   5044 	m_sa = (struct sadb_sa *)(mtod(n, char *) + off);
   5045 	m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
   5046 	m_sa->sadb_sa_exttype = SADB_EXT_SA;
   5047 	m_sa->sadb_sa_spi = htonl(spi);
   5048 	off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
   5049 
   5050 	KASSERTMSG(off == len, "length inconsistency");
   5051 
   5052 	n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
   5053 	    SADB_EXT_ADDRESS_DST);
   5054 	if (!n->m_next) {
   5055 		m_freem(n);
   5056 		return key_senderror(so, m, ENOBUFS);
   5057 	}
   5058 
   5059 	if (n->m_len < sizeof(struct sadb_msg)) {
   5060 		n = m_pullup(n, sizeof(struct sadb_msg));
   5061 		if (n == NULL)
   5062 			return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
   5063 	}
   5064 
   5065 	n->m_pkthdr.len = 0;
   5066 	for (nn = n; nn; nn = nn->m_next)
   5067 		n->m_pkthdr.len += nn->m_len;
   5068 
   5069 	key_fill_replymsg(n, newsav->seq);
   5070 
   5071 	m_freem(m);
   5072 	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
   5073     }
   5074 }
   5075 
   5076 /*
   5077  * allocating new SPI
   5078  * called by key_api_getspi().
   5079  * OUT:
   5080  *	0:	failure.
   5081  *	others: success.
   5082  */
   5083 static u_int32_t
   5084 key_do_getnewspi(const struct sadb_spirange *spirange,
   5085 		 const struct secasindex *saidx)
   5086 {
   5087 	u_int32_t newspi;
   5088 	u_int32_t spmin, spmax;
   5089 	int count = key_spi_trycnt;
   5090 
   5091 	/* set spi range to allocate */
   5092 	if (spirange != NULL) {
   5093 		spmin = spirange->sadb_spirange_min;
   5094 		spmax = spirange->sadb_spirange_max;
   5095 	} else {
   5096 		spmin = key_spi_minval;
   5097 		spmax = key_spi_maxval;
   5098 	}
   5099 	/* IPCOMP needs 2-byte SPI */
   5100 	if (saidx->proto == IPPROTO_IPCOMP) {
   5101 		u_int32_t t;
   5102 		if (spmin >= 0x10000)
   5103 			spmin = 0xffff;
   5104 		if (spmax >= 0x10000)
   5105 			spmax = 0xffff;
   5106 		if (spmin > spmax) {
   5107 			t = spmin; spmin = spmax; spmax = t;
   5108 		}
   5109 	}
   5110 
   5111 	if (spmin == spmax) {
   5112 		if (key_checkspidup(saidx, htonl(spmin))) {
   5113 			IPSECLOG(LOG_DEBUG, "SPI %u exists already.\n", spmin);
   5114 			return 0;
   5115 		}
   5116 
   5117 		count--; /* taking one cost. */
   5118 		newspi = spmin;
   5119 
   5120 	} else {
   5121 
   5122 		/* init SPI */
   5123 		newspi = 0;
   5124 
   5125 		/* when requesting to allocate spi ranged */
   5126 		while (count--) {
   5127 			/* generate pseudo-random SPI value ranged. */
   5128 			newspi = spmin + (key_random() % (spmax - spmin + 1));
   5129 
   5130 			if (!key_checkspidup(saidx, htonl(newspi)))
   5131 				break;
   5132 		}
   5133 
   5134 		if (count == 0 || newspi == 0) {
   5135 			IPSECLOG(LOG_DEBUG, "to allocate spi is failed.\n");
   5136 			return 0;
   5137 		}
   5138 	}
   5139 
   5140 	/* statistics */
   5141 	keystat.getspi_count =
   5142 	    (keystat.getspi_count + key_spi_trycnt - count) / 2;
   5143 
   5144 	return newspi;
   5145 }
   5146 
   5147 static int
   5148 key_handle_natt_info(struct secasvar *sav,
   5149       		     const struct sadb_msghdr *mhp)
   5150 {
   5151 	const char *msg = "?" ;
   5152 	struct sadb_x_nat_t_type *type;
   5153 	struct sadb_x_nat_t_port *sport, *dport;
   5154 	struct sadb_address *iaddr, *raddr;
   5155 	struct sadb_x_nat_t_frag *frag;
   5156 
   5157 	if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] == NULL ||
   5158 	    mhp->ext[SADB_X_EXT_NAT_T_SPORT] == NULL ||
   5159 	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] == NULL)
   5160 		return 0;
   5161 
   5162 	if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type)) {
   5163 		msg = "TYPE";
   5164 		goto bad;
   5165 	}
   5166 
   5167 	if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport)) {
   5168 		msg = "SPORT";
   5169 		goto bad;
   5170 	}
   5171 
   5172 	if (mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
   5173 		msg = "DPORT";
   5174 		goto bad;
   5175 	}
   5176 
   5177 	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL) {
   5178 		IPSECLOG(LOG_DEBUG, "NAT-T OAi present\n");
   5179 		if (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr)) {
   5180 			msg = "OAI";
   5181 			goto bad;
   5182 		}
   5183 	}
   5184 
   5185 	if (mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) {
   5186 		IPSECLOG(LOG_DEBUG, "NAT-T OAr present\n");
   5187 		if (mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr)) {
   5188 			msg = "OAR";
   5189 			goto bad;
   5190 		}
   5191 	}
   5192 
   5193 	if (mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) {
   5194 	    if (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag)) {
   5195 		    msg = "FRAG";
   5196 		    goto bad;
   5197 	    }
   5198 	}
   5199 
   5200 	type = (struct sadb_x_nat_t_type *)mhp->ext[SADB_X_EXT_NAT_T_TYPE];
   5201 	sport = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_SPORT];
   5202 	dport = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_DPORT];
   5203 	iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
   5204 	raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
   5205 	frag = (struct sadb_x_nat_t_frag *)mhp->ext[SADB_X_EXT_NAT_T_FRAG];
   5206 
   5207 	IPSECLOG(LOG_DEBUG, "type %d, sport = %d, dport = %d\n",
   5208 	    type->sadb_x_nat_t_type_type,
   5209 	    ntohs(sport->sadb_x_nat_t_port_port),
   5210 	    ntohs(dport->sadb_x_nat_t_port_port));
   5211 
   5212 	sav->natt_type = type->sadb_x_nat_t_type_type;
   5213 	key_porttosaddr(&sav->sah->saidx.src, sport->sadb_x_nat_t_port_port);
   5214 	key_porttosaddr(&sav->sah->saidx.dst, dport->sadb_x_nat_t_port_port);
   5215 	if (frag)
   5216 		sav->esp_frag = frag->sadb_x_nat_t_frag_fraglen;
   5217 	else
   5218 		sav->esp_frag = IP_MAXPACKET;
   5219 
   5220 	return 0;
   5221 bad:
   5222 	IPSECLOG(LOG_DEBUG, "invalid message %s\n", msg);
   5223 	__USE(msg);
   5224 	return -1;
   5225 }
   5226 
   5227 /* Just update the IPSEC_NAT_T ports if present */
   5228 static int
   5229 key_set_natt_ports(union sockaddr_union *src, union sockaddr_union *dst,
   5230       		     const struct sadb_msghdr *mhp)
   5231 {
   5232 	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL)
   5233 		IPSECLOG(LOG_DEBUG, "NAT-T OAi present\n");
   5234 	if (mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL)
   5235 		IPSECLOG(LOG_DEBUG, "NAT-T OAr present\n");
   5236 
   5237 	if ((mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL) &&
   5238 	    (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL) &&
   5239 	    (mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL)) {
   5240 		struct sadb_x_nat_t_type *type;
   5241 		struct sadb_x_nat_t_port *sport;
   5242 		struct sadb_x_nat_t_port *dport;
   5243 
   5244 		if ((mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type)) ||
   5245 		    (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport)) ||
   5246 		    (mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport))) {
   5247 			IPSECLOG(LOG_DEBUG, "invalid message\n");
   5248 			return -1;
   5249 		}
   5250 
   5251 		type = (struct sadb_x_nat_t_type *)
   5252 		    mhp->ext[SADB_X_EXT_NAT_T_TYPE];
   5253 		sport = (struct sadb_x_nat_t_port *)
   5254 		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
   5255 		dport = (struct sadb_x_nat_t_port *)
   5256 		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
   5257 
   5258 		key_porttosaddr(src, sport->sadb_x_nat_t_port_port);
   5259 		key_porttosaddr(dst, dport->sadb_x_nat_t_port_port);
   5260 
   5261 		IPSECLOG(LOG_DEBUG, "type %d, sport = %d, dport = %d\n",
   5262 		    type->sadb_x_nat_t_type_type,
   5263 		    ntohs(sport->sadb_x_nat_t_port_port),
   5264 		    ntohs(dport->sadb_x_nat_t_port_port));
   5265 	}
   5266 
   5267 	return 0;
   5268 }
   5269 
   5270 
   5271 /*
   5272  * SADB_UPDATE processing
   5273  * receive
   5274  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
   5275  *       key(AE), (identity(SD),) (sensitivity)>
   5276  * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
   5277  * and send
   5278  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
   5279  *       (identity(SD),) (sensitivity)>
   5280  * to the ikmpd.
   5281  *
   5282  * m will always be freed.
   5283  */
   5284 static int
   5285 key_api_update(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
   5286 {
   5287 	struct sadb_sa *sa0;
   5288 	const struct sockaddr *src, *dst;
   5289 	struct secasindex saidx;
   5290 	struct secashead *sah;
   5291 	struct secasvar *sav, *newsav;
   5292 	u_int16_t proto;
   5293 	u_int8_t mode;
   5294 	u_int16_t reqid;
   5295 	int error;
   5296 
   5297 	/* map satype to proto */
   5298 	proto = key_satype2proto(mhp->msg->sadb_msg_satype);
   5299 	if (proto == 0) {
   5300 		IPSECLOG(LOG_DEBUG, "invalid satype is passed.\n");
   5301 		return key_senderror(so, m, EINVAL);
   5302 	}
   5303 
   5304 	if (mhp->ext[SADB_EXT_SA] == NULL ||
   5305 	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   5306 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
   5307 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
   5308 	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
   5309 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
   5310 	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
   5311 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
   5312 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
   5313 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
   5314 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
   5315 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   5316 		return key_senderror(so, m, EINVAL);
   5317 	}
   5318 	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
   5319 	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   5320 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
   5321 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   5322 		return key_senderror(so, m, EINVAL);
   5323 	}
   5324 	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
   5325 		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
   5326 		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
   5327 	} else {
   5328 		mode = IPSEC_MODE_ANY;
   5329 		reqid = 0;
   5330 	}
   5331 	/* XXX boundary checking for other extensions */
   5332 
   5333 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
   5334 	src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
   5335 	dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
   5336 
   5337 	error = key_setsecasidx(proto, mode, reqid, src, dst, &saidx);
   5338 	if (error != 0)
   5339 		return key_senderror(so, m, EINVAL);
   5340 
   5341 	error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp);
   5342 	if (error != 0)
   5343 		return key_senderror(so, m, EINVAL);
   5344 
   5345 	/* get a SA header */
   5346 	sah = key_getsah(&saidx, CMP_REQID);
   5347 	if (sah == NULL) {
   5348 		IPSECLOG(LOG_DEBUG, "no SA index found.\n");
   5349 		return key_senderror(so, m, ENOENT);
   5350 	}
   5351 
   5352 	/* set spidx if there */
   5353 	/* XXX rewrite */
   5354 	error = key_setident(sah, m, mhp);
   5355 	if (error)
   5356 		return key_senderror(so, m, error);
   5357 
   5358 	/* find a SA with sequence number. */
   5359 #ifdef IPSEC_DOSEQCHECK
   5360 	if (mhp->msg->sadb_msg_seq != 0) {
   5361 		sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq);
   5362 		if (sav == NULL) {
   5363 			IPSECLOG(LOG_DEBUG,
   5364 			    "no larval SA with sequence %u exists.\n",
   5365 			    mhp->msg->sadb_msg_seq);
   5366 			return key_senderror(so, m, ENOENT);
   5367 		}
   5368 	}
   5369 #else
   5370 	sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
   5371 	if (sav == NULL) {
   5372 		IPSECLOG(LOG_DEBUG, "no such a SA found (spi:%u)\n",
   5373 		    (u_int32_t)ntohl(sa0->sadb_sa_spi));
   5374 		return key_senderror(so, m, EINVAL);
   5375 	}
   5376 #endif
   5377 
   5378 	/* validity check */
   5379 	if (sav->sah->saidx.proto != proto) {
   5380 		IPSECLOG(LOG_DEBUG, "protocol mismatched (DB=%u param=%u)\n",
   5381 		    sav->sah->saidx.proto, proto);
   5382 		error = EINVAL;
   5383 		goto error;
   5384 	}
   5385 #ifdef IPSEC_DOSEQCHECK
   5386 	if (sav->spi != sa0->sadb_sa_spi) {
   5387 		IPSECLOG(LOG_DEBUG, "SPI mismatched (DB:%u param:%u)\n",
   5388 		    (u_int32_t)ntohl(sav->spi),
   5389 		    (u_int32_t)ntohl(sa0->sadb_sa_spi));
   5390 		error = EINVAL;
   5391 		goto error;
   5392 	}
   5393 #endif
   5394 	if (sav->pid != mhp->msg->sadb_msg_pid) {
   5395 		IPSECLOG(LOG_DEBUG, "pid mismatched (DB:%u param:%u)\n",
   5396 		    sav->pid, mhp->msg->sadb_msg_pid);
   5397 		error = EINVAL;
   5398 		goto error;
   5399 	}
   5400 
   5401 	/*
   5402 	 * Allocate a new SA instead of modifying the existing SA directly
   5403 	 * to avoid race conditions.
   5404 	 */
   5405 	newsav = kmem_zalloc(sizeof(struct secasvar), KM_SLEEP);
   5406 
   5407 	/* copy sav values */
   5408 	newsav->spi = sav->spi;
   5409 	newsav->seq = sav->seq;
   5410 	newsav->created = sav->created;
   5411 	newsav->pid = sav->pid;
   5412 	newsav->sah = sav->sah;
   5413 
   5414 	error = key_setsaval(newsav, m, mhp);
   5415 	if (error) {
   5416 		key_delsav(newsav);
   5417 		goto error;
   5418 	}
   5419 
   5420 	error = key_handle_natt_info(newsav, mhp);
   5421 	if (error != 0) {
   5422 		key_delsav(newsav);
   5423 		goto error;
   5424 	}
   5425 
   5426 	error = key_init_xform(newsav);
   5427 	if (error != 0) {
   5428 		key_delsav(newsav);
   5429 		goto error;
   5430 	}
   5431 
   5432 	/* add to satree */
   5433 	newsav->refcnt = 1;
   5434 	newsav->state = SADB_SASTATE_MATURE;
   5435 	SAVLIST_ENTRY_INIT(newsav);
   5436 	SAVLIST_WRITER_INSERT_TAIL(sah, SADB_SASTATE_MATURE, newsav);
   5437 	key_validate_savlist(sah, SADB_SASTATE_MATURE);
   5438 
   5439 	key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   5440 	KEY_FREESAV(&sav);
   5441 	KEY_FREESAV(&sav);
   5442 
   5443     {
   5444 	struct mbuf *n;
   5445 
   5446 	/* set msg buf from mhp */
   5447 	n = key_getmsgbuf_x1(m, mhp);
   5448 	if (n == NULL) {
   5449 		IPSECLOG(LOG_DEBUG, "No more memory.\n");
   5450 		return key_senderror(so, m, ENOBUFS);
   5451 	}
   5452 
   5453 	m_freem(m);
   5454 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
   5455     }
   5456 error:
   5457 	KEY_SA_UNREF(&sav);
   5458 	return key_senderror(so, m, error);
   5459 }
   5460 
   5461 /*
   5462  * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
   5463  * only called by key_api_update().
   5464  * OUT:
   5465  *	NULL	: not found
   5466  *	others	: found, pointer to a SA.
   5467  */
   5468 #ifdef IPSEC_DOSEQCHECK
   5469 static struct secasvar *
   5470 key_getsavbyseq(struct secashead *sah, u_int32_t seq)
   5471 {
   5472 	struct secasvar *sav;
   5473 	u_int state;
   5474 	int s;
   5475 
   5476 	state = SADB_SASTATE_LARVAL;
   5477 
   5478 	/* search SAD with sequence number ? */
   5479 	s = pserialize_read_enter();
   5480 	SAVLIST_READER_FOREACH(sav, sah, state) {
   5481 		KEY_CHKSASTATE(state, sav->state);
   5482 
   5483 		if (sav->seq == seq) {
   5484 			SA_ADDREF(sav);
   5485 			KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
   5486 			    "DP cause refcnt++:%d SA:%p\n",
   5487 			    sav->refcnt, sav);
   5488 			break;
   5489 		}
   5490 	}
   5491 	pserialize_read_exit(s);
   5492 
   5493 	return sav;
   5494 }
   5495 #endif
   5496 
   5497 /*
   5498  * SADB_ADD processing
   5499  * add an entry to SA database, when received
   5500  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
   5501  *       key(AE), (identity(SD),) (sensitivity)>
   5502  * from the ikmpd,
   5503  * and send
   5504  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
   5505  *       (identity(SD),) (sensitivity)>
   5506  * to the ikmpd.
   5507  *
   5508  * IGNORE identity and sensitivity messages.
   5509  *
   5510  * m will always be freed.
   5511  */
   5512 static int
   5513 key_api_add(struct socket *so, struct mbuf *m,
   5514 	const struct sadb_msghdr *mhp)
   5515 {
   5516 	struct sadb_sa *sa0;
   5517 	const struct sockaddr *src, *dst;
   5518 	struct secasindex saidx;
   5519 	struct secashead *sah;
   5520 	struct secasvar *newsav;
   5521 	u_int16_t proto;
   5522 	u_int8_t mode;
   5523 	u_int16_t reqid;
   5524 	int error;
   5525 
   5526 	/* map satype to proto */
   5527 	proto = key_satype2proto(mhp->msg->sadb_msg_satype);
   5528 	if (proto == 0) {
   5529 		IPSECLOG(LOG_DEBUG, "invalid satype is passed.\n");
   5530 		return key_senderror(so, m, EINVAL);
   5531 	}
   5532 
   5533 	if (mhp->ext[SADB_EXT_SA] == NULL ||
   5534 	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   5535 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
   5536 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
   5537 	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
   5538 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
   5539 	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
   5540 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
   5541 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
   5542 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
   5543 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
   5544 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   5545 		return key_senderror(so, m, EINVAL);
   5546 	}
   5547 	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
   5548 	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   5549 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
   5550 		/* XXX need more */
   5551 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   5552 		return key_senderror(so, m, EINVAL);
   5553 	}
   5554 	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
   5555 		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
   5556 		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
   5557 	} else {
   5558 		mode = IPSEC_MODE_ANY;
   5559 		reqid = 0;
   5560 	}
   5561 
   5562 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
   5563 	src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
   5564 	dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
   5565 
   5566 	error = key_setsecasidx(proto, mode, reqid, src, dst, &saidx);
   5567 	if (error != 0)
   5568 		return key_senderror(so, m, EINVAL);
   5569 
   5570 	error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp);
   5571 	if (error != 0)
   5572 		return key_senderror(so, m, EINVAL);
   5573 
   5574 	/* get a SA header */
   5575 	sah = key_getsah(&saidx, CMP_REQID);
   5576 	if (sah == NULL) {
   5577 		/* create a new SA header */
   5578 		sah = key_newsah(&saidx);
   5579 		if (sah == NULL) {
   5580 			IPSECLOG(LOG_DEBUG, "No more memory.\n");
   5581 			return key_senderror(so, m, ENOBUFS);
   5582 		}
   5583 	}
   5584 
   5585 	/* set spidx if there */
   5586 	/* XXX rewrite */
   5587 	error = key_setident(sah, m, mhp);
   5588 	if (error) {
   5589 		return key_senderror(so, m, error);
   5590 	}
   5591 
   5592     {
   5593 	struct secasvar *sav;
   5594 
   5595 	/* We can create new SA only if SPI is differenct. */
   5596 	sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
   5597 	if (sav != NULL) {
   5598 		KEY_SA_UNREF(&sav);
   5599 		IPSECLOG(LOG_DEBUG, "SA already exists.\n");
   5600 		return key_senderror(so, m, EEXIST);
   5601 	}
   5602     }
   5603 
   5604 	/* create new SA entry. */
   5605 	newsav = KEY_NEWSAV(m, mhp, &error);
   5606 	if (newsav == NULL) {
   5607 		return key_senderror(so, m, error);
   5608 	}
   5609 	newsav->sah = sah;
   5610 
   5611 	error = key_handle_natt_info(newsav, mhp);
   5612 	if (error != 0) {
   5613 		key_delsav(newsav);
   5614 		return key_senderror(so, m, EINVAL);
   5615 	}
   5616 
   5617 	error = key_init_xform(newsav);
   5618 	if (error != 0) {
   5619 		key_delsav(newsav);
   5620 		return key_senderror(so, m, error);
   5621 	}
   5622 
   5623 	/* add to satree */
   5624 	newsav->refcnt = 1;
   5625 	newsav->state = SADB_SASTATE_MATURE;
   5626 	SAVLIST_ENTRY_INIT(newsav);
   5627 	SAVLIST_WRITER_INSERT_TAIL(sah, SADB_SASTATE_MATURE, newsav);
   5628 	key_validate_savlist(sah, SADB_SASTATE_MATURE);
   5629 
   5630 	/*
   5631 	 * don't call key_freesav() here, as we would like to keep the SA
   5632 	 * in the database on success.
   5633 	 */
   5634 
   5635     {
   5636 	struct mbuf *n;
   5637 
   5638 	/* set msg buf from mhp */
   5639 	n = key_getmsgbuf_x1(m, mhp);
   5640 	if (n == NULL) {
   5641 		IPSECLOG(LOG_DEBUG, "No more memory.\n");
   5642 		return key_senderror(so, m, ENOBUFS);
   5643 	}
   5644 
   5645 	m_freem(m);
   5646 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
   5647     }
   5648 }
   5649 
   5650 /* m is retained */
   5651 static int
   5652 key_setident(struct secashead *sah, struct mbuf *m,
   5653 	     const struct sadb_msghdr *mhp)
   5654 {
   5655 	const struct sadb_ident *idsrc, *iddst;
   5656 	int idsrclen, iddstlen;
   5657 
   5658 	KASSERT(!cpu_softintr_p());
   5659 	KASSERT(sah != NULL);
   5660 	KASSERT(m != NULL);
   5661 	KASSERT(mhp != NULL);
   5662 	KASSERT(mhp->msg != NULL);
   5663 
   5664 	/*
   5665 	 * Can be called with an existing sah from key_api_update().
   5666 	 */
   5667 	if (sah->idents != NULL) {
   5668 		kmem_free(sah->idents, sah->idents_len);
   5669 		sah->idents = NULL;
   5670 		sah->idents_len = 0;
   5671 	}
   5672 	if (sah->identd != NULL) {
   5673 		kmem_free(sah->identd, sah->identd_len);
   5674 		sah->identd = NULL;
   5675 		sah->identd_len = 0;
   5676 	}
   5677 
   5678 	/* don't make buffer if not there */
   5679 	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
   5680 	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
   5681 		sah->idents = NULL;
   5682 		sah->identd = NULL;
   5683 		return 0;
   5684 	}
   5685 
   5686 	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
   5687 	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
   5688 		IPSECLOG(LOG_DEBUG, "invalid identity.\n");
   5689 		return EINVAL;
   5690 	}
   5691 
   5692 	idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
   5693 	iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
   5694 	idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
   5695 	iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
   5696 
   5697 	/* validity check */
   5698 	if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
   5699 		IPSECLOG(LOG_DEBUG, "ident type mismatch.\n");
   5700 		return EINVAL;
   5701 	}
   5702 
   5703 	switch (idsrc->sadb_ident_type) {
   5704 	case SADB_IDENTTYPE_PREFIX:
   5705 	case SADB_IDENTTYPE_FQDN:
   5706 	case SADB_IDENTTYPE_USERFQDN:
   5707 	default:
   5708 		/* XXX do nothing */
   5709 		sah->idents = NULL;
   5710 		sah->identd = NULL;
   5711 	 	return 0;
   5712 	}
   5713 
   5714 	/* make structure */
   5715 	sah->idents = kmem_alloc(idsrclen, KM_SLEEP);
   5716 	sah->idents_len = idsrclen;
   5717 	sah->identd = kmem_alloc(iddstlen, KM_SLEEP);
   5718 	sah->identd_len = iddstlen;
   5719 	memcpy(sah->idents, idsrc, idsrclen);
   5720 	memcpy(sah->identd, iddst, iddstlen);
   5721 
   5722 	return 0;
   5723 }
   5724 
   5725 /*
   5726  * m will not be freed on return.
   5727  * it is caller's responsibility to free the result.
   5728  */
   5729 static struct mbuf *
   5730 key_getmsgbuf_x1(struct mbuf *m, const struct sadb_msghdr *mhp)
   5731 {
   5732 	struct mbuf *n;
   5733 
   5734 	KASSERT(m != NULL);
   5735 	KASSERT(mhp != NULL);
   5736 	KASSERT(mhp->msg != NULL);
   5737 
   5738 	/* create new sadb_msg to reply. */
   5739 	n = key_gather_mbuf(m, mhp, 1, 15, SADB_EXT_RESERVED,
   5740 	    SADB_EXT_SA, SADB_X_EXT_SA2,
   5741 	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
   5742 	    SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
   5743 	    SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST,
   5744 	    SADB_X_EXT_NAT_T_TYPE, SADB_X_EXT_NAT_T_SPORT,
   5745 	    SADB_X_EXT_NAT_T_DPORT, SADB_X_EXT_NAT_T_OAI,
   5746 	    SADB_X_EXT_NAT_T_OAR, SADB_X_EXT_NAT_T_FRAG);
   5747 	if (!n)
   5748 		return NULL;
   5749 
   5750 	if (n->m_len < sizeof(struct sadb_msg)) {
   5751 		n = m_pullup(n, sizeof(struct sadb_msg));
   5752 		if (n == NULL)
   5753 			return NULL;
   5754 	}
   5755 	mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
   5756 	mtod(n, struct sadb_msg *)->sadb_msg_len =
   5757 	    PFKEY_UNIT64(n->m_pkthdr.len);
   5758 
   5759 	return n;
   5760 }
   5761 
   5762 static int key_delete_all (struct socket *, struct mbuf *,
   5763 			   const struct sadb_msghdr *, u_int16_t);
   5764 
   5765 /*
   5766  * SADB_DELETE processing
   5767  * receive
   5768  *   <base, SA(*), address(SD)>
   5769  * from the ikmpd, and set SADB_SASTATE_DEAD,
   5770  * and send,
   5771  *   <base, SA(*), address(SD)>
   5772  * to the ikmpd.
   5773  *
   5774  * m will always be freed.
   5775  */
   5776 static int
   5777 key_api_delete(struct socket *so, struct mbuf *m,
   5778 	   const struct sadb_msghdr *mhp)
   5779 {
   5780 	struct sadb_sa *sa0;
   5781 	const struct sockaddr *src, *dst;
   5782 	struct secasindex saidx;
   5783 	struct secashead *sah;
   5784 	struct secasvar *sav = NULL;
   5785 	u_int16_t proto;
   5786 	int error;
   5787 
   5788 	/* map satype to proto */
   5789 	proto = key_satype2proto(mhp->msg->sadb_msg_satype);
   5790 	if (proto == 0) {
   5791 		IPSECLOG(LOG_DEBUG, "invalid satype is passed.\n");
   5792 		return key_senderror(so, m, EINVAL);
   5793 	}
   5794 
   5795 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   5796 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
   5797 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   5798 		return key_senderror(so, m, EINVAL);
   5799 	}
   5800 
   5801 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   5802 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
   5803 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   5804 		return key_senderror(so, m, EINVAL);
   5805 	}
   5806 
   5807 	if (mhp->ext[SADB_EXT_SA] == NULL) {
   5808 		/*
   5809 		 * Caller wants us to delete all non-LARVAL SAs
   5810 		 * that match the src/dst.  This is used during
   5811 		 * IKE INITIAL-CONTACT.
   5812 		 */
   5813 		IPSECLOG(LOG_DEBUG, "doing delete all.\n");
   5814 		return key_delete_all(so, m, mhp, proto);
   5815 	} else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
   5816 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   5817 		return key_senderror(so, m, EINVAL);
   5818 	}
   5819 
   5820 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
   5821 	src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
   5822 	dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
   5823 
   5824 	error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src, dst, &saidx);
   5825 	if (error != 0)
   5826 		return key_senderror(so, m, EINVAL);
   5827 
   5828 	error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp);
   5829 	if (error != 0)
   5830 		return key_senderror(so, m, EINVAL);
   5831 
   5832 	/* get a SA header */
   5833 	sah = key_getsah(&saidx, CMP_HEAD);
   5834 	if (sah != NULL) {
   5835 		/* get a SA with SPI. */
   5836 		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
   5837 	}
   5838 
   5839 	if (sav == NULL) {
   5840 		IPSECLOG(LOG_DEBUG, "no SA found.\n");
   5841 		return key_senderror(so, m, ENOENT);
   5842 	}
   5843 
   5844 	key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   5845 	KEY_FREESAV(&sav);
   5846 	KEY_FREESAV(&sav);
   5847 
   5848     {
   5849 	struct mbuf *n;
   5850 
   5851 	/* create new sadb_msg to reply. */
   5852 	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
   5853 	    SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
   5854 	if (!n)
   5855 		return key_senderror(so, m, ENOBUFS);
   5856 
   5857 	n = key_fill_replymsg(n, 0);
   5858 	if (n == NULL)
   5859 		return key_senderror(so, m, ENOBUFS);
   5860 
   5861 	m_freem(m);
   5862 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
   5863     }
   5864 }
   5865 
   5866 /*
   5867  * delete all SAs for src/dst.  Called from key_api_delete().
   5868  */
   5869 static int
   5870 key_delete_all(struct socket *so, struct mbuf *m,
   5871 	       const struct sadb_msghdr *mhp, u_int16_t proto)
   5872 {
   5873 	const struct sockaddr *src, *dst;
   5874 	struct secasindex saidx;
   5875 	struct secashead *sah;
   5876 	struct secasvar *sav;
   5877 	u_int state;
   5878 	int error;
   5879 
   5880 	src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
   5881 	dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
   5882 
   5883 	error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src, dst, &saidx);
   5884 	if (error != 0)
   5885 		return key_senderror(so, m, EINVAL);
   5886 
   5887 	error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp);
   5888 	if (error != 0)
   5889 		return key_senderror(so, m, EINVAL);
   5890 
   5891 	sah = key_getsah(&saidx, CMP_HEAD);
   5892 	if (sah != NULL) {
   5893 		/* Delete all non-LARVAL SAs. */
   5894 		SASTATE_ALIVE_FOREACH(state) {
   5895 			if (state == SADB_SASTATE_LARVAL)
   5896 				continue;
   5897 		restart:
   5898 			SAVLIST_WRITER_FOREACH(sav, sah, state) {
   5899 				/* sanity check */
   5900 				if (sav->state != state) {
   5901 					IPSECLOG(LOG_DEBUG,
   5902 					    "invalid sav->state "
   5903 					    "(queue: %d SA: %d)\n",
   5904 					    state, sav->state);
   5905 					continue;
   5906 				}
   5907 
   5908 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   5909 				KEY_FREESAV(&sav);
   5910 				goto restart;
   5911 			}
   5912 		}
   5913 	}
   5914     {
   5915 	struct mbuf *n;
   5916 
   5917 	/* create new sadb_msg to reply. */
   5918 	n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
   5919 	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
   5920 	if (!n)
   5921 		return key_senderror(so, m, ENOBUFS);
   5922 
   5923 	n = key_fill_replymsg(n, 0);
   5924 	if (n == NULL)
   5925 		return key_senderror(so, m, ENOBUFS);
   5926 
   5927 	m_freem(m);
   5928 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
   5929     }
   5930 }
   5931 
   5932 /*
   5933  * SADB_GET processing
   5934  * receive
   5935  *   <base, SA(*), address(SD)>
   5936  * from the ikmpd, and get a SP and a SA to respond,
   5937  * and send,
   5938  *   <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
   5939  *       (identity(SD),) (sensitivity)>
   5940  * to the ikmpd.
   5941  *
   5942  * m will always be freed.
   5943  */
   5944 static int
   5945 key_api_get(struct socket *so, struct mbuf *m,
   5946 	const struct sadb_msghdr *mhp)
   5947 {
   5948 	struct sadb_sa *sa0;
   5949 	const struct sockaddr *src, *dst;
   5950 	struct secasindex saidx;
   5951 	struct secashead *sah;
   5952 	struct secasvar *sav = NULL;
   5953 	u_int16_t proto;
   5954 	int error;
   5955 
   5956 	/* map satype to proto */
   5957 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
   5958 		IPSECLOG(LOG_DEBUG, "invalid satype is passed.\n");
   5959 		return key_senderror(so, m, EINVAL);
   5960 	}
   5961 
   5962 	if (mhp->ext[SADB_EXT_SA] == NULL ||
   5963 	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   5964 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
   5965 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   5966 		return key_senderror(so, m, EINVAL);
   5967 	}
   5968 	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
   5969 	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   5970 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
   5971 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   5972 		return key_senderror(so, m, EINVAL);
   5973 	}
   5974 
   5975 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
   5976 	src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
   5977 	dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
   5978 
   5979 	error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src, dst, &saidx);
   5980 	if (error != 0)
   5981 		return key_senderror(so, m, EINVAL);
   5982 
   5983 	error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp);
   5984 	if (error != 0)
   5985 		return key_senderror(so, m, EINVAL);
   5986 
   5987 	/* get a SA header */
   5988 	sah = key_getsah(&saidx, CMP_HEAD);
   5989 	if (sah != NULL) {
   5990 		/* get a SA with SPI. */
   5991 		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
   5992 	}
   5993 	if (sav == NULL) {
   5994 		IPSECLOG(LOG_DEBUG, "no SA found.\n");
   5995 		return key_senderror(so, m, ENOENT);
   5996 	}
   5997 
   5998     {
   5999 	struct mbuf *n;
   6000 	u_int8_t satype;
   6001 
   6002 	/* map proto to satype */
   6003 	satype = key_proto2satype(sah->saidx.proto);
   6004 	if (satype == 0) {
   6005 		KEY_SA_UNREF(&sav);
   6006 		IPSECLOG(LOG_DEBUG, "there was invalid proto in SAD.\n");
   6007 		return key_senderror(so, m, EINVAL);
   6008 	}
   6009 
   6010 	/* create new sadb_msg to reply. */
   6011 	n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
   6012 	    mhp->msg->sadb_msg_pid);
   6013 	KEY_SA_UNREF(&sav);
   6014 	if (!n)
   6015 		return key_senderror(so, m, ENOBUFS);
   6016 
   6017 	m_freem(m);
   6018 	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
   6019     }
   6020 }
   6021 
   6022 /* XXX make it sysctl-configurable? */
   6023 static void
   6024 key_getcomb_setlifetime(struct sadb_comb *comb)
   6025 {
   6026 
   6027 	comb->sadb_comb_soft_allocations = 1;
   6028 	comb->sadb_comb_hard_allocations = 1;
   6029 	comb->sadb_comb_soft_bytes = 0;
   6030 	comb->sadb_comb_hard_bytes = 0;
   6031 	comb->sadb_comb_hard_addtime = 86400;	/* 1 day */
   6032 	comb->sadb_comb_soft_addtime = comb->sadb_comb_hard_addtime * 80 / 100;
   6033 	comb->sadb_comb_hard_usetime = 28800;	/* 8 hours */
   6034 	comb->sadb_comb_soft_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
   6035 }
   6036 
   6037 /*
   6038  * XXX reorder combinations by preference
   6039  * XXX no idea if the user wants ESP authentication or not
   6040  */
   6041 static struct mbuf *
   6042 key_getcomb_esp(void)
   6043 {
   6044 	struct sadb_comb *comb;
   6045 	const struct enc_xform *algo;
   6046 	struct mbuf *result = NULL, *m, *n;
   6047 	int encmin;
   6048 	int i, off, o;
   6049 	int totlen;
   6050 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
   6051 
   6052 	m = NULL;
   6053 	for (i = 1; i <= SADB_EALG_MAX; i++) {
   6054 		algo = esp_algorithm_lookup(i);
   6055 		if (algo == NULL)
   6056 			continue;
   6057 
   6058 		/* discard algorithms with key size smaller than system min */
   6059 		if (_BITS(algo->maxkey) < ipsec_esp_keymin)
   6060 			continue;
   6061 		if (_BITS(algo->minkey) < ipsec_esp_keymin)
   6062 			encmin = ipsec_esp_keymin;
   6063 		else
   6064 			encmin = _BITS(algo->minkey);
   6065 
   6066 		if (ipsec_esp_auth)
   6067 			m = key_getcomb_ah();
   6068 		else {
   6069 			KASSERTMSG(l <= MLEN,
   6070 			    "l=%u > MLEN=%lu", l, (u_long) MLEN);
   6071 			MGET(m, M_DONTWAIT, MT_DATA);
   6072 			if (m) {
   6073 				M_ALIGN(m, l);
   6074 				m->m_len = l;
   6075 				m->m_next = NULL;
   6076 				memset(mtod(m, void *), 0, m->m_len);
   6077 			}
   6078 		}
   6079 		if (!m)
   6080 			goto fail;
   6081 
   6082 		totlen = 0;
   6083 		for (n = m; n; n = n->m_next)
   6084 			totlen += n->m_len;
   6085 		KASSERTMSG((totlen % l) == 0, "totlen=%u, l=%u", totlen, l);
   6086 
   6087 		for (off = 0; off < totlen; off += l) {
   6088 			n = m_pulldown(m, off, l, &o);
   6089 			if (!n) {
   6090 				/* m is already freed */
   6091 				goto fail;
   6092 			}
   6093 			comb = (struct sadb_comb *)(mtod(n, char *) + o);
   6094 			memset(comb, 0, sizeof(*comb));
   6095 			key_getcomb_setlifetime(comb);
   6096 			comb->sadb_comb_encrypt = i;
   6097 			comb->sadb_comb_encrypt_minbits = encmin;
   6098 			comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
   6099 		}
   6100 
   6101 		if (!result)
   6102 			result = m;
   6103 		else
   6104 			m_cat(result, m);
   6105 	}
   6106 
   6107 	return result;
   6108 
   6109  fail:
   6110 	if (result)
   6111 		m_freem(result);
   6112 	return NULL;
   6113 }
   6114 
   6115 static void
   6116 key_getsizes_ah(const struct auth_hash *ah, int alg,
   6117 	        u_int16_t* ksmin, u_int16_t* ksmax)
   6118 {
   6119 	*ksmin = *ksmax = ah->keysize;
   6120 	if (ah->keysize == 0) {
   6121 		/*
   6122 		 * Transform takes arbitrary key size but algorithm
   6123 		 * key size is restricted.  Enforce this here.
   6124 		 */
   6125 		switch (alg) {
   6126 		case SADB_X_AALG_MD5:	*ksmin = *ksmax = 16; break;
   6127 		case SADB_X_AALG_SHA:	*ksmin = *ksmax = 20; break;
   6128 		case SADB_X_AALG_NULL:	*ksmin = 0; *ksmax = 256; break;
   6129 		default:
   6130 			IPSECLOG(LOG_DEBUG, "unknown AH algorithm %u\n", alg);
   6131 			break;
   6132 		}
   6133 	}
   6134 }
   6135 
   6136 /*
   6137  * XXX reorder combinations by preference
   6138  */
   6139 static struct mbuf *
   6140 key_getcomb_ah(void)
   6141 {
   6142 	struct sadb_comb *comb;
   6143 	const struct auth_hash *algo;
   6144 	struct mbuf *m;
   6145 	u_int16_t minkeysize, maxkeysize;
   6146 	int i;
   6147 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
   6148 
   6149 	m = NULL;
   6150 	for (i = 1; i <= SADB_AALG_MAX; i++) {
   6151 #if 1
   6152 		/* we prefer HMAC algorithms, not old algorithms */
   6153 		if (i != SADB_AALG_SHA1HMAC &&
   6154 		    i != SADB_AALG_MD5HMAC &&
   6155 		    i != SADB_X_AALG_SHA2_256 &&
   6156 		    i != SADB_X_AALG_SHA2_384 &&
   6157 		    i != SADB_X_AALG_SHA2_512)
   6158 			continue;
   6159 #endif
   6160 		algo = ah_algorithm_lookup(i);
   6161 		if (!algo)
   6162 			continue;
   6163 		key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
   6164 		/* discard algorithms with key size smaller than system min */
   6165 		if (_BITS(minkeysize) < ipsec_ah_keymin)
   6166 			continue;
   6167 
   6168 		if (!m) {
   6169 			KASSERTMSG(l <= MLEN,
   6170 			    "l=%u > MLEN=%lu", l, (u_long) MLEN);
   6171 			MGET(m, M_DONTWAIT, MT_DATA);
   6172 			if (m) {
   6173 				M_ALIGN(m, l);
   6174 				m->m_len = l;
   6175 				m->m_next = NULL;
   6176 			}
   6177 		} else
   6178 			M_PREPEND(m, l, M_DONTWAIT);
   6179 		if (!m)
   6180 			return NULL;
   6181 
   6182 		if (m->m_len < sizeof(struct sadb_comb)) {
   6183 			m = m_pullup(m, sizeof(struct sadb_comb));
   6184 			if (m == NULL)
   6185 				return NULL;
   6186 		}
   6187 
   6188 		comb = mtod(m, struct sadb_comb *);
   6189 		memset(comb, 0, sizeof(*comb));
   6190 		key_getcomb_setlifetime(comb);
   6191 		comb->sadb_comb_auth = i;
   6192 		comb->sadb_comb_auth_minbits = _BITS(minkeysize);
   6193 		comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
   6194 	}
   6195 
   6196 	return m;
   6197 }
   6198 
   6199 /*
   6200  * not really an official behavior.  discussed in pf_key (at) inner.net in Sep2000.
   6201  * XXX reorder combinations by preference
   6202  */
   6203 static struct mbuf *
   6204 key_getcomb_ipcomp(void)
   6205 {
   6206 	struct sadb_comb *comb;
   6207 	const struct comp_algo *algo;
   6208 	struct mbuf *m;
   6209 	int i;
   6210 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
   6211 
   6212 	m = NULL;
   6213 	for (i = 1; i <= SADB_X_CALG_MAX; i++) {
   6214 		algo = ipcomp_algorithm_lookup(i);
   6215 		if (!algo)
   6216 			continue;
   6217 
   6218 		if (!m) {
   6219 			KASSERTMSG(l <= MLEN,
   6220 			    "l=%u > MLEN=%lu", l, (u_long) MLEN);
   6221 			MGET(m, M_DONTWAIT, MT_DATA);
   6222 			if (m) {
   6223 				M_ALIGN(m, l);
   6224 				m->m_len = l;
   6225 				m->m_next = NULL;
   6226 			}
   6227 		} else
   6228 			M_PREPEND(m, l, M_DONTWAIT);
   6229 		if (!m)
   6230 			return NULL;
   6231 
   6232 		if (m->m_len < sizeof(struct sadb_comb)) {
   6233 			m = m_pullup(m, sizeof(struct sadb_comb));
   6234 			if (m == NULL)
   6235 				return NULL;
   6236 		}
   6237 
   6238 		comb = mtod(m, struct sadb_comb *);
   6239 		memset(comb, 0, sizeof(*comb));
   6240 		key_getcomb_setlifetime(comb);
   6241 		comb->sadb_comb_encrypt = i;
   6242 		/* what should we set into sadb_comb_*_{min,max}bits? */
   6243 	}
   6244 
   6245 	return m;
   6246 }
   6247 
   6248 /*
   6249  * XXX no way to pass mode (transport/tunnel) to userland
   6250  * XXX replay checking?
   6251  * XXX sysctl interface to ipsec_{ah,esp}_keymin
   6252  */
   6253 static struct mbuf *
   6254 key_getprop(const struct secasindex *saidx)
   6255 {
   6256 	struct sadb_prop *prop;
   6257 	struct mbuf *m, *n;
   6258 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
   6259 	int totlen;
   6260 
   6261 	switch (saidx->proto)  {
   6262 	case IPPROTO_ESP:
   6263 		m = key_getcomb_esp();
   6264 		break;
   6265 	case IPPROTO_AH:
   6266 		m = key_getcomb_ah();
   6267 		break;
   6268 	case IPPROTO_IPCOMP:
   6269 		m = key_getcomb_ipcomp();
   6270 		break;
   6271 	default:
   6272 		return NULL;
   6273 	}
   6274 
   6275 	if (!m)
   6276 		return NULL;
   6277 	M_PREPEND(m, l, M_DONTWAIT);
   6278 	if (!m)
   6279 		return NULL;
   6280 
   6281 	totlen = 0;
   6282 	for (n = m; n; n = n->m_next)
   6283 		totlen += n->m_len;
   6284 
   6285 	prop = mtod(m, struct sadb_prop *);
   6286 	memset(prop, 0, sizeof(*prop));
   6287 	prop->sadb_prop_len = PFKEY_UNIT64(totlen);
   6288 	prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
   6289 	prop->sadb_prop_replay = 32;	/* XXX */
   6290 
   6291 	return m;
   6292 }
   6293 
   6294 /*
   6295  * SADB_ACQUIRE processing called by key_checkrequest() and key_api_acquire().
   6296  * send
   6297  *   <base, SA, address(SD), (address(P)), x_policy,
   6298  *       (identity(SD),) (sensitivity,) proposal>
   6299  * to KMD, and expect to receive
   6300  *   <base> with SADB_ACQUIRE if error occurred,
   6301  * or
   6302  *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
   6303  * from KMD by PF_KEY.
   6304  *
   6305  * XXX x_policy is outside of RFC2367 (KAME extension).
   6306  * XXX sensitivity is not supported.
   6307  * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
   6308  * see comment for key_getcomb_ipcomp().
   6309  *
   6310  * OUT:
   6311  *    0     : succeed
   6312  *    others: error number
   6313  */
   6314 static int
   6315 key_acquire(const struct secasindex *saidx, struct secpolicy *sp)
   6316 {
   6317 	struct mbuf *result = NULL, *m;
   6318 #ifndef IPSEC_NONBLOCK_ACQUIRE
   6319 	struct secacq *newacq;
   6320 #endif
   6321 	u_int8_t satype;
   6322 	int error = -1;
   6323 	u_int32_t seq;
   6324 
   6325 	/* sanity check */
   6326 	KASSERT(saidx != NULL);
   6327 	satype = key_proto2satype(saidx->proto);
   6328 	KASSERTMSG(satype != 0, "null satype, protocol %u", saidx->proto);
   6329 
   6330 #ifndef IPSEC_NONBLOCK_ACQUIRE
   6331 	/*
   6332 	 * We never do anything about acquirng SA.  There is anather
   6333 	 * solution that kernel blocks to send SADB_ACQUIRE message until
   6334 	 * getting something message from IKEd.  In later case, to be
   6335 	 * managed with ACQUIRING list.
   6336 	 */
   6337 	/* Get an entry to check whether sending message or not. */
   6338 	mutex_enter(&key_misc.lock);
   6339 	newacq = key_getacq(saidx);
   6340 	if (newacq != NULL) {
   6341 		if (key_blockacq_count < newacq->count) {
   6342 			/* reset counter and do send message. */
   6343 			newacq->count = 0;
   6344 		} else {
   6345 			/* increment counter and do nothing. */
   6346 			newacq->count++;
   6347 			mutex_exit(&key_misc.lock);
   6348 			return 0;
   6349 		}
   6350 	} else {
   6351 		/* make new entry for blocking to send SADB_ACQUIRE. */
   6352 		newacq = key_newacq(saidx);
   6353 		if (newacq == NULL)
   6354 			return ENOBUFS;
   6355 
   6356 		/* add to key_misc.acqlist */
   6357 		LIST_INSERT_HEAD(&key_misc.acqlist, newacq, chain);
   6358 	}
   6359 
   6360 	seq = newacq->seq;
   6361 	mutex_exit(&key_misc.lock);
   6362 #else
   6363 	seq = (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
   6364 #endif
   6365 	m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
   6366 	if (!m) {
   6367 		error = ENOBUFS;
   6368 		goto fail;
   6369 	}
   6370 	result = m;
   6371 
   6372 	/* set sadb_address for saidx's. */
   6373 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC, &saidx->src.sa, FULLMASK,
   6374 	    IPSEC_ULPROTO_ANY);
   6375 	if (!m) {
   6376 		error = ENOBUFS;
   6377 		goto fail;
   6378 	}
   6379 	m_cat(result, m);
   6380 
   6381 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST, &saidx->dst.sa, FULLMASK,
   6382 	    IPSEC_ULPROTO_ANY);
   6383 	if (!m) {
   6384 		error = ENOBUFS;
   6385 		goto fail;
   6386 	}
   6387 	m_cat(result, m);
   6388 
   6389 	/* XXX proxy address (optional) */
   6390 
   6391 	/* set sadb_x_policy */
   6392 	if (sp) {
   6393 		m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
   6394 		if (!m) {
   6395 			error = ENOBUFS;
   6396 			goto fail;
   6397 		}
   6398 		m_cat(result, m);
   6399 	}
   6400 
   6401 	/* XXX identity (optional) */
   6402 #if 0
   6403 	if (idexttype && fqdn) {
   6404 		/* create identity extension (FQDN) */
   6405 		struct sadb_ident *id;
   6406 		int fqdnlen;
   6407 
   6408 		fqdnlen = strlen(fqdn) + 1;	/* +1 for terminating-NUL */
   6409 		id = (struct sadb_ident *)p;
   6410 		memset(id, 0, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
   6411 		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
   6412 		id->sadb_ident_exttype = idexttype;
   6413 		id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
   6414 		memcpy(id + 1, fqdn, fqdnlen);
   6415 		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
   6416 	}
   6417 
   6418 	if (idexttype) {
   6419 		/* create identity extension (USERFQDN) */
   6420 		struct sadb_ident *id;
   6421 		int userfqdnlen;
   6422 
   6423 		if (userfqdn) {
   6424 			/* +1 for terminating-NUL */
   6425 			userfqdnlen = strlen(userfqdn) + 1;
   6426 		} else
   6427 			userfqdnlen = 0;
   6428 		id = (struct sadb_ident *)p;
   6429 		memset(id, 0, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
   6430 		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
   6431 		id->sadb_ident_exttype = idexttype;
   6432 		id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
   6433 		/* XXX is it correct? */
   6434 		if (curlwp)
   6435 			id->sadb_ident_id = kauth_cred_getuid(curlwp->l_cred);
   6436 		if (userfqdn && userfqdnlen)
   6437 			memcpy(id + 1, userfqdn, userfqdnlen);
   6438 		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
   6439 	}
   6440 #endif
   6441 
   6442 	/* XXX sensitivity (optional) */
   6443 
   6444 	/* create proposal/combination extension */
   6445 	m = key_getprop(saidx);
   6446 #if 0
   6447 	/*
   6448 	 * spec conformant: always attach proposal/combination extension,
   6449 	 * the problem is that we have no way to attach it for ipcomp,
   6450 	 * due to the way sadb_comb is declared in RFC2367.
   6451 	 */
   6452 	if (!m) {
   6453 		error = ENOBUFS;
   6454 		goto fail;
   6455 	}
   6456 	m_cat(result, m);
   6457 #else
   6458 	/*
   6459 	 * outside of spec; make proposal/combination extension optional.
   6460 	 */
   6461 	if (m)
   6462 		m_cat(result, m);
   6463 #endif
   6464 
   6465 	if ((result->m_flags & M_PKTHDR) == 0) {
   6466 		error = EINVAL;
   6467 		goto fail;
   6468 	}
   6469 
   6470 	if (result->m_len < sizeof(struct sadb_msg)) {
   6471 		result = m_pullup(result, sizeof(struct sadb_msg));
   6472 		if (result == NULL) {
   6473 			error = ENOBUFS;
   6474 			goto fail;
   6475 		}
   6476 	}
   6477 
   6478 	result->m_pkthdr.len = 0;
   6479 	for (m = result; m; m = m->m_next)
   6480 		result->m_pkthdr.len += m->m_len;
   6481 
   6482 	mtod(result, struct sadb_msg *)->sadb_msg_len =
   6483 	    PFKEY_UNIT64(result->m_pkthdr.len);
   6484 
   6485 	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
   6486 
   6487  fail:
   6488 	if (result)
   6489 		m_freem(result);
   6490 	return error;
   6491 }
   6492 
   6493 #ifndef IPSEC_NONBLOCK_ACQUIRE
   6494 static struct secacq *
   6495 key_newacq(const struct secasindex *saidx)
   6496 {
   6497 	struct secacq *newacq;
   6498 
   6499 	/* get new entry */
   6500 	newacq = kmem_intr_zalloc(sizeof(struct secacq), KM_NOSLEEP);
   6501 	if (newacq == NULL) {
   6502 		IPSECLOG(LOG_DEBUG, "No more memory.\n");
   6503 		return NULL;
   6504 	}
   6505 
   6506 	/* copy secindex */
   6507 	memcpy(&newacq->saidx, saidx, sizeof(newacq->saidx));
   6508 	newacq->seq = (acq_seq == ~0 ? 1 : ++acq_seq);
   6509 	newacq->created = time_uptime;
   6510 	newacq->count = 0;
   6511 
   6512 	return newacq;
   6513 }
   6514 
   6515 static struct secacq *
   6516 key_getacq(const struct secasindex *saidx)
   6517 {
   6518 	struct secacq *acq;
   6519 
   6520 	KASSERT(mutex_owned(&key_misc.lock));
   6521 
   6522 	LIST_FOREACH(acq, &key_misc.acqlist, chain) {
   6523 		if (key_saidx_match(saidx, &acq->saidx, CMP_EXACTLY))
   6524 			return acq;
   6525 	}
   6526 
   6527 	return NULL;
   6528 }
   6529 
   6530 static struct secacq *
   6531 key_getacqbyseq(u_int32_t seq)
   6532 {
   6533 	struct secacq *acq;
   6534 
   6535 	KASSERT(mutex_owned(&key_misc.lock));
   6536 
   6537 	LIST_FOREACH(acq, &key_misc.acqlist, chain) {
   6538 		if (acq->seq == seq)
   6539 			return acq;
   6540 	}
   6541 
   6542 	return NULL;
   6543 }
   6544 #endif
   6545 
   6546 #ifdef notyet
   6547 static struct secspacq *
   6548 key_newspacq(const struct secpolicyindex *spidx)
   6549 {
   6550 	struct secspacq *acq;
   6551 
   6552 	/* get new entry */
   6553 	acq = kmem_intr_zalloc(sizeof(struct secspacq), KM_NOSLEEP);
   6554 	if (acq == NULL) {
   6555 		IPSECLOG(LOG_DEBUG, "No more memory.\n");
   6556 		return NULL;
   6557 	}
   6558 
   6559 	/* copy secindex */
   6560 	memcpy(&acq->spidx, spidx, sizeof(acq->spidx));
   6561 	acq->created = time_uptime;
   6562 	acq->count = 0;
   6563 
   6564 	return acq;
   6565 }
   6566 
   6567 static struct secspacq *
   6568 key_getspacq(const struct secpolicyindex *spidx)
   6569 {
   6570 	struct secspacq *acq;
   6571 
   6572 	LIST_FOREACH(acq, &key_misc.spacqlist, chain) {
   6573 		if (key_spidx_match_exactly(spidx, &acq->spidx))
   6574 			return acq;
   6575 	}
   6576 
   6577 	return NULL;
   6578 }
   6579 #endif /* notyet */
   6580 
   6581 /*
   6582  * SADB_ACQUIRE processing,
   6583  * in first situation, is receiving
   6584  *   <base>
   6585  * from the ikmpd, and clear sequence of its secasvar entry.
   6586  *
   6587  * In second situation, is receiving
   6588  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
   6589  * from a user land process, and return
   6590  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
   6591  * to the socket.
   6592  *
   6593  * m will always be freed.
   6594  */
   6595 static int
   6596 key_api_acquire(struct socket *so, struct mbuf *m,
   6597       	     const struct sadb_msghdr *mhp)
   6598 {
   6599 	const struct sockaddr *src, *dst;
   6600 	struct secasindex saidx;
   6601 	struct secashead *sah;
   6602 	u_int16_t proto;
   6603 	int error;
   6604 
   6605 	/*
   6606 	 * Error message from KMd.
   6607 	 * We assume that if error was occurred in IKEd, the length of PFKEY
   6608 	 * message is equal to the size of sadb_msg structure.
   6609 	 * We do not raise error even if error occurred in this function.
   6610 	 */
   6611 	if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
   6612 #ifndef IPSEC_NONBLOCK_ACQUIRE
   6613 		struct secacq *acq;
   6614 
   6615 		/* check sequence number */
   6616 		if (mhp->msg->sadb_msg_seq == 0) {
   6617 			IPSECLOG(LOG_DEBUG, "must specify sequence number.\n");
   6618 			m_freem(m);
   6619 			return 0;
   6620 		}
   6621 
   6622 		mutex_enter(&key_misc.lock);
   6623 		acq = key_getacqbyseq(mhp->msg->sadb_msg_seq);
   6624 		if (acq == NULL) {
   6625 			mutex_exit(&key_misc.lock);
   6626 			/*
   6627 			 * the specified larval SA is already gone, or we got
   6628 			 * a bogus sequence number.  we can silently ignore it.
   6629 			 */
   6630 			m_freem(m);
   6631 			return 0;
   6632 		}
   6633 
   6634 		/* reset acq counter in order to deletion by timehander. */
   6635 		acq->created = time_uptime;
   6636 		acq->count = 0;
   6637 		mutex_exit(&key_misc.lock);
   6638 #endif
   6639 		m_freem(m);
   6640 		return 0;
   6641 	}
   6642 
   6643 	/*
   6644 	 * This message is from user land.
   6645 	 */
   6646 
   6647 	/* map satype to proto */
   6648 	proto = key_satype2proto(mhp->msg->sadb_msg_satype);
   6649 	if (proto == 0) {
   6650 		IPSECLOG(LOG_DEBUG, "invalid satype is passed.\n");
   6651 		return key_senderror(so, m, EINVAL);
   6652 	}
   6653 
   6654 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   6655 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
   6656 	    mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
   6657 		/* error */
   6658 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   6659 		return key_senderror(so, m, EINVAL);
   6660 	}
   6661 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   6662 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
   6663 	    mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
   6664 		/* error */
   6665 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   6666 		return key_senderror(so, m, EINVAL);
   6667 	}
   6668 
   6669 	src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
   6670 	dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
   6671 
   6672 	error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src, dst, &saidx);
   6673 	if (error != 0)
   6674 		return key_senderror(so, m, EINVAL);
   6675 
   6676 	error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp);
   6677 	if (error != 0)
   6678 		return key_senderror(so, m, EINVAL);
   6679 
   6680 	/* get a SA index */
   6681 	sah = key_getsah(&saidx, CMP_MODE_REQID);
   6682 	if (sah != NULL) {
   6683 		IPSECLOG(LOG_DEBUG, "a SA exists already.\n");
   6684 		return key_senderror(so, m, EEXIST);
   6685 	}
   6686 
   6687 	error = key_acquire(&saidx, NULL);
   6688 	if (error != 0) {
   6689 		IPSECLOG(LOG_DEBUG, "error %d returned from key_acquire.\n",
   6690 		    error);
   6691 		return key_senderror(so, m, error);
   6692 	}
   6693 
   6694 	return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
   6695 }
   6696 
   6697 /*
   6698  * SADB_REGISTER processing.
   6699  * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
   6700  * receive
   6701  *   <base>
   6702  * from the ikmpd, and register a socket to send PF_KEY messages,
   6703  * and send
   6704  *   <base, supported>
   6705  * to KMD by PF_KEY.
   6706  * If socket is detached, must free from regnode.
   6707  *
   6708  * m will always be freed.
   6709  */
   6710 static int
   6711 key_api_register(struct socket *so, struct mbuf *m,
   6712 	     const struct sadb_msghdr *mhp)
   6713 {
   6714 	struct secreg *reg, *newreg = 0;
   6715 
   6716 	/* check for invalid register message */
   6717 	if (mhp->msg->sadb_msg_satype >= __arraycount(key_misc.reglist))
   6718 		return key_senderror(so, m, EINVAL);
   6719 
   6720 	/* When SATYPE_UNSPEC is specified, only return sabd_supported. */
   6721 	if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
   6722 		goto setmsg;
   6723 
   6724 	/* Allocate regnode in advance, out of mutex */
   6725 	newreg = kmem_zalloc(sizeof(*newreg), KM_SLEEP);
   6726 
   6727 	/* check whether existing or not */
   6728 	mutex_enter(&key_misc.lock);
   6729 	LIST_FOREACH(reg, &key_misc.reglist[mhp->msg->sadb_msg_satype], chain) {
   6730 		if (reg->so == so) {
   6731 			IPSECLOG(LOG_DEBUG, "socket exists already.\n");
   6732 			mutex_exit(&key_misc.lock);
   6733 			kmem_free(newreg, sizeof(*newreg));
   6734 			return key_senderror(so, m, EEXIST);
   6735 		}
   6736 	}
   6737 
   6738 	newreg->so = so;
   6739 	((struct keycb *)sotorawcb(so))->kp_registered++;
   6740 
   6741 	/* add regnode to key_misc.reglist. */
   6742 	LIST_INSERT_HEAD(&key_misc.reglist[mhp->msg->sadb_msg_satype], newreg, chain);
   6743 	mutex_exit(&key_misc.lock);
   6744 
   6745   setmsg:
   6746     {
   6747 	struct mbuf *n;
   6748 	struct sadb_supported *sup;
   6749 	u_int len, alen, elen;
   6750 	int off;
   6751 	int i;
   6752 	struct sadb_alg *alg;
   6753 
   6754 	/* create new sadb_msg to reply. */
   6755 	alen = 0;
   6756 	for (i = 1; i <= SADB_AALG_MAX; i++) {
   6757 		if (ah_algorithm_lookup(i))
   6758 			alen += sizeof(struct sadb_alg);
   6759 	}
   6760 	if (alen)
   6761 		alen += sizeof(struct sadb_supported);
   6762 	elen = 0;
   6763 	for (i = 1; i <= SADB_EALG_MAX; i++) {
   6764 		if (esp_algorithm_lookup(i))
   6765 			elen += sizeof(struct sadb_alg);
   6766 	}
   6767 	if (elen)
   6768 		elen += sizeof(struct sadb_supported);
   6769 
   6770 	len = sizeof(struct sadb_msg) + alen + elen;
   6771 
   6772 	if (len > MCLBYTES)
   6773 		return key_senderror(so, m, ENOBUFS);
   6774 
   6775 	MGETHDR(n, M_DONTWAIT, MT_DATA);
   6776 	if (len > MHLEN) {
   6777 		MCLGET(n, M_DONTWAIT);
   6778 		if ((n->m_flags & M_EXT) == 0) {
   6779 			m_freem(n);
   6780 			n = NULL;
   6781 		}
   6782 	}
   6783 	if (!n)
   6784 		return key_senderror(so, m, ENOBUFS);
   6785 
   6786 	n->m_pkthdr.len = n->m_len = len;
   6787 	n->m_next = NULL;
   6788 	off = 0;
   6789 
   6790 	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, char *) + off);
   6791 	n = key_fill_replymsg(n, 0);
   6792 	if (n == NULL)
   6793 		return key_senderror(so, m, ENOBUFS);
   6794 
   6795 	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
   6796 
   6797 	/* for authentication algorithm */
   6798 	if (alen) {
   6799 		sup = (struct sadb_supported *)(mtod(n, char *) + off);
   6800 		sup->sadb_supported_len = PFKEY_UNIT64(alen);
   6801 		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
   6802 		off += PFKEY_ALIGN8(sizeof(*sup));
   6803 
   6804 		for (i = 1; i <= SADB_AALG_MAX; i++) {
   6805 			const struct auth_hash *aalgo;
   6806 			u_int16_t minkeysize, maxkeysize;
   6807 
   6808 			aalgo = ah_algorithm_lookup(i);
   6809 			if (!aalgo)
   6810 				continue;
   6811 			alg = (struct sadb_alg *)(mtod(n, char *) + off);
   6812 			alg->sadb_alg_id = i;
   6813 			alg->sadb_alg_ivlen = 0;
   6814 			key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
   6815 			alg->sadb_alg_minbits = _BITS(minkeysize);
   6816 			alg->sadb_alg_maxbits = _BITS(maxkeysize);
   6817 			off += PFKEY_ALIGN8(sizeof(*alg));
   6818 		}
   6819 	}
   6820 
   6821 	/* for encryption algorithm */
   6822 	if (elen) {
   6823 		sup = (struct sadb_supported *)(mtod(n, char *) + off);
   6824 		sup->sadb_supported_len = PFKEY_UNIT64(elen);
   6825 		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
   6826 		off += PFKEY_ALIGN8(sizeof(*sup));
   6827 
   6828 		for (i = 1; i <= SADB_EALG_MAX; i++) {
   6829 			const struct enc_xform *ealgo;
   6830 
   6831 			ealgo = esp_algorithm_lookup(i);
   6832 			if (!ealgo)
   6833 				continue;
   6834 			alg = (struct sadb_alg *)(mtod(n, char *) + off);
   6835 			alg->sadb_alg_id = i;
   6836 			alg->sadb_alg_ivlen = ealgo->blocksize;
   6837 			alg->sadb_alg_minbits = _BITS(ealgo->minkey);
   6838 			alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
   6839 			off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
   6840 		}
   6841 	}
   6842 
   6843 	KASSERTMSG(off == len, "length inconsistency");
   6844 
   6845 	m_freem(m);
   6846 	return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
   6847     }
   6848 }
   6849 
   6850 /*
   6851  * free secreg entry registered.
   6852  * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
   6853  */
   6854 void
   6855 key_freereg(struct socket *so)
   6856 {
   6857 	struct secreg *reg;
   6858 	int i;
   6859 
   6860 	KASSERT(!cpu_softintr_p());
   6861 	KASSERT(so != NULL);
   6862 
   6863 	/*
   6864 	 * check whether existing or not.
   6865 	 * check all type of SA, because there is a potential that
   6866 	 * one socket is registered to multiple type of SA.
   6867 	 */
   6868 	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
   6869 		mutex_enter(&key_misc.lock);
   6870 		LIST_FOREACH(reg, &key_misc.reglist[i], chain) {
   6871 			if (reg->so == so) {
   6872 				LIST_REMOVE(reg, chain);
   6873 				break;
   6874 			}
   6875 		}
   6876 		mutex_exit(&key_misc.lock);
   6877 		if (reg != NULL)
   6878 			kmem_free(reg, sizeof(*reg));
   6879 	}
   6880 
   6881 	return;
   6882 }
   6883 
   6884 /*
   6885  * SADB_EXPIRE processing
   6886  * send
   6887  *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
   6888  * to KMD by PF_KEY.
   6889  * NOTE: We send only soft lifetime extension.
   6890  *
   6891  * OUT:	0	: succeed
   6892  *	others	: error number
   6893  */
   6894 static int
   6895 key_expire(struct secasvar *sav)
   6896 {
   6897 	int s;
   6898 	int satype;
   6899 	struct mbuf *result = NULL, *m;
   6900 	int len;
   6901 	int error = -1;
   6902 	struct sadb_lifetime *lt;
   6903 
   6904 	/* XXX: Why do we lock ? */
   6905 	s = splsoftnet();	/*called from softclock()*/
   6906 
   6907 	KASSERT(sav != NULL);
   6908 
   6909 	satype = key_proto2satype(sav->sah->saidx.proto);
   6910 	KASSERTMSG(satype != 0, "invalid proto is passed");
   6911 
   6912 	/* set msg header */
   6913 	m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
   6914 	if (!m) {
   6915 		error = ENOBUFS;
   6916 		goto fail;
   6917 	}
   6918 	result = m;
   6919 
   6920 	/* create SA extension */
   6921 	m = key_setsadbsa(sav);
   6922 	if (!m) {
   6923 		error = ENOBUFS;
   6924 		goto fail;
   6925 	}
   6926 	m_cat(result, m);
   6927 
   6928 	/* create SA extension */
   6929 	m = key_setsadbxsa2(sav->sah->saidx.mode,
   6930 	    sav->replay ? sav->replay->count : 0, sav->sah->saidx.reqid);
   6931 	if (!m) {
   6932 		error = ENOBUFS;
   6933 		goto fail;
   6934 	}
   6935 	m_cat(result, m);
   6936 
   6937 	/* create lifetime extension (current and soft) */
   6938 	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
   6939 	m = key_alloc_mbuf(len);
   6940 	if (!m || m->m_next) {	/*XXX*/
   6941 		if (m)
   6942 			m_freem(m);
   6943 		error = ENOBUFS;
   6944 		goto fail;
   6945 	}
   6946 	memset(mtod(m, void *), 0, len);
   6947 	lt = mtod(m, struct sadb_lifetime *);
   6948 	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
   6949 	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
   6950 	lt->sadb_lifetime_allocations = sav->lft_c->sadb_lifetime_allocations;
   6951 	lt->sadb_lifetime_bytes = sav->lft_c->sadb_lifetime_bytes;
   6952 	lt->sadb_lifetime_addtime =
   6953 	    time_mono_to_wall(sav->lft_c->sadb_lifetime_addtime);
   6954 	lt->sadb_lifetime_usetime =
   6955 	    time_mono_to_wall(sav->lft_c->sadb_lifetime_usetime);
   6956 	lt = (struct sadb_lifetime *)(mtod(m, char *) + len / 2);
   6957 	memcpy(lt, sav->lft_s, sizeof(*lt));
   6958 	m_cat(result, m);
   6959 
   6960 	/* set sadb_address for source */
   6961 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC, &sav->sah->saidx.src.sa,
   6962 	    FULLMASK, IPSEC_ULPROTO_ANY);
   6963 	if (!m) {
   6964 		error = ENOBUFS;
   6965 		goto fail;
   6966 	}
   6967 	m_cat(result, m);
   6968 
   6969 	/* set sadb_address for destination */
   6970 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST, &sav->sah->saidx.dst.sa,
   6971 	    FULLMASK, IPSEC_ULPROTO_ANY);
   6972 	if (!m) {
   6973 		error = ENOBUFS;
   6974 		goto fail;
   6975 	}
   6976 	m_cat(result, m);
   6977 
   6978 	if ((result->m_flags & M_PKTHDR) == 0) {
   6979 		error = EINVAL;
   6980 		goto fail;
   6981 	}
   6982 
   6983 	if (result->m_len < sizeof(struct sadb_msg)) {
   6984 		result = m_pullup(result, sizeof(struct sadb_msg));
   6985 		if (result == NULL) {
   6986 			error = ENOBUFS;
   6987 			goto fail;
   6988 		}
   6989 	}
   6990 
   6991 	result->m_pkthdr.len = 0;
   6992 	for (m = result; m; m = m->m_next)
   6993 		result->m_pkthdr.len += m->m_len;
   6994 
   6995 	mtod(result, struct sadb_msg *)->sadb_msg_len =
   6996 	    PFKEY_UNIT64(result->m_pkthdr.len);
   6997 
   6998 	splx(s);
   6999 	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
   7000 
   7001  fail:
   7002 	if (result)
   7003 		m_freem(result);
   7004 	splx(s);
   7005 	return error;
   7006 }
   7007 
   7008 /*
   7009  * SADB_FLUSH processing
   7010  * receive
   7011  *   <base>
   7012  * from the ikmpd, and free all entries in secastree.
   7013  * and send,
   7014  *   <base>
   7015  * to the ikmpd.
   7016  * NOTE: to do is only marking SADB_SASTATE_DEAD.
   7017  *
   7018  * m will always be freed.
   7019  */
   7020 static int
   7021 key_api_flush(struct socket *so, struct mbuf *m,
   7022           const struct sadb_msghdr *mhp)
   7023 {
   7024 	struct sadb_msg *newmsg;
   7025 	struct secashead *sah;
   7026 	struct secasvar *sav;
   7027 	u_int16_t proto;
   7028 	u_int8_t state;
   7029 
   7030 	/* map satype to proto */
   7031 	proto = key_satype2proto(mhp->msg->sadb_msg_satype);
   7032 	if (proto == 0) {
   7033 		IPSECLOG(LOG_DEBUG, "invalid satype is passed.\n");
   7034 		return key_senderror(so, m, EINVAL);
   7035 	}
   7036 
   7037 	/* no SATYPE specified, i.e. flushing all SA. */
   7038 	SAHLIST_READER_FOREACH(sah) {
   7039 		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC &&
   7040 		    proto != sah->saidx.proto)
   7041 			continue;
   7042 
   7043 		SASTATE_ALIVE_FOREACH(state) {
   7044 		restart:
   7045 			SAVLIST_WRITER_FOREACH(sav, sah, state) {
   7046 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   7047 				KEY_FREESAV(&sav);
   7048 				goto restart;
   7049 			}
   7050 		}
   7051 
   7052 		sah->state = SADB_SASTATE_DEAD;
   7053 	}
   7054 
   7055 	if (m->m_len < sizeof(struct sadb_msg) ||
   7056 	    sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
   7057 		IPSECLOG(LOG_DEBUG, "No more memory.\n");
   7058 		return key_senderror(so, m, ENOBUFS);
   7059 	}
   7060 
   7061 	if (m->m_next)
   7062 		m_freem(m->m_next);
   7063 	m->m_next = NULL;
   7064 	m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
   7065 	newmsg = mtod(m, struct sadb_msg *);
   7066 	newmsg->sadb_msg_errno = 0;
   7067 	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
   7068 
   7069 	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
   7070 }
   7071 
   7072 
   7073 static struct mbuf *
   7074 key_setdump_chain(u_int8_t req_satype, int *errorp, int *lenp, pid_t pid)
   7075 {
   7076 	struct secashead *sah;
   7077 	struct secasvar *sav;
   7078 	u_int16_t proto;
   7079 	u_int8_t satype;
   7080 	u_int8_t state;
   7081 	int cnt;
   7082 	struct mbuf *m, *n, *prev;
   7083 
   7084 	KASSERT(mutex_owned(&key_sad.lock));
   7085 
   7086 	*lenp = 0;
   7087 
   7088 	/* map satype to proto */
   7089 	proto = key_satype2proto(req_satype);
   7090 	if (proto == 0) {
   7091 		*errorp = EINVAL;
   7092 		return (NULL);
   7093 	}
   7094 
   7095 	/* count sav entries to be sent to userland. */
   7096 	cnt = 0;
   7097 	SAHLIST_WRITER_FOREACH(sah) {
   7098 		if (req_satype != SADB_SATYPE_UNSPEC &&
   7099 		    proto != sah->saidx.proto)
   7100 			continue;
   7101 
   7102 		SASTATE_ANY_FOREACH(state) {
   7103 			SAVLIST_WRITER_FOREACH(sav, sah, state) {
   7104 				cnt++;
   7105 			}
   7106 		}
   7107 	}
   7108 
   7109 	if (cnt == 0) {
   7110 		*errorp = ENOENT;
   7111 		return (NULL);
   7112 	}
   7113 
   7114 	/* send this to the userland, one at a time. */
   7115 	m = NULL;
   7116 	prev = m;
   7117 	SAHLIST_WRITER_FOREACH(sah) {
   7118 		if (req_satype != SADB_SATYPE_UNSPEC &&
   7119 		    proto != sah->saidx.proto)
   7120 			continue;
   7121 
   7122 		/* map proto to satype */
   7123 		satype = key_proto2satype(sah->saidx.proto);
   7124 		if (satype == 0) {
   7125 			m_freem(m);
   7126 			*errorp = EINVAL;
   7127 			return (NULL);
   7128 		}
   7129 
   7130 		SASTATE_ANY_FOREACH(state) {
   7131 			SAVLIST_WRITER_FOREACH(sav, sah, state) {
   7132 				n = key_setdumpsa(sav, SADB_DUMP, satype,
   7133 				    --cnt, pid);
   7134 				if (!n) {
   7135 					m_freem(m);
   7136 					*errorp = ENOBUFS;
   7137 					return (NULL);
   7138 				}
   7139 
   7140 				if (!m)
   7141 					m = n;
   7142 				else
   7143 					prev->m_nextpkt = n;
   7144 				prev = n;
   7145 			}
   7146 		}
   7147 	}
   7148 
   7149 	if (!m) {
   7150 		*errorp = EINVAL;
   7151 		return (NULL);
   7152 	}
   7153 
   7154 	if ((m->m_flags & M_PKTHDR) != 0) {
   7155 		m->m_pkthdr.len = 0;
   7156 		for (n = m; n; n = n->m_next)
   7157 			m->m_pkthdr.len += n->m_len;
   7158 	}
   7159 
   7160 	*errorp = 0;
   7161 	return (m);
   7162 }
   7163 
   7164 /*
   7165  * SADB_DUMP processing
   7166  * dump all entries including status of DEAD in SAD.
   7167  * receive
   7168  *   <base>
   7169  * from the ikmpd, and dump all secasvar leaves
   7170  * and send,
   7171  *   <base> .....
   7172  * to the ikmpd.
   7173  *
   7174  * m will always be freed.
   7175  */
   7176 static int
   7177 key_api_dump(struct socket *so, struct mbuf *m0,
   7178 	 const struct sadb_msghdr *mhp)
   7179 {
   7180 	u_int16_t proto;
   7181 	u_int8_t satype;
   7182 	struct mbuf *n;
   7183 	int error, len, ok;
   7184 
   7185 	/* map satype to proto */
   7186 	satype = mhp->msg->sadb_msg_satype;
   7187 	proto = key_satype2proto(satype);
   7188 	if (proto == 0) {
   7189 		IPSECLOG(LOG_DEBUG, "invalid satype is passed.\n");
   7190 		return key_senderror(so, m0, EINVAL);
   7191 	}
   7192 
   7193 	/*
   7194 	 * If the requestor has insufficient socket-buffer space
   7195 	 * for the entire chain, nobody gets any response to the DUMP.
   7196 	 * XXX For now, only the requestor ever gets anything.
   7197 	 * Moreover, if the requestor has any space at all, they receive
   7198 	 * the entire chain, otherwise the request is refused with ENOBUFS.
   7199 	 */
   7200 	if (sbspace(&so->so_rcv) <= 0) {
   7201 		return key_senderror(so, m0, ENOBUFS);
   7202 	}
   7203 
   7204 	mutex_enter(&key_sad.lock);
   7205 	n = key_setdump_chain(satype, &error, &len, mhp->msg->sadb_msg_pid);
   7206 	mutex_exit(&key_sad.lock);
   7207 
   7208 	if (n == NULL) {
   7209 		return key_senderror(so, m0, ENOENT);
   7210 	}
   7211 	{
   7212 		uint64_t *ps = PFKEY_STAT_GETREF();
   7213 		ps[PFKEY_STAT_IN_TOTAL]++;
   7214 		ps[PFKEY_STAT_IN_BYTES] += len;
   7215 		PFKEY_STAT_PUTREF();
   7216 	}
   7217 
   7218 	/*
   7219 	 * PF_KEY DUMP responses are no longer broadcast to all PF_KEY sockets.
   7220 	 * The requestor receives either the entire chain, or an
   7221 	 * error message with ENOBUFS.
   7222 	 *
   7223 	 * sbappendaddrchain() takes the chain of entries, one
   7224 	 * packet-record per SPD entry, prepends the key_src sockaddr
   7225 	 * to each packet-record, links the sockaddr mbufs into a new
   7226 	 * list of records, then   appends the entire resulting
   7227 	 * list to the requesting socket.
   7228 	 */
   7229 	ok = sbappendaddrchain(&so->so_rcv, (struct sockaddr *)&key_src, n,
   7230 	    SB_PRIO_ONESHOT_OVERFLOW);
   7231 
   7232 	if (!ok) {
   7233 		PFKEY_STATINC(PFKEY_STAT_IN_NOMEM);
   7234 		m_freem(n);
   7235 		return key_senderror(so, m0, ENOBUFS);
   7236 	}
   7237 
   7238 	m_freem(m0);
   7239 	return 0;
   7240 }
   7241 
   7242 /*
   7243  * SADB_X_PROMISC processing
   7244  *
   7245  * m will always be freed.
   7246  */
   7247 static int
   7248 key_api_promisc(struct socket *so, struct mbuf *m,
   7249 	    const struct sadb_msghdr *mhp)
   7250 {
   7251 	int olen;
   7252 
   7253 	olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
   7254 
   7255 	if (olen < sizeof(struct sadb_msg)) {
   7256 #if 1
   7257 		return key_senderror(so, m, EINVAL);
   7258 #else
   7259 		m_freem(m);
   7260 		return 0;
   7261 #endif
   7262 	} else if (olen == sizeof(struct sadb_msg)) {
   7263 		/* enable/disable promisc mode */
   7264 		struct keycb *kp = (struct keycb *)sotorawcb(so);
   7265 		if (kp == NULL)
   7266 			return key_senderror(so, m, EINVAL);
   7267 		mhp->msg->sadb_msg_errno = 0;
   7268 		switch (mhp->msg->sadb_msg_satype) {
   7269 		case 0:
   7270 		case 1:
   7271 			kp->kp_promisc = mhp->msg->sadb_msg_satype;
   7272 			break;
   7273 		default:
   7274 			return key_senderror(so, m, EINVAL);
   7275 		}
   7276 
   7277 		/* send the original message back to everyone */
   7278 		mhp->msg->sadb_msg_errno = 0;
   7279 		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
   7280 	} else {
   7281 		/* send packet as is */
   7282 
   7283 		m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
   7284 
   7285 		/* TODO: if sadb_msg_seq is specified, send to specific pid */
   7286 		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
   7287 	}
   7288 }
   7289 
   7290 static int (*key_api_typesw[]) (struct socket *, struct mbuf *,
   7291 		const struct sadb_msghdr *) = {
   7292 	NULL,			/* SADB_RESERVED */
   7293 	key_api_getspi,		/* SADB_GETSPI */
   7294 	key_api_update,		/* SADB_UPDATE */
   7295 	key_api_add,		/* SADB_ADD */
   7296 	key_api_delete,		/* SADB_DELETE */
   7297 	key_api_get,		/* SADB_GET */
   7298 	key_api_acquire,	/* SADB_ACQUIRE */
   7299 	key_api_register,	/* SADB_REGISTER */
   7300 	NULL,			/* SADB_EXPIRE */
   7301 	key_api_flush,		/* SADB_FLUSH */
   7302 	key_api_dump,		/* SADB_DUMP */
   7303 	key_api_promisc,	/* SADB_X_PROMISC */
   7304 	NULL,			/* SADB_X_PCHANGE */
   7305 	key_api_spdadd,		/* SADB_X_SPDUPDATE */
   7306 	key_api_spdadd,		/* SADB_X_SPDADD */
   7307 	key_api_spddelete,	/* SADB_X_SPDDELETE */
   7308 	key_api_spdget,		/* SADB_X_SPDGET */
   7309 	NULL,			/* SADB_X_SPDACQUIRE */
   7310 	key_api_spddump,	/* SADB_X_SPDDUMP */
   7311 	key_api_spdflush,	/* SADB_X_SPDFLUSH */
   7312 	key_api_spdadd,		/* SADB_X_SPDSETIDX */
   7313 	NULL,			/* SADB_X_SPDEXPIRE */
   7314 	key_api_spddelete2,	/* SADB_X_SPDDELETE2 */
   7315 	key_api_nat_map,	/* SADB_X_NAT_T_NEW_MAPPING */
   7316 };
   7317 
   7318 /*
   7319  * parse sadb_msg buffer to process PFKEYv2,
   7320  * and create a data to response if needed.
   7321  * I think to be dealed with mbuf directly.
   7322  * IN:
   7323  *     msgp  : pointer to pointer to a received buffer pulluped.
   7324  *             This is rewrited to response.
   7325  *     so    : pointer to socket.
   7326  * OUT:
   7327  *    length for buffer to send to user process.
   7328  */
   7329 int
   7330 key_parse(struct mbuf *m, struct socket *so)
   7331 {
   7332 	struct sadb_msg *msg;
   7333 	struct sadb_msghdr mh;
   7334 	u_int orglen;
   7335 	int error;
   7336 
   7337 	KASSERT(m != NULL);
   7338 	KASSERT(so != NULL);
   7339 
   7340 #if 0	/*kdebug_sadb assumes msg in linear buffer*/
   7341 	if (KEYDEBUG_ON(KEYDEBUG_KEY_DUMP)) {
   7342 		IPSECLOG(LOG_DEBUG, "passed sadb_msg\n");
   7343 		kdebug_sadb(msg);
   7344 	}
   7345 #endif
   7346 
   7347 	if (m->m_len < sizeof(struct sadb_msg)) {
   7348 		m = m_pullup(m, sizeof(struct sadb_msg));
   7349 		if (!m)
   7350 			return ENOBUFS;
   7351 	}
   7352 	msg = mtod(m, struct sadb_msg *);
   7353 	orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
   7354 
   7355 	if ((m->m_flags & M_PKTHDR) == 0 ||
   7356 	    m->m_pkthdr.len != orglen) {
   7357 		IPSECLOG(LOG_DEBUG, "invalid message length.\n");
   7358 		PFKEY_STATINC(PFKEY_STAT_OUT_INVLEN);
   7359 		error = EINVAL;
   7360 		goto senderror;
   7361 	}
   7362 
   7363 	if (msg->sadb_msg_version != PF_KEY_V2) {
   7364 		IPSECLOG(LOG_DEBUG, "PF_KEY version %u is mismatched.\n",
   7365 		    msg->sadb_msg_version);
   7366 		PFKEY_STATINC(PFKEY_STAT_OUT_INVVER);
   7367 		error = EINVAL;
   7368 		goto senderror;
   7369 	}
   7370 
   7371 	if (msg->sadb_msg_type > SADB_MAX) {
   7372 		IPSECLOG(LOG_DEBUG, "invalid type %u is passed.\n",
   7373 		    msg->sadb_msg_type);
   7374 		PFKEY_STATINC(PFKEY_STAT_OUT_INVMSGTYPE);
   7375 		error = EINVAL;
   7376 		goto senderror;
   7377 	}
   7378 
   7379 	/* for old-fashioned code - should be nuked */
   7380 	if (m->m_pkthdr.len > MCLBYTES) {
   7381 		m_freem(m);
   7382 		return ENOBUFS;
   7383 	}
   7384 	if (m->m_next) {
   7385 		struct mbuf *n;
   7386 
   7387 		MGETHDR(n, M_DONTWAIT, MT_DATA);
   7388 		if (n && m->m_pkthdr.len > MHLEN) {
   7389 			MCLGET(n, M_DONTWAIT);
   7390 			if ((n->m_flags & M_EXT) == 0) {
   7391 				m_free(n);
   7392 				n = NULL;
   7393 			}
   7394 		}
   7395 		if (!n) {
   7396 			m_freem(m);
   7397 			return ENOBUFS;
   7398 		}
   7399 		m_copydata(m, 0, m->m_pkthdr.len, mtod(n, void *));
   7400 		n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
   7401 		n->m_next = NULL;
   7402 		m_freem(m);
   7403 		m = n;
   7404 	}
   7405 
   7406 	/* align the mbuf chain so that extensions are in contiguous region. */
   7407 	error = key_align(m, &mh);
   7408 	if (error)
   7409 		return error;
   7410 
   7411 	if (m->m_next) {	/*XXX*/
   7412 		m_freem(m);
   7413 		return ENOBUFS;
   7414 	}
   7415 
   7416 	msg = mh.msg;
   7417 
   7418 	/* check SA type */
   7419 	switch (msg->sadb_msg_satype) {
   7420 	case SADB_SATYPE_UNSPEC:
   7421 		switch (msg->sadb_msg_type) {
   7422 		case SADB_GETSPI:
   7423 		case SADB_UPDATE:
   7424 		case SADB_ADD:
   7425 		case SADB_DELETE:
   7426 		case SADB_GET:
   7427 		case SADB_ACQUIRE:
   7428 		case SADB_EXPIRE:
   7429 			IPSECLOG(LOG_DEBUG,
   7430 			    "must specify satype when msg type=%u.\n",
   7431 			    msg->sadb_msg_type);
   7432 			PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
   7433 			error = EINVAL;
   7434 			goto senderror;
   7435 		}
   7436 		break;
   7437 	case SADB_SATYPE_AH:
   7438 	case SADB_SATYPE_ESP:
   7439 	case SADB_X_SATYPE_IPCOMP:
   7440 	case SADB_X_SATYPE_TCPSIGNATURE:
   7441 		switch (msg->sadb_msg_type) {
   7442 		case SADB_X_SPDADD:
   7443 		case SADB_X_SPDDELETE:
   7444 		case SADB_X_SPDGET:
   7445 		case SADB_X_SPDDUMP:
   7446 		case SADB_X_SPDFLUSH:
   7447 		case SADB_X_SPDSETIDX:
   7448 		case SADB_X_SPDUPDATE:
   7449 		case SADB_X_SPDDELETE2:
   7450 			IPSECLOG(LOG_DEBUG, "illegal satype=%u\n",
   7451 			    msg->sadb_msg_type);
   7452 			PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
   7453 			error = EINVAL;
   7454 			goto senderror;
   7455 		}
   7456 		break;
   7457 	case SADB_SATYPE_RSVP:
   7458 	case SADB_SATYPE_OSPFV2:
   7459 	case SADB_SATYPE_RIPV2:
   7460 	case SADB_SATYPE_MIP:
   7461 		IPSECLOG(LOG_DEBUG, "type %u isn't supported.\n",
   7462 		    msg->sadb_msg_satype);
   7463 		PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
   7464 		error = EOPNOTSUPP;
   7465 		goto senderror;
   7466 	case 1:	/* XXX: What does it do? */
   7467 		if (msg->sadb_msg_type == SADB_X_PROMISC)
   7468 			break;
   7469 		/*FALLTHROUGH*/
   7470 	default:
   7471 		IPSECLOG(LOG_DEBUG, "invalid type %u is passed.\n",
   7472 		    msg->sadb_msg_satype);
   7473 		PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
   7474 		error = EINVAL;
   7475 		goto senderror;
   7476 	}
   7477 
   7478 	/* check field of upper layer protocol and address family */
   7479 	if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL &&
   7480 	    mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
   7481 		struct sadb_address *src0, *dst0;
   7482 		u_int plen;
   7483 
   7484 		src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
   7485 		dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
   7486 
   7487 		/* check upper layer protocol */
   7488 		if (src0->sadb_address_proto != dst0->sadb_address_proto) {
   7489 			IPSECLOG(LOG_DEBUG, "upper layer protocol mismatched.\n");
   7490 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7491 			error = EINVAL;
   7492 			goto senderror;
   7493 		}
   7494 
   7495 		/* check family */
   7496 		if (PFKEY_ADDR_SADDR(src0)->sa_family !=
   7497 		    PFKEY_ADDR_SADDR(dst0)->sa_family) {
   7498 			IPSECLOG(LOG_DEBUG, "address family mismatched.\n");
   7499 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7500 			error = EINVAL;
   7501 			goto senderror;
   7502 		}
   7503 		if (PFKEY_ADDR_SADDR(src0)->sa_len !=
   7504 		    PFKEY_ADDR_SADDR(dst0)->sa_len) {
   7505 			IPSECLOG(LOG_DEBUG,
   7506 			    "address struct size mismatched.\n");
   7507 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7508 			error = EINVAL;
   7509 			goto senderror;
   7510 		}
   7511 
   7512 		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
   7513 		case AF_INET:
   7514 			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
   7515 			    sizeof(struct sockaddr_in)) {
   7516 				PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7517 				error = EINVAL;
   7518 				goto senderror;
   7519 			}
   7520 			break;
   7521 		case AF_INET6:
   7522 			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
   7523 			    sizeof(struct sockaddr_in6)) {
   7524 				PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7525 				error = EINVAL;
   7526 				goto senderror;
   7527 			}
   7528 			break;
   7529 		default:
   7530 			IPSECLOG(LOG_DEBUG, "unsupported address family.\n");
   7531 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7532 			error = EAFNOSUPPORT;
   7533 			goto senderror;
   7534 		}
   7535 
   7536 		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
   7537 		case AF_INET:
   7538 			plen = sizeof(struct in_addr) << 3;
   7539 			break;
   7540 		case AF_INET6:
   7541 			plen = sizeof(struct in6_addr) << 3;
   7542 			break;
   7543 		default:
   7544 			plen = 0;	/*fool gcc*/
   7545 			break;
   7546 		}
   7547 
   7548 		/* check max prefix length */
   7549 		if (src0->sadb_address_prefixlen > plen ||
   7550 		    dst0->sadb_address_prefixlen > plen) {
   7551 			IPSECLOG(LOG_DEBUG, "illegal prefixlen.\n");
   7552 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7553 			error = EINVAL;
   7554 			goto senderror;
   7555 		}
   7556 
   7557 		/*
   7558 		 * prefixlen == 0 is valid because there can be a case when
   7559 		 * all addresses are matched.
   7560 		 */
   7561 	}
   7562 
   7563 	if (msg->sadb_msg_type >= __arraycount(key_api_typesw) ||
   7564 	    key_api_typesw[msg->sadb_msg_type] == NULL) {
   7565 		PFKEY_STATINC(PFKEY_STAT_OUT_INVMSGTYPE);
   7566 		error = EINVAL;
   7567 		goto senderror;
   7568 	}
   7569 
   7570 	return (*key_api_typesw[msg->sadb_msg_type])(so, m, &mh);
   7571 
   7572 senderror:
   7573 	return key_senderror(so, m, error);
   7574 }
   7575 
   7576 static int
   7577 key_senderror(struct socket *so, struct mbuf *m, int code)
   7578 {
   7579 	struct sadb_msg *msg;
   7580 
   7581 	KASSERT(m->m_len >= sizeof(struct sadb_msg));
   7582 
   7583 	msg = mtod(m, struct sadb_msg *);
   7584 	msg->sadb_msg_errno = code;
   7585 	return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
   7586 }
   7587 
   7588 /*
   7589  * set the pointer to each header into message buffer.
   7590  * m will be freed on error.
   7591  * XXX larger-than-MCLBYTES extension?
   7592  */
   7593 static int
   7594 key_align(struct mbuf *m, struct sadb_msghdr *mhp)
   7595 {
   7596 	struct mbuf *n;
   7597 	struct sadb_ext *ext;
   7598 	size_t off, end;
   7599 	int extlen;
   7600 	int toff;
   7601 
   7602 	KASSERT(m != NULL);
   7603 	KASSERT(mhp != NULL);
   7604 	KASSERT(m->m_len >= sizeof(struct sadb_msg));
   7605 
   7606 	/* initialize */
   7607 	memset(mhp, 0, sizeof(*mhp));
   7608 
   7609 	mhp->msg = mtod(m, struct sadb_msg *);
   7610 	mhp->ext[0] = (struct sadb_ext *)mhp->msg;	/*XXX backward compat */
   7611 
   7612 	end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
   7613 	extlen = end;	/*just in case extlen is not updated*/
   7614 	for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
   7615 		n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
   7616 		if (!n) {
   7617 			/* m is already freed */
   7618 			return ENOBUFS;
   7619 		}
   7620 		ext = (struct sadb_ext *)(mtod(n, char *) + toff);
   7621 
   7622 		/* set pointer */
   7623 		switch (ext->sadb_ext_type) {
   7624 		case SADB_EXT_SA:
   7625 		case SADB_EXT_ADDRESS_SRC:
   7626 		case SADB_EXT_ADDRESS_DST:
   7627 		case SADB_EXT_ADDRESS_PROXY:
   7628 		case SADB_EXT_LIFETIME_CURRENT:
   7629 		case SADB_EXT_LIFETIME_HARD:
   7630 		case SADB_EXT_LIFETIME_SOFT:
   7631 		case SADB_EXT_KEY_AUTH:
   7632 		case SADB_EXT_KEY_ENCRYPT:
   7633 		case SADB_EXT_IDENTITY_SRC:
   7634 		case SADB_EXT_IDENTITY_DST:
   7635 		case SADB_EXT_SENSITIVITY:
   7636 		case SADB_EXT_PROPOSAL:
   7637 		case SADB_EXT_SUPPORTED_AUTH:
   7638 		case SADB_EXT_SUPPORTED_ENCRYPT:
   7639 		case SADB_EXT_SPIRANGE:
   7640 		case SADB_X_EXT_POLICY:
   7641 		case SADB_X_EXT_SA2:
   7642 		case SADB_X_EXT_NAT_T_TYPE:
   7643 		case SADB_X_EXT_NAT_T_SPORT:
   7644 		case SADB_X_EXT_NAT_T_DPORT:
   7645 		case SADB_X_EXT_NAT_T_OAI:
   7646 		case SADB_X_EXT_NAT_T_OAR:
   7647 		case SADB_X_EXT_NAT_T_FRAG:
   7648 			/* duplicate check */
   7649 			/*
   7650 			 * XXX Are there duplication payloads of either
   7651 			 * KEY_AUTH or KEY_ENCRYPT ?
   7652 			 */
   7653 			if (mhp->ext[ext->sadb_ext_type] != NULL) {
   7654 				IPSECLOG(LOG_DEBUG,
   7655 				    "duplicate ext_type %u is passed.\n",
   7656 				    ext->sadb_ext_type);
   7657 				m_freem(m);
   7658 				PFKEY_STATINC(PFKEY_STAT_OUT_DUPEXT);
   7659 				return EINVAL;
   7660 			}
   7661 			break;
   7662 		default:
   7663 			IPSECLOG(LOG_DEBUG, "invalid ext_type %u is passed.\n",
   7664 			    ext->sadb_ext_type);
   7665 			m_freem(m);
   7666 			PFKEY_STATINC(PFKEY_STAT_OUT_INVEXTTYPE);
   7667 			return EINVAL;
   7668 		}
   7669 
   7670 		extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
   7671 
   7672 		if (key_validate_ext(ext, extlen)) {
   7673 			m_freem(m);
   7674 			PFKEY_STATINC(PFKEY_STAT_OUT_INVLEN);
   7675 			return EINVAL;
   7676 		}
   7677 
   7678 		n = m_pulldown(m, off, extlen, &toff);
   7679 		if (!n) {
   7680 			/* m is already freed */
   7681 			return ENOBUFS;
   7682 		}
   7683 		ext = (struct sadb_ext *)(mtod(n, char *) + toff);
   7684 
   7685 		mhp->ext[ext->sadb_ext_type] = ext;
   7686 		mhp->extoff[ext->sadb_ext_type] = off;
   7687 		mhp->extlen[ext->sadb_ext_type] = extlen;
   7688 	}
   7689 
   7690 	if (off != end) {
   7691 		m_freem(m);
   7692 		PFKEY_STATINC(PFKEY_STAT_OUT_INVLEN);
   7693 		return EINVAL;
   7694 	}
   7695 
   7696 	return 0;
   7697 }
   7698 
   7699 static int
   7700 key_validate_ext(const struct sadb_ext *ext, int len)
   7701 {
   7702 	const struct sockaddr *sa;
   7703 	enum { NONE, ADDR } checktype = NONE;
   7704 	int baselen = 0;
   7705 	const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
   7706 
   7707 	if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
   7708 		return EINVAL;
   7709 
   7710 	/* if it does not match minimum/maximum length, bail */
   7711 	if (ext->sadb_ext_type >= __arraycount(minsize) ||
   7712 	    ext->sadb_ext_type >= __arraycount(maxsize))
   7713 		return EINVAL;
   7714 	if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
   7715 		return EINVAL;
   7716 	if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
   7717 		return EINVAL;
   7718 
   7719 	/* more checks based on sadb_ext_type XXX need more */
   7720 	switch (ext->sadb_ext_type) {
   7721 	case SADB_EXT_ADDRESS_SRC:
   7722 	case SADB_EXT_ADDRESS_DST:
   7723 	case SADB_EXT_ADDRESS_PROXY:
   7724 		baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
   7725 		checktype = ADDR;
   7726 		break;
   7727 	case SADB_EXT_IDENTITY_SRC:
   7728 	case SADB_EXT_IDENTITY_DST:
   7729 		if (((const struct sadb_ident *)ext)->sadb_ident_type ==
   7730 		    SADB_X_IDENTTYPE_ADDR) {
   7731 			baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
   7732 			checktype = ADDR;
   7733 		} else
   7734 			checktype = NONE;
   7735 		break;
   7736 	default:
   7737 		checktype = NONE;
   7738 		break;
   7739 	}
   7740 
   7741 	switch (checktype) {
   7742 	case NONE:
   7743 		break;
   7744 	case ADDR:
   7745 		sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
   7746 		if (len < baselen + sal)
   7747 			return EINVAL;
   7748 		if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
   7749 			return EINVAL;
   7750 		break;
   7751 	}
   7752 
   7753 	return 0;
   7754 }
   7755 
   7756 static int
   7757 key_do_init(void)
   7758 {
   7759 	int i, error;
   7760 
   7761 	mutex_init(&key_misc.lock, MUTEX_DEFAULT, IPL_NONE);
   7762 	key_psz = pserialize_create();
   7763 	mutex_init(&key_spd.lock, MUTEX_DEFAULT, IPL_NONE);
   7764 	cv_init(&key_spd.cv, "key_sp");
   7765 	mutex_init(&key_sad.lock, MUTEX_DEFAULT, IPL_NONE);
   7766 
   7767 	pfkeystat_percpu = percpu_alloc(sizeof(uint64_t) * PFKEY_NSTATS);
   7768 
   7769 	callout_init(&key_timehandler_ch, 0);
   7770 	error = workqueue_create(&key_timehandler_wq, "key_timehandler",
   7771 	    key_timehandler_work, NULL, PRI_SOFTNET, IPL_SOFTNET, WQ_MPSAFE);
   7772 	if (error != 0)
   7773 		panic("%s: workqueue_create failed (%d)\n", __func__, error);
   7774 
   7775 	for (i = 0; i < IPSEC_DIR_MAX; i++) {
   7776 		PSLIST_INIT(&key_spd.splist[i]);
   7777 	}
   7778 
   7779 	PSLIST_INIT(&key_spd.socksplist);
   7780 
   7781 	PSLIST_INIT(&key_sad.sahlist);
   7782 
   7783 	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
   7784 		LIST_INIT(&key_misc.reglist[i]);
   7785 	}
   7786 
   7787 #ifndef IPSEC_NONBLOCK_ACQUIRE
   7788 	LIST_INIT(&key_misc.acqlist);
   7789 #endif
   7790 #ifdef notyet
   7791 	LIST_INIT(&key_misc.spacqlist);
   7792 #endif
   7793 
   7794 	/* system default */
   7795 	ip4_def_policy.policy = IPSEC_POLICY_NONE;
   7796 	ip4_def_policy.state = IPSEC_SPSTATE_ALIVE;
   7797 	localcount_init(&ip4_def_policy.localcount);
   7798 
   7799 #ifdef INET6
   7800 	ip6_def_policy.policy = IPSEC_POLICY_NONE;
   7801 	ip6_def_policy.state = IPSEC_SPSTATE_ALIVE;
   7802 	localcount_init(&ip6_def_policy.localcount);
   7803 #endif
   7804 
   7805 	callout_reset(&key_timehandler_ch, hz, key_timehandler, NULL);
   7806 
   7807 	/* initialize key statistics */
   7808 	keystat.getspi_count = 1;
   7809 
   7810 	aprint_verbose("IPsec: Initialized Security Association Processing.\n");
   7811 
   7812 	return (0);
   7813 }
   7814 
   7815 void
   7816 key_init(void)
   7817 {
   7818 	static ONCE_DECL(key_init_once);
   7819 
   7820 	sysctl_net_keyv2_setup(NULL);
   7821 	sysctl_net_key_compat_setup(NULL);
   7822 
   7823 	RUN_ONCE(&key_init_once, key_do_init);
   7824 
   7825 	key_init_so();
   7826 }
   7827 
   7828 /*
   7829  * XXX: maybe This function is called after INBOUND IPsec processing.
   7830  *
   7831  * Special check for tunnel-mode packets.
   7832  * We must make some checks for consistency between inner and outer IP header.
   7833  *
   7834  * xxx more checks to be provided
   7835  */
   7836 int
   7837 key_checktunnelsanity(
   7838     struct secasvar *sav,
   7839     u_int family,
   7840     void *src,
   7841     void *dst
   7842 )
   7843 {
   7844 
   7845 	/* XXX: check inner IP header */
   7846 
   7847 	return 1;
   7848 }
   7849 
   7850 #if 0
   7851 #define hostnamelen	strlen(hostname)
   7852 
   7853 /*
   7854  * Get FQDN for the host.
   7855  * If the administrator configured hostname (by hostname(1)) without
   7856  * domain name, returns nothing.
   7857  */
   7858 static const char *
   7859 key_getfqdn(void)
   7860 {
   7861 	int i;
   7862 	int hasdot;
   7863 	static char fqdn[MAXHOSTNAMELEN + 1];
   7864 
   7865 	if (!hostnamelen)
   7866 		return NULL;
   7867 
   7868 	/* check if it comes with domain name. */
   7869 	hasdot = 0;
   7870 	for (i = 0; i < hostnamelen; i++) {
   7871 		if (hostname[i] == '.')
   7872 			hasdot++;
   7873 	}
   7874 	if (!hasdot)
   7875 		return NULL;
   7876 
   7877 	/* NOTE: hostname may not be NUL-terminated. */
   7878 	memset(fqdn, 0, sizeof(fqdn));
   7879 	memcpy(fqdn, hostname, hostnamelen);
   7880 	fqdn[hostnamelen] = '\0';
   7881 	return fqdn;
   7882 }
   7883 
   7884 /*
   7885  * get username@FQDN for the host/user.
   7886  */
   7887 static const char *
   7888 key_getuserfqdn(void)
   7889 {
   7890 	const char *host;
   7891 	static char userfqdn[MAXHOSTNAMELEN + MAXLOGNAME + 2];
   7892 	struct proc *p = curproc;
   7893 	char *q;
   7894 
   7895 	if (!p || !p->p_pgrp || !p->p_pgrp->pg_session)
   7896 		return NULL;
   7897 	if (!(host = key_getfqdn()))
   7898 		return NULL;
   7899 
   7900 	/* NOTE: s_login may not be-NUL terminated. */
   7901 	memset(userfqdn, 0, sizeof(userfqdn));
   7902 	memcpy(userfqdn, Mp->p_pgrp->pg_session->s_login, AXLOGNAME);
   7903 	userfqdn[MAXLOGNAME] = '\0';	/* safeguard */
   7904 	q = userfqdn + strlen(userfqdn);
   7905 	*q++ = '@';
   7906 	memcpy(q, host, strlen(host));
   7907 	q += strlen(host);
   7908 	*q++ = '\0';
   7909 
   7910 	return userfqdn;
   7911 }
   7912 #endif
   7913 
   7914 /* record data transfer on SA, and update timestamps */
   7915 void
   7916 key_sa_recordxfer(struct secasvar *sav, struct mbuf *m)
   7917 {
   7918 
   7919 	KASSERT(sav != NULL);
   7920 	KASSERT(sav->lft_c != NULL);
   7921 	KASSERT(m != NULL);
   7922 
   7923 	/*
   7924 	 * XXX Currently, there is a difference of bytes size
   7925 	 * between inbound and outbound processing.
   7926 	 */
   7927 	sav->lft_c->sadb_lifetime_bytes += m->m_pkthdr.len;
   7928 	/* to check bytes lifetime is done in key_timehandler(). */
   7929 
   7930 	/*
   7931 	 * We use the number of packets as the unit of
   7932 	 * sadb_lifetime_allocations.  We increment the variable
   7933 	 * whenever {esp,ah}_{in,out}put is called.
   7934 	 */
   7935 	sav->lft_c->sadb_lifetime_allocations++;
   7936 	/* XXX check for expires? */
   7937 
   7938 	/*
   7939 	 * NOTE: We record CURRENT sadb_lifetime_usetime by using wall clock,
   7940 	 * in seconds.  HARD and SOFT lifetime are measured by the time
   7941 	 * difference (again in seconds) from sadb_lifetime_usetime.
   7942 	 *
   7943 	 *	usetime
   7944 	 *	v     expire   expire
   7945 	 * -----+-----+--------+---> t
   7946 	 *	<--------------> HARD
   7947 	 *	<-----> SOFT
   7948 	 */
   7949 	sav->lft_c->sadb_lifetime_usetime = time_uptime;
   7950 	/* XXX check for expires? */
   7951 
   7952 	return;
   7953 }
   7954 
   7955 /* dumb version */
   7956 void
   7957 key_sa_routechange(struct sockaddr *dst)
   7958 {
   7959 	struct secashead *sah;
   7960 	struct route *ro;
   7961 	const struct sockaddr *sa;
   7962 
   7963 	SAHLIST_READER_FOREACH(sah) {
   7964 		ro = &sah->sa_route;
   7965 		sa = rtcache_getdst(ro);
   7966 		if (sa != NULL && dst->sa_len == sa->sa_len &&
   7967 		    memcmp(dst, sa, dst->sa_len) == 0)
   7968 			rtcache_free(ro);
   7969 	}
   7970 
   7971 	return;
   7972 }
   7973 
   7974 static void
   7975 key_sa_chgstate(struct secasvar *sav, u_int8_t state)
   7976 {
   7977 	struct secasvar *_sav;
   7978 
   7979 	KASSERT(sav != NULL);
   7980 
   7981 	if (sav->state == state)
   7982 		return;
   7983 
   7984 	SAVLIST_WRITER_REMOVE(sav);
   7985 	SAVLIST_ENTRY_DESTROY(sav);
   7986 	SAVLIST_ENTRY_INIT(sav);
   7987 
   7988 	sav->state = state;
   7989 	if (!SADB_SASTATE_USABLE_P(sav)) {
   7990 		/* We don't need to care about the order */
   7991 		SAVLIST_WRITER_INSERT_HEAD(sav->sah, state, sav);
   7992 		return;
   7993 	}
   7994 	/*
   7995 	 * Sort the list by lft_c->sadb_lifetime_addtime
   7996 	 * in ascending order.
   7997 	 */
   7998 	SAVLIST_READER_FOREACH(_sav, sav->sah, state) {
   7999 		if (_sav->lft_c->sadb_lifetime_addtime >
   8000 		    sav->lft_c->sadb_lifetime_addtime) {
   8001 			SAVLIST_WRITER_INSERT_BEFORE(_sav, sav);
   8002 			break;
   8003 		}
   8004 	}
   8005 	if (_sav == NULL) {
   8006 		SAVLIST_WRITER_INSERT_TAIL(sav->sah, state, sav);
   8007 	}
   8008 	key_validate_savlist(sav->sah, state);
   8009 }
   8010 
   8011 /* XXX too much? */
   8012 static struct mbuf *
   8013 key_alloc_mbuf(int l)
   8014 {
   8015 	struct mbuf *m = NULL, *n;
   8016 	int len, t;
   8017 
   8018 	len = l;
   8019 	while (len > 0) {
   8020 		MGET(n, M_DONTWAIT, MT_DATA);
   8021 		if (n && len > MLEN)
   8022 			MCLGET(n, M_DONTWAIT);
   8023 		if (!n) {
   8024 			m_freem(m);
   8025 			return NULL;
   8026 		}
   8027 
   8028 		n->m_next = NULL;
   8029 		n->m_len = 0;
   8030 		n->m_len = M_TRAILINGSPACE(n);
   8031 		/* use the bottom of mbuf, hoping we can prepend afterwards */
   8032 		if (n->m_len > len) {
   8033 			t = (n->m_len - len) & ~(sizeof(long) - 1);
   8034 			n->m_data += t;
   8035 			n->m_len = len;
   8036 		}
   8037 
   8038 		len -= n->m_len;
   8039 
   8040 		if (m)
   8041 			m_cat(m, n);
   8042 		else
   8043 			m = n;
   8044 	}
   8045 
   8046 	return m;
   8047 }
   8048 
   8049 static struct mbuf *
   8050 key_setdump(u_int8_t req_satype, int *errorp, uint32_t pid)
   8051 {
   8052 	struct secashead *sah;
   8053 	struct secasvar *sav;
   8054 	u_int16_t proto;
   8055 	u_int8_t satype;
   8056 	u_int8_t state;
   8057 	int cnt;
   8058 	struct mbuf *m, *n;
   8059 
   8060 	KASSERT(mutex_owned(&key_sad.lock));
   8061 
   8062 	/* map satype to proto */
   8063 	proto = key_satype2proto(req_satype);
   8064 	if (proto == 0) {
   8065 		*errorp = EINVAL;
   8066 		return (NULL);
   8067 	}
   8068 
   8069 	/* count sav entries to be sent to the userland. */
   8070 	cnt = 0;
   8071 	SAHLIST_WRITER_FOREACH(sah) {
   8072 		if (req_satype != SADB_SATYPE_UNSPEC &&
   8073 		    proto != sah->saidx.proto)
   8074 			continue;
   8075 
   8076 		SASTATE_ANY_FOREACH(state) {
   8077 			SAVLIST_WRITER_FOREACH(sav, sah, state) {
   8078 				cnt++;
   8079 			}
   8080 		}
   8081 	}
   8082 
   8083 	if (cnt == 0) {
   8084 		*errorp = ENOENT;
   8085 		return (NULL);
   8086 	}
   8087 
   8088 	/* send this to the userland, one at a time. */
   8089 	m = NULL;
   8090 	SAHLIST_WRITER_FOREACH(sah) {
   8091 		if (req_satype != SADB_SATYPE_UNSPEC &&
   8092 		    proto != sah->saidx.proto)
   8093 			continue;
   8094 
   8095 		/* map proto to satype */
   8096 		satype = key_proto2satype(sah->saidx.proto);
   8097 		if (satype == 0) {
   8098 			m_freem(m);
   8099 			*errorp = EINVAL;
   8100 			return (NULL);
   8101 		}
   8102 
   8103 		SASTATE_ANY_FOREACH(state) {
   8104 			SAVLIST_WRITER_FOREACH(sav, sah, state) {
   8105 				n = key_setdumpsa(sav, SADB_DUMP, satype,
   8106 				    --cnt, pid);
   8107 				if (!n) {
   8108 					m_freem(m);
   8109 					*errorp = ENOBUFS;
   8110 					return (NULL);
   8111 				}
   8112 
   8113 				if (!m)
   8114 					m = n;
   8115 				else
   8116 					m_cat(m, n);
   8117 			}
   8118 		}
   8119 	}
   8120 
   8121 	if (!m) {
   8122 		*errorp = EINVAL;
   8123 		return (NULL);
   8124 	}
   8125 
   8126 	if ((m->m_flags & M_PKTHDR) != 0) {
   8127 		m->m_pkthdr.len = 0;
   8128 		for (n = m; n; n = n->m_next)
   8129 			m->m_pkthdr.len += n->m_len;
   8130 	}
   8131 
   8132 	*errorp = 0;
   8133 	return (m);
   8134 }
   8135 
   8136 static struct mbuf *
   8137 key_setspddump(int *errorp, pid_t pid)
   8138 {
   8139 	struct secpolicy *sp;
   8140 	int cnt;
   8141 	u_int dir;
   8142 	struct mbuf *m, *n;
   8143 
   8144 	KASSERT(mutex_owned(&key_spd.lock));
   8145 
   8146 	/* search SPD entry and get buffer size. */
   8147 	cnt = 0;
   8148 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
   8149 		SPLIST_WRITER_FOREACH(sp, dir) {
   8150 			cnt++;
   8151 		}
   8152 	}
   8153 
   8154 	if (cnt == 0) {
   8155 		*errorp = ENOENT;
   8156 		return (NULL);
   8157 	}
   8158 
   8159 	m = NULL;
   8160 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
   8161 		SPLIST_WRITER_FOREACH(sp, dir) {
   8162 			--cnt;
   8163 			n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt, pid);
   8164 
   8165 			if (!n) {
   8166 				*errorp = ENOBUFS;
   8167 				m_freem(m);
   8168 				return (NULL);
   8169 			}
   8170 			if (!m)
   8171 				m = n;
   8172 			else {
   8173 				m->m_pkthdr.len += n->m_pkthdr.len;
   8174 				m_cat(m, n);
   8175 			}
   8176 		}
   8177 	}
   8178 
   8179 	*errorp = 0;
   8180 	return (m);
   8181 }
   8182 
   8183 int
   8184 key_get_used(void) {
   8185 	return !SPLIST_READER_EMPTY(IPSEC_DIR_INBOUND) ||
   8186 	    !SPLIST_READER_EMPTY(IPSEC_DIR_OUTBOUND) ||
   8187 	    !SOCKSPLIST_READER_EMPTY();
   8188 }
   8189 
   8190 void
   8191 key_update_used(void)
   8192 {
   8193 	switch (ipsec_enabled) {
   8194 	default:
   8195 	case 0:
   8196 #ifdef notyet
   8197 		/* XXX: racy */
   8198 		ipsec_used = 0;
   8199 #endif
   8200 		break;
   8201 	case 1:
   8202 #ifndef notyet
   8203 		/* XXX: racy */
   8204 		if (!ipsec_used)
   8205 #endif
   8206 		ipsec_used = key_get_used();
   8207 		break;
   8208 	case 2:
   8209 		ipsec_used = 1;
   8210 		break;
   8211 	}
   8212 }
   8213 
   8214 static int
   8215 sysctl_net_key_dumpsa(SYSCTLFN_ARGS)
   8216 {
   8217 	struct mbuf *m, *n;
   8218 	int err2 = 0;
   8219 	char *p, *ep;
   8220 	size_t len;
   8221 	int error;
   8222 
   8223 	if (newp)
   8224 		return (EPERM);
   8225 	if (namelen != 1)
   8226 		return (EINVAL);
   8227 
   8228 	mutex_enter(&key_sad.lock);
   8229 	m = key_setdump(name[0], &error, l->l_proc->p_pid);
   8230 	mutex_exit(&key_sad.lock);
   8231 	if (!m)
   8232 		return (error);
   8233 	if (!oldp)
   8234 		*oldlenp = m->m_pkthdr.len;
   8235 	else {
   8236 		p = oldp;
   8237 		if (*oldlenp < m->m_pkthdr.len) {
   8238 			err2 = ENOMEM;
   8239 			ep = p + *oldlenp;
   8240 		} else {
   8241 			*oldlenp = m->m_pkthdr.len;
   8242 			ep = p + m->m_pkthdr.len;
   8243 		}
   8244 		for (n = m; n; n = n->m_next) {
   8245 			len =  (ep - p < n->m_len) ?
   8246 				ep - p : n->m_len;
   8247 			error = copyout(mtod(n, const void *), p, len);
   8248 			p += len;
   8249 			if (error)
   8250 				break;
   8251 		}
   8252 		if (error == 0)
   8253 			error = err2;
   8254 	}
   8255 	m_freem(m);
   8256 
   8257 	return (error);
   8258 }
   8259 
   8260 static int
   8261 sysctl_net_key_dumpsp(SYSCTLFN_ARGS)
   8262 {
   8263 	struct mbuf *m, *n;
   8264 	int err2 = 0;
   8265 	char *p, *ep;
   8266 	size_t len;
   8267 	int error;
   8268 
   8269 	if (newp)
   8270 		return (EPERM);
   8271 	if (namelen != 0)
   8272 		return (EINVAL);
   8273 
   8274 	mutex_enter(&key_spd.lock);
   8275 	m = key_setspddump(&error, l->l_proc->p_pid);
   8276 	mutex_exit(&key_spd.lock);
   8277 	if (!m)
   8278 		return (error);
   8279 	if (!oldp)
   8280 		*oldlenp = m->m_pkthdr.len;
   8281 	else {
   8282 		p = oldp;
   8283 		if (*oldlenp < m->m_pkthdr.len) {
   8284 			err2 = ENOMEM;
   8285 			ep = p + *oldlenp;
   8286 		} else {
   8287 			*oldlenp = m->m_pkthdr.len;
   8288 			ep = p + m->m_pkthdr.len;
   8289 		}
   8290 		for (n = m; n; n = n->m_next) {
   8291 			len = (ep - p < n->m_len) ? ep - p : n->m_len;
   8292 			error = copyout(mtod(n, const void *), p, len);
   8293 			p += len;
   8294 			if (error)
   8295 				break;
   8296 		}
   8297 		if (error == 0)
   8298 			error = err2;
   8299 	}
   8300 	m_freem(m);
   8301 
   8302 	return (error);
   8303 }
   8304 
   8305 /*
   8306  * Create sysctl tree for native IPSEC key knobs, originally
   8307  * under name "net.keyv2"  * with MIB number { CTL_NET, PF_KEY_V2. }.
   8308  * However, sysctl(8) never checked for nodes under { CTL_NET, PF_KEY_V2 };
   8309  * and in any case the part of our sysctl namespace used for dumping the
   8310  * SPD and SA database  *HAS* to be compatible with the KAME sysctl
   8311  * namespace, for API reasons.
   8312  *
   8313  * Pending a consensus on the right way  to fix this, add a level of
   8314  * indirection in how we number the `native' IPSEC key nodes;
   8315  * and (as requested by Andrew Brown)  move registration of the
   8316  * KAME-compatible names  to a separate function.
   8317  */
   8318 #if 0
   8319 #  define IPSEC_PFKEY PF_KEY_V2
   8320 # define IPSEC_PFKEY_NAME "keyv2"
   8321 #else
   8322 #  define IPSEC_PFKEY PF_KEY
   8323 # define IPSEC_PFKEY_NAME "key"
   8324 #endif
   8325 
   8326 static int
   8327 sysctl_net_key_stats(SYSCTLFN_ARGS)
   8328 {
   8329 
   8330 	return (NETSTAT_SYSCTL(pfkeystat_percpu, PFKEY_NSTATS));
   8331 }
   8332 
   8333 static void
   8334 sysctl_net_keyv2_setup(struct sysctllog **clog)
   8335 {
   8336 
   8337 	sysctl_createv(clog, 0, NULL, NULL,
   8338 		       CTLFLAG_PERMANENT,
   8339 		       CTLTYPE_NODE, IPSEC_PFKEY_NAME, NULL,
   8340 		       NULL, 0, NULL, 0,
   8341 		       CTL_NET, IPSEC_PFKEY, CTL_EOL);
   8342 
   8343 	sysctl_createv(clog, 0, NULL, NULL,
   8344 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8345 		       CTLTYPE_INT, "debug", NULL,
   8346 		       NULL, 0, &key_debug_level, 0,
   8347 		       CTL_NET, IPSEC_PFKEY, KEYCTL_DEBUG_LEVEL, CTL_EOL);
   8348 	sysctl_createv(clog, 0, NULL, NULL,
   8349 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8350 		       CTLTYPE_INT, "spi_try", NULL,
   8351 		       NULL, 0, &key_spi_trycnt, 0,
   8352 		       CTL_NET, IPSEC_PFKEY, KEYCTL_SPI_TRY, CTL_EOL);
   8353 	sysctl_createv(clog, 0, NULL, NULL,
   8354 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8355 		       CTLTYPE_INT, "spi_min_value", NULL,
   8356 		       NULL, 0, &key_spi_minval, 0,
   8357 		       CTL_NET, IPSEC_PFKEY, KEYCTL_SPI_MIN_VALUE, CTL_EOL);
   8358 	sysctl_createv(clog, 0, NULL, NULL,
   8359 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8360 		       CTLTYPE_INT, "spi_max_value", NULL,
   8361 		       NULL, 0, &key_spi_maxval, 0,
   8362 		       CTL_NET, IPSEC_PFKEY, KEYCTL_SPI_MAX_VALUE, CTL_EOL);
   8363 	sysctl_createv(clog, 0, NULL, NULL,
   8364 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8365 		       CTLTYPE_INT, "random_int", NULL,
   8366 		       NULL, 0, &key_int_random, 0,
   8367 		       CTL_NET, IPSEC_PFKEY, KEYCTL_RANDOM_INT, CTL_EOL);
   8368 	sysctl_createv(clog, 0, NULL, NULL,
   8369 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8370 		       CTLTYPE_INT, "larval_lifetime", NULL,
   8371 		       NULL, 0, &key_larval_lifetime, 0,
   8372 		       CTL_NET, IPSEC_PFKEY, KEYCTL_LARVAL_LIFETIME, CTL_EOL);
   8373 	sysctl_createv(clog, 0, NULL, NULL,
   8374 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8375 		       CTLTYPE_INT, "blockacq_count", NULL,
   8376 		       NULL, 0, &key_blockacq_count, 0,
   8377 		       CTL_NET, IPSEC_PFKEY, KEYCTL_BLOCKACQ_COUNT, CTL_EOL);
   8378 	sysctl_createv(clog, 0, NULL, NULL,
   8379 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8380 		       CTLTYPE_INT, "blockacq_lifetime", NULL,
   8381 		       NULL, 0, &key_blockacq_lifetime, 0,
   8382 		       CTL_NET, IPSEC_PFKEY, KEYCTL_BLOCKACQ_LIFETIME, CTL_EOL);
   8383 	sysctl_createv(clog, 0, NULL, NULL,
   8384 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8385 		       CTLTYPE_INT, "esp_keymin", NULL,
   8386 		       NULL, 0, &ipsec_esp_keymin, 0,
   8387 		       CTL_NET, IPSEC_PFKEY, KEYCTL_ESP_KEYMIN, CTL_EOL);
   8388 	sysctl_createv(clog, 0, NULL, NULL,
   8389 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8390 		       CTLTYPE_INT, "prefered_oldsa", NULL,
   8391 		       NULL, 0, &key_prefered_oldsa, 0,
   8392 		       CTL_NET, PF_KEY, KEYCTL_PREFERED_OLDSA, CTL_EOL);
   8393 	sysctl_createv(clog, 0, NULL, NULL,
   8394 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8395 		       CTLTYPE_INT, "esp_auth", NULL,
   8396 		       NULL, 0, &ipsec_esp_auth, 0,
   8397 		       CTL_NET, IPSEC_PFKEY, KEYCTL_ESP_AUTH, CTL_EOL);
   8398 	sysctl_createv(clog, 0, NULL, NULL,
   8399 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8400 		       CTLTYPE_INT, "ah_keymin", NULL,
   8401 		       NULL, 0, &ipsec_ah_keymin, 0,
   8402 		       CTL_NET, IPSEC_PFKEY, KEYCTL_AH_KEYMIN, CTL_EOL);
   8403 	sysctl_createv(clog, 0, NULL, NULL,
   8404 		       CTLFLAG_PERMANENT,
   8405 		       CTLTYPE_STRUCT, "stats",
   8406 		       SYSCTL_DESCR("PF_KEY statistics"),
   8407 		       sysctl_net_key_stats, 0, NULL, 0,
   8408 		       CTL_NET, IPSEC_PFKEY, CTL_CREATE, CTL_EOL);
   8409 }
   8410 
   8411 /*
   8412  * Register sysctl names used by setkey(8). For historical reasons,
   8413  * and to share a single API, these names appear under { CTL_NET, PF_KEY }
   8414  * for both IPSEC and KAME IPSEC.
   8415  */
   8416 static void
   8417 sysctl_net_key_compat_setup(struct sysctllog **clog)
   8418 {
   8419 
   8420 	sysctl_createv(clog, 0, NULL, NULL,
   8421 		       CTLFLAG_PERMANENT,
   8422 		       CTLTYPE_NODE, "key", NULL,
   8423 		       NULL, 0, NULL, 0,
   8424 		       CTL_NET, PF_KEY, CTL_EOL);
   8425 
   8426 	/* Register the net.key.dump{sa,sp} nodes used by setkey(8). */
   8427 	sysctl_createv(clog, 0, NULL, NULL,
   8428 		       CTLFLAG_PERMANENT,
   8429 		       CTLTYPE_STRUCT, "dumpsa", NULL,
   8430 		       sysctl_net_key_dumpsa, 0, NULL, 0,
   8431 		       CTL_NET, PF_KEY, KEYCTL_DUMPSA, CTL_EOL);
   8432 	sysctl_createv(clog, 0, NULL, NULL,
   8433 		       CTLFLAG_PERMANENT,
   8434 		       CTLTYPE_STRUCT, "dumpsp", NULL,
   8435 		       sysctl_net_key_dumpsp, 0, NULL, 0,
   8436 		       CTL_NET, PF_KEY, KEYCTL_DUMPSP, CTL_EOL);
   8437 }
   8438