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