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