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