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