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