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