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