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