xref: /netbsd-src/crypto/dist/ipsec-tools/src/racoon/pfkey.c (revision 0df165c04d0a9ca1adde9ed2b890344c937954a6)
1 /*	$NetBSD: pfkey.c,v 1.24 2007/11/09 16:27:58 vanhu Exp $	*/
2 
3 /* $Id: pfkey.c,v 1.24 2007/11/09 16:27:58 vanhu Exp $ */
4 
5 /*
6  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the project nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #include "config.h"
35 
36 #include <stdlib.h>
37 #include <string.h>
38 #include <stdio.h>
39 #include <netdb.h>
40 #include <errno.h>
41 #ifdef HAVE_UNISTD_H
42 #include <unistd.h>
43 #endif
44 #include <netdb.h>
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
47 
48 #ifdef ENABLE_NATT
49 # ifdef __linux__
50 #  include <linux/udp.h>
51 # endif
52 # if defined(__NetBSD__) || defined(__FreeBSD__) ||	\
53   (defined(__APPLE__) && defined(__MACH__))
54 #  include <netinet/udp.h>
55 # endif
56 #endif
57 
58 #include <sys/types.h>
59 #include <sys/param.h>
60 #include <sys/socket.h>
61 #include <sys/queue.h>
62 #include <sys/sysctl.h>
63 
64 #include <net/route.h>
65 #include <net/pfkeyv2.h>
66 
67 #include <netinet/in.h>
68 #include PATH_IPSEC_H
69 #include <fcntl.h>
70 
71 #include "libpfkey.h"
72 
73 #include "var.h"
74 #include "misc.h"
75 #include "vmbuf.h"
76 #include "plog.h"
77 #include "sockmisc.h"
78 #include "debug.h"
79 
80 #include "schedule.h"
81 #include "localconf.h"
82 #include "remoteconf.h"
83 #include "handler.h"
84 #include "policy.h"
85 #include "proposal.h"
86 #include "isakmp_var.h"
87 #include "isakmp.h"
88 #include "isakmp_inf.h"
89 #include "ipsec_doi.h"
90 #include "oakley.h"
91 #include "pfkey.h"
92 #include "algorithm.h"
93 #include "sainfo.h"
94 #include "admin.h"
95 #include "privsep.h"
96 #include "strnames.h"
97 #include "backupsa.h"
98 #include "gcmalloc.h"
99 #include "nattraversal.h"
100 #include "crypto_openssl.h"
101 #include "grabmyaddr.h"
102 
103 #if defined(SADB_X_EALG_RIJNDAELCBC) && !defined(SADB_X_EALG_AESCBC)
104 #define SADB_X_EALG_AESCBC  SADB_X_EALG_RIJNDAELCBC
105 #endif
106 
107 /* prototype */
108 static u_int ipsecdoi2pfkey_aalg __P((u_int));
109 static u_int ipsecdoi2pfkey_ealg __P((u_int));
110 static u_int ipsecdoi2pfkey_calg __P((u_int));
111 static u_int ipsecdoi2pfkey_alg __P((u_int, u_int));
112 static u_int keylen_aalg __P((u_int));
113 static u_int keylen_ealg __P((u_int, int));
114 
115 static int pk_recvgetspi __P((caddr_t *));
116 static int pk_recvupdate __P((caddr_t *));
117 static int pk_recvadd __P((caddr_t *));
118 static int pk_recvdelete __P((caddr_t *));
119 static int pk_recvacquire __P((caddr_t *));
120 static int pk_recvexpire __P((caddr_t *));
121 static int pk_recvflush __P((caddr_t *));
122 static int getsadbpolicy __P((caddr_t *, int *, int, struct ph2handle *));
123 static int pk_recvspdupdate __P((caddr_t *));
124 static int pk_recvspdadd __P((caddr_t *));
125 static int pk_recvspddelete __P((caddr_t *));
126 static int pk_recvspdexpire __P((caddr_t *));
127 static int pk_recvspdget __P((caddr_t *));
128 static int pk_recvspddump __P((caddr_t *));
129 static int pk_recvspdflush __P((caddr_t *));
130 static struct sadb_msg *pk_recv __P((int, int *));
131 
132 static int (*pkrecvf[]) __P((caddr_t *)) = {
133 NULL,
134 pk_recvgetspi,
135 pk_recvupdate,
136 pk_recvadd,
137 pk_recvdelete,
138 NULL,	/* SADB_GET */
139 pk_recvacquire,
140 NULL,	/* SABD_REGISTER */
141 pk_recvexpire,
142 pk_recvflush,
143 NULL,	/* SADB_DUMP */
144 NULL,	/* SADB_X_PROMISC */
145 NULL,	/* SADB_X_PCHANGE */
146 pk_recvspdupdate,
147 pk_recvspdadd,
148 pk_recvspddelete,
149 pk_recvspdget,
150 NULL,	/* SADB_X_SPDACQUIRE */
151 pk_recvspddump,
152 pk_recvspdflush,
153 NULL,	/* SADB_X_SPDSETIDX */
154 pk_recvspdexpire,
155 NULL,	/* SADB_X_SPDDELETE2 */
156 NULL,	/* SADB_X_NAT_T_NEW_MAPPING */
157 NULL,	/* SADB_X_MIGRATE */
158 #if (SADB_MAX > 24)
159 #error "SADB extra message?"
160 #endif
161 };
162 
163 static int addnewsp __P((caddr_t *));
164 
165 /* cope with old kame headers - ugly */
166 #ifndef SADB_X_AALG_MD5
167 #define SADB_X_AALG_MD5		SADB_AALG_MD5
168 #endif
169 #ifndef SADB_X_AALG_SHA
170 #define SADB_X_AALG_SHA		SADB_AALG_SHA
171 #endif
172 #ifndef SADB_X_AALG_NULL
173 #define SADB_X_AALG_NULL	SADB_AALG_NULL
174 #endif
175 
176 #ifndef SADB_X_EALG_BLOWFISHCBC
177 #define SADB_X_EALG_BLOWFISHCBC	SADB_EALG_BLOWFISHCBC
178 #endif
179 #ifndef SADB_X_EALG_CAST128CBC
180 #define SADB_X_EALG_CAST128CBC	SADB_EALG_CAST128CBC
181 #endif
182 #ifndef SADB_X_EALG_RC5CBC
183 #ifdef SADB_EALG_RC5CBC
184 #define SADB_X_EALG_RC5CBC	SADB_EALG_RC5CBC
185 #endif
186 #endif
187 
188 /*
189  * PF_KEY packet handler
190  *	0: success
191  *	-1: fail
192  */
193 int
194 pfkey_handler()
195 {
196 	struct sadb_msg *msg;
197 	int len;
198 	caddr_t mhp[SADB_EXT_MAX + 1];
199 	int error = -1;
200 
201 	/* receive pfkey message. */
202 	len = 0;
203 	msg = (struct sadb_msg *)pk_recv(lcconf->sock_pfkey, &len);
204 	if (msg == NULL) {
205 		if (len < 0) {
206 			plog(LLV_ERROR, LOCATION, NULL,
207 				"failed to recv from pfkey (%s)\n",
208 				strerror(errno));
209 			goto end;
210 		} else {
211 			/* short message - msg not ready */
212 			return 0;
213 		}
214 	}
215 
216 	plog(LLV_DEBUG, LOCATION, NULL, "get pfkey %s message\n",
217 		s_pfkey_type(msg->sadb_msg_type));
218 	plogdump(LLV_DEBUG2, msg, msg->sadb_msg_len << 3);
219 
220 	/* validity check */
221 	if (msg->sadb_msg_errno) {
222 		int pri;
223 
224 		/* when SPD is empty, treat the state as no error. */
225 		if (msg->sadb_msg_type == SADB_X_SPDDUMP &&
226 		    msg->sadb_msg_errno == ENOENT)
227 			pri = LLV_DEBUG;
228 		else
229 			pri = LLV_ERROR;
230 
231 		plog(pri, LOCATION, NULL,
232 			"pfkey %s failed: %s\n",
233 			s_pfkey_type(msg->sadb_msg_type),
234 			strerror(msg->sadb_msg_errno));
235 
236 		goto end;
237 	}
238 
239 	/* check pfkey message. */
240 	if (pfkey_align(msg, mhp)) {
241 		plog(LLV_ERROR, LOCATION, NULL,
242 			"libipsec failed pfkey align (%s)\n",
243 			ipsec_strerror());
244 		goto end;
245 	}
246 	if (pfkey_check(mhp)) {
247 		plog(LLV_ERROR, LOCATION, NULL,
248 			"libipsec failed pfkey check (%s)\n",
249 			ipsec_strerror());
250 		goto end;
251 	}
252 	msg = (struct sadb_msg *)mhp[0];
253 
254 	/* safety check */
255 	if (msg->sadb_msg_type >= ARRAYLEN(pkrecvf)) {
256 		plog(LLV_ERROR, LOCATION, NULL,
257 			"unknown PF_KEY message type=%u\n",
258 			msg->sadb_msg_type);
259 		goto end;
260 	}
261 
262 	if (pkrecvf[msg->sadb_msg_type] == NULL) {
263 		plog(LLV_INFO, LOCATION, NULL,
264 			"unsupported PF_KEY message %s\n",
265 			s_pfkey_type(msg->sadb_msg_type));
266 		goto end;
267 	}
268 
269 	if ((pkrecvf[msg->sadb_msg_type])(mhp) < 0)
270 		goto end;
271 
272 	error = 0;
273 end:
274 	if (msg)
275 		racoon_free(msg);
276 	return(error);
277 }
278 
279 /*
280  * dump SADB
281  */
282 vchar_t *
283 pfkey_dump_sadb(satype)
284 	int satype;
285 {
286 	int s = -1;
287 	vchar_t *buf = NULL;
288 	pid_t pid = getpid();
289 	struct sadb_msg *msg = NULL;
290 	size_t bl, ml;
291 	int len;
292 
293 	if ((s = privsep_pfkey_open()) < 0) {
294 		plog(LLV_ERROR, LOCATION, NULL,
295 			"libipsec failed pfkey open: %s\n",
296 			ipsec_strerror());
297 		return NULL;
298 	}
299 
300 	plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_dump\n");
301 	if (pfkey_send_dump(s, satype) < 0) {
302 		plog(LLV_ERROR, LOCATION, NULL,
303 			"libipsec failed dump: %s\n", ipsec_strerror());
304 		goto fail;
305 	}
306 
307 	while (1) {
308 		if (msg)
309 			racoon_free(msg);
310 		msg = pk_recv(s, &len);
311 		if (msg == NULL) {
312 			if (len < 0)
313 				goto done;
314 			else
315 				continue;
316 		}
317 
318 		if (msg->sadb_msg_type != SADB_DUMP || msg->sadb_msg_pid != pid)
319 		{
320 		    plog(LLV_DEBUG, LOCATION, NULL,
321 			 "discarding non-sadb dump msg %p, our pid=%i\n", msg, pid);
322 		    plog(LLV_DEBUG, LOCATION, NULL,
323 			 "type %i, pid %i\n", msg->sadb_msg_type, msg->sadb_msg_pid);
324 		    continue;
325 		}
326 
327 
328 		ml = msg->sadb_msg_len << 3;
329 		bl = buf ? buf->l : 0;
330 		buf = vrealloc(buf, bl + ml);
331 		if (buf == NULL) {
332 			plog(LLV_ERROR, LOCATION, NULL,
333 				"failed to reallocate buffer to dump.\n");
334 			goto fail;
335 		}
336 		memcpy(buf->v + bl, msg, ml);
337 
338 		if (msg->sadb_msg_seq == 0)
339 			break;
340 	}
341 	goto done;
342 
343 fail:
344 	if (buf)
345 		vfree(buf);
346 	buf = NULL;
347 done:
348 	if (msg)
349 		racoon_free(msg);
350 	if (s >= 0)
351 		privsep_pfkey_close(s);
352 	return buf;
353 }
354 
355 #ifdef ENABLE_ADMINPORT
356 /*
357  * flush SADB
358  */
359 void
360 pfkey_flush_sadb(proto)
361 	u_int proto;
362 {
363 	int satype;
364 
365 	/* convert to SADB_SATYPE */
366 	if ((satype = admin2pfkey_proto(proto)) < 0)
367 		return;
368 
369 	plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_flush\n");
370 	if (pfkey_send_flush(lcconf->sock_pfkey, satype) < 0) {
371 		plog(LLV_ERROR, LOCATION, NULL,
372 			"libipsec failed send flush (%s)\n", ipsec_strerror());
373 		return;
374 	}
375 
376 	return;
377 }
378 #endif
379 
380 /*
381  * These are the SATYPEs that we manage.  We register to get
382  * PF_KEY messages related to these SATYPEs, and we also use
383  * this list to determine which SATYPEs to delete SAs for when
384  * we receive an INITIAL-CONTACT.
385  */
386 const struct pfkey_satype pfkey_satypes[] = {
387 	{ SADB_SATYPE_AH,	"AH" },
388 	{ SADB_SATYPE_ESP,	"ESP" },
389 	{ SADB_X_SATYPE_IPCOMP,	"IPCOMP" },
390 };
391 const int pfkey_nsatypes =
392     sizeof(pfkey_satypes) / sizeof(pfkey_satypes[0]);
393 
394 /*
395  * PF_KEY initialization
396  */
397 int
398 pfkey_init()
399 {
400 	int i, reg_fail;
401 
402 	if ((lcconf->sock_pfkey = privsep_pfkey_open()) < 0) {
403 		plog(LLV_ERROR, LOCATION, NULL,
404 			"libipsec failed pfkey open (%s)\n", ipsec_strerror());
405 		return -1;
406 	}
407 	if (fcntl(lcconf->sock_pfkey, F_SETFL, O_NONBLOCK) == -1)
408 		plog(LLV_WARNING, LOCATION, NULL,
409 		    "failed to set the pfkey socket to NONBLOCK\n");
410 
411 	for (i = 0, reg_fail = 0; i < pfkey_nsatypes; i++) {
412 		plog(LLV_DEBUG, LOCATION, NULL,
413 		    "call pfkey_send_register for %s\n",
414 		    pfkey_satypes[i].ps_name);
415 		if (pfkey_send_register(lcconf->sock_pfkey,
416 					pfkey_satypes[i].ps_satype) < 0 ||
417 		    pfkey_recv_register(lcconf->sock_pfkey) < 0) {
418 			plog(LLV_WARNING, LOCATION, NULL,
419 			    "failed to register %s (%s)\n",
420 			    pfkey_satypes[i].ps_name,
421 			    ipsec_strerror());
422 			reg_fail++;
423 		}
424 	}
425 
426 	if (reg_fail == pfkey_nsatypes) {
427 		plog(LLV_ERROR, LOCATION, NULL,
428 			"failed to regist any protocol.\n");
429 		pfkey_close(lcconf->sock_pfkey);
430 		return -1;
431 	}
432 
433 	initsp();
434 
435 	if (pfkey_send_spddump(lcconf->sock_pfkey) < 0) {
436 		plog(LLV_ERROR, LOCATION, NULL,
437 			"libipsec sending spddump failed: %s\n",
438 			ipsec_strerror());
439 		pfkey_close(lcconf->sock_pfkey);
440 		return -1;
441 	}
442 #if 0
443 	if (pfkey_promisc_toggle(1) < 0) {
444 		pfkey_close(lcconf->sock_pfkey);
445 		return -1;
446 	}
447 #endif
448 	return 0;
449 }
450 
451 /* %%% for conversion */
452 /* IPSECDOI_ATTR_AUTH -> SADB_AALG */
453 static u_int
454 ipsecdoi2pfkey_aalg(hashtype)
455 	u_int hashtype;
456 {
457 	switch (hashtype) {
458 	case IPSECDOI_ATTR_AUTH_HMAC_MD5:
459 		return SADB_AALG_MD5HMAC;
460 	case IPSECDOI_ATTR_AUTH_HMAC_SHA1:
461 		return SADB_AALG_SHA1HMAC;
462 	case IPSECDOI_ATTR_AUTH_HMAC_SHA2_256:
463 #if (defined SADB_X_AALG_SHA2_256) && !defined(SADB_X_AALG_SHA2_256HMAC)
464 		return SADB_X_AALG_SHA2_256;
465 #else
466 		return SADB_X_AALG_SHA2_256HMAC;
467 #endif
468 	case IPSECDOI_ATTR_AUTH_HMAC_SHA2_384:
469 #if (defined SADB_X_AALG_SHA2_384) && !defined(SADB_X_AALG_SHA2_384HMAC)
470 		return SADB_X_AALG_SHA2_384;
471 #else
472 		return SADB_X_AALG_SHA2_384HMAC;
473 #endif
474 	case IPSECDOI_ATTR_AUTH_HMAC_SHA2_512:
475 #if (defined SADB_X_AALG_SHA2_512) && !defined(SADB_X_AALG_SHA2_512HMAC)
476 		return SADB_X_AALG_SHA2_512;
477 #else
478 		return SADB_X_AALG_SHA2_512HMAC;
479 #endif
480 	case IPSECDOI_ATTR_AUTH_KPDK:		/* need special care */
481 		return SADB_AALG_NONE;
482 
483 	/* not supported */
484 	case IPSECDOI_ATTR_AUTH_DES_MAC:
485 		plog(LLV_ERROR, LOCATION, NULL,
486 			"Not supported hash type: %u\n", hashtype);
487 		return ~0;
488 
489 	case 0: /* reserved */
490 	default:
491 		return SADB_AALG_NONE;
492 
493 		plog(LLV_ERROR, LOCATION, NULL,
494 			"Invalid hash type: %u\n", hashtype);
495 		return ~0;
496 	}
497 	/*NOTREACHED*/
498 }
499 
500 /* IPSECDOI_ESP -> SADB_EALG */
501 static u_int
502 ipsecdoi2pfkey_ealg(t_id)
503 	u_int t_id;
504 {
505 	switch (t_id) {
506 	case IPSECDOI_ESP_DES_IV64:		/* sa_flags |= SADB_X_EXT_OLD */
507 		return SADB_EALG_DESCBC;
508 	case IPSECDOI_ESP_DES:
509 		return SADB_EALG_DESCBC;
510 	case IPSECDOI_ESP_3DES:
511 		return SADB_EALG_3DESCBC;
512 #ifdef SADB_X_EALG_RC5CBC
513 	case IPSECDOI_ESP_RC5:
514 		return SADB_X_EALG_RC5CBC;
515 #endif
516 	case IPSECDOI_ESP_CAST:
517 		return SADB_X_EALG_CAST128CBC;
518 	case IPSECDOI_ESP_BLOWFISH:
519 		return SADB_X_EALG_BLOWFISHCBC;
520 	case IPSECDOI_ESP_DES_IV32:	/* flags |= (SADB_X_EXT_OLD|
521 							SADB_X_EXT_IV4B)*/
522 		return SADB_EALG_DESCBC;
523 	case IPSECDOI_ESP_NULL:
524 		return SADB_EALG_NULL;
525 #ifdef SADB_X_EALG_AESCBC
526 	case IPSECDOI_ESP_AES:
527 		return SADB_X_EALG_AESCBC;
528 #endif
529 #ifdef SADB_X_EALG_TWOFISHCBC
530 	case IPSECDOI_ESP_TWOFISH:
531 		return SADB_X_EALG_TWOFISHCBC;
532 #endif
533 #ifdef SADB_X_EALG_CAMELLIACBC
534 	case IPSECDOI_ESP_CAMELLIA:
535 		return SADB_X_EALG_CAMELLIACBC;
536 #endif
537 
538 	/* not supported */
539 	case IPSECDOI_ESP_3IDEA:
540 	case IPSECDOI_ESP_IDEA:
541 	case IPSECDOI_ESP_RC4:
542 		plog(LLV_ERROR, LOCATION, NULL,
543 			"Not supported transform: %u\n", t_id);
544 		return ~0;
545 
546 	case 0: /* reserved */
547 	default:
548 		plog(LLV_ERROR, LOCATION, NULL,
549 			"Invalid transform id: %u\n", t_id);
550 		return ~0;
551 	}
552 	/*NOTREACHED*/
553 }
554 
555 /* IPCOMP -> SADB_CALG */
556 static u_int
557 ipsecdoi2pfkey_calg(t_id)
558 	u_int t_id;
559 {
560 	switch (t_id) {
561 	case IPSECDOI_IPCOMP_OUI:
562 		return SADB_X_CALG_OUI;
563 	case IPSECDOI_IPCOMP_DEFLATE:
564 		return SADB_X_CALG_DEFLATE;
565 	case IPSECDOI_IPCOMP_LZS:
566 		return SADB_X_CALG_LZS;
567 
568 	case 0: /* reserved */
569 	default:
570 		plog(LLV_ERROR, LOCATION, NULL,
571 			"Invalid transform id: %u\n", t_id);
572 		return ~0;
573 	}
574 	/*NOTREACHED*/
575 }
576 
577 /* IPSECDOI_PROTO -> SADB_SATYPE */
578 u_int
579 ipsecdoi2pfkey_proto(proto)
580 	u_int proto;
581 {
582 	switch (proto) {
583 	case IPSECDOI_PROTO_IPSEC_AH:
584 		return SADB_SATYPE_AH;
585 	case IPSECDOI_PROTO_IPSEC_ESP:
586 		return SADB_SATYPE_ESP;
587 	case IPSECDOI_PROTO_IPCOMP:
588 		return SADB_X_SATYPE_IPCOMP;
589 
590 	default:
591 		plog(LLV_ERROR, LOCATION, NULL,
592 			"Invalid ipsec_doi proto: %u\n", proto);
593 		return ~0;
594 	}
595 	/*NOTREACHED*/
596 }
597 
598 static u_int
599 ipsecdoi2pfkey_alg(algclass, type)
600 	u_int algclass, type;
601 {
602 	switch (algclass) {
603 	case IPSECDOI_ATTR_AUTH:
604 		return ipsecdoi2pfkey_aalg(type);
605 	case IPSECDOI_PROTO_IPSEC_ESP:
606 		return ipsecdoi2pfkey_ealg(type);
607 	case IPSECDOI_PROTO_IPCOMP:
608 		return ipsecdoi2pfkey_calg(type);
609 	default:
610 		plog(LLV_ERROR, LOCATION, NULL,
611 			"Invalid ipsec_doi algclass: %u\n", algclass);
612 		return ~0;
613 	}
614 	/*NOTREACHED*/
615 }
616 
617 /* SADB_SATYPE -> IPSECDOI_PROTO */
618 u_int
619 pfkey2ipsecdoi_proto(satype)
620 	u_int satype;
621 {
622 	switch (satype) {
623 	case SADB_SATYPE_AH:
624 		return IPSECDOI_PROTO_IPSEC_AH;
625 	case SADB_SATYPE_ESP:
626 		return IPSECDOI_PROTO_IPSEC_ESP;
627 	case SADB_X_SATYPE_IPCOMP:
628 		return IPSECDOI_PROTO_IPCOMP;
629 
630 	default:
631 		plog(LLV_ERROR, LOCATION, NULL,
632 			"Invalid pfkey proto: %u\n", satype);
633 		return ~0;
634 	}
635 	/*NOTREACHED*/
636 }
637 
638 /* IPSECDOI_ATTR_ENC_MODE -> IPSEC_MODE */
639 u_int
640 ipsecdoi2pfkey_mode(mode)
641 	u_int mode;
642 {
643 	switch (mode) {
644 	case IPSECDOI_ATTR_ENC_MODE_TUNNEL:
645 #ifdef ENABLE_NATT
646 	case IPSECDOI_ATTR_ENC_MODE_UDPTUNNEL_RFC:
647 	case IPSECDOI_ATTR_ENC_MODE_UDPTUNNEL_DRAFT:
648 #endif
649 		return IPSEC_MODE_TUNNEL;
650 	case IPSECDOI_ATTR_ENC_MODE_TRNS:
651 #ifdef ENABLE_NATT
652 	case IPSECDOI_ATTR_ENC_MODE_UDPTRNS_RFC:
653 	case IPSECDOI_ATTR_ENC_MODE_UDPTRNS_DRAFT:
654 #endif
655 		return IPSEC_MODE_TRANSPORT;
656 	default:
657 		plog(LLV_ERROR, LOCATION, NULL, "Invalid mode type: %u\n", mode);
658 		return ~0;
659 	}
660 	/*NOTREACHED*/
661 }
662 
663 /* IPSECDOI_ATTR_ENC_MODE -> IPSEC_MODE */
664 u_int
665 pfkey2ipsecdoi_mode(mode)
666 	u_int mode;
667 {
668 	switch (mode) {
669 	case IPSEC_MODE_TUNNEL:
670 		return IPSECDOI_ATTR_ENC_MODE_TUNNEL;
671 	case IPSEC_MODE_TRANSPORT:
672 		return IPSECDOI_ATTR_ENC_MODE_TRNS;
673 	case IPSEC_MODE_ANY:
674 		return IPSECDOI_ATTR_ENC_MODE_ANY;
675 	default:
676 		plog(LLV_ERROR, LOCATION, NULL, "Invalid mode type: %u\n", mode);
677 		return ~0;
678 	}
679 	/*NOTREACHED*/
680 }
681 
682 /* default key length for encryption algorithm */
683 static u_int
684 keylen_aalg(hashtype)
685 	u_int hashtype;
686 {
687 	int res;
688 
689 	if (hashtype == 0)
690 		return SADB_AALG_NONE;
691 
692 	res = alg_ipsec_hmacdef_hashlen(hashtype);
693 	if (res == -1) {
694 		plog(LLV_ERROR, LOCATION, NULL,
695 			"invalid hmac algorithm %u.\n", hashtype);
696 		return ~0;
697 	}
698 	return res;
699 }
700 
701 /* default key length for encryption algorithm */
702 static u_int
703 keylen_ealg(enctype, encklen)
704 	u_int enctype;
705 	int encklen;
706 {
707 	int res;
708 
709 	res = alg_ipsec_encdef_keylen(enctype, encklen);
710 	if (res == -1) {
711 		plog(LLV_ERROR, LOCATION, NULL,
712 			"invalid encryption algorithm %u.\n", enctype);
713 		return ~0;
714 	}
715 	return res;
716 }
717 
718 int
719 pfkey_convertfromipsecdoi(proto_id, t_id, hashtype,
720 		e_type, e_keylen, a_type, a_keylen, flags)
721 	u_int proto_id;
722 	u_int t_id;
723 	u_int hashtype;
724 	u_int *e_type;
725 	u_int *e_keylen;
726 	u_int *a_type;
727 	u_int *a_keylen;
728 	u_int *flags;
729 {
730 	*flags = 0;
731 	switch (proto_id) {
732 	case IPSECDOI_PROTO_IPSEC_ESP:
733 		if ((*e_type = ipsecdoi2pfkey_ealg(t_id)) == ~0)
734 			goto bad;
735 		if ((*e_keylen = keylen_ealg(t_id, *e_keylen)) == ~0)
736 			goto bad;
737 		*e_keylen >>= 3;
738 
739 		if ((*a_type = ipsecdoi2pfkey_aalg(hashtype)) == ~0)
740 			goto bad;
741 		if ((*a_keylen = keylen_aalg(hashtype)) == ~0)
742 			goto bad;
743 		*a_keylen >>= 3;
744 
745 		if (*e_type == SADB_EALG_NONE) {
746 			plog(LLV_ERROR, LOCATION, NULL, "no ESP algorithm.\n");
747 			goto bad;
748 		}
749 		break;
750 
751 	case IPSECDOI_PROTO_IPSEC_AH:
752 		if ((*a_type = ipsecdoi2pfkey_aalg(hashtype)) == ~0)
753 			goto bad;
754 		if ((*a_keylen = keylen_aalg(hashtype)) == ~0)
755 			goto bad;
756 		*a_keylen >>= 3;
757 
758 		if (t_id == IPSECDOI_ATTR_AUTH_HMAC_MD5
759 		 && hashtype == IPSECDOI_ATTR_AUTH_KPDK) {
760 			/* AH_MD5 + Auth(KPDK) = RFC1826 keyed-MD5 */
761 			*a_type = SADB_X_AALG_MD5;
762 			*flags |= SADB_X_EXT_OLD;
763 		}
764 		*e_type = SADB_EALG_NONE;
765 		*e_keylen = 0;
766 		if (*a_type == SADB_AALG_NONE) {
767 			plog(LLV_ERROR, LOCATION, NULL, "no AH algorithm.\n");
768 			goto bad;
769 		}
770 		break;
771 
772 	case IPSECDOI_PROTO_IPCOMP:
773 		if ((*e_type = ipsecdoi2pfkey_calg(t_id)) == ~0)
774 			goto bad;
775 		*e_keylen = 0;
776 
777 		*flags = SADB_X_EXT_RAWCPI;
778 
779 		*a_type = SADB_AALG_NONE;
780 		*a_keylen = 0;
781 		if (*e_type == SADB_X_CALG_NONE) {
782 			plog(LLV_ERROR, LOCATION, NULL, "no IPCOMP algorithm.\n");
783 			goto bad;
784 		}
785 		break;
786 
787 	default:
788 		plog(LLV_ERROR, LOCATION, NULL, "unknown IPsec protocol.\n");
789 		goto bad;
790 	}
791 
792 	return 0;
793 
794     bad:
795 	errno = EINVAL;
796 	return -1;
797 }
798 
799 /* called from scheduler */
800 void
801 pfkey_timeover_stub(p)
802 	void *p;
803 {
804 
805 	pfkey_timeover((struct ph2handle *)p);
806 }
807 
808 void
809 pfkey_timeover(iph2)
810 	struct ph2handle *iph2;
811 {
812 	plog(LLV_ERROR, LOCATION, NULL,
813 		"%s give up to get IPsec-SA due to time up to wait.\n",
814 		saddrwop2str(iph2->dst));
815 	SCHED_KILL(iph2->sce);
816 
817 	/* If initiator side, send error to kernel by SADB_ACQUIRE. */
818 	if (iph2->side == INITIATOR)
819 		pk_sendeacquire(iph2);
820 
821 	unbindph12(iph2);
822 	remph2(iph2);
823 	delph2(iph2);
824 
825 	return;
826 }
827 
828 /*%%%*/
829 /* send getspi message per ipsec protocol per remote address */
830 /*
831  * the local address and remote address in ph1handle are dealed
832  * with destination address and source address respectively.
833  * Because SPI is decided by responder.
834  */
835 int
836 pk_sendgetspi(iph2)
837 	struct ph2handle *iph2;
838 {
839 	struct sockaddr *src = NULL, *dst = NULL;
840 	u_int satype, mode;
841 	struct saprop *pp;
842 	struct saproto *pr;
843 	u_int32_t minspi, maxspi;
844 	int proxy = 0;
845 
846 	if (iph2->side == INITIATOR) {
847 		pp = iph2->proposal;
848 		proxy = iph2->ph1->rmconf->support_proxy;
849 	} else {
850 		pp = iph2->approval;
851 		if (iph2->sainfo && iph2->sainfo->id_i)
852 			proxy = 1;
853 	}
854 
855 	/* for mobile IPv6 */
856 	if (proxy && iph2->src_id && iph2->dst_id &&
857 	    ipsecdoi_transportmode(pp)) {
858 		src = iph2->src_id;
859 		dst = iph2->dst_id;
860 	} else {
861 		src = iph2->src;
862 		dst = iph2->dst;
863 	}
864 
865 	for (pr = pp->head; pr != NULL; pr = pr->next) {
866 
867 		/* validity check */
868 		satype = ipsecdoi2pfkey_proto(pr->proto_id);
869 		if (satype == ~0) {
870 			plog(LLV_ERROR, LOCATION, NULL,
871 				"invalid proto_id %d\n", pr->proto_id);
872 			return -1;
873 		}
874 		/* this works around a bug in Linux kernel where it allocates 4 byte
875 		   spi's for IPCOMP */
876 		else if (satype == SADB_X_SATYPE_IPCOMP) {
877 			minspi = 0x100;
878 			maxspi = 0xffff;
879 		}
880 		else {
881 			minspi = 0;
882 			maxspi = 0;
883 		}
884 		mode = ipsecdoi2pfkey_mode(pr->encmode);
885 		if (mode == ~0) {
886 			plog(LLV_ERROR, LOCATION, NULL,
887 				"invalid encmode %d\n", pr->encmode);
888 			return -1;
889 		}
890 
891 #ifdef ENABLE_NATT
892 		/* XXX should we do a copy of src/dst for each pr ?
893 		 */
894 		if (! pr->udp_encap) {
895 			/* Remove port information, that SA doesn't use it */
896 			set_port(src, 0);
897 			set_port(dst, 0);
898 		}
899 #endif
900 		plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_getspi\n");
901 		if (pfkey_send_getspi(
902 				lcconf->sock_pfkey,
903 				satype,
904 				mode,
905 				dst,			/* src of SA */
906 				src,			/* dst of SA */
907 				minspi, maxspi,
908 				pr->reqid_in, iph2->seq) < 0) {
909 			plog(LLV_ERROR, LOCATION, NULL,
910 				"ipseclib failed send getspi (%s)\n",
911 				ipsec_strerror());
912 			return -1;
913 		}
914 		plog(LLV_DEBUG, LOCATION, NULL,
915 			"pfkey GETSPI sent: %s\n",
916 			sadbsecas2str(dst, src, satype, 0, mode));
917 	}
918 
919 	return 0;
920 }
921 
922 /*
923  * receive GETSPI from kernel.
924  */
925 static int
926 pk_recvgetspi(mhp)
927 	caddr_t *mhp;
928 {
929 	struct sadb_msg *msg;
930 	struct sadb_sa *sa;
931 	struct ph2handle *iph2;
932 	struct sockaddr *dst;
933 	int proto_id;
934 	int allspiok, notfound;
935 	struct saprop *pp;
936 	struct saproto *pr;
937 
938 	/* validity check */
939 	if (mhp[SADB_EXT_SA] == NULL
940 	 || mhp[SADB_EXT_ADDRESS_DST] == NULL) {
941 		plog(LLV_ERROR, LOCATION, NULL,
942 			"inappropriate sadb getspi message passed.\n");
943 		return -1;
944 	}
945 	msg = (struct sadb_msg *)mhp[0];
946 	sa = (struct sadb_sa *)mhp[SADB_EXT_SA];
947 	dst = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]); /* note SA dir */
948 
949 	/* the message has to be processed or not ? */
950 	if (msg->sadb_msg_pid != getpid()) {
951 		plog(LLV_DEBUG, LOCATION, NULL,
952 			"%s message is not interesting "
953 			"because pid %d is not mine.\n",
954 			s_pfkey_type(msg->sadb_msg_type),
955 			msg->sadb_msg_pid);
956 		return -1;
957 	}
958 
959 	iph2 = getph2byseq(msg->sadb_msg_seq);
960 	if (iph2 == NULL) {
961 		plog(LLV_DEBUG, LOCATION, NULL,
962 			"seq %d of %s message not interesting.\n",
963 			msg->sadb_msg_seq,
964 			s_pfkey_type(msg->sadb_msg_type));
965 		return -1;
966 	}
967 
968 	if (iph2->status != PHASE2ST_GETSPISENT) {
969 		plog(LLV_ERROR, LOCATION, NULL,
970 			"status mismatch (db:%d msg:%d)\n",
971 			iph2->status, PHASE2ST_GETSPISENT);
972 		return -1;
973 	}
974 
975 	/* set SPI, and check to get all spi whether or not */
976 	allspiok = 1;
977 	notfound = 1;
978 	proto_id = pfkey2ipsecdoi_proto(msg->sadb_msg_satype);
979 	pp = iph2->side == INITIATOR ? iph2->proposal : iph2->approval;
980 
981 	for (pr = pp->head; pr != NULL; pr = pr->next) {
982 		if (pr->proto_id == proto_id && pr->spi == 0) {
983 			pr->spi = sa->sadb_sa_spi;
984 			notfound = 0;
985 			plog(LLV_DEBUG, LOCATION, NULL,
986 				"pfkey GETSPI succeeded: %s\n",
987 				sadbsecas2str(iph2->dst, iph2->src,
988 				    msg->sadb_msg_satype,
989 				    sa->sadb_sa_spi,
990 				    ipsecdoi2pfkey_mode(pr->encmode)));
991 		}
992 		if (pr->spi == 0)
993 			allspiok = 0;	/* not get all spi */
994 	}
995 
996 	if (notfound) {
997 		plog(LLV_ERROR, LOCATION, NULL,
998 			"get spi for unknown address %s\n",
999 			saddrwop2str(iph2->dst));
1000 		return -1;
1001 	}
1002 
1003 	if (allspiok) {
1004 		/* update status */
1005 		iph2->status = PHASE2ST_GETSPIDONE;
1006 		if (isakmp_post_getspi(iph2) < 0) {
1007 			plog(LLV_ERROR, LOCATION, NULL,
1008 				"failed to start post getspi.\n");
1009 			unbindph12(iph2);
1010 			remph2(iph2);
1011 			delph2(iph2);
1012 			iph2 = NULL;
1013 			return -1;
1014 		}
1015 	}
1016 
1017 	return 0;
1018 }
1019 
1020 /*
1021  * set inbound SA
1022  */
1023 int
1024 pk_sendupdate(iph2)
1025 	struct ph2handle *iph2;
1026 {
1027 	struct saproto *pr;
1028 	struct pfkey_send_sa_args sa_args;
1029 	int proxy = 0;
1030 
1031 	/* sanity check */
1032 	if (iph2->approval == NULL) {
1033 		plog(LLV_ERROR, LOCATION, NULL,
1034 			"no approvaled SAs found.\n");
1035 	}
1036 
1037 	if (iph2->side == INITIATOR)
1038 		proxy = iph2->ph1->rmconf->support_proxy;
1039 	else if (iph2->sainfo && iph2->sainfo->id_i)
1040 		proxy = 1;
1041 
1042 	/* fill in some needed for pfkey_send_update2 */
1043 	memset (&sa_args, 0, sizeof (sa_args));
1044 	sa_args.so = lcconf->sock_pfkey;
1045 	sa_args.l_addtime = iph2->approval->lifetime;
1046 	sa_args.seq = iph2->seq;
1047 	sa_args.wsize = 4;
1048 
1049 	/* for mobile IPv6 */
1050 	if (proxy && iph2->src_id && iph2->dst_id &&
1051 	    ipsecdoi_transportmode(iph2->approval)) {
1052 		sa_args.dst = iph2->src_id;
1053 		sa_args.src = iph2->dst_id;
1054 	} else {
1055 		sa_args.dst = iph2->src;
1056 		sa_args.src = iph2->dst;
1057 	}
1058 
1059 	for (pr = iph2->approval->head; pr != NULL; pr = pr->next) {
1060 		/* validity check */
1061 		sa_args.satype = ipsecdoi2pfkey_proto(pr->proto_id);
1062 		if (sa_args.satype == ~0) {
1063 			plog(LLV_ERROR, LOCATION, NULL,
1064 				"invalid proto_id %d\n", pr->proto_id);
1065 			return -1;
1066 		}
1067 		else if (sa_args.satype == SADB_X_SATYPE_IPCOMP) {
1068 			/* IPCOMP has no replay window */
1069 			sa_args.wsize = 0;
1070 		}
1071 #ifdef ENABLE_SAMODE_UNSPECIFIED
1072 		sa_args.mode = IPSEC_MODE_ANY;
1073 #else
1074 		sa_args.mode = ipsecdoi2pfkey_mode(pr->encmode);
1075 		if (sa_args.mode == ~0) {
1076 			plog(LLV_ERROR, LOCATION, NULL,
1077 				"invalid encmode %d\n", pr->encmode);
1078 			return -1;
1079 		}
1080 #endif
1081 		/* set algorithm type and key length */
1082 		sa_args.e_keylen = pr->head->encklen;
1083 		if (pfkey_convertfromipsecdoi(
1084 				pr->proto_id,
1085 				pr->head->trns_id,
1086 				pr->head->authtype,
1087 				&sa_args.e_type, &sa_args.e_keylen,
1088 				&sa_args.a_type, &sa_args.a_keylen,
1089 				&sa_args.flags) < 0)
1090 			return -1;
1091 
1092 #if 0
1093 		sa_args.l_bytes = iph2->approval->lifebyte * 1024,
1094 #else
1095 		sa_args.l_bytes = 0;
1096 #endif
1097 
1098 #ifdef HAVE_SECCTX
1099 		if (*iph2->approval->sctx.ctx_str) {
1100 			sa_args.ctxdoi = iph2->approval->sctx.ctx_doi;
1101 			sa_args.ctxalg = iph2->approval->sctx.ctx_alg;
1102 			sa_args.ctxstrlen = iph2->approval->sctx.ctx_strlen;
1103 			sa_args.ctxstr = iph2->approval->sctx.ctx_str;
1104 		}
1105 #endif /* HAVE_SECCTX */
1106 
1107 #ifdef ENABLE_NATT
1108 		if (pr->udp_encap) {
1109 			sa_args.l_natt_type = iph2->ph1->natt_options->encaps_type;
1110 			sa_args.l_natt_sport = extract_port (iph2->ph1->remote);
1111 			sa_args.l_natt_dport = extract_port (iph2->ph1->local);
1112 			sa_args.l_natt_oa = NULL;  // FIXME: Here comes OA!!!
1113 #ifdef SADB_X_EXT_NAT_T_FRAG
1114 			sa_args.l_natt_frag = iph2->ph1->rmconf->esp_frag;
1115 #endif
1116 		} else {
1117 			/* Remove port information, that SA doesn't use it */
1118 			set_port(sa_args.src, 0);
1119 			set_port(sa_args.dst, 0);
1120 		}
1121 
1122 #endif
1123 		/* more info to fill in */
1124 		sa_args.spi = pr->spi;
1125 		sa_args.reqid = pr->reqid_in;
1126 		sa_args.keymat = pr->keymat->v;
1127 
1128 		plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_update2\n");
1129 		if (pfkey_send_update2(&sa_args) < 0) {
1130 			plog(LLV_ERROR, LOCATION, NULL,
1131 				"libipsec failed send update (%s)\n",
1132 				ipsec_strerror());
1133 			return -1;
1134 		}
1135 
1136 		if (!lcconf->pathinfo[LC_PATHTYPE_BACKUPSA])
1137 			continue;
1138 
1139 		/*
1140 		 * It maybe good idea to call backupsa_to_file() after
1141 		 * racoon will receive the sadb_update messages.
1142 		 * But it is impossible because there is not key in the
1143 		 * information from the kernel.
1144 		 */
1145 
1146 		/* change some things before backing up */
1147 		sa_args.wsize = 4;
1148 		sa_args.l_bytes = iph2->approval->lifebyte * 1024;
1149 
1150 		if (backupsa_to_file(&sa_args) < 0) {
1151 			plog(LLV_ERROR, LOCATION, NULL,
1152 				"backuped SA failed: %s\n",
1153 				sadbsecas2str(sa_args.src, sa_args.dst,
1154 				sa_args.satype, sa_args.spi, sa_args.mode));
1155 		}
1156 		plog(LLV_DEBUG, LOCATION, NULL,
1157 			"backuped SA: %s\n",
1158 			sadbsecas2str(sa_args.src, sa_args.dst,
1159 			sa_args.satype, sa_args.spi, sa_args.mode));
1160 	}
1161 
1162 	return 0;
1163 }
1164 
1165 static int
1166 pk_recvupdate(mhp)
1167 	caddr_t *mhp;
1168 {
1169 	struct sadb_msg *msg;
1170 	struct sadb_sa *sa;
1171 	struct sockaddr *src, *dst;
1172 	struct ph2handle *iph2;
1173 	u_int proto_id, encmode, sa_mode;
1174 	int incomplete = 0;
1175 	struct saproto *pr;
1176 
1177 	/* ignore this message because of local test mode. */
1178 	if (f_local)
1179 		return 0;
1180 
1181 	/* sanity check */
1182 	if (mhp[0] == NULL
1183 	 || mhp[SADB_EXT_SA] == NULL
1184 	 || mhp[SADB_EXT_ADDRESS_SRC] == NULL
1185 	 || mhp[SADB_EXT_ADDRESS_DST] == NULL) {
1186 		plog(LLV_ERROR, LOCATION, NULL,
1187 			"inappropriate sadb update message passed.\n");
1188 		return -1;
1189 	}
1190 	msg = (struct sadb_msg *)mhp[0];
1191 	src = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]);
1192 	dst = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]);
1193 	sa = (struct sadb_sa *)mhp[SADB_EXT_SA];
1194 
1195 	sa_mode = mhp[SADB_X_EXT_SA2] == NULL
1196 		? IPSEC_MODE_ANY
1197 		: ((struct sadb_x_sa2 *)mhp[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
1198 
1199 	/* the message has to be processed or not ? */
1200 	if (msg->sadb_msg_pid != getpid()) {
1201 		plog(LLV_DEBUG, LOCATION, NULL,
1202 			"%s message is not interesting "
1203 			"because pid %d is not mine.\n",
1204 			s_pfkey_type(msg->sadb_msg_type),
1205 			msg->sadb_msg_pid);
1206 		return -1;
1207 	}
1208 
1209 	iph2 = getph2byseq(msg->sadb_msg_seq);
1210 	if (iph2 == NULL) {
1211 		plog(LLV_DEBUG, LOCATION, NULL,
1212 			"seq %d of %s message not interesting.\n",
1213 			msg->sadb_msg_seq,
1214 			s_pfkey_type(msg->sadb_msg_type));
1215 		return -1;
1216 	}
1217 
1218 	if (iph2->status != PHASE2ST_ADDSA) {
1219 		plog(LLV_ERROR, LOCATION, NULL,
1220 			"status mismatch (db:%d msg:%d)\n",
1221 			iph2->status, PHASE2ST_ADDSA);
1222 		return -1;
1223 	}
1224 
1225 	/* check to complete all keys ? */
1226 	for (pr = iph2->approval->head; pr != NULL; pr = pr->next) {
1227 		proto_id = pfkey2ipsecdoi_proto(msg->sadb_msg_satype);
1228 		if (proto_id == ~0) {
1229 			plog(LLV_ERROR, LOCATION, NULL,
1230 				"invalid proto_id %d\n", msg->sadb_msg_satype);
1231 			return -1;
1232 		}
1233 		encmode = pfkey2ipsecdoi_mode(sa_mode);
1234 		if (encmode == ~0) {
1235 			plog(LLV_ERROR, LOCATION, NULL,
1236 				"invalid encmode %d\n", sa_mode);
1237 			return -1;
1238 		}
1239 
1240 		if (pr->proto_id == proto_id
1241 		 && pr->spi == sa->sadb_sa_spi) {
1242 			pr->ok = 1;
1243 			plog(LLV_DEBUG, LOCATION, NULL,
1244 				"pfkey UPDATE succeeded: %s\n",
1245 				sadbsecas2str(iph2->dst, iph2->src,
1246 				    msg->sadb_msg_satype,
1247 				    sa->sadb_sa_spi,
1248 				    sa_mode));
1249 
1250 			plog(LLV_INFO, LOCATION, NULL,
1251 				"IPsec-SA established: %s\n",
1252 				sadbsecas2str(iph2->dst, iph2->src,
1253 					msg->sadb_msg_satype, sa->sadb_sa_spi,
1254 					sa_mode));
1255 		}
1256 
1257 		if (pr->ok == 0)
1258 			incomplete = 1;
1259 	}
1260 
1261 	if (incomplete)
1262 		return 0;
1263 
1264 	/* turn off the timer for calling pfkey_timeover() */
1265 	SCHED_KILL(iph2->sce);
1266 
1267 	/* update status */
1268 	iph2->status = PHASE2ST_ESTABLISHED;
1269 
1270 #ifdef ENABLE_STATS
1271 	gettimeofday(&iph2->end, NULL);
1272 	syslog(LOG_NOTICE, "%s(%s): %8.6f",
1273 		"phase2", "quick", timedelta(&iph2->start, &iph2->end));
1274 #endif
1275 
1276 	/* count up */
1277 	iph2->ph1->ph2cnt++;
1278 
1279 	/* turn off schedule */
1280 	SCHED_KILL(iph2->scr);
1281 
1282 	/* Force the update of ph2's ports, as there is at least one
1283 	 * situation where they'll mismatch with ph1's values
1284 	 */
1285 
1286 #ifdef ENABLE_NATT
1287 	set_port(iph2->src, extract_port(iph2->ph1->local));
1288 	set_port(iph2->dst, extract_port(iph2->ph1->remote));
1289 #endif
1290 
1291 	/*
1292 	 * since we are going to reuse the phase2 handler, we need to
1293 	 * remain it and refresh all the references between ph1 and ph2 to use.
1294 	 */
1295 	unbindph12(iph2);
1296 
1297 	iph2->sce = sched_new(iph2->approval->lifetime,
1298 	    isakmp_ph2expire_stub, iph2);
1299 
1300 	plog(LLV_DEBUG, LOCATION, NULL, "===\n");
1301 	return 0;
1302 }
1303 
1304 /*
1305  * set outbound SA
1306  */
1307 int
1308 pk_sendadd(iph2)
1309 	struct ph2handle *iph2;
1310 {
1311 	struct saproto *pr;
1312 	int proxy = 0;
1313 	struct pfkey_send_sa_args sa_args;
1314 
1315 	/* sanity check */
1316 	if (iph2->approval == NULL) {
1317 		plog(LLV_ERROR, LOCATION, NULL,
1318 			"no approvaled SAs found.\n");
1319 		return -1;
1320 	}
1321 
1322 	if (iph2->side == INITIATOR)
1323 		proxy = iph2->ph1->rmconf->support_proxy;
1324 	else if (iph2->sainfo && iph2->sainfo->id_i)
1325 		proxy = 1;
1326 
1327 	/* fill in some needed for pfkey_send_update2 */
1328 	memset (&sa_args, 0, sizeof (sa_args));
1329 	sa_args.so = lcconf->sock_pfkey;
1330 	sa_args.l_addtime = iph2->approval->lifetime;
1331 	sa_args.seq = iph2->seq;
1332 	sa_args.wsize = 4;
1333 
1334 	/* for mobile IPv6 */
1335 	if (proxy && iph2->src_id && iph2->dst_id &&
1336 	    ipsecdoi_transportmode(iph2->approval)) {
1337 		sa_args.src = iph2->src_id;
1338 		sa_args.dst = iph2->dst_id;
1339 	} else {
1340 		sa_args.src = iph2->src;
1341 		sa_args.dst = iph2->dst;
1342 	}
1343 
1344 	for (pr = iph2->approval->head; pr != NULL; pr = pr->next) {
1345 		/* validity check */
1346 		sa_args.satype = ipsecdoi2pfkey_proto(pr->proto_id);
1347 		if (sa_args.satype == ~0) {
1348 			plog(LLV_ERROR, LOCATION, NULL,
1349 				"invalid proto_id %d\n", pr->proto_id);
1350 			return -1;
1351 		}
1352 		else if (sa_args.satype == SADB_X_SATYPE_IPCOMP) {
1353 			/* no replay window for IPCOMP */
1354 			sa_args.wsize = 0;
1355 		}
1356 #ifdef ENABLE_SAMODE_UNSPECIFIED
1357 		sa_args.mode = IPSEC_MODE_ANY;
1358 #else
1359 		sa_args.mode = ipsecdoi2pfkey_mode(pr->encmode);
1360 		if (sa_args.mode == ~0) {
1361 			plog(LLV_ERROR, LOCATION, NULL,
1362 				"invalid encmode %d\n", pr->encmode);
1363 			return -1;
1364 		}
1365 #endif
1366 
1367 		/* set algorithm type and key length */
1368 		sa_args.e_keylen = pr->head->encklen;
1369 		if (pfkey_convertfromipsecdoi(
1370 				pr->proto_id,
1371 				pr->head->trns_id,
1372 				pr->head->authtype,
1373 				&sa_args.e_type, &sa_args.e_keylen,
1374 				&sa_args.a_type, &sa_args.a_keylen,
1375 				&sa_args.flags) < 0)
1376 			return -1;
1377 
1378 #if 0
1379 		sa_args.l_bytes = iph2->approval->lifebyte * 1024,
1380 #else
1381 		sa_args.l_bytes = 0;
1382 #endif
1383 
1384 #ifdef HAVE_SECCTX
1385 		if (*iph2->approval->sctx.ctx_str) {
1386 			sa_args.ctxdoi = iph2->approval->sctx.ctx_doi;
1387 			sa_args.ctxalg = iph2->approval->sctx.ctx_alg;
1388 			sa_args.ctxstrlen = iph2->approval->sctx.ctx_strlen;
1389 			sa_args.ctxstr = iph2->approval->sctx.ctx_str;
1390 		}
1391 #endif /* HAVE_SECCTX */
1392 
1393 #ifdef ENABLE_NATT
1394 		plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_add2 "
1395 		    "(NAT flavor)\n");
1396 
1397 		if (pr->udp_encap) {
1398 			sa_args.l_natt_type = UDP_ENCAP_ESPINUDP;
1399 			sa_args.l_natt_sport = extract_port(iph2->ph1->local);
1400 			sa_args.l_natt_dport = extract_port(iph2->ph1->remote);
1401 			sa_args.l_natt_oa = NULL; // FIXME: Here comes OA!!!
1402 #ifdef SADB_X_EXT_NAT_T_FRAG
1403 			sa_args.l_natt_frag = iph2->ph1->rmconf->esp_frag;
1404 #endif
1405 		} else {
1406 			/* Remove port information, that SA doesn't use it */
1407 			set_port(sa_args.src, 0);
1408 			set_port(sa_args.dst, 0);
1409 		}
1410 
1411 #else
1412 		/* Remove port information, it is not used without NAT-T */
1413 		set_port(sa_args.src, 0);
1414 		set_port(sa_args.dst, 0);
1415 #endif
1416 
1417 		/* more info to fill in */
1418 		sa_args.spi = pr->spi_p;
1419 		sa_args.reqid = pr->reqid_out;
1420 		sa_args.keymat = pr->keymat_p->v;
1421 
1422 		plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_add2\n");
1423 		if (pfkey_send_add2(&sa_args) < 0) {
1424 			plog(LLV_ERROR, LOCATION, NULL,
1425 				"libipsec failed send add (%s)\n",
1426 				ipsec_strerror());
1427 			return -1;
1428 		}
1429 
1430 		if (!lcconf->pathinfo[LC_PATHTYPE_BACKUPSA])
1431 			continue;
1432 
1433 		/*
1434 		 * It maybe good idea to call backupsa_to_file() after
1435 		 * racoon will receive the sadb_update messages.
1436 		 * But it is impossible because there is not key in the
1437 		 * information from the kernel.
1438 		 */
1439 		if (backupsa_to_file(&sa_args) < 0) {
1440 			plog(LLV_ERROR, LOCATION, NULL,
1441 				"backuped SA failed: %s\n",
1442 				sadbsecas2str(sa_args.src, sa_args.dst,
1443 				sa_args.satype, sa_args.spi, sa_args.mode));
1444 		}
1445 		plog(LLV_DEBUG, LOCATION, NULL,
1446 			"backuped SA: %s\n",
1447 			sadbsecas2str(sa_args.src, sa_args.dst,
1448 			sa_args.satype, sa_args.spi, sa_args.mode));
1449 	}
1450 	return 0;
1451 }
1452 
1453 static int
1454 pk_recvadd(mhp)
1455 	caddr_t *mhp;
1456 {
1457 	struct sadb_msg *msg;
1458 	struct sadb_sa *sa;
1459 	struct sockaddr *src, *dst;
1460 	struct ph2handle *iph2;
1461 	u_int sa_mode;
1462 
1463 	/* ignore this message because of local test mode. */
1464 	if (f_local)
1465 		return 0;
1466 
1467 	/* sanity check */
1468 	if (mhp[0] == NULL
1469 	 || mhp[SADB_EXT_SA] == NULL
1470 	 || mhp[SADB_EXT_ADDRESS_SRC] == NULL
1471 	 || mhp[SADB_EXT_ADDRESS_DST] == NULL) {
1472 		plog(LLV_ERROR, LOCATION, NULL,
1473 			"inappropriate sadb add message passed.\n");
1474 		return -1;
1475 	}
1476 	msg = (struct sadb_msg *)mhp[0];
1477 	src = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]);
1478 	dst = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]);
1479 	sa = (struct sadb_sa *)mhp[SADB_EXT_SA];
1480 
1481 	sa_mode = mhp[SADB_X_EXT_SA2] == NULL
1482 		? IPSEC_MODE_ANY
1483 		: ((struct sadb_x_sa2 *)mhp[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
1484 
1485 	/* the message has to be processed or not ? */
1486 	if (msg->sadb_msg_pid != getpid()) {
1487 		plog(LLV_DEBUG, LOCATION, NULL,
1488 			"%s message is not interesting "
1489 			"because pid %d is not mine.\n",
1490 			s_pfkey_type(msg->sadb_msg_type),
1491 			msg->sadb_msg_pid);
1492 		return -1;
1493 	}
1494 
1495 	iph2 = getph2byseq(msg->sadb_msg_seq);
1496 	if (iph2 == NULL) {
1497 		plog(LLV_DEBUG, LOCATION, NULL,
1498 			"seq %d of %s message not interesting.\n",
1499 			msg->sadb_msg_seq,
1500 			s_pfkey_type(msg->sadb_msg_type));
1501 		return -1;
1502 	}
1503 
1504 	/*
1505 	 * NOTE don't update any status of phase2 handle
1506 	 * because they must be updated by SADB_UPDATE message
1507 	 */
1508 
1509 	plog(LLV_INFO, LOCATION, NULL,
1510 		"IPsec-SA established: %s\n",
1511 		sadbsecas2str(iph2->src, iph2->dst,
1512 			msg->sadb_msg_satype, sa->sadb_sa_spi, sa_mode));
1513 
1514 	plog(LLV_DEBUG, LOCATION, NULL, "===\n");
1515 	return 0;
1516 }
1517 
1518 static int
1519 pk_recvexpire(mhp)
1520 	caddr_t *mhp;
1521 {
1522 	struct sadb_msg *msg;
1523 	struct sadb_sa *sa;
1524 	struct sockaddr *src, *dst;
1525 	struct ph2handle *iph2;
1526 	u_int proto_id, sa_mode;
1527 
1528 	/* sanity check */
1529 	if (mhp[0] == NULL
1530 	 || mhp[SADB_EXT_SA] == NULL
1531 	 || mhp[SADB_EXT_ADDRESS_SRC] == NULL
1532 	 || mhp[SADB_EXT_ADDRESS_DST] == NULL
1533 	 || (mhp[SADB_EXT_LIFETIME_HARD] != NULL
1534 	  && mhp[SADB_EXT_LIFETIME_SOFT] != NULL)) {
1535 		plog(LLV_ERROR, LOCATION, NULL,
1536 			"inappropriate sadb expire message passed.\n");
1537 		return -1;
1538 	}
1539 	msg = (struct sadb_msg *)mhp[0];
1540 	sa = (struct sadb_sa *)mhp[SADB_EXT_SA];
1541 	src = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]);
1542 	dst = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]);
1543 
1544 	sa_mode = mhp[SADB_X_EXT_SA2] == NULL
1545 		? IPSEC_MODE_ANY
1546 		: ((struct sadb_x_sa2 *)mhp[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
1547 
1548 	proto_id = pfkey2ipsecdoi_proto(msg->sadb_msg_satype);
1549 	if (proto_id == ~0) {
1550 		plog(LLV_ERROR, LOCATION, NULL,
1551 			"invalid proto_id %d\n", msg->sadb_msg_satype);
1552 		return -1;
1553 	}
1554 
1555 	plog(LLV_INFO, LOCATION, NULL,
1556 		"IPsec-SA expired: %s\n",
1557 		sadbsecas2str(src, dst,
1558 			msg->sadb_msg_satype, sa->sadb_sa_spi, sa_mode));
1559 
1560 	iph2 = getph2bysaidx(src, dst, proto_id, sa->sadb_sa_spi);
1561 	if (iph2 == NULL) {
1562 		/*
1563 		 * Ignore it because two expire messages are come up.
1564 		 * phase2 handler has been deleted already when 2nd message
1565 		 * is received.
1566 		 */
1567 		plog(LLV_DEBUG, LOCATION, NULL,
1568 			"no such a SA found: %s\n",
1569 			sadbsecas2str(src, dst,
1570 			    msg->sadb_msg_satype, sa->sadb_sa_spi,
1571 			    sa_mode));
1572 		return 0;
1573 	}
1574 	if (iph2->status != PHASE2ST_ESTABLISHED) {
1575 		/*
1576 		 * If the status is not equal to PHASE2ST_ESTABLISHED,
1577 		 * racoon ignores this expire message.  There are two reason.
1578 		 * One is that the phase 2 probably starts because there is
1579 		 * a potential that racoon receives the acquire message
1580 		 * without receiving a expire message.  Another is that racoon
1581 		 * may receive the multiple expire messages from the kernel.
1582 		 */
1583 		plog(LLV_WARNING, LOCATION, NULL,
1584 			"the expire message is received "
1585 			"but the handler has not been established.\n");
1586 		return 0;
1587 	}
1588 
1589 	/* turn off the timer for calling isakmp_ph2expire() */
1590 	SCHED_KILL(iph2->sce);
1591 
1592 	iph2->status = PHASE2ST_EXPIRED;
1593 
1594 	/* INITIATOR, begin phase 2 exchange. */
1595 	/* allocate buffer for status management of pfkey message */
1596 	if (iph2->side == INITIATOR) {
1597 
1598 		initph2(iph2);
1599 
1600 		/* update status for re-use */
1601 		iph2->status = PHASE2ST_STATUS2;
1602 
1603 		/* start isakmp initiation by using ident exchange */
1604 		if (isakmp_post_acquire(iph2) < 0) {
1605 			plog(LLV_ERROR, LOCATION, iph2->dst,
1606 				"failed to begin ipsec sa "
1607 				"re-negotication.\n");
1608 			unbindph12(iph2);
1609 			remph2(iph2);
1610 			delph2(iph2);
1611 			return -1;
1612 		}
1613 
1614 		return 0;
1615 		/*NOTREACHED*/
1616 	}
1617 
1618 	/* If not received SADB_EXPIRE, INITIATOR delete ph2handle. */
1619 	/* RESPONDER always delete ph2handle, keep silent.  RESPONDER doesn't
1620 	 * manage IPsec SA, so delete the list */
1621 	unbindph12(iph2);
1622 	remph2(iph2);
1623 	delph2(iph2);
1624 
1625 	return 0;
1626 }
1627 
1628 static int
1629 pk_recvacquire(mhp)
1630 	caddr_t *mhp;
1631 {
1632 	struct sadb_msg *msg;
1633 	struct sadb_x_policy *xpl;
1634 	struct secpolicy *sp_out = NULL, *sp_in = NULL;
1635 #define MAXNESTEDSA	5	/* XXX */
1636 	struct ph2handle *iph2[MAXNESTEDSA];
1637 	struct sockaddr *src, *dst;
1638 	int n;	/* # of phase 2 handler */
1639 	int remoteid=0;
1640 #ifdef HAVE_SECCTX
1641 	struct sadb_x_sec_ctx *m_sec_ctx;
1642 #endif /* HAVE_SECCTX */
1643 	struct policyindex spidx;
1644 
1645 
1646 	/* ignore this message because of local test mode. */
1647 	if (f_local)
1648 		return 0;
1649 
1650 	/* sanity check */
1651 	if (mhp[0] == NULL
1652 	 || mhp[SADB_EXT_ADDRESS_SRC] == NULL
1653 	 || mhp[SADB_EXT_ADDRESS_DST] == NULL
1654 	 || mhp[SADB_X_EXT_POLICY] == NULL) {
1655 		plog(LLV_ERROR, LOCATION, NULL,
1656 			"inappropriate sadb acquire message passed.\n");
1657 		return -1;
1658 	}
1659 	msg = (struct sadb_msg *)mhp[0];
1660 	xpl = (struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY];
1661 	src = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]);
1662 	dst = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]);
1663 
1664 #ifdef HAVE_SECCTX
1665 	m_sec_ctx = (struct sadb_x_sec_ctx *)mhp[SADB_X_EXT_SEC_CTX];
1666 
1667 	if (m_sec_ctx != NULL) {
1668 		plog(LLV_INFO, LOCATION, NULL, "security context doi: %u\n",
1669 		     m_sec_ctx->sadb_x_ctx_doi);
1670 		plog(LLV_INFO, LOCATION, NULL,
1671 		     "security context algorithm: %u\n",
1672 		     m_sec_ctx->sadb_x_ctx_alg);
1673 		plog(LLV_INFO, LOCATION, NULL, "security context length: %u\n",
1674 		     m_sec_ctx->sadb_x_ctx_len);
1675 		plog(LLV_INFO, LOCATION, NULL, "security context: %s\n",
1676 		     ((char *)m_sec_ctx + sizeof(struct sadb_x_sec_ctx)));
1677 	}
1678 #endif /* HAVE_SECCTX */
1679 
1680 	/* ignore if type is not IPSEC_POLICY_IPSEC */
1681 	if (xpl->sadb_x_policy_type != IPSEC_POLICY_IPSEC) {
1682 		plog(LLV_DEBUG, LOCATION, NULL,
1683 			"ignore ACQUIRE message. type is not IPsec.\n");
1684 		return 0;
1685 	}
1686 
1687 	/* ignore it if src is multicast address */
1688     {
1689 	struct sockaddr *sa = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]);
1690 
1691 	if ((sa->sa_family == AF_INET
1692 	  && IN_MULTICAST(ntohl(((struct sockaddr_in *)sa)->sin_addr.s_addr)))
1693 #ifdef INET6
1694 	 || (sa->sa_family == AF_INET6
1695 	  && IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)sa)->sin6_addr))
1696 #endif
1697 	) {
1698 		plog(LLV_DEBUG, LOCATION, NULL,
1699 			"ignore due to multicast address: %s.\n",
1700 			saddrwop2str(sa));
1701 		return 0;
1702 	}
1703     }
1704 
1705     	/* ignore, if we do not listen on source address */
1706 	{
1707 		/* reasons behind:
1708 		 * - if we'll contact peer from address we do not listen -
1709 		 *   we will be unable to complete negotiation;
1710 		 * - if we'll negotiate using address we're listening -
1711 		 *   remote peer will send packets to address different
1712 		 *   than one in the policy, so kernel will drop them;
1713 		 * => therefore this acquire is not for us! --Aidas
1714 		 */
1715 		struct sockaddr *sa = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]);
1716 		struct myaddrs *p;
1717 		int do_listen = 0;
1718 		for (p = lcconf->myaddrs; p; p = p->next) {
1719 			if (!cmpsaddrwop(p->addr, sa)) {
1720 				do_listen = 1;
1721 				break;
1722 			}
1723 		}
1724 
1725 		if (!do_listen) {
1726 			plog(LLV_DEBUG, LOCATION, NULL,
1727 				"ignore because do not listen on source address : %s.\n",
1728 				saddrwop2str(sa));
1729 			return 0;
1730 		}
1731 	}
1732 
1733 	/*
1734 	 * If there is a phase 2 handler against the policy identifier in
1735 	 * the acquire message, and if
1736 	 *    1. its state is less than PHASE2ST_ESTABLISHED, then racoon
1737 	 *       should ignore such a acquire message because the phase 2
1738 	 *       is just negotiating.
1739 	 *    2. its state is equal to PHASE2ST_ESTABLISHED, then racoon
1740 	 *       has to prcesss such a acquire message because racoon may
1741 	 *       lost the expire message.
1742 	 */
1743 	iph2[0] = getph2byid(src, dst, xpl->sadb_x_policy_id);
1744 	if (iph2[0] != NULL) {
1745 		if (iph2[0]->status < PHASE2ST_ESTABLISHED) {
1746 			plog(LLV_DEBUG, LOCATION, NULL,
1747 				"ignore the acquire because ph2 found\n");
1748 			return -1;
1749 		}
1750 		if (iph2[0]->status == PHASE2ST_EXPIRED)
1751 			iph2[0] = NULL;
1752 		/*FALLTHROUGH*/
1753 	}
1754 
1755 	/* search for proper policyindex */
1756 	sp_out = getspbyspid(xpl->sadb_x_policy_id);
1757 	if (sp_out == NULL) {
1758 		plog(LLV_ERROR, LOCATION, NULL, "no policy found: id:%d.\n",
1759 			xpl->sadb_x_policy_id);
1760 		return -1;
1761 	}
1762 	plog(LLV_DEBUG, LOCATION, NULL,
1763 		"suitable outbound SP found: %s.\n", spidx2str(&sp_out->spidx));
1764 
1765 	/* get inbound policy */
1766     {
1767 
1768 	memset(&spidx, 0, sizeof(spidx));
1769 	spidx.dir = IPSEC_DIR_INBOUND;
1770 	memcpy(&spidx.src, &sp_out->spidx.dst, sizeof(spidx.src));
1771 	memcpy(&spidx.dst, &sp_out->spidx.src, sizeof(spidx.dst));
1772 	spidx.prefs = sp_out->spidx.prefd;
1773 	spidx.prefd = sp_out->spidx.prefs;
1774 	spidx.ul_proto = sp_out->spidx.ul_proto;
1775 
1776 #ifdef HAVE_SECCTX
1777 	if (m_sec_ctx) {
1778 		spidx.sec_ctx.ctx_doi = m_sec_ctx->sadb_x_ctx_doi;
1779 		spidx.sec_ctx.ctx_alg = m_sec_ctx->sadb_x_ctx_alg;
1780 		spidx.sec_ctx.ctx_strlen = m_sec_ctx->sadb_x_ctx_len;
1781 		memcpy(spidx.sec_ctx.ctx_str,
1782 		      ((char *)m_sec_ctx + sizeof(struct sadb_x_sec_ctx)),
1783 		      spidx.sec_ctx.ctx_strlen);
1784 	}
1785 #endif /* HAVE_SECCTX */
1786 
1787 	sp_in = getsp(&spidx);
1788 	if (sp_in) {
1789 		plog(LLV_DEBUG, LOCATION, NULL,
1790 			"suitable inbound SP found: %s.\n",
1791 			spidx2str(&sp_in->spidx));
1792 	} else {
1793 		plog(LLV_NOTIFY, LOCATION, NULL,
1794 			"no in-bound policy found: %s\n",
1795 			spidx2str(&spidx));
1796 	}
1797     }
1798 
1799 	memset(iph2, 0, MAXNESTEDSA);
1800 
1801 	n = 0;
1802 
1803 	/* allocate a phase 2 */
1804 	iph2[n] = newph2();
1805 	if (iph2[n] == NULL) {
1806 		plog(LLV_ERROR, LOCATION, NULL,
1807 			"failed to allocate phase2 entry.\n");
1808 		return -1;
1809 	}
1810 	iph2[n]->side = INITIATOR;
1811 	iph2[n]->spid = xpl->sadb_x_policy_id;
1812 	iph2[n]->satype = msg->sadb_msg_satype;
1813 	iph2[n]->seq = msg->sadb_msg_seq;
1814 	iph2[n]->status = PHASE2ST_STATUS2;
1815 
1816 	/* set end addresses of SA */
1817 	iph2[n]->dst = dupsaddr(PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]));
1818 	if (iph2[n]->dst == NULL) {
1819 		delph2(iph2[n]);
1820 		return -1;
1821 	}
1822 	iph2[n]->src = dupsaddr(PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]));
1823 	if (iph2[n]->src == NULL) {
1824 		delph2(iph2[n]);
1825 		return -1;
1826 	}
1827 
1828 	plog(LLV_DEBUG, LOCATION, NULL,
1829 		"new acquire %s\n", spidx2str(&sp_out->spidx));
1830 
1831 	/* get sainfo */
1832     {
1833 	vchar_t *idsrc, *iddst;
1834 
1835 	idsrc = ipsecdoi_sockaddr2id((struct sockaddr *)&sp_out->spidx.src,
1836 				sp_out->spidx.prefs, sp_out->spidx.ul_proto);
1837 	if (idsrc == NULL) {
1838 		plog(LLV_ERROR, LOCATION, NULL,
1839 			"failed to get ID for %s\n",
1840 			spidx2str(&sp_out->spidx));
1841 		delph2(iph2[n]);
1842 		return -1;
1843 	}
1844 	iddst = ipsecdoi_sockaddr2id((struct sockaddr *)&sp_out->spidx.dst,
1845 				sp_out->spidx.prefd, sp_out->spidx.ul_proto);
1846 	if (iddst == NULL) {
1847 		plog(LLV_ERROR, LOCATION, NULL,
1848 			"failed to get ID for %s\n",
1849 			spidx2str(&sp_out->spidx));
1850 		vfree(idsrc);
1851 		delph2(iph2[n]);
1852 		return -1;
1853 	}
1854 	{
1855 		struct remoteconf *conf;
1856 		conf = getrmconf(iph2[n]->dst);
1857 		if (conf != NULL)
1858 			remoteid=conf->ph1id;
1859 		else{
1860 			plog(LLV_DEBUG, LOCATION, NULL, "Warning: no valid rmconf !\n");
1861 			remoteid=0;
1862 		}
1863 	}
1864 	iph2[n]->sainfo = getsainfo(idsrc, iddst, NULL, NULL, remoteid);
1865 	vfree(idsrc);
1866 	vfree(iddst);
1867 	if (iph2[n]->sainfo == NULL) {
1868 		plog(LLV_ERROR, LOCATION, NULL,
1869 			"failed to get sainfo.\n");
1870 		delph2(iph2[n]);
1871 		return -1;
1872 		/* XXX should use the algorithm list from register message */
1873 	}
1874 
1875 	plog(LLV_DEBUG, LOCATION, NULL,
1876 		"selected sainfo: %s\n", sainfo2str(iph2[n]->sainfo));
1877     }
1878 
1879 	if (set_proposal_from_policy(iph2[n], sp_out, sp_in) < 0) {
1880 		plog(LLV_ERROR, LOCATION, NULL,
1881 			"failed to create saprop.\n");
1882 		delph2(iph2[n]);
1883 		return -1;
1884 	}
1885 #ifdef HAVE_SECCTX
1886 	if (m_sec_ctx) {
1887 		set_secctx_in_proposal(iph2[n], spidx);
1888 	}
1889 #endif /* HAVE_SECCTX */
1890 
1891 	insph2(iph2[n]);
1892 
1893 	/* start isakmp initiation by using ident exchange */
1894 	/* XXX should be looped if there are multiple phase 2 handler. */
1895 	if (isakmp_post_acquire(iph2[n]) < 0) {
1896 		plog(LLV_ERROR, LOCATION, NULL,
1897 			"failed to begin ipsec sa negotication.\n");
1898 		goto err;
1899 	}
1900 
1901 	return 0;
1902 
1903 err:
1904 	while (n >= 0) {
1905 		unbindph12(iph2[n]);
1906 		remph2(iph2[n]);
1907 		delph2(iph2[n]);
1908 		iph2[n] = NULL;
1909 		n--;
1910 	}
1911 	return -1;
1912 }
1913 
1914 static int
1915 pk_recvdelete(mhp)
1916 	caddr_t *mhp;
1917 {
1918 	struct sadb_msg *msg;
1919 	struct sadb_sa *sa;
1920 	struct sockaddr *src, *dst;
1921 	struct ph2handle *iph2 = NULL;
1922 	u_int proto_id;
1923 
1924 	/* ignore this message because of local test mode. */
1925 	if (f_local)
1926 		return 0;
1927 
1928 	/* sanity check */
1929 	if (mhp[0] == NULL
1930 	 || mhp[SADB_EXT_SA] == NULL
1931 	 || mhp[SADB_EXT_ADDRESS_SRC] == NULL
1932 	 || mhp[SADB_EXT_ADDRESS_DST] == NULL) {
1933 		plog(LLV_ERROR, LOCATION, NULL,
1934 			"inappropriate sadb delete message passed.\n");
1935 		return -1;
1936 	}
1937 	msg = (struct sadb_msg *)mhp[0];
1938 	sa = (struct sadb_sa *)mhp[SADB_EXT_SA];
1939 	src = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]);
1940 	dst = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]);
1941 
1942 	/* the message has to be processed or not ? */
1943 	if (msg->sadb_msg_pid == getpid()) {
1944 		plog(LLV_DEBUG, LOCATION, NULL,
1945 			"%s message is not interesting "
1946 			"because the message was originated by me.\n",
1947 			s_pfkey_type(msg->sadb_msg_type));
1948 		return -1;
1949 	}
1950 
1951 	proto_id = pfkey2ipsecdoi_proto(msg->sadb_msg_satype);
1952 	if (proto_id == ~0) {
1953 		plog(LLV_ERROR, LOCATION, NULL,
1954 			"invalid proto_id %d\n", msg->sadb_msg_satype);
1955 		return -1;
1956 	}
1957 
1958 	iph2 = getph2bysaidx(src, dst, proto_id, sa->sadb_sa_spi);
1959 	if (iph2 == NULL) {
1960 		/* ignore */
1961 		plog(LLV_ERROR, LOCATION, NULL,
1962 			"no iph2 found: %s\n",
1963 			sadbsecas2str(src, dst, msg->sadb_msg_satype,
1964 				sa->sadb_sa_spi, IPSEC_MODE_ANY));
1965 		return 0;
1966 	}
1967 
1968 	plog(LLV_ERROR, LOCATION, NULL,
1969 		"pfkey DELETE received: %s\n",
1970 		sadbsecas2str(iph2->src, iph2->dst,
1971 			msg->sadb_msg_satype, sa->sadb_sa_spi, IPSEC_MODE_ANY));
1972 
1973 	/* send delete information */
1974 	if (iph2->status == PHASE2ST_ESTABLISHED)
1975 		isakmp_info_send_d2(iph2);
1976 
1977 	unbindph12(iph2);
1978 	remph2(iph2);
1979 	delph2(iph2);
1980 
1981 	return 0;
1982 }
1983 
1984 static int
1985 pk_recvflush(mhp)
1986 	caddr_t *mhp;
1987 {
1988 	/* ignore this message because of local test mode. */
1989 	if (f_local)
1990 		return 0;
1991 
1992 	/* sanity check */
1993 	if (mhp[0] == NULL) {
1994 		plog(LLV_ERROR, LOCATION, NULL,
1995 			"inappropriate sadb flush message passed.\n");
1996 		return -1;
1997 	}
1998 
1999 	flushph2();
2000 
2001 	return 0;
2002 }
2003 
2004 static int
2005 getsadbpolicy(policy0, policylen0, type, iph2)
2006 	caddr_t *policy0;
2007 	int *policylen0, type;
2008 	struct ph2handle *iph2;
2009 {
2010 	struct policyindex *spidx = (struct policyindex *)iph2->spidx_gen;
2011 	struct sadb_x_policy *xpl;
2012 	struct sadb_x_ipsecrequest *xisr;
2013 	struct saproto *pr;
2014 	struct saproto **pr_rlist;
2015 	int rlist_len = 0;
2016 	caddr_t policy, p;
2017 	int policylen;
2018 	int xisrlen;
2019 	u_int satype, mode;
2020 	int len = 0;
2021 #ifdef HAVE_SECCTX
2022 	int ctxlen = 0;
2023 #endif /* HAVE_SECCTX */
2024 
2025 
2026 	/* get policy buffer size */
2027 	policylen = sizeof(struct sadb_x_policy);
2028 	if (type != SADB_X_SPDDELETE) {
2029 		for (pr = iph2->approval->head; pr; pr = pr->next) {
2030 			xisrlen = sizeof(*xisr);
2031 			if (pr->encmode == IPSECDOI_ATTR_ENC_MODE_TUNNEL) {
2032 				xisrlen += (sysdep_sa_len(iph2->src)
2033 				          + sysdep_sa_len(iph2->dst));
2034 			}
2035 
2036 			policylen += PFKEY_ALIGN8(xisrlen);
2037 		}
2038 	}
2039 
2040 #ifdef HAVE_SECCTX
2041 	if (*spidx->sec_ctx.ctx_str) {
2042 		ctxlen = sizeof(struct sadb_x_sec_ctx)
2043 				+ PFKEY_ALIGN8(spidx->sec_ctx.ctx_strlen);
2044 		policylen += ctxlen;
2045 	}
2046 #endif /* HAVE_SECCTX */
2047 
2048 	/* make policy structure */
2049 	policy = racoon_malloc(policylen);
2050 	memset((void*)policy, 0xcd, policylen);
2051 	if (!policy) {
2052 		plog(LLV_ERROR, LOCATION, NULL,
2053 			"buffer allocation failed.\n");
2054 		return -1;
2055 	}
2056 
2057 	xpl = (struct sadb_x_policy *)policy;
2058 	xpl->sadb_x_policy_len = PFKEY_UNIT64(policylen);
2059 	xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
2060 	xpl->sadb_x_policy_type = IPSEC_POLICY_IPSEC;
2061 	xpl->sadb_x_policy_dir = spidx->dir;
2062 	xpl->sadb_x_policy_id = 0;
2063 #ifdef HAVE_PFKEY_POLICY_PRIORITY
2064 	xpl->sadb_x_policy_priority = PRIORITY_DEFAULT;
2065 #endif
2066 	len++;
2067 
2068 #ifdef HAVE_SECCTX
2069 	if (*spidx->sec_ctx.ctx_str) {
2070 		struct sadb_x_sec_ctx *p;
2071 
2072 		p = (struct sadb_x_sec_ctx *)(xpl + len);
2073 		memset(p, 0, ctxlen);
2074 		p->sadb_x_sec_len = PFKEY_UNIT64(ctxlen);
2075 		p->sadb_x_sec_exttype = SADB_X_EXT_SEC_CTX;
2076 		p->sadb_x_ctx_len = spidx->sec_ctx.ctx_strlen;
2077 		p->sadb_x_ctx_doi = spidx->sec_ctx.ctx_doi;
2078 		p->sadb_x_ctx_alg = spidx->sec_ctx.ctx_alg;
2079 
2080 		memcpy(p + 1,spidx->sec_ctx.ctx_str,spidx->sec_ctx.ctx_strlen);
2081 		len += ctxlen;
2082 	}
2083 #endif /* HAVE_SECCTX */
2084 
2085 	/* no need to append policy information any more if type is SPDDELETE */
2086 	if (type == SADB_X_SPDDELETE)
2087 		goto end;
2088 
2089 	xisr = (struct sadb_x_ipsecrequest *)(xpl + len);
2090 
2091 	/* The order of things is reversed for use in add policy messages */
2092 	for (pr = iph2->approval->head; pr; pr = pr->next) rlist_len++;
2093 	pr_rlist = racoon_malloc((rlist_len+1)*sizeof(struct saproto*));
2094 	if (!pr_rlist) {
2095 		plog(LLV_ERROR, LOCATION, NULL,
2096 			"buffer allocation failed.\n");
2097 		return -1;
2098 	}
2099 	pr_rlist[rlist_len--] = NULL;
2100 	for (pr = iph2->approval->head; pr; pr = pr->next) pr_rlist[rlist_len--] = pr;
2101 	rlist_len = 0;
2102 
2103 	for (pr = pr_rlist[rlist_len++]; pr; pr = pr_rlist[rlist_len++]) {
2104 
2105 		satype = doi2ipproto(pr->proto_id);
2106 		if (satype == ~0) {
2107 			plog(LLV_ERROR, LOCATION, NULL,
2108 				"invalid proto_id %d\n", pr->proto_id);
2109 			goto err;
2110 		}
2111 		mode = ipsecdoi2pfkey_mode(pr->encmode);
2112 		if (mode == ~0) {
2113 			plog(LLV_ERROR, LOCATION, NULL,
2114 				"invalid encmode %d\n", pr->encmode);
2115 			goto err;
2116 		}
2117 
2118 		/*
2119 		 * the policy level cannot be unique because the policy
2120 		 * is defined later than SA, so req_id cannot be bound to SA.
2121 		 */
2122 		xisr->sadb_x_ipsecrequest_proto = satype;
2123 		xisr->sadb_x_ipsecrequest_mode = mode;
2124 		if(iph2->proposal->head->reqid_in > 0){
2125 			xisr->sadb_x_ipsecrequest_level = IPSEC_LEVEL_UNIQUE;
2126 			xisr->sadb_x_ipsecrequest_reqid = iph2->proposal->head->reqid_in;
2127 		}else{
2128 			xisr->sadb_x_ipsecrequest_level = IPSEC_LEVEL_REQUIRE;
2129 			xisr->sadb_x_ipsecrequest_reqid = 0;
2130 		}
2131 		p = (caddr_t)(xisr + 1);
2132 
2133 		xisrlen = sizeof(*xisr);
2134 
2135 		if (pr->encmode == IPSECDOI_ATTR_ENC_MODE_TUNNEL) {
2136 			int src_len, dst_len;
2137 
2138 			src_len = sysdep_sa_len(iph2->src);
2139 			dst_len = sysdep_sa_len(iph2->dst);
2140 			xisrlen += src_len + dst_len;
2141 
2142 			memcpy(p, iph2->src, src_len);
2143 			p += src_len;
2144 
2145 			memcpy(p, iph2->dst, dst_len);
2146 			p += dst_len;
2147 		}
2148 
2149 		xisr->sadb_x_ipsecrequest_len = PFKEY_ALIGN8(xisrlen);
2150 		xisr = (struct sadb_x_ipsecrequest *)p;
2151 
2152 	}
2153 	racoon_free(pr_rlist);
2154 
2155 end:
2156 	*policy0 = policy;
2157 	*policylen0 = policylen;
2158 
2159 	return 0;
2160 
2161 err:
2162 	if (policy)
2163 		racoon_free(policy);
2164 	if (pr_rlist) racoon_free(pr_rlist);
2165 
2166 	return -1;
2167 }
2168 
2169 int
2170 pk_sendspdupdate2(iph2)
2171 	struct ph2handle *iph2;
2172 {
2173 	struct policyindex *spidx = (struct policyindex *)iph2->spidx_gen;
2174 	caddr_t policy = NULL;
2175 	int policylen = 0;
2176 	u_int64_t ltime, vtime;
2177 
2178 	ltime = iph2->approval->lifetime;
2179 	vtime = 0;
2180 
2181 	if (getsadbpolicy(&policy, &policylen, SADB_X_SPDUPDATE, iph2)) {
2182 		plog(LLV_ERROR, LOCATION, NULL,
2183 			"getting sadb policy failed.\n");
2184 		return -1;
2185 	}
2186 
2187 	if (pfkey_send_spdupdate2(
2188 			lcconf->sock_pfkey,
2189 			(struct sockaddr *)&spidx->src,
2190 			spidx->prefs,
2191 			(struct sockaddr *)&spidx->dst,
2192 			spidx->prefd,
2193 			spidx->ul_proto,
2194 			ltime, vtime,
2195 			policy, policylen, 0) < 0) {
2196 		plog(LLV_ERROR, LOCATION, NULL,
2197 			"libipsec failed send spdupdate2 (%s)\n",
2198 			ipsec_strerror());
2199 		goto end;
2200 	}
2201 	plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_spdupdate2\n");
2202 
2203 end:
2204 	if (policy)
2205 		racoon_free(policy);
2206 
2207 	return 0;
2208 }
2209 
2210 static int
2211 pk_recvspdupdate(mhp)
2212 	caddr_t *mhp;
2213 {
2214 	struct sadb_address *saddr, *daddr;
2215 	struct sadb_x_policy *xpl;
2216  	struct sadb_lifetime *lt;
2217 	struct policyindex spidx;
2218 	struct secpolicy *sp;
2219  	u_int64_t created;
2220 
2221 	/* sanity check */
2222 	if (mhp[0] == NULL
2223 	 || mhp[SADB_EXT_ADDRESS_SRC] == NULL
2224 	 || mhp[SADB_EXT_ADDRESS_DST] == NULL
2225 	 || mhp[SADB_X_EXT_POLICY] == NULL) {
2226 		plog(LLV_ERROR, LOCATION, NULL,
2227 			"inappropriate sadb spdupdate message passed.\n");
2228 		return -1;
2229 	}
2230 	saddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_SRC];
2231 	daddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_DST];
2232 	xpl = (struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY];
2233 	lt = (struct sadb_lifetime*)mhp[SADB_EXT_LIFETIME_HARD];
2234 	if(lt != NULL)
2235 		created = lt->sadb_lifetime_addtime;
2236 	else
2237 		created = 0;
2238 
2239 #ifdef HAVE_PFKEY_POLICY_PRIORITY
2240 	KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2241 			saddr + 1,
2242 			daddr + 1,
2243 			saddr->sadb_address_prefixlen,
2244 			daddr->sadb_address_prefixlen,
2245 			saddr->sadb_address_proto,
2246 			xpl->sadb_x_policy_priority,
2247 			created,
2248 			&spidx);
2249 #else
2250 	KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2251 			saddr + 1,
2252 			daddr + 1,
2253 			saddr->sadb_address_prefixlen,
2254 			daddr->sadb_address_prefixlen,
2255 			saddr->sadb_address_proto,
2256 			created,
2257 			&spidx);
2258 #endif
2259 
2260 #ifdef HAVE_SECCTX
2261 	if (mhp[SADB_X_EXT_SEC_CTX] != NULL) {
2262 		struct sadb_x_sec_ctx *ctx;
2263 
2264 		ctx = (struct sadb_x_sec_ctx *)mhp[SADB_X_EXT_SEC_CTX];
2265 		spidx.sec_ctx.ctx_alg = ctx->sadb_x_ctx_alg;
2266 		spidx.sec_ctx.ctx_doi = ctx->sadb_x_ctx_doi;
2267 		spidx.sec_ctx.ctx_strlen = ctx->sadb_x_ctx_len;
2268 		memcpy(spidx.sec_ctx.ctx_str, ctx + 1, ctx->sadb_x_ctx_len);
2269 	}
2270 #endif /* HAVE_SECCTX */
2271 
2272 	sp = getsp(&spidx);
2273 	if (sp == NULL) {
2274 		plog(LLV_ERROR, LOCATION, NULL,
2275 			"such policy does not already exist: \"%s\"\n",
2276 			spidx2str(&spidx));
2277 	} else {
2278 		remsp(sp);
2279 		delsp(sp);
2280 	}
2281 
2282 	if (addnewsp(mhp) < 0)
2283 		return -1;
2284 
2285 	return 0;
2286 }
2287 
2288 /*
2289  * this function has to be used by responder side.
2290  */
2291 int
2292 pk_sendspdadd2(iph2)
2293 	struct ph2handle *iph2;
2294 {
2295 	struct policyindex *spidx = (struct policyindex *)iph2->spidx_gen;
2296 	caddr_t policy = NULL;
2297 	int policylen = 0;
2298 	u_int64_t ltime, vtime;
2299 
2300 	ltime = iph2->approval->lifetime;
2301 	vtime = 0;
2302 
2303 	if (getsadbpolicy(&policy, &policylen, SADB_X_SPDADD, iph2)) {
2304 		plog(LLV_ERROR, LOCATION, NULL,
2305 			"getting sadb policy failed.\n");
2306 		return -1;
2307 	}
2308 
2309 	if (pfkey_send_spdadd2(
2310 			lcconf->sock_pfkey,
2311 			(struct sockaddr *)&spidx->src,
2312 			spidx->prefs,
2313 			(struct sockaddr *)&spidx->dst,
2314 			spidx->prefd,
2315 			spidx->ul_proto,
2316 			ltime, vtime,
2317 			policy, policylen, 0) < 0) {
2318 		plog(LLV_ERROR, LOCATION, NULL,
2319 			"libipsec failed send spdadd2 (%s)\n",
2320 			ipsec_strerror());
2321 		goto end;
2322 	}
2323 	plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_spdadd2\n");
2324 
2325 end:
2326 	if (policy)
2327 		racoon_free(policy);
2328 
2329 	return 0;
2330 }
2331 
2332 static int
2333 pk_recvspdadd(mhp)
2334 	caddr_t *mhp;
2335 {
2336 	struct sadb_address *saddr, *daddr;
2337 	struct sadb_x_policy *xpl;
2338 	struct sadb_lifetime *lt;
2339 	struct policyindex spidx;
2340 	struct secpolicy *sp;
2341 	u_int64_t created;
2342 
2343 	/* sanity check */
2344 	if (mhp[0] == NULL
2345 	 || mhp[SADB_EXT_ADDRESS_SRC] == NULL
2346 	 || mhp[SADB_EXT_ADDRESS_DST] == NULL
2347 	 || mhp[SADB_X_EXT_POLICY] == NULL) {
2348 		plog(LLV_ERROR, LOCATION, NULL,
2349 			"inappropriate sadb spdadd message passed.\n");
2350 		return -1;
2351 	}
2352 	saddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_SRC];
2353 	daddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_DST];
2354 	xpl = (struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY];
2355 	lt = (struct sadb_lifetime*)mhp[SADB_EXT_LIFETIME_HARD];
2356 	if(lt != NULL)
2357 		created = lt->sadb_lifetime_addtime;
2358 	else
2359 		created = 0;
2360 
2361 #ifdef HAVE_PFKEY_POLICY_PRIORITY
2362 	KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2363 			saddr + 1,
2364 			daddr + 1,
2365 			saddr->sadb_address_prefixlen,
2366 			daddr->sadb_address_prefixlen,
2367 			saddr->sadb_address_proto,
2368 			xpl->sadb_x_policy_priority,
2369 			created,
2370 			&spidx);
2371 #else
2372 	KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2373 			saddr + 1,
2374 			daddr + 1,
2375 			saddr->sadb_address_prefixlen,
2376 			daddr->sadb_address_prefixlen,
2377 			saddr->sadb_address_proto,
2378 			created,
2379 			&spidx);
2380 #endif
2381 
2382 #ifdef HAVE_SECCTX
2383 	if (mhp[SADB_X_EXT_SEC_CTX] != NULL) {
2384 		struct sadb_x_sec_ctx *ctx;
2385 
2386 		ctx = (struct sadb_x_sec_ctx *)mhp[SADB_X_EXT_SEC_CTX];
2387 		spidx.sec_ctx.ctx_alg = ctx->sadb_x_ctx_alg;
2388 		spidx.sec_ctx.ctx_doi = ctx->sadb_x_ctx_doi;
2389 		spidx.sec_ctx.ctx_strlen = ctx->sadb_x_ctx_len;
2390 		memcpy(spidx.sec_ctx.ctx_str, ctx + 1, ctx->sadb_x_ctx_len);
2391 	}
2392 #endif /* HAVE_SECCTX */
2393 
2394 	sp = getsp(&spidx);
2395 	if (sp != NULL) {
2396 		plog(LLV_ERROR, LOCATION, NULL,
2397 			"such policy already exists. "
2398 			"anyway replace it: %s\n",
2399 			spidx2str(&spidx));
2400 		remsp(sp);
2401 		delsp(sp);
2402 	}
2403 
2404 	if (addnewsp(mhp) < 0)
2405 		return -1;
2406 
2407 	return 0;
2408 }
2409 
2410 /*
2411  * this function has to be used by responder side.
2412  */
2413 int
2414 pk_sendspddelete(iph2)
2415 	struct ph2handle *iph2;
2416 {
2417 	struct policyindex *spidx = (struct policyindex *)iph2->spidx_gen;
2418 	caddr_t policy = NULL;
2419 	int policylen;
2420 
2421 	if (getsadbpolicy(&policy, &policylen, SADB_X_SPDDELETE, iph2)) {
2422 		plog(LLV_ERROR, LOCATION, NULL,
2423 			"getting sadb policy failed.\n");
2424 		return -1;
2425 	}
2426 
2427 	if (pfkey_send_spddelete(
2428 			lcconf->sock_pfkey,
2429 			(struct sockaddr *)&spidx->src,
2430 			spidx->prefs,
2431 			(struct sockaddr *)&spidx->dst,
2432 			spidx->prefd,
2433 			spidx->ul_proto,
2434 			policy, policylen, 0) < 0) {
2435 		plog(LLV_ERROR, LOCATION, NULL,
2436 			"libipsec failed send spddelete (%s)\n",
2437 			ipsec_strerror());
2438 		goto end;
2439 	}
2440 	plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_spddelete\n");
2441 
2442 end:
2443 	if (policy)
2444 		racoon_free(policy);
2445 
2446 	return 0;
2447 }
2448 
2449 static int
2450 pk_recvspddelete(mhp)
2451 	caddr_t *mhp;
2452 {
2453 	struct sadb_address *saddr, *daddr;
2454 	struct sadb_x_policy *xpl;
2455 	struct sadb_lifetime *lt;
2456 	struct policyindex spidx;
2457 	struct secpolicy *sp;
2458 	u_int64_t created;
2459 
2460 	/* sanity check */
2461 	if (mhp[0] == NULL
2462 	 || mhp[SADB_EXT_ADDRESS_SRC] == NULL
2463 	 || mhp[SADB_EXT_ADDRESS_DST] == NULL
2464 	 || mhp[SADB_X_EXT_POLICY] == NULL) {
2465 		plog(LLV_ERROR, LOCATION, NULL,
2466 			"inappropriate sadb spddelete message passed.\n");
2467 		return -1;
2468 	}
2469 	saddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_SRC];
2470 	daddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_DST];
2471 	xpl = (struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY];
2472 	lt = (struct sadb_lifetime*)mhp[SADB_EXT_LIFETIME_HARD];
2473 	if(lt != NULL)
2474 		created = lt->sadb_lifetime_addtime;
2475 	else
2476 		created = 0;
2477 
2478 #ifdef HAVE_PFKEY_POLICY_PRIORITY
2479 	KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2480 			saddr + 1,
2481 			daddr + 1,
2482 			saddr->sadb_address_prefixlen,
2483 			daddr->sadb_address_prefixlen,
2484 			saddr->sadb_address_proto,
2485 			xpl->sadb_x_policy_priority,
2486 			created,
2487 			&spidx);
2488 #else
2489 	KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2490 			saddr + 1,
2491 			daddr + 1,
2492 			saddr->sadb_address_prefixlen,
2493 			daddr->sadb_address_prefixlen,
2494 			saddr->sadb_address_proto,
2495 			created,
2496 			&spidx);
2497 #endif
2498 
2499 #ifdef HAVE_SECCTX
2500 	if (mhp[SADB_X_EXT_SEC_CTX] != NULL) {
2501 		struct sadb_x_sec_ctx *ctx;
2502 
2503 		ctx = (struct sadb_x_sec_ctx *)mhp[SADB_X_EXT_SEC_CTX];
2504 		spidx.sec_ctx.ctx_alg = ctx->sadb_x_ctx_alg;
2505 		spidx.sec_ctx.ctx_doi = ctx->sadb_x_ctx_doi;
2506 		spidx.sec_ctx.ctx_strlen = ctx->sadb_x_ctx_len;
2507 		memcpy(spidx.sec_ctx.ctx_str, ctx + 1, ctx->sadb_x_ctx_len);
2508 	}
2509 #endif /* HAVE_SECCTX */
2510 
2511 	sp = getsp(&spidx);
2512 	if (sp == NULL) {
2513 		plog(LLV_ERROR, LOCATION, NULL,
2514 			"no policy found: %s\n",
2515 			spidx2str(&spidx));
2516 		return -1;
2517 	}
2518 
2519 	remsp(sp);
2520 	delsp(sp);
2521 
2522 	return 0;
2523 }
2524 
2525 static int
2526 pk_recvspdexpire(mhp)
2527 	caddr_t *mhp;
2528 {
2529 	struct sadb_address *saddr, *daddr;
2530 	struct sadb_x_policy *xpl;
2531 	struct sadb_lifetime *lt;
2532 	struct policyindex spidx;
2533 	struct secpolicy *sp;
2534 	u_int64_t created;
2535 
2536 	/* sanity check */
2537 	if (mhp[0] == NULL
2538 	 || mhp[SADB_EXT_ADDRESS_SRC] == NULL
2539 	 || mhp[SADB_EXT_ADDRESS_DST] == NULL
2540 	 || mhp[SADB_X_EXT_POLICY] == NULL) {
2541 		plog(LLV_ERROR, LOCATION, NULL,
2542 			"inappropriate sadb spdexpire message passed.\n");
2543 		return -1;
2544 	}
2545 	saddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_SRC];
2546 	daddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_DST];
2547 	xpl = (struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY];
2548 	lt = (struct sadb_lifetime*)mhp[SADB_EXT_LIFETIME_HARD];
2549 	if(lt != NULL)
2550 		created = lt->sadb_lifetime_addtime;
2551 	else
2552 		created = 0;
2553 
2554 #ifdef HAVE_PFKEY_POLICY_PRIORITY
2555 	KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2556 			saddr + 1,
2557 			daddr + 1,
2558 			saddr->sadb_address_prefixlen,
2559 			daddr->sadb_address_prefixlen,
2560 			saddr->sadb_address_proto,
2561 			xpl->sadb_x_policy_priority,
2562 			created,
2563 			&spidx);
2564 #else
2565 	KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2566 			saddr + 1,
2567 			daddr + 1,
2568 			saddr->sadb_address_prefixlen,
2569 			daddr->sadb_address_prefixlen,
2570 			saddr->sadb_address_proto,
2571 			created,
2572 			&spidx);
2573 #endif
2574 
2575 #ifdef HAVE_SECCTX
2576 	if (mhp[SADB_X_EXT_SEC_CTX] != NULL) {
2577 		struct sadb_x_sec_ctx *ctx;
2578 
2579 		ctx = (struct sadb_x_sec_ctx *)mhp[SADB_X_EXT_SEC_CTX];
2580 		spidx.sec_ctx.ctx_alg = ctx->sadb_x_ctx_alg;
2581 		spidx.sec_ctx.ctx_doi = ctx->sadb_x_ctx_doi;
2582 		spidx.sec_ctx.ctx_strlen = ctx->sadb_x_ctx_len;
2583 		memcpy(spidx.sec_ctx.ctx_str, ctx + 1, ctx->sadb_x_ctx_len);
2584 	}
2585 #endif /* HAVE_SECCTX */
2586 
2587 	sp = getsp(&spidx);
2588 	if (sp == NULL) {
2589 		plog(LLV_ERROR, LOCATION, NULL,
2590 			"no policy found: %s\n",
2591 			spidx2str(&spidx));
2592 		return -1;
2593 	}
2594 
2595 	remsp(sp);
2596 	delsp(sp);
2597 
2598 	return 0;
2599 }
2600 
2601 static int
2602 pk_recvspdget(mhp)
2603 	caddr_t *mhp;
2604 {
2605 	/* sanity check */
2606 	if (mhp[0] == NULL) {
2607 		plog(LLV_ERROR, LOCATION, NULL,
2608 			"inappropriate sadb spdget message passed.\n");
2609 		return -1;
2610 	}
2611 
2612 	return 0;
2613 }
2614 
2615 static int
2616 pk_recvspddump(mhp)
2617 	caddr_t *mhp;
2618 {
2619 	struct sadb_msg *msg;
2620 	struct sadb_address *saddr, *daddr;
2621 	struct sadb_x_policy *xpl;
2622 	struct sadb_lifetime *lt;
2623 	struct policyindex spidx;
2624 	struct secpolicy *sp;
2625 	u_int64_t created;
2626 
2627 	/* sanity check */
2628 	if (mhp[0] == NULL) {
2629 		plog(LLV_ERROR, LOCATION, NULL,
2630 			"inappropriate sadb spddump message passed.\n");
2631 		return -1;
2632 	}
2633 	msg = (struct sadb_msg *)mhp[0];
2634 
2635 	saddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_SRC];
2636 	daddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_DST];
2637 	xpl = (struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY];
2638 	lt = (struct sadb_lifetime*)mhp[SADB_EXT_LIFETIME_HARD];
2639 	if(lt != NULL)
2640 		created = lt->sadb_lifetime_addtime;
2641 	else
2642 		created = 0;
2643 
2644 	if (saddr == NULL || daddr == NULL || xpl == NULL) {
2645 		plog(LLV_ERROR, LOCATION, NULL,
2646 			"inappropriate sadb spddump message passed.\n");
2647 		return -1;
2648 	}
2649 
2650 #ifdef HAVE_PFKEY_POLICY_PRIORITY
2651 	KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2652 			saddr + 1,
2653 			daddr + 1,
2654 			saddr->sadb_address_prefixlen,
2655 			daddr->sadb_address_prefixlen,
2656 			saddr->sadb_address_proto,
2657 			xpl->sadb_x_policy_priority,
2658 			created,
2659 			&spidx);
2660 #else
2661 	KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2662 			saddr + 1,
2663 			daddr + 1,
2664 			saddr->sadb_address_prefixlen,
2665 			daddr->sadb_address_prefixlen,
2666 			saddr->sadb_address_proto,
2667 			created,
2668 			&spidx);
2669 #endif
2670 
2671 #ifdef HAVE_SECCTX
2672 	if (mhp[SADB_X_EXT_SEC_CTX] != NULL) {
2673 		struct sadb_x_sec_ctx *ctx;
2674 
2675 		ctx = (struct sadb_x_sec_ctx *)mhp[SADB_X_EXT_SEC_CTX];
2676 		spidx.sec_ctx.ctx_alg = ctx->sadb_x_ctx_alg;
2677 		spidx.sec_ctx.ctx_doi = ctx->sadb_x_ctx_doi;
2678 		spidx.sec_ctx.ctx_strlen = ctx->sadb_x_ctx_len;
2679 		memcpy(spidx.sec_ctx.ctx_str, ctx + 1, ctx->sadb_x_ctx_len);
2680 	}
2681 #endif /* HAVE_SECCTX */
2682 
2683 	sp = getsp(&spidx);
2684 	if (sp != NULL) {
2685 		plog(LLV_ERROR, LOCATION, NULL,
2686 			"such policy already exists. "
2687 			"anyway replace it: %s\n",
2688 			spidx2str(&spidx));
2689 		remsp(sp);
2690 		delsp(sp);
2691 	}
2692 
2693 	if (addnewsp(mhp) < 0)
2694 		return -1;
2695 
2696 	return 0;
2697 }
2698 
2699 static int
2700 pk_recvspdflush(mhp)
2701 	caddr_t *mhp;
2702 {
2703 	/* sanity check */
2704 	if (mhp[0] == NULL) {
2705 		plog(LLV_ERROR, LOCATION, NULL,
2706 			"inappropriate sadb spdflush message passed.\n");
2707 		return -1;
2708 	}
2709 
2710 	flushsp();
2711 
2712 	return 0;
2713 }
2714 
2715 /*
2716  * send error against acquire message to kenrel.
2717  */
2718 int
2719 pk_sendeacquire(iph2)
2720 	struct ph2handle *iph2;
2721 {
2722 	struct sadb_msg *newmsg;
2723 	int len;
2724 
2725 	len = sizeof(struct sadb_msg);
2726 	newmsg = racoon_calloc(1, len);
2727 	if (newmsg == NULL) {
2728 		plog(LLV_ERROR, LOCATION, NULL,
2729 			"failed to get buffer to send acquire.\n");
2730 		return -1;
2731 	}
2732 
2733 	memset(newmsg, 0, len);
2734 	newmsg->sadb_msg_version = PF_KEY_V2;
2735 	newmsg->sadb_msg_type = SADB_ACQUIRE;
2736 	newmsg->sadb_msg_errno = ENOENT;	/* XXX */
2737 	newmsg->sadb_msg_satype = iph2->satype;
2738 	newmsg->sadb_msg_len = PFKEY_UNIT64(len);
2739 	newmsg->sadb_msg_reserved = 0;
2740 	newmsg->sadb_msg_seq = iph2->seq;
2741 	newmsg->sadb_msg_pid = (u_int32_t)getpid();
2742 
2743 	/* send message */
2744 	len = pfkey_send(lcconf->sock_pfkey, newmsg, len);
2745 
2746 	racoon_free(newmsg);
2747 
2748 	return 0;
2749 }
2750 
2751 /*
2752  * check if the algorithm is supported or not.
2753  * OUT	 0: ok
2754  *	-1: ng
2755  */
2756 int
2757 pk_checkalg(class, calg, keylen)
2758 	int class, calg, keylen;
2759 {
2760 	int sup, error;
2761 	u_int alg;
2762 	struct sadb_alg alg0;
2763 
2764 	switch (algclass2doi(class)) {
2765 	case IPSECDOI_PROTO_IPSEC_ESP:
2766 		sup = SADB_EXT_SUPPORTED_ENCRYPT;
2767 		break;
2768 	case IPSECDOI_ATTR_AUTH:
2769 		sup = SADB_EXT_SUPPORTED_AUTH;
2770 		break;
2771 	case IPSECDOI_PROTO_IPCOMP:
2772 		plog(LLV_DEBUG, LOCATION, NULL,
2773 			"compression algorithm can not be checked "
2774 			"because sadb message doesn't support it.\n");
2775 		return 0;
2776 	default:
2777 		plog(LLV_ERROR, LOCATION, NULL,
2778 			"invalid algorithm class.\n");
2779 		return -1;
2780 	}
2781 	alg = ipsecdoi2pfkey_alg(algclass2doi(class), algtype2doi(class, calg));
2782 	if (alg == ~0)
2783 		return -1;
2784 
2785 	if (keylen == 0) {
2786 		if (ipsec_get_keylen(sup, alg, &alg0)) {
2787 			plog(LLV_ERROR, LOCATION, NULL,
2788 				"%s.\n", ipsec_strerror());
2789 			return -1;
2790 		}
2791 		keylen = alg0.sadb_alg_minbits;
2792 	}
2793 
2794 	error = ipsec_check_keylen(sup, alg, keylen);
2795 	if (error)
2796 		plog(LLV_ERROR, LOCATION, NULL,
2797 			"%s.\n", ipsec_strerror());
2798 
2799 	return error;
2800 }
2801 
2802 /*
2803  * differences with pfkey_recv() in libipsec/pfkey.c:
2804  * - never performs busy wait loop.
2805  * - returns NULL and set *lenp to negative on fatal failures
2806  * - returns NULL and set *lenp to non-negative on non-fatal failures
2807  * - returns non-NULL on success
2808  */
2809 static struct sadb_msg *
2810 pk_recv(so, lenp)
2811 	int so;
2812 	int *lenp;
2813 {
2814 	struct sadb_msg buf, *newmsg;
2815 	int reallen;
2816 	int retry = 0;
2817 
2818 	*lenp = -1;
2819 	do
2820 	{
2821 	    plog(LLV_DEBUG, LOCATION, NULL, "pk_recv: retry[%d] recv() \n", retry );
2822 	    *lenp = recv(so, (caddr_t)&buf, sizeof(buf), MSG_PEEK | MSG_DONTWAIT);
2823 	    retry++;
2824 	}
2825 	while (*lenp < 0 && errno == EAGAIN && retry < 3);
2826 	if (*lenp < 0)
2827 	{
2828 	    if ( errno == EAGAIN ) *lenp = 0; /* non-fatal */
2829  	    return NULL;	/*fatal*/
2830 	}
2831 
2832 	else if (*lenp < sizeof(buf))
2833 		return NULL;
2834 
2835 	reallen = PFKEY_UNUNIT64(buf.sadb_msg_len);
2836 	if (reallen < sizeof(buf)) {
2837 		*lenp = -1;
2838 		errno = EIO;
2839 		return NULL;    /*fatal*/
2840 	}
2841 	if ((newmsg = racoon_calloc(1, reallen)) == NULL)
2842 		return NULL;
2843 
2844 	*lenp = recv(so, (caddr_t)newmsg, reallen, MSG_PEEK);
2845 	if (*lenp < 0) {
2846 		racoon_free(newmsg);
2847 		return NULL;	/*fatal*/
2848 	} else if (*lenp != reallen) {
2849 		racoon_free(newmsg);
2850 		return NULL;
2851 	}
2852 
2853 	*lenp = recv(so, (caddr_t)newmsg, reallen, 0);
2854 	if (*lenp < 0) {
2855 		racoon_free(newmsg);
2856 		return NULL;	/*fatal*/
2857 	} else if (*lenp != reallen) {
2858 		racoon_free(newmsg);
2859 		return NULL;
2860 	}
2861 
2862 	return newmsg;
2863 }
2864 
2865 /* see handler.h */
2866 u_int32_t
2867 pk_getseq()
2868 {
2869 	return eay_random();
2870 }
2871 
2872 static int
2873 addnewsp(mhp)
2874 	caddr_t *mhp;
2875 {
2876 	struct secpolicy *new = NULL;
2877 	struct sadb_address *saddr, *daddr;
2878 	struct sadb_x_policy *xpl;
2879 	struct sadb_lifetime *lt;
2880 	u_int64_t created;
2881 
2882 	/* sanity check */
2883 	if (mhp[SADB_EXT_ADDRESS_SRC] == NULL
2884 	 || mhp[SADB_EXT_ADDRESS_DST] == NULL
2885 	 || mhp[SADB_X_EXT_POLICY] == NULL) {
2886 		plog(LLV_ERROR, LOCATION, NULL,
2887 			"inappropriate sadb spd management message passed.\n");
2888 		goto bad;
2889 	}
2890 
2891 	saddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_SRC];
2892 	daddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_DST];
2893 	xpl = (struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY];
2894 	lt = (struct sadb_lifetime*)mhp[SADB_EXT_LIFETIME_HARD];
2895 	if(lt != NULL)
2896 		created = lt->sadb_lifetime_addtime;
2897 	else
2898 		created = 0;
2899 	lt = (struct sadb_lifetime*)mhp[SADB_EXT_LIFETIME_HARD];
2900 	if(lt != NULL)
2901 		created = lt->sadb_lifetime_addtime;
2902 	else
2903 		created = 0;
2904 
2905 #ifdef __linux__
2906 	/* bsd skips over per-socket policies because there will be no
2907 	 * src and dst extensions in spddump messages. On Linux the only
2908 	 * way to achieve the same is check for policy id.
2909 	 */
2910 	if (xpl->sadb_x_policy_id % 8 >= 3) return 0;
2911 #endif
2912 
2913 	new = newsp();
2914 	if (new == NULL) {
2915 		plog(LLV_ERROR, LOCATION, NULL,
2916 			"failed to allocate buffer\n");
2917 		goto bad;
2918 	}
2919 
2920 	new->spidx.dir = xpl->sadb_x_policy_dir;
2921 	new->id = xpl->sadb_x_policy_id;
2922 	new->policy = xpl->sadb_x_policy_type;
2923 	new->req = NULL;
2924 
2925 	/* check policy */
2926 	switch (xpl->sadb_x_policy_type) {
2927 	case IPSEC_POLICY_DISCARD:
2928 	case IPSEC_POLICY_NONE:
2929 	case IPSEC_POLICY_ENTRUST:
2930 	case IPSEC_POLICY_BYPASS:
2931 		break;
2932 
2933 	case IPSEC_POLICY_IPSEC:
2934 	    {
2935 		int tlen;
2936 		struct sadb_x_ipsecrequest *xisr;
2937 		struct ipsecrequest **p_isr = &new->req;
2938 
2939 		/* validity check */
2940 		if (PFKEY_EXTLEN(xpl) < sizeof(*xpl)) {
2941 			plog(LLV_ERROR, LOCATION, NULL,
2942 				"invalid msg length.\n");
2943 			goto bad;
2944 		}
2945 
2946 		tlen = PFKEY_EXTLEN(xpl) - sizeof(*xpl);
2947 		xisr = (struct sadb_x_ipsecrequest *)(xpl + 1);
2948 
2949 		while (tlen > 0) {
2950 
2951 			/* length check */
2952 			if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) {
2953 				plog(LLV_ERROR, LOCATION, NULL,
2954 					"invalid msg length.\n");
2955 				goto bad;
2956 			}
2957 
2958 			/* allocate request buffer */
2959 			*p_isr = newipsecreq();
2960 			if (*p_isr == NULL) {
2961 				plog(LLV_ERROR, LOCATION, NULL,
2962 					"failed to get new ipsecreq.\n");
2963 				goto bad;
2964 			}
2965 
2966 			/* set values */
2967 			(*p_isr)->next = NULL;
2968 
2969 			switch (xisr->sadb_x_ipsecrequest_proto) {
2970 			case IPPROTO_ESP:
2971 			case IPPROTO_AH:
2972 			case IPPROTO_IPCOMP:
2973 				break;
2974 			default:
2975 				plog(LLV_ERROR, LOCATION, NULL,
2976 					"invalid proto type: %u\n",
2977 					xisr->sadb_x_ipsecrequest_proto);
2978 				goto bad;
2979 			}
2980 			(*p_isr)->saidx.proto = xisr->sadb_x_ipsecrequest_proto;
2981 
2982 			switch (xisr->sadb_x_ipsecrequest_mode) {
2983 			case IPSEC_MODE_TRANSPORT:
2984 			case IPSEC_MODE_TUNNEL:
2985 				break;
2986 			case IPSEC_MODE_ANY:
2987 			default:
2988 				plog(LLV_ERROR, LOCATION, NULL,
2989 					"invalid mode: %u\n",
2990 					xisr->sadb_x_ipsecrequest_mode);
2991 				goto bad;
2992 			}
2993 			(*p_isr)->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
2994 
2995 			switch (xisr->sadb_x_ipsecrequest_level) {
2996 			case IPSEC_LEVEL_DEFAULT:
2997 			case IPSEC_LEVEL_USE:
2998 			case IPSEC_LEVEL_REQUIRE:
2999 				break;
3000 			case IPSEC_LEVEL_UNIQUE:
3001 				(*p_isr)->saidx.reqid =
3002 					xisr->sadb_x_ipsecrequest_reqid;
3003 				break;
3004 
3005 			default:
3006 				plog(LLV_ERROR, LOCATION, NULL,
3007 					"invalid level: %u\n",
3008 					xisr->sadb_x_ipsecrequest_level);
3009 				goto bad;
3010 			}
3011 			(*p_isr)->level = xisr->sadb_x_ipsecrequest_level;
3012 
3013 			/* set IP addresses if there */
3014 			if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
3015 				struct sockaddr *paddr;
3016 
3017 				paddr = (struct sockaddr *)(xisr + 1);
3018 				bcopy(paddr, &(*p_isr)->saidx.src,
3019 					sysdep_sa_len(paddr));
3020 
3021 				paddr = (struct sockaddr *)((caddr_t)paddr
3022 							+ sysdep_sa_len(paddr));
3023 				bcopy(paddr, &(*p_isr)->saidx.dst,
3024 					sysdep_sa_len(paddr));
3025 			}
3026 
3027 			(*p_isr)->sp = new;
3028 
3029 			/* initialization for the next. */
3030 			p_isr = &(*p_isr)->next;
3031 			tlen -= xisr->sadb_x_ipsecrequest_len;
3032 
3033 			/* validity check */
3034 			if (tlen < 0) {
3035 				plog(LLV_ERROR, LOCATION, NULL,
3036 					"becoming tlen < 0\n");
3037 			}
3038 
3039 			xisr = (struct sadb_x_ipsecrequest *)((caddr_t)xisr
3040 			                 + xisr->sadb_x_ipsecrequest_len);
3041 		}
3042 	    }
3043 		break;
3044 	default:
3045 		plog(LLV_ERROR, LOCATION, NULL,
3046 			"invalid policy type.\n");
3047 		goto bad;
3048 	}
3049 
3050 #ifdef HAVE_PFKEY_POLICY_PRIORITY
3051 	KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
3052 			saddr + 1,
3053 			daddr + 1,
3054 			saddr->sadb_address_prefixlen,
3055 			daddr->sadb_address_prefixlen,
3056 			saddr->sadb_address_proto,
3057 			xpl->sadb_x_policy_priority,
3058 			created,
3059 			&new->spidx);
3060 #else
3061 	KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
3062 			saddr + 1,
3063 			daddr + 1,
3064 			saddr->sadb_address_prefixlen,
3065 			daddr->sadb_address_prefixlen,
3066 			saddr->sadb_address_proto,
3067 			created,
3068 			&new->spidx);
3069 #endif
3070 
3071 #ifdef HAVE_SECCTX
3072 	if (mhp[SADB_X_EXT_SEC_CTX] != NULL) {
3073 		struct sadb_x_sec_ctx *ctx;
3074 
3075 		ctx = (struct sadb_x_sec_ctx *)mhp[SADB_X_EXT_SEC_CTX];
3076 		new->spidx.sec_ctx.ctx_alg = ctx->sadb_x_ctx_alg;
3077 		new->spidx.sec_ctx.ctx_doi = ctx->sadb_x_ctx_doi;
3078 		new->spidx.sec_ctx.ctx_strlen = ctx->sadb_x_ctx_len;
3079 		memcpy(new->spidx.sec_ctx.ctx_str,ctx + 1,ctx->sadb_x_ctx_len);
3080 	}
3081 #endif /* HAVE_SECCTX */
3082 
3083 	inssp(new);
3084 
3085 	return 0;
3086 bad:
3087 	if (new != NULL) {
3088 		if (new->req != NULL)
3089 			racoon_free(new->req);
3090 		racoon_free(new);
3091 	}
3092 	return -1;
3093 }
3094 
3095 /* proto/mode/src->dst spi */
3096 const char *
3097 sadbsecas2str(src, dst, proto, spi, mode)
3098 	struct sockaddr *src, *dst;
3099 	int proto;
3100 	u_int32_t spi;
3101 	int mode;
3102 {
3103 	static char buf[256];
3104 	u_int doi_proto, doi_mode = 0;
3105 	char *p;
3106 	int blen, i;
3107 
3108 	doi_proto = pfkey2ipsecdoi_proto(proto);
3109 	if (doi_proto == ~0)
3110 		return NULL;
3111 	if (mode) {
3112 		doi_mode = pfkey2ipsecdoi_mode(mode);
3113 		if (doi_mode == ~0)
3114 			return NULL;
3115 	}
3116 
3117 	blen = sizeof(buf) - 1;
3118 	p = buf;
3119 
3120 	i = snprintf(p, blen, "%s%s%s ",
3121 		s_ipsecdoi_proto(doi_proto),
3122 		mode ? "/" : "",
3123 		mode ? s_ipsecdoi_encmode(doi_mode) : "");
3124 	if (i < 0 || i >= blen)
3125 		return NULL;
3126 	p += i;
3127 	blen -= i;
3128 
3129 	i = snprintf(p, blen, "%s->", saddr2str(src));
3130 	if (i < 0 || i >= blen)
3131 		return NULL;
3132 	p += i;
3133 	blen -= i;
3134 
3135 	i = snprintf(p, blen, "%s ", saddr2str(dst));
3136 	if (i < 0 || i >= blen)
3137 		return NULL;
3138 	p += i;
3139 	blen -= i;
3140 
3141 	if (spi) {
3142 		snprintf(p, blen, "spi=%lu(0x%lx)", (unsigned long)ntohl(spi),
3143 		    (unsigned long)ntohl(spi));
3144 	}
3145 
3146 	return buf;
3147 }
3148