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