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