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