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