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