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