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