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