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