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