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