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