Home | History | Annotate | Line # | Download | only in racoon
      1 /*	$NetBSD: isakmp.c,v 1.81 2025/03/08 16:39:08 christos Exp $	*/
      2 
      3 /* Id: isakmp.c,v 1.74 2006/05/07 21:32:59 manubsd 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 <sys/types.h>
     37 #include <sys/param.h>
     38 #include <sys/socket.h>
     39 #include <sys/queue.h>
     40 
     41 #include <netinet/in.h>
     42 #include <arpa/inet.h>
     43 
     44 #include PATH_IPSEC_H
     45 
     46 #include <stdlib.h>
     47 #include <stdio.h>
     48 #include <string.h>
     49 #include <errno.h>
     50 #if TIME_WITH_SYS_TIME
     51 # include <sys/time.h>
     52 # include <time.h>
     53 #else
     54 # if HAVE_SYS_TIME_H
     55 #  include <sys/time.h>
     56 # else
     57 #  include <time.h>
     58 # endif
     59 #endif
     60 #include <netdb.h>
     61 #ifdef HAVE_UNISTD_H
     62 #include <unistd.h>
     63 #endif
     64 #include <ctype.h>
     65 #ifdef ENABLE_HYBRID
     66 #include <resolv.h>
     67 #endif
     68 
     69 #include "var.h"
     70 #include "misc.h"
     71 #include "vmbuf.h"
     72 #include "plog.h"
     73 #include "sockmisc.h"
     74 #include "schedule.h"
     75 #include "session.h"
     76 #include "debug.h"
     77 
     78 #include "remoteconf.h"
     79 #include "localconf.h"
     80 #include "grabmyaddr.h"
     81 #include "admin.h"
     82 #include "privsep.h"
     83 #include "isakmp_var.h"
     84 #include "isakmp.h"
     85 #include "oakley.h"
     86 #include "evt.h"
     87 #include "handler.h"
     88 #include "ipsec_doi.h"
     89 #include "pfkey.h"
     90 #include "crypto_openssl.h"
     91 #include "policy.h"
     92 #include "algorithm.h"
     93 #include "proposal.h"
     94 #include "sainfo.h"
     95 #include "isakmp_ident.h"
     96 #include "isakmp_agg.h"
     97 #include "isakmp_base.h"
     98 #include "isakmp_quick.h"
     99 #include "isakmp_inf.h"
    100 #include "isakmp_newg.h"
    101 #ifdef ENABLE_HYBRID
    102 #include "vendorid.h"
    103 #include "isakmp_xauth.h"
    104 #include "isakmp_unity.h"
    105 #include "isakmp_cfg.h"
    106 #endif
    107 #ifdef ENABLE_FRAG
    108 #include "isakmp_frag.h"
    109 #endif
    110 #include "strnames.h"
    111 #include "str2val.h"
    112 
    113 #include <fcntl.h>
    114 
    115 #ifdef ENABLE_NATT
    116 # include "nattraversal.h"
    117 #endif
    118 # ifdef __linux__
    119 #  include <linux/udp.h>
    120 #  include <linux/ip.h>
    121 #  ifndef SOL_UDP
    122 #   define SOL_UDP 17
    123 #  endif
    124 # endif /* __linux__ */
    125 # if defined(__NetBSD__) || defined(__FreeBSD__) ||	\
    126   (defined(__APPLE__) && defined(__MACH__))
    127 #  include <netinet/in.h>
    128 #  include <netinet/udp.h>
    129 #  include <netinet/in_systm.h>
    130 #  include <netinet/ip.h>
    131 #  define SOL_UDP IPPROTO_UDP
    132 # endif /* __NetBSD__ / __FreeBSD__ */
    133 
    134 static int nostate1(struct ph1handle *, vchar_t *);
    135 static int nostate2(struct ph2handle *, vchar_t *);
    136 
    137 static int (*ph1exchange[][2][PHASE1ST_MAX])(struct ph1handle *, vchar_t *) = {
    138  /* error */
    139  { { 0 }, { 0 }, },
    140  /* Identity Protection exchange */
    141  {
    142   { nostate1, ident_i1send, nostate1, ident_i2recv, ident_i2send,
    143     ident_i3recv, ident_i3send, ident_i4recv, ident_i4send, nostate1, nostate1,},
    144   { nostate1, ident_r1recv, ident_r1send, ident_r2recv, ident_r2send,
    145     ident_r3recv, ident_r3send, nostate1, nostate1, nostate1, nostate1, },
    146  },
    147  /* Aggressive exchange */
    148  {
    149   { nostate1, agg_i1send, nostate1, agg_i2recv, agg_i2send,
    150     nostate1, nostate1, nostate1, nostate1, nostate1, nostate1, },
    151   { nostate1, agg_r1recv, agg_r1send, agg_r2recv, agg_r2send,
    152     nostate1, nostate1, nostate1, nostate1, nostate1, nostate1, },
    153  },
    154  /* Base exchange */
    155  {
    156   { nostate1, base_i1send, nostate1, base_i2recv, base_i2send,
    157     base_i3recv, base_i3send, nostate1, nostate1, nostate1, nostate1, },
    158   { nostate1, base_r1recv, base_r1send, base_r2recv, base_r2send,
    159     nostate1, nostate1, nostate1, nostate1, nostate1, nostate1, },
    160  },
    161 };
    162 
    163 static int (*ph2exchange[][2][PHASE2ST_MAX])(struct ph2handle *, vchar_t *) = {
    164  /* error */
    165  { { 0 }, { 0 }, },
    166  /* Quick mode for IKE */
    167  {
    168   { nostate2, nostate2, quick_i1prep, nostate2, quick_i1send,
    169     quick_i2recv, quick_i2send, quick_i3recv, nostate2, nostate2, },
    170   { nostate2, quick_r1recv, quick_r1prep, nostate2, quick_r2send,
    171     quick_r3recv, quick_r3prep, quick_r3send, nostate2, nostate2, }
    172  },
    173 };
    174 
    175 static u_char r_ck0[] = { 0,0,0,0,0,0,0,0 }; /* used to verify the r_ck. */
    176 
    177 static int isakmp_main(vchar_t *, struct sockaddr *, struct sockaddr *);
    178 static int ph1_main(struct ph1handle *, vchar_t *);
    179 static int quick_main(struct ph2handle *, vchar_t *);
    180 static int isakmp_ph1begin_r(vchar_t *, struct sockaddr *, struct sockaddr *,
    181     uint8_t);
    182 static int isakmp_ph2begin_i(struct ph1handle *, struct ph2handle *);
    183 static int isakmp_ph2begin_r(struct ph1handle *, vchar_t *);
    184 static int etypesw1(int);
    185 static int etypesw2(int);
    186 static int isakmp_ph1resend(struct ph1handle *);
    187 static int isakmp_ph2resend(struct ph2handle *);
    188 
    189 #ifdef ENABLE_FRAG
    190 static int frag_handler(struct ph1handle *,
    191     vchar_t *, struct sockaddr *, struct sockaddr *);
    192 #endif
    193 
    194 /*
    195  * isakmp packet handler
    196  */
    197 /*ARGSUSED*/
    198 static int
    199 isakmp_handler(void *ctx __unused, int so_isakmp)
    200 {
    201 	struct isakmp isakmp;
    202 	union {
    203 		char		buf[sizeof (isakmp) + 4];
    204 		uint32_t	non_esp[2];
    205 		struct		{
    206 				     struct udphdr udp;
    207 #ifdef __linux
    208 				     struct iphdr ip;
    209 #else
    210 				     struct ip ip;
    211 #endif
    212 				     char buf[sizeof(isakmp) + 4];
    213 				} lbuf;
    214 	} x;
    215 	struct sockaddr_storage remote;
    216 	struct sockaddr_storage local;
    217 	unsigned int remote_len = sizeof(remote);
    218 	unsigned int local_len = sizeof(local);
    219 	ssize_t len = 0;
    220 	int extralen = 0;
    221 	vchar_t *buf = NULL, *tmpbuf = NULL;
    222 	int error = -1, res;
    223 
    224 	/* read message by MSG_PEEK */
    225 	while ((len = recvfromto(so_isakmp, x.buf, sizeof(x),
    226 		    MSG_PEEK, (struct sockaddr *)&remote, &remote_len,
    227 		    (struct sockaddr *)&local, &local_len)) < 0) {
    228 		if (errno == EINTR)
    229 			continue;
    230 		plog(LLV_ERROR, LOCATION, NULL,
    231 			"failed to receive isakmp packet: %s\n",
    232 			strerror (errno));
    233 		goto end;
    234 	}
    235 
    236 	/* keep-alive packet - ignore */
    237 	if (len == 1 && (x.buf[0]&0xff) == 0xff) {
    238 		/* Pull the keep-alive packet */
    239 		if ((len = recvfrom(so_isakmp, (char *)x.buf, 1,
    240 		    0, (struct sockaddr *)&remote, &remote_len)) != 1) {
    241 			plog(LLV_ERROR, LOCATION, NULL,
    242 			    "failed to receive keep alive packet: %s\n",
    243 			    strerror (errno));
    244 		}
    245 		goto end;
    246 	}
    247 
    248 	/* Lucent IKE in UDP encapsulation */
    249 	{
    250 #ifdef __linux__
    251 		if (ntohs(x.lbuf.udp.dest) == 501) {
    252 			extralen += sizeof(x.lbuf.udp) + x.lbuf.ip.ihl;
    253 		}
    254 #else
    255 		if (ntohs(x.lbuf.udp.uh_dport) == 501) {
    256 			extralen += sizeof(x.lbuf.udp) + x.lbuf.ip.ip_hl;
    257 		}
    258 #endif
    259 	}
    260 
    261 #ifdef ENABLE_NATT
    262 	/* we don't know about portchange yet,
    263 	   look for non-esp marker instead */
    264 	if (x.non_esp[0] == 0 && x.non_esp[1] != 0)
    265 		extralen = NON_ESP_MARKER_LEN;
    266 #endif
    267 
    268 	/* now we know if there is an extra non-esp
    269 	   marker at the beginning or not */
    270 	memcpy ((char *)&isakmp, x.buf + extralen, sizeof (isakmp));
    271 
    272 	/* check isakmp header length, as well as sanity of header length */
    273 	if (len < sizeof(isakmp) || ntohl(isakmp.len) < sizeof(isakmp)) {
    274 		plog(LLV_ERROR, LOCATION, (struct sockaddr *)&remote,
    275 		    "packet shorter than isakmp header size (%zu, %u, %zu)\n",
    276 		    len, ntohl(isakmp.len), sizeof(isakmp));
    277 		/* dummy receive */
    278 		if ((len = recvfrom(so_isakmp, (char *)&isakmp, sizeof(isakmp),
    279 			    0, (struct sockaddr *)&remote, &remote_len)) < 0) {
    280 			plog(LLV_ERROR, LOCATION, NULL,
    281 				"failed to receive isakmp packet: %s\n",
    282 				strerror (errno));
    283 		}
    284 		goto end;
    285 	}
    286 
    287 	/* reject it if the size is tooooo big. */
    288 	if (ntohl(isakmp.len) > 0xffff) {
    289 		plog(LLV_ERROR, LOCATION, NULL,
    290 			"the length in the isakmp header is too big.\n");
    291 		if ((len = recvfrom(so_isakmp, (char *)&isakmp, sizeof(isakmp),
    292 			    0, (struct sockaddr *)&remote, &remote_len)) < 0) {
    293 			plog(LLV_ERROR, LOCATION, NULL,
    294 				"failed to receive isakmp packet: %s\n",
    295 				strerror (errno));
    296 		}
    297 		goto end;
    298 	}
    299 
    300 	/* read real message */
    301 	if ((tmpbuf = vmalloc(ntohl(isakmp.len) + extralen)) == NULL) {
    302 		plog(LLV_ERROR, LOCATION, NULL,
    303 			"failed to allocate reading buffer (%u Bytes)\n",
    304 			ntohl(isakmp.len) + extralen);
    305 		/* dummy receive */
    306 		if ((len = recvfrom(so_isakmp, (char *)&isakmp, sizeof(isakmp),
    307 			    0, (struct sockaddr *)&remote, &remote_len)) < 0) {
    308 			plog(LLV_ERROR, LOCATION, NULL,
    309 				"failed to receive isakmp packet: %s\n",
    310 				strerror (errno));
    311 		}
    312 		goto end;
    313 	}
    314 
    315 	while ((len = recvfromto(so_isakmp, (char *)tmpbuf->v, tmpbuf->l,
    316 	                    0, (struct sockaddr *)&remote, &remote_len,
    317 	                    (struct sockaddr *)&local, &local_len)) < 0) {
    318 		if (errno == EINTR)
    319 			continue;
    320 		plog(LLV_ERROR, LOCATION, NULL,
    321 			"failed to receive isakmp packet: %s\n",
    322 			strerror (errno));
    323 		goto end;
    324 	}
    325 
    326 	if ((buf = vmalloc(len - extralen)) == NULL) {
    327 		plog(LLV_ERROR, LOCATION, NULL,
    328 			"failed to allocate reading buffer (%zu Bytes)\n",
    329 			(len - extralen));
    330 		goto end;
    331 	}
    332 
    333 	memcpy (buf->v, tmpbuf->v + extralen, buf->l);
    334 
    335 	len -= extralen;
    336 
    337 	if (len != buf->l) {
    338 		plog(LLV_ERROR, LOCATION, (struct sockaddr *)&remote,
    339 			"received invalid length (%zd != %zu), why ?\n",
    340 			len, buf->l);
    341 		goto end;
    342 	}
    343 
    344 	plog(LLV_DEBUG, LOCATION, NULL, "===\n");
    345 	plog(LLV_DEBUG, LOCATION, NULL,
    346 		"%zd bytes message received %s\n",
    347 		len, saddr2str_fromto("from %s to %s",
    348 			(struct sockaddr *)&remote,
    349 			(struct sockaddr *)&local));
    350 	plogdump(LLV_DEBUG, buf->v, buf->l);
    351 
    352 	/* avoid packets with malicious port/address */
    353 	if (extract_port((struct sockaddr *)&remote) == 0) {
    354 		plog(LLV_ERROR, LOCATION, (struct sockaddr *)&remote,
    355 			"src port == 0 (valid as UDP but not with IKE)\n");
    356 		goto end;
    357 	}
    358 
    359 	/* XXX: check sender whether to be allowed or not to accept */
    360 
    361 	/* XXX: I don't know how to check isakmp half connection attack. */
    362 
    363 	/* simply reply if the packet was processed. */
    364 	res=check_recvdpkt((struct sockaddr *)&remote,(struct sockaddr *)&local, buf);
    365 	if (res) {
    366 		plog(LLV_NOTIFY, LOCATION, NULL,
    367 			"the packet is retransmitted by %s (%d).\n",
    368 			 saddr2str((struct sockaddr *)&remote), res);
    369 		error = 0;
    370 		goto end;
    371 	}
    372 
    373 	/* isakmp main routine */
    374 	if (isakmp_main(buf, (struct sockaddr *)&remote,
    375 			(struct sockaddr *)&local) != 0) goto end;
    376 
    377 	error = 0;
    378 
    379 end:
    380 	if (tmpbuf != NULL)
    381 		vfree(tmpbuf);
    382 	if (buf != NULL)
    383 		vfree(buf);
    384 	return error;
    385 }
    386 
    387 /*
    388  * main processing to handle isakmp payload
    389  */
    390 static int
    391 isakmp_main(vchar_t *msg, struct sockaddr *remote, struct sockaddr *local)
    392 {
    393 	struct isakmp *isakmp = (struct isakmp *)msg->v;
    394 	isakmp_index *index1 = (isakmp_index *)isakmp;
    395 	uint32_t msgid = isakmp->msgid;
    396 	struct ph1handle *iph1;
    397 
    398 #ifdef HAVE_PRINT_ISAKMP_C
    399 	isakmp_printpacket(msg, remote, local, 0);
    400 #endif
    401 
    402 	/* the initiator's cookie must not be zero */
    403 	if (memcmp(&isakmp->i_ck, r_ck0, sizeof(cookie_t)) == 0) {
    404 		plog(LLV_ERROR, LOCATION, remote,
    405 			"malformed cookie received.\n");
    406 		return -1;
    407 	}
    408 
    409 	/* Check the Major and Minor Version fields. */
    410 	/*
    411 	 * XXX Is is right to check version here ?
    412 	 * I think it may no be here because the version depends
    413 	 * on exchange status.
    414 	 */
    415 	if (isakmp->v < ISAKMP_VERSION_NUMBER) {
    416 		if (ISAKMP_GETMAJORV(isakmp->v) < ISAKMP_MAJOR_VERSION) {
    417 			plog(LLV_ERROR, LOCATION, remote,
    418 				"invalid major version %d.\n",
    419 				ISAKMP_GETMAJORV(isakmp->v));
    420 			return -1;
    421 		}
    422 #if ISAKMP_MINOR_VERSION > 0
    423 		if (ISAKMP_GETMINORV(isakmp->v) < ISAKMP_MINOR_VERSION) {
    424 			plog(LLV_ERROR, LOCATION, remote,
    425 				"invalid minor version %d.\n",
    426 				ISAKMP_GETMINORV(isakmp->v));
    427 			return -1;
    428 		}
    429 #endif
    430 	}
    431 
    432 	/* check the Flags field. */
    433 	/* XXX How is the exclusive check, E and A ? */
    434 	if (isakmp->flags & ~(ISAKMP_FLAG_E | ISAKMP_FLAG_C | ISAKMP_FLAG_A)) {
    435 		plog(LLV_ERROR, LOCATION, remote,
    436 			"invalid flag 0x%02x.\n", isakmp->flags);
    437 		return -1;
    438 	}
    439 
    440 	/* ignore commit bit. */
    441 	if (ISSET(isakmp->flags, ISAKMP_FLAG_C)) {
    442 		if (isakmp->msgid == 0) {
    443 			isakmp_info_send_nx(isakmp, remote, local,
    444 				ISAKMP_NTYPE_INVALID_FLAGS, NULL);
    445 			plog(LLV_ERROR, LOCATION, remote,
    446 				"Commit bit on phase1 forbidden.\n");
    447 			return -1;
    448 		}
    449 	}
    450 
    451 	iph1 = getph1byindex(index1);
    452 	if (iph1 != NULL) {
    453 		/* validity check */
    454 		if (memcmp(&isakmp->r_ck, r_ck0, sizeof(cookie_t)) == 0 &&
    455 		    iph1->side == INITIATOR) {
    456 			plog(LLV_DEBUG, LOCATION, remote,
    457 				"malformed cookie received or "
    458 				"the initiator's cookies collide.\n");
    459 			return -1;
    460 		}
    461 
    462 #ifdef ENABLE_NATT
    463 		/* Floating ports for NAT-T */
    464 		if (NATT_AVAILABLE(iph1) &&
    465 		    ! (iph1->natt_flags & NAT_PORTS_CHANGED) &&
    466 		    ((cmpsaddr(iph1->remote, remote) != CMPSADDR_MATCH) ||
    467 		     (cmpsaddr(iph1->local, local) != CMPSADDR_MATCH)))
    468 		{
    469 			/* prevent memory leak */
    470 			racoon_free(iph1->remote);
    471 			racoon_free(iph1->local);
    472 			iph1->remote = NULL;
    473 			iph1->local = NULL;
    474 
    475 			/* copy-in new addresses */
    476 			iph1->remote = dupsaddr(remote);
    477 			if (iph1->remote == NULL) {
    478            			plog(LLV_ERROR, LOCATION, iph1->remote,
    479 				   "phase1 failed: dupsaddr failed.\n");
    480 				remph1(iph1);
    481 				delph1(iph1);
    482 				return -1;
    483 			}
    484 			iph1->local = dupsaddr(local);
    485 			if (iph1->local == NULL) {
    486            			plog(LLV_ERROR, LOCATION, iph1->remote,
    487 				   "phase1 failed: dupsaddr failed.\n");
    488 				remph1(iph1);
    489 				delph1(iph1);
    490 				return -1;
    491 			}
    492 
    493 			/* set the flag to prevent further port floating
    494 			   (FIXME: should we allow it? E.g. when the NAT gw
    495 			    is rebooted?) */
    496 			iph1->natt_flags |= NAT_PORTS_CHANGED | NAT_ADD_NON_ESP_MARKER;
    497 
    498 			/* print some neat info */
    499 			plog (LLV_INFO, LOCATION, NULL,
    500 			      "NAT-T: ports changed to: %s\n",
    501 			      saddr2str_fromto ("%s<->%s", iph1->remote, iph1->local));
    502 
    503 			natt_keepalive_add_ph1 (iph1);
    504 		}
    505 #endif
    506 
    507 		/* must be same addresses in one stream of a phase at least. */
    508 		if (cmpsaddr(iph1->remote, remote) != CMPSADDR_MATCH) {
    509 			char *saddr_db, *saddr_act;
    510 
    511 			saddr_db = racoon_strdup(saddr2str(iph1->remote));
    512 			saddr_act = racoon_strdup(saddr2str(remote));
    513 			STRDUP_FATAL(saddr_db);
    514 			STRDUP_FATAL(saddr_act);
    515 
    516 			plog(LLV_WARNING, LOCATION, remote,
    517 				"remote address mismatched. db=%s, act=%s\n",
    518 				saddr_db, saddr_act);
    519 
    520 			racoon_free(saddr_db);
    521 			racoon_free(saddr_act);
    522 		}
    523 
    524 		/*
    525 		 * don't check of exchange type here because other type will be
    526 		 * with same index, for example, informational exchange.
    527 		 */
    528 
    529 		/* XXX more acceptable check */
    530 	}
    531 
    532 	switch (isakmp->etype) {
    533 	case ISAKMP_ETYPE_IDENT:
    534 	case ISAKMP_ETYPE_AGG:
    535 	case ISAKMP_ETYPE_BASE:
    536 		/* phase 1 validity check */
    537 		if (isakmp->msgid != 0) {
    538 			plog(LLV_ERROR, LOCATION, remote,
    539 				"message id should be zero in phase1.\n");
    540 			return -1;
    541 		}
    542 
    543 		/* search for isakmp status record of phase 1 */
    544 		if (iph1 == NULL) {
    545 			/*
    546 			 * the packet must be the 1st message from a initiator
    547 			 * or the 2nd message from the responder.
    548 			 */
    549 
    550 			/* search for phase1 handle by index without r_ck */
    551 			iph1 = getph1byindex0(index1);
    552 			if (iph1 == NULL) {
    553 				/*it must be the 1st message from a initiator.*/
    554 				if (memcmp(&isakmp->r_ck, r_ck0,
    555 					sizeof(cookie_t)) != 0) {
    556 
    557 					plog(LLV_DEBUG, LOCATION, remote,
    558 						"malformed cookie received "
    559 						"or the spi expired.\n");
    560 					return -1;
    561 				}
    562 
    563 				/* it must be responder's 1st exchange. */
    564 				if (isakmp_ph1begin_r(msg, remote, local,
    565 					isakmp->etype) < 0)
    566 					return -1;
    567 				break;
    568 
    569 				/*NOTREACHED*/
    570 			}
    571 
    572 			/* it must be the 2nd message from the responder. */
    573 			if (iph1->side != INITIATOR) {
    574 				plog(LLV_DEBUG, LOCATION, remote,
    575 					"malformed cookie received. "
    576 					"it has to be as the initiator.  %s\n",
    577 					isakmp_pindex(&iph1->index, 0));
    578 				return -1;
    579 			}
    580 		}
    581 
    582 		/*
    583 		 * Don't delete phase 1 handler when the exchange type
    584 		 * in handler is not equal to packet's one because of no
    585 		 * authencication completed.
    586 		 */
    587 		if (iph1->etype != isakmp->etype) {
    588 			plog(LLV_ERROR, LOCATION, iph1->remote,
    589 				"exchange type is mismatched: "
    590 				"db=%s packet=%s, ignore it.\n",
    591 				s_isakmp_etype(iph1->etype),
    592 				s_isakmp_etype(isakmp->etype));
    593 			return -1;
    594 		}
    595 
    596 #ifdef ENABLE_FRAG
    597 		if (isakmp->np == ISAKMP_NPTYPE_FRAG)
    598 			return frag_handler(iph1, msg, remote, local);
    599 #endif
    600 
    601 		/* call main process of phase 1 */
    602 		if (ph1_main(iph1, msg) < 0) {
    603 			plog(LLV_ERROR, LOCATION, iph1->remote,
    604 				"phase1 negotiation failed.\n");
    605 			remph1(iph1);
    606 			delph1(iph1);
    607 			return -1;
    608 		}
    609 		break;
    610 
    611 	case ISAKMP_ETYPE_AUTH:
    612 		plog(LLV_INFO, LOCATION, remote,
    613 			"unsupported exchange %d received.\n",
    614 			isakmp->etype);
    615 		break;
    616 
    617 	case ISAKMP_ETYPE_INFO:
    618 	case ISAKMP_ETYPE_ACKINFO:
    619 		/*
    620 		 * iph1 must be present for Information message.
    621 		 * if iph1 is null then trying to get the phase1 status
    622 		 * as the packet from responder again initiator's 1st
    623 		 * exchange in phase 1.
    624 		 * NOTE: We think such informational exchange should be ignored.
    625 		 */
    626 		if (iph1 == NULL) {
    627 			iph1 = getph1byindex0(index1);
    628 			if (iph1 == NULL) {
    629 				plog(LLV_ERROR, LOCATION, remote,
    630 					"unknown Informational "
    631 					"exchange received.\n");
    632 				return -1;
    633 			}
    634 			if (cmpsaddr(iph1->remote, remote) != CMPSADDR_MATCH) {
    635 				plog(LLV_WARNING, LOCATION, remote,
    636 					"remote address mismatched. "
    637 					"db=%s\n",
    638 					saddr2str(iph1->remote));
    639 			}
    640 		}
    641 
    642 #ifdef ENABLE_FRAG
    643 		if (isakmp->np == ISAKMP_NPTYPE_FRAG)
    644 			return frag_handler(iph1, msg, remote, local);
    645 #endif
    646 
    647 		if (isakmp_info_recv(iph1, msg) < 0)
    648 			return -1;
    649 		break;
    650 
    651 	case ISAKMP_ETYPE_QUICK:
    652 	{
    653 		struct ph2handle *iph2;
    654 
    655 		if (iph1 == NULL) {
    656 			isakmp_info_send_nx(isakmp, remote, local,
    657 				ISAKMP_NTYPE_INVALID_COOKIE, NULL);
    658 			plog(LLV_ERROR, LOCATION, remote,
    659 				"can't start the quick mode, "
    660 				"there is no ISAKMP-SA, %s\n",
    661 				isakmp_pindex((isakmp_index *)&isakmp->i_ck,
    662 					isakmp->msgid));
    663 			return -1;
    664 		}
    665 #ifdef ENABLE_HYBRID
    666 		/* Reinit the IVM if it's still there */
    667 		if (iph1->mode_cfg && iph1->mode_cfg->ivm) {
    668 			oakley_delivm(iph1->mode_cfg->ivm);
    669 			iph1->mode_cfg->ivm = NULL;
    670 		}
    671 #endif
    672 #ifdef ENABLE_FRAG
    673 		if (isakmp->np == ISAKMP_NPTYPE_FRAG)
    674 			return frag_handler(iph1, msg, remote, local);
    675 #endif
    676 
    677 		/* check status of phase 1 whether negotiated or not. */
    678 		if (iph1->status != PHASE1ST_ESTABLISHED &&
    679 		    iph1->status != PHASE1ST_DYING) {
    680 			plog(LLV_ERROR, LOCATION, remote,
    681 				"can't start the quick mode, "
    682 				"there is no valid ISAKMP-SA, %s\n",
    683 				isakmp_pindex(&iph1->index, iph1->msgid));
    684 			return -1;
    685 		}
    686 
    687 		/* search isakmp phase 2 status record. */
    688 		iph2 = getph2bymsgid(iph1, msgid);
    689 		if (iph2 == NULL) {
    690 			/* it must be new negotiation as responder */
    691 			if (isakmp_ph2begin_r(iph1, msg) < 0)
    692 				return -1;
    693 			return 0;
    694 			/*NOTREACHED*/
    695 		}
    696 
    697 		/* commit bit. */
    698 		/* XXX
    699 		 * we keep to set commit bit during negotiation.
    700 		 * When SA is configured, bit will be reset.
    701 		 * XXX
    702 		 * don't initiate commit bit.  should be fixed in the future.
    703 		 */
    704 		if (ISSET(isakmp->flags, ISAKMP_FLAG_C))
    705 			iph2->flags |= ISAKMP_FLAG_C;
    706 
    707 		/* call main process of quick mode */
    708 		if (quick_main(iph2, msg) < 0) {
    709 			plog(LLV_ERROR, LOCATION, iph1->remote,
    710 				"phase2 negotiation failed.\n");
    711 			remph2(iph2);
    712 			delph2(iph2);
    713 			return -1;
    714 		}
    715 	}
    716 		break;
    717 
    718 	case ISAKMP_ETYPE_NEWGRP:
    719 		if (iph1 == NULL) {
    720 			plog(LLV_ERROR, LOCATION, remote,
    721 				"Unknown new group mode exchange, "
    722 				"there is no ISAKMP-SA.\n");
    723 			return -1;
    724 		}
    725 
    726 #ifdef ENABLE_FRAG
    727 		if (isakmp->np == ISAKMP_NPTYPE_FRAG)
    728 			return frag_handler(iph1, msg, remote, local);
    729 #endif
    730 
    731 		isakmp_newgroup_r(iph1, msg);
    732 		break;
    733 
    734 #ifdef ENABLE_HYBRID
    735 	case ISAKMP_ETYPE_CFG:
    736 		if (iph1 == NULL) {
    737 			plog(LLV_ERROR, LOCATION, NULL,
    738 			     "mode config %d from %s, "
    739 			     "but we have no ISAKMP-SA.\n",
    740 			     isakmp->etype, saddr2str(remote));
    741 			return -1;
    742 		}
    743 
    744 #ifdef ENABLE_FRAG
    745 		if (isakmp->np == ISAKMP_NPTYPE_FRAG)
    746 			return frag_handler(iph1, msg, remote, local);
    747 #endif
    748 
    749 		isakmp_cfg_r(iph1, msg);
    750 		break;
    751 #endif
    752 
    753 	case ISAKMP_ETYPE_NONE:
    754 	default:
    755 		plog(LLV_ERROR, LOCATION, NULL,
    756 			"Invalid exchange type %d from %s.\n",
    757 			isakmp->etype, saddr2str(remote));
    758 		return -1;
    759 	}
    760 
    761 	return 0;
    762 }
    763 
    764 /*
    765  * main function of phase 1.
    766  */
    767 static int
    768 ph1_main(struct ph1handle *iph1, vchar_t *msg)
    769 {
    770 	int error;
    771 #ifdef ENABLE_STATS
    772 	struct timeval start, end;
    773 #endif
    774 
    775 	/* ignore a packet */
    776 	if (iph1->status >= PHASE1ST_ESTABLISHED)
    777 		return 0;
    778 
    779 #ifdef ENABLE_STATS
    780 	gettimeofday(&start, NULL);
    781 #endif
    782 	/* receive */
    783 	if (ph1exchange[etypesw1(iph1->etype)]
    784 		       [iph1->side]
    785 		       [iph1->status] == NULL) {
    786 		plog(LLV_ERROR, LOCATION, iph1->remote,
    787 			"why isn't the function defined.\n");
    788 		return -1;
    789 	}
    790 	error = (ph1exchange[etypesw1(iph1->etype)]
    791 			    [iph1->side]
    792 			    [iph1->status])(iph1, msg);
    793 	if (error != 0) {
    794 
    795 		/* XXX
    796 		 * When an invalid packet is received on phase1, it should
    797 		 * be selected to process this packet.  That is to respond
    798 		 * with a notify and delete phase 1 handler, OR not to respond
    799 		 * and keep phase 1 handler. However, in PHASE1ST_START when
    800 		 * acting as RESPONDER we must not keep phase 1 handler or else
    801 		 * it will stay forever.
    802 		 */
    803 
    804 		if (iph1->side == RESPONDER && iph1->status == PHASE1ST_START) {
    805 			plog(LLV_ERROR, LOCATION, iph1->remote,
    806 				"failed to pre-process ph1 packet (side: %d, status %d).\n",
    807 				iph1->side, iph1->status);
    808 			return -1;
    809 		} else {
    810 			/* ignore the error and keep phase 1 handler */
    811 			return 0;
    812 		}
    813 	}
    814 
    815 #ifndef ENABLE_FRAG
    816 	/* free resend buffer */
    817 	if (iph1->sendbuf == NULL) {
    818 		plog(LLV_ERROR, LOCATION, NULL,
    819 			"no buffer found as sendbuf\n");
    820 		return -1;
    821 	}
    822 #endif
    823 
    824 	VPTRINIT(iph1->sendbuf);
    825 
    826 	/* turn off schedule */
    827 	sched_cancel(&iph1->scr);
    828 
    829 	/* send */
    830 	plog(LLV_DEBUG, LOCATION, NULL, "===\n");
    831 	if ((ph1exchange[etypesw1(iph1->etype)]
    832 			[iph1->side]
    833 			[iph1->status])(iph1, msg) != 0) {
    834 		plog(LLV_ERROR, LOCATION, iph1->remote,
    835 			"failed to process ph1 packet (side: %d, status: %d).\n",
    836 			iph1->side, iph1->status);
    837 		return -1;
    838 	}
    839 
    840 #ifdef ENABLE_STATS
    841 	gettimeofday(&end, NULL);
    842 	syslog(LOG_NOTICE, "%s(%s): %8.6f",
    843 		"phase1", s_isakmp_state(iph1->etype, iph1->side, iph1->status),
    844 		timedelta(&start, &end));
    845 #endif
    846 	if (iph1->status == PHASE1ST_ESTABLISHED) {
    847 
    848 #ifdef ENABLE_STATS
    849 		gettimeofday(&iph1->end, NULL);
    850 		syslog(LOG_NOTICE, "%s(%s): %8.6f",
    851 			"phase1", s_isakmp_etype(iph1->etype),
    852 			timedelta(&iph1->start, &iph1->end));
    853 #endif
    854 
    855 		/* save created date. */
    856 		(void)time(&iph1->created);
    857 
    858 		/* migrate ph2s from dying ph1s */
    859 		migrate_dying_ph12(iph1);
    860 
    861 		/* add to the schedule to expire, and seve back pointer. */
    862 		if (ph1_rekey_enabled(iph1)) {
    863 			sched_schedule(&iph1->sce,
    864 				       iph1->approval->lifetime *
    865 				       PFKEY_SOFT_LIFETIME_RATE / 100,
    866 				       isakmp_ph1dying_stub);
    867 		} else {
    868 			sched_schedule(&iph1->sce, iph1->approval->lifetime,
    869 				       isakmp_ph1expire_stub);
    870 		}
    871 
    872 #ifdef ENABLE_HYBRID
    873 		if (iph1->mode_cfg->flags & ISAKMP_CFG_VENDORID_XAUTH) {
    874 			switch (iph1->approval->authmethod) {
    875 			case OAKLEY_ATTR_AUTH_METHOD_HYBRID_RSA_R:
    876 			case OAKLEY_ATTR_AUTH_METHOD_HYBRID_DSS_R:
    877 			case OAKLEY_ATTR_AUTH_METHOD_XAUTH_PSKEY_R:
    878 			case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSASIG_R:
    879 			case OAKLEY_ATTR_AUTH_METHOD_XAUTH_DSSSIG_R:
    880 			case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSAENC_R:
    881 			case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSAREV_R:
    882 				xauth_sendreq(iph1);
    883 				/* XXX Don't process INITIAL_CONTACT */
    884 				iph1->rmconf->ini_contact = 0;
    885 				break;
    886 			case OAKLEY_ATTR_AUTH_METHOD_RSASIG:
    887 				if (iph1->rmconf->mode_cfg)
    888 					error = isakmp_cfg_getconfig(iph1);
    889 				break;
    890 			default:
    891 				break;
    892 			}
    893 		}
    894 #endif
    895 #ifdef ENABLE_DPD
    896 		/* Schedule the r_u_there.... */
    897 		if(iph1->dpd_support && iph1->rmconf->dpd_interval)
    898 			isakmp_sched_r_u(iph1, 0);
    899 #endif
    900 
    901 		/* INITIAL-CONTACT processing */
    902 		/* don't anything if local test mode. */
    903 		if (!f_local
    904 		 && iph1->rmconf->ini_contact && !getcontacted(iph1->remote)) {
    905 			/* send INITIAL-CONTACT */
    906 			isakmp_info_send_n1(iph1,
    907 					ISAKMP_NTYPE_INITIAL_CONTACT, NULL);
    908 			/* insert a node into contacted list. */
    909 			if (inscontacted(iph1->remote) == -1) {
    910 				plog(LLV_ERROR, LOCATION, iph1->remote,
    911 					"failed to add contacted list.\n");
    912 				/* ignore */
    913 			}
    914 		}
    915 		if (iph1->initial_contact_received)
    916 			isakmp_info_recv_initialcontact(iph1, NULL);
    917 
    918 		log_ph1established(iph1);
    919 		plog(LLV_DEBUG, LOCATION, NULL, "===\n");
    920 
    921 		/*
    922 		 * SA up shell script hook: do it now,except if
    923 		 * ISAKMP mode config was requested. In the later
    924 		 * case it is done when we receive the configuration.
    925 		 */
    926 		if ((iph1->status == PHASE1ST_ESTABLISHED) &&
    927 		    !iph1->rmconf->mode_cfg) {
    928 			switch (iph1->approval->authmethod) {
    929 #ifdef ENABLE_HYBRID
    930 			case OAKLEY_ATTR_AUTH_METHOD_XAUTH_PSKEY_R:
    931 			case OAKLEY_ATTR_AUTH_METHOD_HYBRID_RSA_R:
    932 			case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSASIG_R:
    933 			/* Unimplemeted... */
    934 			case OAKLEY_ATTR_AUTH_METHOD_HYBRID_DSS_R:
    935 			case OAKLEY_ATTR_AUTH_METHOD_XAUTH_DSSSIG_R:
    936 			case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSAENC_R:
    937 			case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSAREV_R:
    938 				break;
    939 #endif
    940 			default:
    941 				script_hook(iph1, SCRIPT_PHASE1_UP);
    942 				break;
    943 			}
    944 		}
    945 		if ((iph1->rmconf->mode_cfg) &&
    946 		    !(iph1->mode_cfg->flags & ISAKMP_CFG_VENDORID_XAUTH)) {
    947 			error = isakmp_cfg_getconfig(iph1);
    948 		}
    949 	}
    950 
    951 	return 0;
    952 }
    953 
    954 /*
    955  * main function of quick mode.
    956  */
    957 static int
    958 quick_main(struct ph2handle *iph2, vchar_t *msg)
    959 {
    960 	struct isakmp *isakmp = (struct isakmp *)msg->v;
    961 	int error;
    962 #ifdef ENABLE_STATS
    963 	struct timeval start, end;
    964 #endif
    965 
    966 	/* ignore a packet */
    967 	if (iph2->status == PHASE2ST_ESTABLISHED
    968 	 || iph2->status == PHASE2ST_GETSPISENT)
    969 		return 0;
    970 
    971 #ifdef ENABLE_STATS
    972 	gettimeofday(&start, NULL);
    973 #endif
    974 
    975 	/* receive */
    976 	if (ph2exchange[etypesw2(isakmp->etype)]
    977 		       [iph2->side]
    978 		       [iph2->status] == NULL) {
    979 		plog(LLV_ERROR, LOCATION, iph2->ph1->remote,
    980 			"why isn't the function defined.\n");
    981 		return -1;
    982 	}
    983 	error = (ph2exchange[etypesw2(isakmp->etype)]
    984 			    [iph2->side]
    985 			    [iph2->status])(iph2, msg);
    986 	if (error != 0) {
    987 		plog(LLV_ERROR, LOCATION, iph2->ph1->remote,
    988 			"failed to pre-process ph2 packet (side: %d, status %d).\n",
    989 			iph2->side, iph2->status);
    990 		if (error == ISAKMP_INTERNAL_ERROR)
    991 			return 0;
    992 		isakmp_info_send_n1(iph2->ph1, error, NULL);
    993 		return -1;
    994 	}
    995 
    996 	/* when using commit bit, status will be reached here. */
    997 	if (iph2->status == PHASE2ST_ADDSA)
    998 		return 0;
    999 
   1000 	/* free resend buffer */
   1001 	if (iph2->sendbuf == NULL) {
   1002 		plog(LLV_ERROR, LOCATION, NULL,
   1003 			"no buffer found as sendbuf\n");
   1004 		return -1;
   1005 	}
   1006 	VPTRINIT(iph2->sendbuf);
   1007 
   1008 	/* turn off schedule */
   1009 	sched_cancel(&iph2->scr);
   1010 
   1011 	/* send */
   1012 	plog(LLV_DEBUG, LOCATION, NULL, "===\n");
   1013 	if ((ph2exchange[etypesw2(isakmp->etype)]
   1014 			[iph2->side]
   1015 			[iph2->status])(iph2, msg) != 0) {
   1016 		plog(LLV_ERROR, LOCATION, iph2->ph1->remote,
   1017 			"failed to process ph2 packet (side: %d, status: %d).\n",
   1018 			iph2->side, iph2->status);
   1019 		return -1;
   1020 	}
   1021 
   1022 #ifdef ENABLE_STATS
   1023 	gettimeofday(&end, NULL);
   1024 	syslog(LOG_NOTICE, "%s(%s): %8.6f",
   1025 		"phase2",
   1026 		s_isakmp_state(ISAKMP_ETYPE_QUICK, iph2->side, iph2->status),
   1027 		timedelta(&start, &end));
   1028 #endif
   1029 
   1030 	return 0;
   1031 }
   1032 
   1033 /* new negotiation of phase 1 for initiator */
   1034 struct ph1handle *
   1035 isakmp_ph1begin_i(struct remoteconf *rmconf,
   1036     struct sockaddr *remote, struct sockaddr *local)
   1037 {
   1038 	struct ph1handle *iph1;
   1039 #ifdef ENABLE_STATS
   1040 	struct timeval start, end;
   1041 #endif
   1042 
   1043 	/* get new entry to isakmp status table. */
   1044 	iph1 = newph1();
   1045 	if (iph1 == NULL)
   1046 		return NULL;
   1047 
   1048 	iph1->status = PHASE1ST_START;
   1049 	iph1->rmconf = rmconf;
   1050 	iph1->side = INITIATOR;
   1051 	iph1->version = ISAKMP_VERSION_NUMBER;
   1052 	iph1->msgid = 0;
   1053 	iph1->flags = 0;
   1054 	iph1->ph2cnt = 0;
   1055 #ifdef HAVE_GSSAPI
   1056 	iph1->gssapi_state = NULL;
   1057 #endif
   1058 #ifdef ENABLE_HYBRID
   1059 	if ((iph1->mode_cfg = isakmp_cfg_mkstate()) == NULL) {
   1060 		delph1(iph1);
   1061 		return NULL;
   1062 	}
   1063 #endif
   1064 #ifdef ENABLE_FRAG
   1065 
   1066 	if(rmconf->ike_frag == ISAKMP_FRAG_FORCE)
   1067 		iph1->frag = 1;
   1068 	else
   1069 		iph1->frag = 0;
   1070 	iph1->frag_last_index = 0;
   1071 	iph1->frag_chain = NULL;
   1072 #endif
   1073 	iph1->approval = NULL;
   1074 
   1075 	/* XXX copy remote address */
   1076 	if (copy_ph1addresses(iph1, rmconf, remote, local) < 0) {
   1077 		delph1(iph1);
   1078 		return NULL;
   1079 	}
   1080 
   1081 	(void)insph1(iph1);
   1082 
   1083 	/* start phase 1 exchange */
   1084 	iph1->etype = rmconf->etypes->type;
   1085 
   1086 	plog(LLV_DEBUG, LOCATION, NULL, "===\n");
   1087     {
   1088 	char *a;
   1089 
   1090 	a = racoon_strdup(saddr2str(iph1->local));
   1091 	STRDUP_FATAL(a);
   1092 
   1093 	plog(LLV_INFO, LOCATION, NULL,
   1094 		"initiate new phase 1 negotiation: %s<=>%s\n",
   1095 		a, saddr2str(iph1->remote));
   1096 	racoon_free(a);
   1097     }
   1098 	plog(LLV_INFO, LOCATION, NULL,
   1099 		"begin %s mode.\n",
   1100 		s_isakmp_etype(iph1->etype));
   1101 
   1102 #ifdef ENABLE_STATS
   1103 	gettimeofday(&iph1->start, NULL);
   1104 	gettimeofday(&start, NULL);
   1105 #endif
   1106 	/* start exchange */
   1107 	if ((ph1exchange[etypesw1(iph1->etype)]
   1108 			[iph1->side]
   1109 			[iph1->status])(iph1, NULL) != 0) {
   1110 		/* failed to start phase 1 negotiation */
   1111 		remph1(iph1);
   1112 		delph1(iph1);
   1113 
   1114 		return NULL;
   1115 	}
   1116 
   1117 #ifdef ENABLE_STATS
   1118 	gettimeofday(&end, NULL);
   1119 	syslog(LOG_NOTICE, "%s(%s): %8.6f",
   1120 		"phase1",
   1121 		s_isakmp_state(iph1->etype, iph1->side, iph1->status),
   1122 		timedelta(&start, &end));
   1123 #endif
   1124 
   1125 	return iph1;
   1126 }
   1127 
   1128 /* new negotiation of phase 1 for responder */
   1129 static int
   1130 isakmp_ph1begin_r(vchar_t *msg, struct sockaddr *remote, struct sockaddr *local,
   1131     uint8_t etype)
   1132 {
   1133 	struct isakmp *isakmp = (struct isakmp *)msg->v;
   1134 	struct ph1handle *iph1;
   1135 	struct rmconfselector rmsel;
   1136 #ifdef ENABLE_STATS
   1137 	struct timeval start, end;
   1138 #endif
   1139 
   1140 	/* check if this etype is allowed */
   1141 	memset(&rmsel, 0, sizeof(rmsel));
   1142 	rmsel.remote = remote;
   1143 	if (enumrmconf(&rmsel, check_etypeok, (void *) (intptr_t) etype) == 0) {
   1144 		plog(LLV_ERROR, LOCATION, remote,
   1145 		     "exchange %s not allowed in any applicable rmconf.\n",
   1146 		     s_isakmp_etype(etype));
   1147 		return -1;
   1148 	}
   1149 
   1150 	/* get new entry to isakmp status table. */
   1151 	iph1 = newph1();
   1152 	if (iph1 == NULL)
   1153 		return -1;
   1154 
   1155 	memcpy(&iph1->index.i_ck, &isakmp->i_ck, sizeof(iph1->index.i_ck));
   1156 	iph1->status = PHASE1ST_START;
   1157 	iph1->flags = 0;
   1158 	iph1->side = RESPONDER;
   1159 	iph1->etype = etype;
   1160 	iph1->version = isakmp->v;
   1161 	iph1->msgid = 0;
   1162 #ifdef HAVE_GSSAPI
   1163 	iph1->gssapi_state = NULL;
   1164 #endif
   1165 #ifdef ENABLE_HYBRID
   1166 	if ((iph1->mode_cfg = isakmp_cfg_mkstate()) == NULL) {
   1167 		delph1(iph1);
   1168 		return -1;
   1169 	}
   1170 #endif
   1171 #ifdef ENABLE_FRAG
   1172 	iph1->frag = 0;
   1173 	iph1->frag_last_index = 0;
   1174 	iph1->frag_chain = NULL;
   1175 #endif
   1176 	iph1->approval = NULL;
   1177 
   1178 #ifdef ENABLE_NATT
   1179 	/* RFC3947 says that we MUST accept new phases1 on NAT-T floated port.
   1180 	 * We have to setup this flag now to correctly generate the first reply.
   1181 	 * Don't know if a better check could be done for that ?
   1182 	 */
   1183 	if(extract_port(local) == lcconf->port_isakmp_natt)
   1184 		iph1->natt_flags |= (NAT_PORTS_CHANGED);
   1185 #endif
   1186 
   1187 	/* copy remote address; remote and local always contain
   1188 	 * port numbers so rmconf is not needed */
   1189 	if (copy_ph1addresses(iph1, NULL, remote, local) < 0) {
   1190 		delph1(iph1);
   1191 		return -1;
   1192 	}
   1193 	(void)insph1(iph1);
   1194 
   1195 	plog(LLV_DEBUG, LOCATION, NULL, "===\n");
   1196     {
   1197 	char *a;
   1198 
   1199 	a = racoon_strdup(saddr2str(iph1->local));
   1200 	STRDUP_FATAL(a);
   1201 
   1202 	plog(LLV_INFO, LOCATION, NULL,
   1203 		"respond new phase 1 negotiation: %s<=>%s\n",
   1204 		a, saddr2str(iph1->remote));
   1205 	racoon_free(a);
   1206     }
   1207 	plog(LLV_INFO, LOCATION, NULL,
   1208 		"begin %s mode.\n", s_isakmp_etype(etype));
   1209 
   1210 #ifdef ENABLE_STATS
   1211 	gettimeofday(&iph1->start, NULL);
   1212 	gettimeofday(&start, NULL);
   1213 #endif
   1214 
   1215 #ifndef ENABLE_FRAG
   1216 
   1217 	/* start exchange */
   1218 	if ((ph1exchange[etypesw1(iph1->etype)]
   1219 	                [iph1->side]
   1220 	                [iph1->status])(iph1, msg) < 0
   1221 	 || (ph1exchange[etypesw1(iph1->etype)]
   1222 			[iph1->side]
   1223 			[iph1->status])(iph1, msg) < 0) {
   1224 		plog(LLV_ERROR, LOCATION, remote,
   1225 			"failed to process ph1 packet (side: %d, status: %d).\n",
   1226 			iph1->side, iph1->status);
   1227 		remph1(iph1);
   1228 		delph1(iph1);
   1229 		return -1;
   1230 	}
   1231 
   1232 #ifdef ENABLE_STATS
   1233 	gettimeofday(&end, NULL);
   1234 	syslog(LOG_NOTICE, "%s(%s): %8.6f",
   1235 		"phase1",
   1236 		s_isakmp_state(iph1->etype, iph1->side, iph1->status),
   1237 		timedelta(&start, &end));
   1238 #endif
   1239 
   1240 	return 0;
   1241 
   1242 #else /* ENABLE_FRAG */
   1243 
   1244 	/* now that we have a phase1 handle, feed back into our
   1245 	 * main receive function to catch fragmented packets
   1246 	 */
   1247 
   1248 	return isakmp_main(msg, remote, local);
   1249 
   1250 #endif /* ENABLE_FRAG */
   1251 
   1252 }
   1253 
   1254 /* new negotiation of phase 2 for initiator */
   1255 static int
   1256 isakmp_ph2begin_i(struct ph1handle *iph1, struct ph2handle *iph2)
   1257 {
   1258 #ifdef ENABLE_HYBRID
   1259 	if (xauth_check(iph1) != 0) {
   1260 		plog(LLV_ERROR, LOCATION, NULL,
   1261 		    "Attempt to start phase 2 whereas Xauth failed\n");
   1262 		return -1;
   1263 	}
   1264 #endif
   1265 
   1266 	/* fixup ph2 ports for this ph1 */
   1267 	if (extract_port(iph2->src) == 0)
   1268 		set_port(iph2->src, extract_port(iph1->local));
   1269 	if (extract_port(iph2->dst) == 0)
   1270 		set_port(iph2->dst, extract_port(iph1->remote));
   1271 
   1272 	/* found ISAKMP-SA. */
   1273 	plog(LLV_DEBUG, LOCATION, NULL, "===\n");
   1274 	plog(LLV_DEBUG, LOCATION, NULL, "begin QUICK mode.\n");
   1275     {
   1276 	char *a;
   1277 	a = racoon_strdup(saddr2str(iph2->src));
   1278 	STRDUP_FATAL(a);
   1279 
   1280 	plog(LLV_INFO, LOCATION, NULL,
   1281 		"initiate new phase 2 negotiation: %s<=>%s\n",
   1282 		a, saddr2str(iph2->dst));
   1283 	racoon_free(a);
   1284     }
   1285 
   1286 #ifdef ENABLE_STATS
   1287 	gettimeofday(&iph2->start, NULL);
   1288 #endif
   1289 	if (iph2->status != PHASE2ST_EXPIRED) /* Phase 1 is already bound (ongoing rekeying) */
   1290 		bindph12(iph1, iph2);
   1291 	iph2->status = PHASE2ST_STATUS2;
   1292 
   1293 	if ((ph2exchange[etypesw2(ISAKMP_ETYPE_QUICK)]
   1294 			 [iph2->side]
   1295 			 [iph2->status])(iph2, NULL) < 0) {
   1296 		/* release ipsecsa handler due to internal error. */
   1297 		remph2(iph2);
   1298 		return -1;
   1299 	}
   1300 	return 0;
   1301 }
   1302 
   1303 /* new negotiation of phase 2 for responder */
   1304 static int
   1305 isakmp_ph2begin_r(struct ph1handle *iph1, vchar_t *msg)
   1306 {
   1307 	struct isakmp *isakmp = (struct isakmp *)msg->v;
   1308 	struct ph2handle *iph2 = 0;
   1309 	int error;
   1310 #ifdef ENABLE_STATS
   1311 	struct timeval start, end;
   1312 #endif
   1313 #ifdef ENABLE_HYBRID
   1314 	if (xauth_check(iph1) != 0) {
   1315 		plog(LLV_ERROR, LOCATION, NULL,
   1316 		    "Attempt to start phase 2 whereas Xauth failed\n");
   1317 		return -1;
   1318 	}
   1319 #endif
   1320 
   1321 	iph2 = newph2();
   1322 	if (iph2 == NULL) {
   1323 		plog(LLV_ERROR, LOCATION, NULL,
   1324 			"failed to allocate phase2 entry.\n");
   1325 		return -1;
   1326 	}
   1327 
   1328 	iph2->side = RESPONDER;
   1329 	iph2->status = PHASE2ST_START;
   1330 	iph2->flags = isakmp->flags;
   1331 	iph2->msgid = isakmp->msgid;
   1332 	iph2->seq = pk_getseq();
   1333 	iph2->ivm = oakley_newiv2(iph1, iph2->msgid);
   1334 	if (iph2->ivm == NULL) {
   1335 		delph2(iph2);
   1336 		return -1;
   1337 	}
   1338 	iph2->dst = dupsaddr(iph1->remote);	/* XXX should be considered */
   1339 	if (iph2->dst == NULL) {
   1340 		delph2(iph2);
   1341 		return -1;
   1342 	}
   1343 	iph2->src = dupsaddr(iph1->local);	/* XXX should be considered */
   1344 	if (iph2->src == NULL) {
   1345 		delph2(iph2);
   1346 		return -1;
   1347 	}
   1348 
   1349 	/* add new entry to isakmp status table */
   1350 	insph2(iph2);
   1351 	bindph12(iph1, iph2);
   1352 
   1353 	plog(LLV_DEBUG, LOCATION, NULL, "===\n");
   1354     {
   1355 	char *a;
   1356 
   1357 	a = racoon_strdup(saddr2str(iph2->src));
   1358 	STRDUP_FATAL(a);
   1359 
   1360 	plog(LLV_INFO, LOCATION, NULL,
   1361 		"respond new phase 2 negotiation: %s<=>%s\n",
   1362 		a, saddr2str(iph2->dst));
   1363 	racoon_free(a);
   1364     }
   1365 
   1366 #ifdef ENABLE_STATS
   1367 	gettimeofday(&start, NULL);
   1368 #endif
   1369 
   1370 	error = (ph2exchange[etypesw2(ISAKMP_ETYPE_QUICK)]
   1371 	                   [iph2->side]
   1372 	                   [iph2->status])(iph2, msg);
   1373 	if (error != 0) {
   1374 		plog(LLV_ERROR, LOCATION, iph1->remote,
   1375 			"failed to pre-process ph2 packet (side: %d, status: %d).\n",
   1376 			iph2->side, iph2->status);
   1377 		if (error != ISAKMP_INTERNAL_ERROR)
   1378 			isakmp_info_send_n1(iph2->ph1, error, NULL);
   1379 		/*
   1380 		 * release handler because it's wrong that ph2handle is kept
   1381 		 * after failed to check message for responder's.
   1382 		 */
   1383 		remph2(iph2);
   1384 		delph2(iph2);
   1385 		return -1;
   1386 	}
   1387 
   1388 	/* send */
   1389 	plog(LLV_DEBUG, LOCATION, NULL, "===\n");
   1390 	if ((ph2exchange[etypesw2(isakmp->etype)]
   1391 			[iph2->side]
   1392 			[iph2->status])(iph2, msg) < 0) {
   1393 		plog(LLV_ERROR, LOCATION, iph2->ph1->remote,
   1394 			"failed to process ph2 packet (side: %d, status: %d).\n",
   1395 			iph2->side, iph2->status);
   1396 		/* don't release handler */
   1397 		return -1;
   1398 	}
   1399 #ifdef ENABLE_STATS
   1400 	gettimeofday(&end, NULL);
   1401 	syslog(LOG_NOTICE, "%s(%s): %8.6f",
   1402 		"phase2",
   1403 		s_isakmp_state(ISAKMP_ETYPE_QUICK, iph2->side, iph2->status),
   1404 		timedelta(&start, &end));
   1405 #endif
   1406 
   1407 	return 0;
   1408 }
   1409 
   1410 /*
   1411  * parse ISAKMP payloads, without ISAKMP base header.
   1412  */
   1413 vchar_t *
   1414 isakmp_parsewoh(int np0, struct isakmp_gen *gen, int len)
   1415 {
   1416 	u_char np = np0 & 0xff;
   1417 	int tlen, plen;
   1418 	vchar_t *result;
   1419 	struct isakmp_parse_t *p, *ep;
   1420 
   1421 	plog(LLV_DEBUG, LOCATION, NULL, "begin.\n");
   1422 
   1423 	/*
   1424 	 * 5 is a magic number, but any value larger than 2 should be fine
   1425 	 * as we do vrealloc() in the following loop.
   1426 	 */
   1427 	result = vmalloc(sizeof(struct isakmp_parse_t) * 5);
   1428 	if (result == NULL) {
   1429 		plog(LLV_ERROR, LOCATION, NULL,
   1430 			"failed to get buffer.\n");
   1431 		return NULL;
   1432 	}
   1433 	p = (struct isakmp_parse_t *)result->v;
   1434 	ep = (struct isakmp_parse_t *)(result->v + result->l - sizeof(*ep));
   1435 
   1436 	tlen = len;
   1437 
   1438 	/* parse through general headers */
   1439 	while (0 < tlen && np != ISAKMP_NPTYPE_NONE) {
   1440 		if (tlen <= sizeof(struct isakmp_gen)) {
   1441 			/* don't send information, see isakmp_ident_r1() */
   1442 			plog(LLV_ERROR, LOCATION, NULL,
   1443 				"invalid length of payload\n");
   1444 			vfree(result);
   1445 			return NULL;
   1446 		}
   1447 
   1448 		plog(LLV_DEBUG, LOCATION, NULL,
   1449 			"seen nptype=%u(%s)\n", np, s_isakmp_nptype(np));
   1450 
   1451 		p->type = np;
   1452 		p->len = ntohs(gen->len);
   1453 		if (p->len < sizeof(struct isakmp_gen) || p->len > tlen) {
   1454 			plog(LLV_DEBUG, LOCATION, NULL,
   1455 				"invalid length of payload\n");
   1456 			vfree(result);
   1457 			return NULL;
   1458 		}
   1459 		p->ptr = gen;
   1460 		p++;
   1461 		if (ep <= p) {
   1462 			off_t off;
   1463 
   1464 			off = p - (struct isakmp_parse_t *)result->v;
   1465 			result = vrealloc(result, result->l * 2);
   1466 			if (result == NULL) {
   1467 				plog(LLV_DEBUG, LOCATION, NULL,
   1468 					"failed to realloc buffer.\n");
   1469 				vfree(result);
   1470 				return NULL;
   1471 			}
   1472 			ep = (struct isakmp_parse_t *)
   1473 				(result->v + result->l - sizeof(*ep));
   1474 			p = (struct isakmp_parse_t *)result->v;
   1475 			p += off;
   1476 		}
   1477 
   1478 		np = gen->np;
   1479 		plen = ntohs(gen->len);
   1480 		gen = (struct isakmp_gen *)((caddr_t)gen + plen);
   1481 		tlen -= plen;
   1482 	}
   1483 	p->type = ISAKMP_NPTYPE_NONE;
   1484 	p->len = 0;
   1485 	p->ptr = NULL;
   1486 
   1487 	plog(LLV_DEBUG, LOCATION, NULL, "succeed.\n");
   1488 
   1489 	return result;
   1490 }
   1491 
   1492 /*
   1493  * parse ISAKMP payloads, including ISAKMP base header.
   1494  */
   1495 vchar_t *
   1496 isakmp_parse(vchar_t *buf)
   1497 {
   1498 	struct isakmp *isakmp = (struct isakmp *)buf->v;
   1499 	struct isakmp_gen *gen;
   1500 	size_t tlen;
   1501 	vchar_t *result;
   1502 	u_char np;
   1503 
   1504 	np = isakmp->np;
   1505 	gen = (struct isakmp_gen *)(buf->v + sizeof(*isakmp));
   1506 	tlen = buf->l - sizeof(struct isakmp);
   1507 	result = isakmp_parsewoh(np, gen, tlen);
   1508 
   1509 	return result;
   1510 }
   1511 
   1512 /* %%% */
   1513 int
   1514 isakmp_init()
   1515 {
   1516 	/* initialize a isakmp status table */
   1517 	initph1tree();
   1518 	initph2tree();
   1519 	initctdtree();
   1520 	init_recvdpkt();
   1521 
   1522 	return 0;
   1523 }
   1524 
   1525 /*
   1526  * make strings containing i_cookie + r_cookie + msgid
   1527  */
   1528 const char *
   1529 isakmp_pindex(const isakmp_index *index1, const uint32_t msgid)
   1530 {
   1531 	static char buf[64];
   1532 	const u_char *p;
   1533 	int i, j;
   1534 
   1535 	memset(buf, 0, sizeof(buf));
   1536 
   1537 	/* copy index */
   1538 	p = (const u_char *)index1;
   1539 	for (j = 0, i = 0; i < sizeof(isakmp_index); i++) {
   1540 		snprintf((char *)&buf[j], sizeof(buf) - j, "%02x", p[i]);
   1541 		j += 2;
   1542 		switch (i) {
   1543 		case 7:
   1544 			buf[j++] = ':';
   1545 		}
   1546 	}
   1547 
   1548 	if (msgid == 0)
   1549 		return buf;
   1550 
   1551 	/* copy msgid */
   1552 	snprintf((char *)&buf[j], sizeof(buf) - j, ":%08x", ntohs(msgid));
   1553 
   1554 	return buf;
   1555 }
   1556 
   1557 /* open ISAKMP sockets. */
   1558 int
   1559 isakmp_open(struct sockaddr *addr, int udp_encap)
   1560 {
   1561 	const int yes = 1;
   1562 	int fd;
   1563 	struct sockaddr_in *sin = (struct sockaddr_in *) addr;
   1564 #ifdef INET6
   1565 	struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) addr;
   1566 	int pktinfo;
   1567 #endif
   1568 #ifdef ENABLE_NATT
   1569 	int option = -1;
   1570 #endif
   1571 
   1572 	/* warn if wildcard address - should we forbid this? */
   1573 	switch (addr->sa_family) {
   1574 	case AF_INET:
   1575 		if (sin->sin_addr.s_addr == 0)
   1576 			plog(LLV_WARNING, LOCATION, NULL,
   1577 			     "listening to wildcard address,"
   1578 			     "broadcast IKE packet may kill you\n");
   1579 		break;
   1580 #ifdef INET6
   1581 	case AF_INET6:
   1582 		if (IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr)) {
   1583 			plog(LLV_DEBUG, LOCATION, NULL,
   1584 			     "ignoring multicast address %s\n",
   1585 			     saddr2str(addr));
   1586 			return -1;
   1587 		}
   1588 
   1589 		if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr))
   1590 			plog(LLV_WARNING, LOCATION, NULL,
   1591 			     "listening to wildcard address, "
   1592 			     "broadcast IKE packet may kill you\n");
   1593 		break;
   1594 #endif
   1595 	default:
   1596 		plog(LLV_ERROR, LOCATION, NULL,
   1597 		     "unsupported address family %d\n",
   1598 		     addr->sa_family);
   1599 		return -1;
   1600 	}
   1601 
   1602 	if ((fd = privsep_socket(addr->sa_family, SOCK_DGRAM, 0)) < 0) {
   1603 		plog(LLV_ERROR, LOCATION, NULL,
   1604 		     "socket(%s)\n", strerror(errno));
   1605 		return -1;
   1606 	}
   1607 	close_on_exec(fd);
   1608 	if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1)
   1609 		plog(LLV_WARNING, LOCATION, NULL,
   1610 		     "failed to put socket in non-blocking mode\n");
   1611 
   1612 	/* receive my interface address on inbound packets. */
   1613 	switch (addr->sa_family) {
   1614 	case AF_INET:
   1615 		if (setsockopt(fd, IPPROTO_IP,
   1616 #ifdef __linux__
   1617 			       IP_PKTINFO,
   1618 #else
   1619 			       IP_RECVDSTADDR,
   1620 #endif
   1621 			       (const void *) &yes, sizeof(yes)) < 0) {
   1622 			plog(LLV_ERROR, LOCATION, NULL,
   1623 			     "setsockopt IP_RECVDSTADDR (%s)\n",
   1624 			     strerror(errno));
   1625 			goto err;
   1626 		}
   1627 
   1628 #ifdef ENABLE_NATT
   1629 		if (udp_encap)
   1630 			option = UDP_ENCAP_ESPINUDP;
   1631 #if defined(ENABLE_NATT_00) || defined(ENABLE_NATT_01)
   1632 		else
   1633 			option = UDP_ENCAP_ESPINUDP_NON_IKE;
   1634 #endif
   1635 		if (option == -1)
   1636 			break;
   1637 
   1638 		if (setsockopt(fd, SOL_UDP,
   1639 			       UDP_ENCAP, &option,
   1640 			       sizeof(option)) < 0) {
   1641 			plog(LLV_WARNING, LOCATION, NULL,
   1642 			     "setsockopt(%s): UDP_ENCAP %s\n",
   1643 			     option == UDP_ENCAP_ESPINUDP ? "UDP_ENCAP_ESPINUDP" : "UDP_ENCAP_ESPINUDP_NON_IKE",
   1644 			     strerror(errno));
   1645 		} else {
   1646 			plog(LLV_INFO, LOCATION, NULL,
   1647 			     "%s used for NAT-T\n",
   1648 			     saddr2str(addr));
   1649 		}
   1650 #endif
   1651 		break;
   1652 
   1653 #ifdef INET6
   1654 	case AF_INET6:
   1655 #if defined(INET6_ADVAPI)
   1656 #ifdef IPV6_RECVPKTINFO
   1657 		pktinfo = IPV6_RECVPKTINFO;
   1658 #else  /* old adv. API */
   1659 		pktinfo = IPV6_PKTINFO;
   1660 #endif /* IPV6_RECVPKTINFO */
   1661 #else
   1662 		pktinfo = IPV6_RECVDSTADDR;
   1663 #endif
   1664 		if (setsockopt(fd, IPPROTO_IPV6, pktinfo,
   1665 			       &yes, sizeof(yes)) < 0) {
   1666 			plog(LLV_ERROR, LOCATION, NULL,
   1667 			     "setsockopt IPV6_RECVDSTADDR (%d):%s\n",
   1668 			     pktinfo, strerror(errno));
   1669 			goto err;
   1670 		}
   1671 
   1672 #ifdef IPV6_USE_MIN_MTU
   1673 		if (setsockopt(fd, IPPROTO_IPV6, IPV6_USE_MIN_MTU,
   1674 			       &yes, sizeof(yes)) < 0) {
   1675 			plog(LLV_ERROR, LOCATION, NULL,
   1676 			     "setsockopt IPV6_USE_MIN_MTU (%s)\n",
   1677 			     strerror(errno));
   1678 			goto err;
   1679 		}
   1680 #endif
   1681 		break;
   1682 #endif
   1683 	}
   1684 
   1685 	if (setsockopt(fd, SOL_SOCKET,
   1686 #ifdef __linux__
   1687 		       SO_REUSEADDR,
   1688 #else
   1689 		       SO_REUSEPORT,
   1690 #endif
   1691 		       &yes, sizeof(yes)) < 0) {
   1692 		plog(LLV_ERROR, LOCATION, NULL,
   1693 		     "failed to set REUSE flag on %s (%s).\n",
   1694 		     saddr2str(addr), strerror(errno));
   1695 		goto err;
   1696 	}
   1697 
   1698 	if (setsockopt_bypass(fd, addr->sa_family) < 0)
   1699 		goto err;
   1700 
   1701 	if (privsep_bind(fd, addr, sysdep_sa_len(addr)) < 0) {
   1702 		plog(LLV_ERROR, LOCATION, addr,
   1703 		     "failed to bind to address %s (%s).\n",
   1704 		     saddr2str(addr), strerror(errno));
   1705 		goto err;
   1706 	}
   1707 
   1708 	plog(LLV_INFO, LOCATION, NULL,
   1709 	     "%s used as isakmp port (fd=%d)\n",
   1710 	     saddr2str(addr), fd);
   1711 
   1712 	monitor_fd(fd, isakmp_handler, NULL, 1);
   1713 	return fd;
   1714 
   1715 err:
   1716 	close(fd);
   1717 	return -1;
   1718 }
   1719 
   1720 void
   1721 isakmp_close(int fd)
   1722 {
   1723 	unmonitor_fd(fd);
   1724 	close(fd);
   1725 }
   1726 
   1727 int
   1728 isakmp_send(struct ph1handle *iph1, vchar_t *sbuf)
   1729 {
   1730 	int len = 0;
   1731 	int s;
   1732 	vchar_t *vbuf = NULL, swap;
   1733 
   1734 #ifdef ENABLE_NATT
   1735 	size_t extralen = NON_ESP_MARKER_USE(iph1) ? NON_ESP_MARKER_LEN : 0;
   1736 
   1737 	/* Check if NON_ESP_MARKER_LEN is already there (happens when resending packets)
   1738 	 */
   1739 	if(extralen == NON_ESP_MARKER_LEN &&
   1740 	   *(uint32_t *)sbuf->v == 0)
   1741 		extralen = 0;
   1742 
   1743 #ifdef ENABLE_FRAG
   1744 	/*
   1745 	 * Do not add the non ESP marker for a packet that will
   1746 	 * be fragmented. The non ESP marker should appear in
   1747 	 * all fragment's packets, but not in the fragmented packet
   1748 	 */
   1749 	if (iph1->frag && sbuf->l > ISAKMP_FRAG_MAXLEN)
   1750 		extralen = 0;
   1751 #endif
   1752 	if (extralen)
   1753 		plog (LLV_DEBUG, LOCATION, NULL, "Adding NON-ESP marker\n");
   1754 
   1755 	/* If NAT-T port floating is in use, 4 zero bytes (non-ESP marker)
   1756 	   must added just before the packet itself. For this we must
   1757 	   allocate a new buffer and release it at the end. */
   1758 	if (extralen) {
   1759 		if ((vbuf = vmalloc (sbuf->l + extralen)) == NULL) {
   1760 			plog(LLV_ERROR, LOCATION, NULL,
   1761 			    "vbuf allocation failed\n");
   1762 			return -1;
   1763 		}
   1764 		*(uint32_t *)vbuf->v = 0;
   1765 		memcpy (vbuf->v + extralen, sbuf->v, sbuf->l);
   1766 		/* ensures that the modified buffer will be sent back to the caller, so
   1767 		 * add_recvdpkt() will add the correct buffer
   1768 		 */
   1769 		swap = *sbuf;
   1770 		*sbuf = *vbuf;
   1771 		*vbuf = swap;
   1772 		vfree(vbuf);
   1773 	}
   1774 #endif
   1775 
   1776 	/* select the socket to be sent */
   1777 	s = myaddr_getfd(iph1->local);
   1778 	if (s == -1)
   1779 		return -1;
   1780 
   1781 	plog (LLV_DEBUG, LOCATION, NULL, "%zu bytes %s\n", sbuf->l,
   1782 	      saddr2str_fromto("from %s to %s", iph1->local, iph1->remote));
   1783 
   1784 #ifdef ENABLE_FRAG
   1785 	if (iph1->frag && sbuf->l > ISAKMP_FRAG_MAXLEN) {
   1786 		if (isakmp_sendfrags(iph1, sbuf) == -1) {
   1787 			plog(LLV_ERROR, LOCATION, NULL,
   1788 			    "isakmp_sendfrags failed\n");
   1789 			return -1;
   1790 		}
   1791 	} else
   1792 #endif
   1793 	{
   1794 		len = sendfromto(s, sbuf->v, sbuf->l,
   1795 		    iph1->local, iph1->remote, lcconf->count_persend);
   1796 
   1797 		if (len == -1) {
   1798 			plog(LLV_ERROR, LOCATION, NULL, "sendfromto failed\n");
   1799 			return -1;
   1800 		}
   1801 	}
   1802 
   1803 	return 0;
   1804 }
   1805 
   1806 /* called from scheduler */
   1807 static void
   1808 isakmp_ph1resend_stub(struct sched *p)
   1809 {
   1810 	struct ph1handle *iph1 = container_of(p, struct ph1handle, scr);
   1811 
   1812 	if (isakmp_ph1resend(iph1) < 0) {
   1813 		remph1(iph1);
   1814 		delph1(iph1);
   1815 	}
   1816 }
   1817 
   1818 static int
   1819 isakmp_ph1resend(struct ph1handle *iph1)
   1820 {
   1821 	/* Note: NEVER do the rem/del here, it will be done by the caller or by the _stub function
   1822 	 */
   1823 	if (iph1->retry_counter <= 0) {
   1824 		plog(LLV_ERROR, LOCATION, NULL,
   1825 			"phase1 negotiation failed due to time up. %s\n",
   1826 			isakmp_pindex(&iph1->index, iph1->msgid));
   1827 		/* XXX is the peer really "dead" here ??? */
   1828 		script_hook(iph1, SCRIPT_PHASE1_DEAD);
   1829 		evt_phase1(iph1, EVT_PHASE1_NO_RESPONSE, NULL);
   1830 
   1831 		return -1;
   1832 	}
   1833 
   1834 	if (isakmp_send(iph1, iph1->sendbuf) < 0){
   1835 		plog(LLV_ERROR, LOCATION, NULL,
   1836 			 "phase1 negotiation failed due to send error. %s\n",
   1837 			 isakmp_pindex(&iph1->index, iph1->msgid));
   1838 		evt_phase1(iph1, EVT_PHASE1_NO_RESPONSE, NULL);
   1839 		return -1;
   1840 	}
   1841 
   1842 	plog(LLV_DEBUG, LOCATION, NULL,
   1843 		"resend phase1 packet %s\n",
   1844 		isakmp_pindex(&iph1->index, iph1->msgid));
   1845 
   1846 	iph1->retry_counter--;
   1847 
   1848 	sched_schedule(&iph1->scr, lcconf->retry_interval,
   1849 		       isakmp_ph1resend_stub);
   1850 
   1851 	return 0;
   1852 }
   1853 
   1854 int
   1855 isakmp_ph1send(struct ph1handle *iph1)
   1856 {
   1857 	iph1->retry_counter = lcconf->retry_counter;
   1858 	return isakmp_ph1resend(iph1);
   1859 }
   1860 
   1861 /* called from scheduler */
   1862 static void
   1863 isakmp_ph2resend_stub(struct sched *p)
   1864 {
   1865 	struct ph2handle *iph2 = container_of(p, struct ph2handle, scr);
   1866 
   1867 	if (isakmp_ph2resend(iph2) < 0) {
   1868 		remph2(iph2);
   1869 		delph2(iph2);
   1870 	}
   1871 }
   1872 
   1873 static int
   1874 isakmp_ph2resend(struct ph2handle *iph2)
   1875 {
   1876 	/* Note: NEVER do the unbind/rem/del here, it will be done by the caller or by the _stub function
   1877 	 */
   1878 	if (iph2->ph1->status >= PHASE1ST_EXPIRED) {
   1879 		plog(LLV_ERROR, LOCATION, NULL,
   1880 			"phase2 negotiation failed due to phase1 expired. %s\n",
   1881 				isakmp_pindex(&iph2->ph1->index, iph2->msgid));
   1882 		return -1;
   1883 	}
   1884 
   1885 	if (iph2->retry_counter <= 0) {
   1886 		plog(LLV_ERROR, LOCATION, NULL,
   1887 			"phase2 negotiation failed due to time up. %s\n",
   1888 				isakmp_pindex(&iph2->ph1->index, iph2->msgid));
   1889 		evt_phase2(iph2, EVT_PHASE2_NO_RESPONSE, NULL);
   1890 		unbindph12(iph2);
   1891 		return -1;
   1892 	}
   1893 
   1894 	if (isakmp_send(iph2->ph1, iph2->sendbuf) < 0){
   1895 		plog(LLV_ERROR, LOCATION, NULL,
   1896 			"phase2 negotiation failed due to send error. %s\n",
   1897 				isakmp_pindex(&iph2->ph1->index, iph2->msgid));
   1898 		evt_phase2(iph2, EVT_PHASE2_NO_RESPONSE, NULL);
   1899 		return -1;
   1900 	}
   1901 
   1902 	plog(LLV_DEBUG, LOCATION, NULL,
   1903 		"resend phase2 packet %s\n",
   1904 		isakmp_pindex(&iph2->ph1->index, iph2->msgid));
   1905 
   1906 	iph2->retry_counter--;
   1907 
   1908 	sched_schedule(&iph2->scr, lcconf->retry_interval,
   1909 		       isakmp_ph2resend_stub);
   1910 
   1911 	return 0;
   1912 }
   1913 
   1914 int
   1915 isakmp_ph2send(struct ph2handle *iph2)
   1916 {
   1917 	iph2->retry_counter = lcconf->retry_counter;
   1918 	return isakmp_ph2resend(iph2);
   1919 }
   1920 
   1921 /* called from scheduler */
   1922 void
   1923 isakmp_ph1dying_stub(struct sched *p)
   1924 {
   1925 
   1926 	isakmp_ph1dying(container_of(p, struct ph1handle, sce));
   1927 }
   1928 
   1929 void
   1930 isakmp_ph1dying(struct ph1handle *iph1)
   1931 {
   1932 	struct ph1handle *new_iph1;
   1933 	struct ph2handle *p;
   1934 
   1935 	if (iph1->status >= PHASE1ST_DYING)
   1936 		return;
   1937 
   1938 	/* Going away in after a while... */
   1939 	iph1->status = PHASE1ST_DYING;
   1940 
   1941 	/* Any fresh phase1s? */
   1942 	new_iph1 = getph1(iph1, iph1->local, iph1->remote, 1);
   1943 	if (new_iph1 == NULL) {
   1944 		LIST_FOREACH(p, &iph1->ph2tree, ph1bind) {
   1945 			if (p->status != PHASE2ST_ESTABLISHED)
   1946 				continue;
   1947 
   1948 			plog(LLV_INFO, LOCATION, NULL,
   1949 			     "renegotiating phase1 to %s due to "
   1950 			     "active phase2\n",
   1951 			     saddrwop2str(iph1->remote));
   1952 
   1953 			if (iph1->side == INITIATOR)
   1954 				isakmp_ph1begin_i(iph1->rmconf, iph1->remote,
   1955 						  iph1->local);
   1956 
   1957 			break;
   1958 		}
   1959 	} else {
   1960 		migrate_ph12(iph1, new_iph1);
   1961 	}
   1962 
   1963 	/* Schedule for expiration */
   1964 	sched_schedule(&iph1->sce, iph1->approval->lifetime *
   1965 		       (100 - PFKEY_SOFT_LIFETIME_RATE) / 100,
   1966 		       isakmp_ph1expire_stub);
   1967 }
   1968 
   1969 /* called from scheduler */
   1970 void
   1971 isakmp_ph1expire_stub(struct sched *p)
   1972 {
   1973 	isakmp_ph1expire(container_of(p, struct ph1handle, sce));
   1974 }
   1975 
   1976 void
   1977 isakmp_ph1expire(struct ph1handle *iph1)
   1978 {
   1979 	char *src, *dst;
   1980 
   1981 	if (iph1->status < PHASE1ST_EXPIRED) {
   1982 		src = racoon_strdup(saddr2str(iph1->local));
   1983 		dst = racoon_strdup(saddr2str(iph1->remote));
   1984 		STRDUP_FATAL(src);
   1985 		STRDUP_FATAL(dst);
   1986 
   1987 		plog(LLV_INFO, LOCATION, NULL,
   1988 			 "ISAKMP-SA expired %s-%s spi:%s\n",
   1989 			 src, dst,
   1990 			 isakmp_pindex(&iph1->index, 0));
   1991 		racoon_free(src);
   1992 		racoon_free(dst);
   1993 		iph1->status = PHASE1ST_EXPIRED;
   1994 	}
   1995 
   1996 	isakmp_ph1delete(iph1);
   1997 }
   1998 
   1999 /* called from scheduler */
   2000 void
   2001 isakmp_ph1delete_stub(struct sched *p)
   2002 {
   2003 
   2004 	isakmp_ph1delete(container_of(p, struct ph1handle, sce));
   2005 }
   2006 
   2007 void
   2008 isakmp_ph1delete(struct ph1handle *iph1)
   2009 {
   2010 	struct ph2handle *p, *next;
   2011 	struct ph1handle *new_iph1;
   2012 	char *src, *dst;
   2013 
   2014 	/* Migrate established phase2s. Any fresh phase1s? */
   2015 	new_iph1 = getph1(iph1, iph1->local, iph1->remote, 1);
   2016 	if (new_iph1 != NULL)
   2017 		migrate_ph12(iph1, new_iph1);
   2018 
   2019 	/* Discard any left phase2s */
   2020 	for (p = LIST_FIRST(&iph1->ph2tree); p; p = next) {
   2021 		next = LIST_NEXT(p, ph1bind);
   2022 		if (p->status == PHASE2ST_ESTABLISHED)
   2023 			isakmp_info_send_d2(p);
   2024 		/* remove all ph2 handles,
   2025 		 * as ph1handle will be expired soon
   2026 		 */
   2027 		delete_spd(p, 1);
   2028 		remph2(p);
   2029 		delph2(p);
   2030 	}
   2031 
   2032 	src = racoon_strdup(saddr2str(iph1->local));
   2033 	dst = racoon_strdup(saddr2str(iph1->remote));
   2034 	STRDUP_FATAL(src);
   2035 	STRDUP_FATAL(dst);
   2036 
   2037 	plog(LLV_INFO, LOCATION, NULL,
   2038 		"ISAKMP-SA deleted %s-%s spi:%s\n",
   2039 		src, dst, isakmp_pindex(&iph1->index, 0));
   2040 
   2041 	evt_phase1(iph1, EVT_PHASE1_DOWN, NULL);
   2042 	if (new_iph1 == NULL && ph1_rekey_enabled(iph1))
   2043 		script_hook(iph1, SCRIPT_PHASE1_DEAD);
   2044 
   2045 	racoon_free(src);
   2046 	racoon_free(dst);
   2047 
   2048 	remph1(iph1);
   2049 	delph1(iph1);
   2050 }
   2051 
   2052 /* called from scheduler.
   2053  * this function will call only isakmp_ph2delete().
   2054  * phase 2 handler remain forever if kernel doesn't cry a expire of phase 2 SA
   2055  * by something cause.  That's why this function is called after phase 2 SA
   2056  * expires in the userland.
   2057  */
   2058 void
   2059 isakmp_ph2expire_stub(struct sched *p)
   2060 {
   2061 
   2062 	isakmp_ph2expire(container_of(p, struct ph2handle, sce));
   2063 }
   2064 
   2065 void
   2066 isakmp_ph2expire(struct ph2handle *iph2)
   2067 {
   2068 	char *src, *dst;
   2069 
   2070 	src = racoon_strdup(saddrwop2str(iph2->src));
   2071 	dst = racoon_strdup(saddrwop2str(iph2->dst));
   2072 	STRDUP_FATAL(src);
   2073 	STRDUP_FATAL(dst);
   2074 
   2075 	plog(LLV_INFO, LOCATION, NULL,
   2076 		"phase2 sa expired %s-%s\n", src, dst);
   2077 	racoon_free(src);
   2078 	racoon_free(dst);
   2079 
   2080 	iph2->status = PHASE2ST_EXPIRED;
   2081 	sched_schedule(&iph2->sce, 1, isakmp_ph2delete_stub);
   2082 }
   2083 
   2084 /* called from scheduler */
   2085 void
   2086 isakmp_ph2delete_stub(struct sched *p)
   2087 {
   2088 
   2089 	isakmp_ph2delete(container_of(p, struct ph2handle, sce));
   2090 }
   2091 
   2092 void
   2093 isakmp_ph2delete(struct ph2handle *iph2)
   2094 {
   2095 	char *src, *dst;
   2096 
   2097 	src = racoon_strdup(saddrwop2str(iph2->src));
   2098 	dst = racoon_strdup(saddrwop2str(iph2->dst));
   2099 	STRDUP_FATAL(src);
   2100 	STRDUP_FATAL(dst);
   2101 
   2102 	plog(LLV_INFO, LOCATION, NULL,
   2103 		"phase2 sa deleted %s-%s\n", src, dst);
   2104 	racoon_free(src);
   2105 	racoon_free(dst);
   2106 
   2107 	remph2(iph2);
   2108 	delph2(iph2);
   2109 
   2110 	return;
   2111 }
   2112 
   2113 /* %%%
   2115  * Interface between PF_KEYv2 and ISAKMP
   2116  */
   2117 /*
   2118  * receive ACQUIRE from kernel, and begin either phase1 or phase2.
   2119  * if phase1 has been finished, begin phase2.
   2120  */
   2121 int
   2122 isakmp_post_acquire(struct ph2handle *iph2, struct ph1handle *iph1hint,
   2123     int nopassive)
   2124 {
   2125 	struct remoteconf *rmconf;
   2126 	struct ph1handle *iph1 = NULL;
   2127 
   2128 	plog(LLV_DEBUG, LOCATION, NULL, "in post_acquire\n");
   2129 
   2130 	/* Search appropriate configuration with masking port. Note that
   2131 	 * we always use iph2->dst, and not iph2->sa_dst.
   2132 	 *
   2133 	 * XXX One possible need for using iph2->sa_dst if not NULL would
   2134 	 * be for selecting a remote configuration based on a stable
   2135 	 * address of a mobile node (not a CoA provided by MIGRATE/KMADDRESS
   2136 	 * as iph2->dst hint). This scenario would require additional changes,
   2137 	 * so no need to bother yet. --arno */
   2138 
   2139 	if (iph1hint == NULL || iph1hint->rmconf == NULL) {
   2140 		rmconf = getrmconf(iph2->dst, nopassive ? GETRMCONF_F_NO_PASSIVE : 0);
   2141 		if (rmconf == NULL) {
   2142 			plog(LLV_ERROR, LOCATION, NULL,
   2143 				"no configuration found for %s.\n",
   2144 				saddrwop2str(iph2->dst));
   2145 			return -1;
   2146 		}
   2147 	} else {
   2148 		rmconf = iph1hint->rmconf;
   2149 	}
   2150 
   2151 	/* if passive mode, ignore the acquire message */
   2152 	if (nopassive && rmconf->passive) {
   2153 		plog(LLV_DEBUG, LOCATION, NULL,
   2154 			"because of passive mode, "
   2155 			"ignore the acquire message for %s.\n",
   2156 			saddrwop2str(iph2->dst));
   2157 		return -1;
   2158 	}
   2159 
   2160 	/*
   2161 	 * XXX Searching by IP addresses + ports might fail on
   2162 	 * some cases, we should use the ISAKMP identity to search
   2163 	 * matching ISAKMP.
   2164 	 */
   2165 	iph1 = getph1(iph1hint, iph2->src, iph2->dst, 0);
   2166 
   2167 	/* no ISAKMP-SA found. */
   2168 	if (iph1 == NULL) {
   2169 		iph2->retry_checkph1 = lcconf->retry_checkph1;
   2170 		sched_schedule(&iph2->sce, 1, isakmp_chkph1there_stub);
   2171 		plog(LLV_INFO, LOCATION, NULL,
   2172 			"IPsec-SA request for %s queued "
   2173 			"due to no phase1 found.\n",
   2174 			saddrwop2str(iph2->dst));
   2175 
   2176 		/* start phase 1 negotiation as a initiator. */
   2177 		if (isakmp_ph1begin_i(rmconf, iph2->dst, iph2->src) == NULL) {
   2178 			sched_cancel(&iph2->sce);
   2179 			return -1;
   2180 		}
   2181 
   2182 		return 0;
   2183 		/*NOTREACHED*/
   2184 	}
   2185 
   2186 	/* found ISAKMP-SA, but on negotiation. */
   2187 	if (iph1->status < PHASE1ST_ESTABLISHED) {
   2188 		iph2->retry_checkph1 = lcconf->retry_checkph1;
   2189 		sched_schedule(&iph2->sce, 1, isakmp_chkph1there_stub);
   2190 		plog(LLV_INFO, LOCATION, iph2->dst,
   2191 			"request for establishing IPsec-SA was queued "
   2192 			"due to no phase1 found.\n");
   2193 		return 0;
   2194 		/*NOTREACHED*/
   2195 	}
   2196 
   2197 	/* found established ISAKMP-SA */
   2198 	/* i.e. iph1->status == PHASE1ST_ESTABLISHED */
   2199 
   2200 	/* found ISAKMP-SA. */
   2201 	plog(LLV_DEBUG, LOCATION, NULL, "begin QUICK mode.\n");
   2202 
   2203 	/* begin quick mode */
   2204 	if (isakmp_ph2begin_i(iph1, iph2))
   2205 		return -1;
   2206 
   2207 	return 0;
   2208 }
   2209 
   2210 int
   2211 isakmp_get_sainfo(struct ph2handle *iph2, struct secpolicy *sp_out,
   2212     struct secpolicy *sp_in)
   2213 {
   2214 	struct remoteconf *conf;
   2215 	uint32_t remoteid = 0;
   2216 
   2217 	plog(LLV_DEBUG, LOCATION, NULL,
   2218 		"new acquire %s\n", spidx2str(&sp_out->spidx));
   2219 
   2220 	/* get sainfo */
   2221 	{
   2222 		vchar_t *idsrc, *iddst;
   2223 
   2224 		idsrc = ipsecdoi_sockaddr2id((struct sockaddr *)&sp_out->spidx.src,
   2225 			sp_out->spidx.prefs, sp_out->spidx.ul_proto);
   2226 		if (idsrc == NULL) {
   2227 			plog(LLV_ERROR, LOCATION, NULL,
   2228 				"failed to get ID for %s\n",
   2229 				spidx2str(&sp_out->spidx));
   2230 			return -1;
   2231 		}
   2232 		iddst = ipsecdoi_sockaddr2id((struct sockaddr *)&sp_out->spidx.dst,
   2233 			sp_out->spidx.prefd, sp_out->spidx.ul_proto);
   2234 		if (iddst == NULL) {
   2235 			plog(LLV_ERROR, LOCATION, NULL,
   2236 				"failed to get ID for %s\n",
   2237 				spidx2str(&sp_out->spidx));
   2238 			vfree(idsrc);
   2239 			return -1;
   2240 		}
   2241 
   2242 		conf = getrmconf(iph2->dst, 0);
   2243 		if (conf != NULL)
   2244 			remoteid = conf->ph1id;
   2245 		else
   2246 			plog(LLV_DEBUG, LOCATION, NULL, "Warning: no valid rmconf !\n");
   2247 
   2248 		iph2->sainfo = getsainfo(idsrc, iddst, NULL, NULL, remoteid);
   2249 		vfree(idsrc);
   2250 		vfree(iddst);
   2251 		if (iph2->sainfo == NULL) {
   2252 			plog(LLV_ERROR, LOCATION, NULL,
   2253 				"failed to get sainfo.\n");
   2254 			return -1;
   2255 			/* XXX should use the algorithm list from register message */
   2256 		}
   2257 
   2258 		plog(LLV_DEBUG, LOCATION, NULL,
   2259 			"selected sainfo: %s\n", sainfo2str(iph2->sainfo));
   2260 	}
   2261 
   2262 	if (set_proposal_from_policy(iph2, sp_out, sp_in) < 0) {
   2263 		plog(LLV_ERROR, LOCATION, NULL,
   2264 			"failed to create saprop.\n");
   2265 		return -1;
   2266 	}
   2267 
   2268 	return 0;
   2269 }
   2270 
   2271 
   2272 /*
   2273  * receive GETSPI from kernel.
   2274  */
   2275 int
   2276 isakmp_post_getspi(struct ph2handle *iph2)
   2277 {
   2278 #ifdef ENABLE_STATS
   2279 	struct timeval start, end;
   2280 #endif
   2281 
   2282 	/* don't process it because there is no suitable phase1-sa. */
   2283 	if (iph2->ph1->status >= PHASE1ST_EXPIRED) {
   2284 		plog(LLV_ERROR, LOCATION, iph2->ph1->remote,
   2285 			"the negotiation is stopped, "
   2286 			"because there is no suitable ISAKMP-SA.\n");
   2287 		return -1;
   2288 	}
   2289 
   2290 #ifdef ENABLE_STATS
   2291 	gettimeofday(&start, NULL);
   2292 #endif
   2293 	if ((ph2exchange[etypesw2(ISAKMP_ETYPE_QUICK)]
   2294 	                [iph2->side]
   2295 	                [iph2->status])(iph2, NULL) != 0)
   2296 		return -1;
   2297 #ifdef ENABLE_STATS
   2298 	gettimeofday(&end, NULL);
   2299 	syslog(LOG_NOTICE, "%s(%s): %8.6f",
   2300 		"phase2",
   2301 		s_isakmp_state(ISAKMP_ETYPE_QUICK, iph2->side, iph2->status),
   2302 		timedelta(&start, &end));
   2303 #endif
   2304 
   2305 	return 0;
   2306 }
   2307 
   2308 /* called by scheduler */
   2309 void
   2310 isakmp_chkph1there_stub(struct sched *p)
   2311 {
   2312 	isakmp_chkph1there(container_of(p, struct ph2handle, sce));
   2313 }
   2314 
   2315 void
   2316 isakmp_chkph1there(struct ph2handle *iph2)
   2317 {
   2318 	struct ph1handle *iph1;
   2319 
   2320 	iph2->retry_checkph1--;
   2321 	if (iph2->retry_checkph1 < 0) {
   2322 		plog(LLV_ERROR, LOCATION, iph2->dst,
   2323 			"phase2 negotiation failed "
   2324 			"due to time up waiting for phase1. %s\n",
   2325 			sadbsecas2str(iph2->src, iph2->dst,
   2326 				iph2->satype, 0, 0));
   2327 		plog(LLV_INFO, LOCATION, NULL,
   2328 			"delete phase 2 handler.\n");
   2329 
   2330 		/* send acquire to kernel as error */
   2331 		pk_sendeacquire(iph2);
   2332 
   2333 		remph2(iph2);
   2334 		delph2(iph2);
   2335 
   2336 		return;
   2337 	}
   2338 
   2339 	/* Search isakmp status table by address and port */
   2340 	iph1 = getph1byaddr(iph2->src, iph2->dst, 0);
   2341 
   2342 	/* XXX Even if ph1 as responder is there, should we not start
   2343 	 * phase 2 negotiation ? */
   2344 	if (iph1 != NULL
   2345 	 && iph1->status == PHASE1ST_ESTABLISHED) {
   2346 		/* found isakmp-sa */
   2347 
   2348 		plog(LLV_DEBUG2, LOCATION, NULL, "CHKPH1THERE: got a ph1 handler, setting ports.\n");
   2349 		plog(LLV_DEBUG2, LOCATION, NULL, "iph1->local: %s\n", saddr2str(iph1->local));
   2350 		plog(LLV_DEBUG2, LOCATION, NULL, "iph1->remote: %s\n", saddr2str(iph1->remote));
   2351 		plog(LLV_DEBUG2, LOCATION, NULL, "before:\n");
   2352 		plog(LLV_DEBUG2, LOCATION, NULL, "src: %s\n", saddr2str(iph2->src));
   2353 		plog(LLV_DEBUG2, LOCATION, NULL, "dst: %s\n", saddr2str(iph2->dst));
   2354 		set_port(iph2->src, extract_port(iph1->local));
   2355 		set_port(iph2->dst, extract_port(iph1->remote));
   2356 		plog(LLV_DEBUG2, LOCATION, NULL, "After:\n");
   2357 		plog(LLV_DEBUG2, LOCATION, NULL, "src: %s\n", saddr2str(iph2->src));
   2358 		plog(LLV_DEBUG2, LOCATION, NULL, "dst: %s\n", saddr2str(iph2->dst));
   2359 
   2360 		/* begin quick mode */
   2361 		(void)isakmp_ph2begin_i(iph1, iph2);
   2362 		return;
   2363 	}
   2364 
   2365 	plog(LLV_DEBUG2, LOCATION, NULL, "CHKPH1THERE: no established ph1 handler found\n");
   2366 
   2367 	/* no isakmp-sa found */
   2368 	sched_schedule(&iph2->sce, 1, isakmp_chkph1there_stub);
   2369 
   2370 	return;
   2371 }
   2372 
   2373 /* copy variable data into ALLOCATED buffer. */
   2374 caddr_t
   2375 isakmp_set_attr_v(caddr_t buf, int type, caddr_t val, int len)
   2376 {
   2377 	struct isakmp_data *data;
   2378 
   2379 	data = (struct isakmp_data *)buf;
   2380 	data->type = htons((uint16_t)type | ISAKMP_GEN_TLV);
   2381 	data->lorv = htons((uint16_t)len);
   2382 	memcpy(data + 1, val, len);
   2383 
   2384 	return buf + sizeof(*data) + len;
   2385 }
   2386 
   2387 /* copy fixed length data into ALLOCATED buffer. */
   2388 caddr_t
   2389 isakmp_set_attr_l(caddr_t buf, int type, uint32_t val)
   2390 {
   2391 	struct isakmp_data *data;
   2392 
   2393 	data = (struct isakmp_data *)buf;
   2394 	data->type = htons((uint16_t)type | ISAKMP_GEN_TV);
   2395 	data->lorv = htons((uint16_t)val);
   2396 
   2397 	return buf + sizeof(*data);
   2398 }
   2399 
   2400 /* add a variable data attribute to the buffer by reallocating it. */
   2401 vchar_t *
   2402 isakmp_add_attr_v(vchar_t *buf0, int type, caddr_t val, int len)
   2403 {
   2404 	vchar_t *buf = NULL;
   2405 	struct isakmp_data *data;
   2406 	size_t tlen;
   2407 	size_t oldlen = 0;
   2408 
   2409 	tlen = sizeof(*data) + len;
   2410 
   2411 	if (buf0) {
   2412 		oldlen = buf0->l;
   2413 		buf = vrealloc(buf0, oldlen + tlen);
   2414 	} else
   2415 		buf = vmalloc(tlen);
   2416 	if (!buf) {
   2417 		plog(LLV_ERROR, LOCATION, NULL,
   2418 			"failed to get a attribute buffer.\n");
   2419 		return NULL;
   2420 	}
   2421 
   2422 	data = (struct isakmp_data *)(buf->v + oldlen);
   2423 	data->type = htons((uint16_t)type | ISAKMP_GEN_TLV);
   2424 	data->lorv = htons((uint16_t)len);
   2425 	memcpy(data + 1, val, len);
   2426 
   2427 	return buf;
   2428 }
   2429 
   2430 /* add a fixed data attribute to the buffer by reallocating it. */
   2431 vchar_t *
   2432 isakmp_add_attr_l(vchar_t *buf0, int type, uint32_t val)
   2433 {
   2434 	vchar_t *buf = NULL;
   2435 	struct isakmp_data *data;
   2436 	size_t tlen;
   2437 	size_t oldlen = 0;
   2438 
   2439 	tlen = sizeof(*data);
   2440 
   2441 	if (buf0) {
   2442 		oldlen = buf0->l;
   2443 		buf = vrealloc(buf0, oldlen + tlen);
   2444 	} else
   2445 		buf = vmalloc(tlen);
   2446 	if (!buf) {
   2447 		plog(LLV_ERROR, LOCATION, NULL,
   2448 			"failed to get a attribute buffer.\n");
   2449 		return NULL;
   2450 	}
   2451 
   2452 	data = (struct isakmp_data *)(buf->v + oldlen);
   2453 	data->type = htons((uint16_t)type | ISAKMP_GEN_TV);
   2454 	data->lorv = htons((uint16_t)val);
   2455 
   2456 	return buf;
   2457 }
   2458 
   2459 /*
   2460  * calculate cookie and set.
   2461  */
   2462 int
   2463 isakmp_newcookie(caddr_t place, struct sockaddr *remote, struct sockaddr *local)
   2464 {
   2465 	vchar_t *buf = NULL, *buf2 = NULL;
   2466 	char *p;
   2467 	size_t blen;
   2468 	size_t alen;
   2469 	caddr_t sa1, sa2;
   2470 	time_t t;
   2471 	int error = -1;
   2472 	u_short port;
   2473 
   2474 
   2475 	if (remote->sa_family != local->sa_family) {
   2476 		plog(LLV_ERROR, LOCATION, NULL,
   2477 			"address family mismatch, remote:%d local:%d\n",
   2478 			remote->sa_family, local->sa_family);
   2479 		goto end;
   2480 	}
   2481 	switch (remote->sa_family) {
   2482 	case AF_INET:
   2483 		alen = sizeof(struct in_addr);
   2484 		sa1 = (caddr_t)&((struct sockaddr_in *)remote)->sin_addr;
   2485 		sa2 = (caddr_t)&((struct sockaddr_in *)local)->sin_addr;
   2486 		break;
   2487 #ifdef INET6
   2488 	case AF_INET6:
   2489 		alen = sizeof(struct in6_addr);
   2490 		sa1 = (caddr_t)&((struct sockaddr_in6 *)remote)->sin6_addr;
   2491 		sa2 = (caddr_t)&((struct sockaddr_in6 *)local)->sin6_addr;
   2492 		break;
   2493 #endif
   2494 	default:
   2495 		plog(LLV_ERROR, LOCATION, NULL,
   2496 			"invalid family: %d\n", remote->sa_family);
   2497 		goto end;
   2498 	}
   2499 	blen = (alen + sizeof(u_short)) * 2
   2500 		+ sizeof(time_t) + lcconf->secret_size;
   2501 	buf = vmalloc(blen);
   2502 	if (buf == NULL) {
   2503 		plog(LLV_ERROR, LOCATION, NULL,
   2504 			"failed to get a cookie.\n");
   2505 		goto end;
   2506 	}
   2507 	p = buf->v;
   2508 
   2509 	/* copy my address */
   2510 	memcpy(p, sa1, alen);
   2511 	p += alen;
   2512 	port = ((struct sockaddr_in *)remote)->sin_port;
   2513 	memcpy(p, &port, sizeof(u_short));
   2514 	p += sizeof(u_short);
   2515 
   2516 	/* copy target address */
   2517 	memcpy(p, sa2, alen);
   2518 	p += alen;
   2519 	port = ((struct sockaddr_in *)local)->sin_port;
   2520 	memcpy(p, &port, sizeof(u_short));
   2521 	p += sizeof(u_short);
   2522 
   2523 	/* copy time */
   2524 	t = time(0);
   2525 	memcpy(p, (caddr_t)&t, sizeof(t));
   2526 	p += sizeof(t);
   2527 
   2528 	/* copy random value */
   2529 	buf2 = eay_set_random(lcconf->secret_size);
   2530 	if (buf2 == NULL)
   2531 		goto end;
   2532 	memcpy(p, buf2->v, lcconf->secret_size);
   2533 	p += lcconf->secret_size;
   2534 	vfree(buf2);
   2535 
   2536 	buf2 = eay_sha1_one(buf);
   2537 	memcpy(place, buf2->v, sizeof(cookie_t));
   2538 
   2539 	sa1 = val2str(place, sizeof (cookie_t));
   2540 	plog(LLV_DEBUG, LOCATION, NULL, "new cookie:\n%s\n", sa1);
   2541 	racoon_free(sa1);
   2542 
   2543 	error = 0;
   2544 end:
   2545 	if (buf != NULL)
   2546 		vfree(buf);
   2547 	if (buf2 != NULL)
   2548 		vfree(buf2);
   2549 	return error;
   2550 }
   2551 
   2552 /*
   2553  * save partner's(payload) data into phhandle.
   2554  */
   2555 int
   2556 isakmp_p2ph( vchar_t **buf, struct isakmp_gen *gen)
   2557 {
   2558 	/* XXX to be checked in each functions for logging. */
   2559 	if (*buf) {
   2560 		plog(LLV_WARNING, LOCATION, NULL,
   2561 			"ignore this payload, same payload type exist.\n");
   2562 		return -1;
   2563 	}
   2564 
   2565 	*buf = vmalloc(ntohs(gen->len) - sizeof(*gen));
   2566 	if (*buf == NULL) {
   2567 		plog(LLV_ERROR, LOCATION, NULL,
   2568 			"failed to get buffer.\n");
   2569 		return -1;
   2570 	}
   2571 	memcpy((*buf)->v, gen + 1, (*buf)->l);
   2572 
   2573 	return 0;
   2574 }
   2575 
   2576 uint32_t
   2577 isakmp_newmsgid2(struct ph1handle *iph1)
   2578 {
   2579 	uint32_t msgid2;
   2580 
   2581 	do {
   2582 		msgid2 = eay_random();
   2583 	} while (getph2bymsgid(iph1, msgid2));
   2584 
   2585 	return msgid2;
   2586 }
   2587 
   2588 /*
   2589  * set values into allocated buffer of isakmp header for phase 1
   2590  */
   2591 static caddr_t
   2592 set_isakmp_header(vchar_t *vbuf, struct ph1handle *iph1, int nptype,
   2593     uint8_t etype, uint8_t flags, uint32_t msgid)
   2594 {
   2595 	struct isakmp *isakmp;
   2596 
   2597 	if (vbuf->l < sizeof(*isakmp))
   2598 		return NULL;
   2599 
   2600 	isakmp = (struct isakmp *)vbuf->v;
   2601 
   2602 	memcpy(&isakmp->i_ck, &iph1->index.i_ck, sizeof(cookie_t));
   2603 	memcpy(&isakmp->r_ck, &iph1->index.r_ck, sizeof(cookie_t));
   2604 	isakmp->np = nptype;
   2605 	isakmp->v = iph1->version;
   2606 	isakmp->etype = etype;
   2607 	isakmp->flags = flags;
   2608 	isakmp->msgid = msgid;
   2609 	isakmp->len = htonl(vbuf->l);
   2610 
   2611 	return vbuf->v + sizeof(*isakmp);
   2612 }
   2613 
   2614 /*
   2615  * set values into allocated buffer of isakmp header for phase 1
   2616  */
   2617 caddr_t
   2618 set_isakmp_header1(vchar_t *vbuf, struct ph1handle *iph1, int nptype)
   2619 {
   2620 	return set_isakmp_header (vbuf, iph1, nptype, iph1->etype, iph1->flags, iph1->msgid);
   2621 }
   2622 
   2623 /*
   2624  * set values into allocated buffer of isakmp header for phase 2
   2625  */
   2626 caddr_t
   2627 set_isakmp_header2(vchar_t *vbuf, struct ph2handle *iph2, int nptype)
   2628 {
   2629 	return set_isakmp_header (vbuf, iph2->ph1, nptype, ISAKMP_ETYPE_QUICK, iph2->flags, iph2->msgid);
   2630 }
   2631 
   2632 /*
   2633  * set values into allocated buffer of isakmp payload.
   2634  */
   2635 caddr_t
   2636 set_isakmp_payload(caddr_t buf, vchar_t *src, int nptype)
   2637 {
   2638 	struct isakmp_gen *gen;
   2639 	caddr_t p = buf;
   2640 
   2641 	plog(LLV_DEBUG, LOCATION, NULL, "add payload of len %zu, next type %d\n",
   2642 	    src->l, nptype);
   2643 
   2644 	gen = (struct isakmp_gen *)p;
   2645 	gen->np = nptype;
   2646 	gen->len = htons(sizeof(*gen) + src->l);
   2647 	p += sizeof(*gen);
   2648 	memcpy(p, src->v, src->l);
   2649 	p += src->l;
   2650 
   2651 	return p;
   2652 }
   2653 
   2654 static int
   2655 etypesw1(int etype)
   2656 {
   2657 	switch (etype) {
   2658 	case ISAKMP_ETYPE_IDENT:
   2659 		return 1;
   2660 	case ISAKMP_ETYPE_AGG:
   2661 		return 2;
   2662 	case ISAKMP_ETYPE_BASE:
   2663 		return 3;
   2664 	default:
   2665 		return 0;
   2666 	}
   2667 	/*NOTREACHED*/
   2668 }
   2669 
   2670 static int
   2671 etypesw2(int etype)
   2672 {
   2673 	switch (etype) {
   2674 	case ISAKMP_ETYPE_QUICK:
   2675 		return 1;
   2676 	default:
   2677 		return 0;
   2678 	}
   2679 	/*NOTREACHED*/
   2680 }
   2681 
   2682 #ifdef HAVE_PRINT_ISAKMP_C
   2683 /* for print-isakmp.c */
   2684 char *snapend;
   2685 extern void isakmp_print(const u_char *, u_int, const u_char *);
   2686 
   2687 char *getname(const u_char *);
   2688 #ifdef INET6
   2689 char *getname6(const u_char *);
   2690 #endif
   2691 int safeputchar(int);
   2692 
   2693 /*
   2694  * Return a name for the IP address pointed to by ap.  This address
   2695  * is assumed to be in network byte order.
   2696  */
   2697 char *
   2698 getname(ap)
   2699 	const u_char *ap;
   2700 {
   2701 	struct sockaddr_in addr;
   2702 	static char ntop_buf[NI_MAXHOST];
   2703 
   2704 	memset(&addr, 0, sizeof(addr));
   2705 #ifndef __linux__
   2706 	addr.sin_len = sizeof(struct sockaddr_in);
   2707 #endif
   2708 	addr.sin_family = AF_INET;
   2709 	memcpy(&addr.sin_addr, ap, sizeof(addr.sin_addr));
   2710 	if (getnameinfo((struct sockaddr *)&addr, sizeof(addr),
   2711 			ntop_buf, sizeof(ntop_buf), NULL, 0,
   2712 			NI_NUMERICHOST | niflags))
   2713 		strlcpy(ntop_buf, "?", sizeof(ntop_buf));
   2714 
   2715 	return ntop_buf;
   2716 }
   2717 
   2718 #ifdef INET6
   2719 /*
   2720  * Return a name for the IP6 address pointed to by ap.  This address
   2721  * is assumed to be in network byte order.
   2722  */
   2723 char *
   2724 getname6(ap)
   2725 	const u_char *ap;
   2726 {
   2727 	struct sockaddr_in6 addr;
   2728 	static char ntop_buf[NI_MAXHOST];
   2729 
   2730 	memset(&addr, 0, sizeof(addr));
   2731 	addr.sin6_len = sizeof(struct sockaddr_in6);
   2732 	addr.sin6_family = AF_INET6;
   2733 	memcpy(&addr.sin6_addr, ap, sizeof(addr.sin6_addr));
   2734 	if (getnameinfo((struct sockaddr *)&addr, addr.sin6_len,
   2735 			ntop_buf, sizeof(ntop_buf), NULL, 0,
   2736 			NI_NUMERICHOST | niflags))
   2737 		strlcpy(ntop_buf, "?", sizeof(ntop_buf));
   2738 
   2739 	return ntop_buf;
   2740 }
   2741 #endif /* INET6 */
   2742 
   2743 int
   2744 safeputchar(c)
   2745 	int c;
   2746 {
   2747 	unsigned char ch;
   2748 
   2749 	ch = (unsigned char)(c & 0xff);
   2750 	if (c < 0x80 && isprint(c))
   2751 		return printf("%c", c & 0xff);
   2752 	else
   2753 		return printf("\\%03o", c & 0xff);
   2754 }
   2755 
   2756 void
   2757 isakmp_printpacket(msg, from, my, decoded)
   2758 	vchar_t *msg;
   2759 	struct sockaddr *from;
   2760 	struct sockaddr *my;
   2761 	int decoded;
   2762 {
   2763 #ifdef YIPS_DEBUG
   2764 	struct timeval tv;
   2765 	int s;
   2766 	char hostbuf[NI_MAXHOST];
   2767 	char portbuf[NI_MAXSERV];
   2768 	struct isakmp *isakmp;
   2769 	vchar_t *buf;
   2770 #endif
   2771 
   2772 	if (loglevel < LLV_DEBUG)
   2773 		return;
   2774 
   2775 #ifdef YIPS_DEBUG
   2776 	plog(LLV_DEBUG, LOCATION, NULL, "begin.\n");
   2777 
   2778 	gettimeofday(&tv, NULL);
   2779 	s = tv.tv_sec % 3600;
   2780 	printf("%02d:%02d.%06u ", s / 60, s % 60, (uint32_t)tv.tv_usec);
   2781 
   2782 	if (from) {
   2783 		if (getnameinfo(from, sysdep_sa_len(from), hostbuf, sizeof(hostbuf),
   2784 				portbuf, sizeof(portbuf),
   2785 				NI_NUMERICHOST | NI_NUMERICSERV | niflags)) {
   2786 			strlcpy(hostbuf, "?", sizeof(hostbuf));
   2787 			strlcpy(portbuf, "?", sizeof(portbuf));
   2788 		}
   2789 		printf("%s:%s", hostbuf, portbuf);
   2790 	} else
   2791 		printf("?");
   2792 	printf(" -> ");
   2793 	if (my) {
   2794 		if (getnameinfo(my, sysdep_sa_len(my), hostbuf, sizeof(hostbuf),
   2795 				portbuf, sizeof(portbuf),
   2796 				NI_NUMERICHOST | NI_NUMERICSERV | niflags)) {
   2797 			strlcpy(hostbuf, "?", sizeof(hostbuf));
   2798 			strlcpy(portbuf, "?", sizeof(portbuf));
   2799 		}
   2800 		printf("%s:%s", hostbuf, portbuf);
   2801 	} else
   2802 		printf("?");
   2803 	printf(": ");
   2804 
   2805 	buf = vdup(msg);
   2806 	if (!buf) {
   2807 		printf("(malloc fail)\n");
   2808 		return;
   2809 	}
   2810 	if (decoded) {
   2811 		isakmp = (struct isakmp *)buf->v;
   2812 		if (isakmp->flags & ISAKMP_FLAG_E) {
   2813 #if 0
   2814 			int pad;
   2815 			pad = *(u_char *)(buf->v + buf->l - 1);
   2816 			if (buf->l < pad && 2 < vflag)
   2817 				printf("(wrong padding)");
   2818 #endif
   2819 			isakmp->flags &= ~ISAKMP_FLAG_E;
   2820 		}
   2821 	}
   2822 
   2823 	snapend = buf->v + buf->l;
   2824 	isakmp_print(buf->v, buf->l, NULL);
   2825 	vfree(buf);
   2826 	printf("\n");
   2827 	fflush(stdout);
   2828 
   2829 	return;
   2830 #endif
   2831 }
   2832 #endif /*HAVE_PRINT_ISAKMP_C*/
   2833 
   2834 int
   2835 copy_ph1addresses(struct ph1handle *iph1, struct remoteconf *rmconf,
   2836     struct sockaddr *remote, struct sockaddr *local)
   2837 {
   2838 	uint16_t port = 0;
   2839 
   2840 	/* address portion must be grabbed from real remote address "remote" */
   2841 	iph1->remote = dupsaddr(remote);
   2842 	if (iph1->remote == NULL)
   2843 		return -1;
   2844 
   2845 	/*
   2846 	 * if remote has no port # (in case of initiator - from ACQUIRE msg)
   2847 	 * - if remote.conf specifies port #, use that
   2848 	 * - if remote.conf does not, use lcconf->port_isakmp
   2849 	 * if remote has port # (in case of responder - from recvfrom(2))
   2850 	 * respect content of "remote".
   2851 	 */
   2852 	if (extract_port(iph1->remote) == 0) {
   2853 		port = 0;
   2854 		if (rmconf != NULL)
   2855 			port = extract_port(rmconf->remote);
   2856 		if (port == 0)
   2857 			port = lcconf->port_isakmp;
   2858 		set_port(iph1->remote, port);
   2859 	}
   2860 
   2861 	if (local == NULL)
   2862 		iph1->local = getlocaladdr(iph1->remote);
   2863 	else
   2864 		iph1->local = dupsaddr(local);
   2865 	if (iph1->local == NULL)
   2866 		return -1;
   2867 
   2868 	if (extract_port(iph1->local) == 0) {
   2869 		port = myaddr_getsport(iph1->local);
   2870 		if (port == 0)
   2871 			port = PORT_ISAKMP;
   2872 		set_port(iph1->local, port);
   2873 	}
   2874 
   2875 #ifdef ENABLE_NATT
   2876 	if (extract_port(iph1->local) == lcconf->port_isakmp_natt) {
   2877 		plog(LLV_DEBUG, LOCATION, NULL, "Marking ports as changed\n");
   2878 		iph1->natt_flags |= NAT_ADD_NON_ESP_MARKER;
   2879 	}
   2880 #endif
   2881 
   2882 	return 0;
   2883 }
   2884 
   2885 /*ARGSUSED*/
   2886 static int
   2887 nostate1(struct ph1handle *iph1, vchar_t *msg __unused)
   2888 {
   2889 	plog(LLV_ERROR, LOCATION, iph1->remote, "wrong state %u.\n",
   2890 			iph1->status);
   2891 	return -1;
   2892 }
   2893 
   2894 /*ARGSUSED*/
   2895 static int
   2896 nostate2(struct ph2handle *iph2, vchar_t *msg __unused)
   2897 {
   2898 	plog(LLV_ERROR, LOCATION, iph2->ph1->remote, "wrong state %u.\n",
   2899 		iph2->status);
   2900 	return -1;
   2901 }
   2902 
   2903 void
   2904 log_ph1established(const struct ph1handle *iph1)
   2905 {
   2906 	char *src, *dst;
   2907 
   2908 	src = racoon_strdup(saddr2str(iph1->local));
   2909 	dst = racoon_strdup(saddr2str(iph1->remote));
   2910 	STRDUP_FATAL(src);
   2911 	STRDUP_FATAL(dst);
   2912 
   2913 	plog(LLV_INFO, LOCATION, NULL,
   2914 		"ISAKMP-SA established %s-%s spi:%s\n",
   2915 		src, dst,
   2916 		isakmp_pindex(&iph1->index, 0));
   2917 
   2918 	evt_phase1(iph1, EVT_PHASE1_UP, NULL);
   2919 	if(!iph1->rmconf->mode_cfg)
   2920 		evt_phase1(iph1, EVT_PHASE1_MODE_CFG, NULL);
   2921 
   2922 	racoon_free(src);
   2923 	racoon_free(dst);
   2924 
   2925 	return;
   2926 }
   2927 
   2928 struct payload_list *
   2929 isakmp_plist_append_full (struct payload_list *plist, vchar_t *payload,
   2930 			  uint8_t payload_type, uint8_t free_payload)
   2931 {
   2932 	if (! plist) {
   2933 		plist = racoon_malloc (sizeof (struct payload_list));
   2934 		plist->prev = NULL;
   2935 	}
   2936 	else {
   2937 		plist->next = racoon_malloc (sizeof (struct payload_list));
   2938 		plist->next->prev = plist;
   2939 		plist = plist->next;
   2940 	}
   2941 
   2942 	plist->next = NULL;
   2943 	plist->payload = payload;
   2944 	plist->payload_type = payload_type;
   2945 	plist->free_payload = free_payload;
   2946 
   2947 	return plist;
   2948 }
   2949 
   2950 vchar_t *
   2951 isakmp_plist_set_all (struct payload_list **plist, struct ph1handle *iph1)
   2952 {
   2953 	struct payload_list *ptr = *plist, *first;
   2954 	size_t tlen = sizeof (struct isakmp), n = 0;
   2955 	vchar_t *buf = NULL;
   2956 	char *p;
   2957 
   2958 	/* Seek to the first item.  */
   2959 	while (ptr->prev) ptr = ptr->prev;
   2960 	first = ptr;
   2961 
   2962 	/* Compute the whole length.  */
   2963 	while (ptr) {
   2964 		tlen += ptr->payload->l + sizeof (struct isakmp_gen);
   2965 		ptr = ptr->next;
   2966 	}
   2967 
   2968 	buf = vmalloc(tlen);
   2969 	if (buf == NULL) {
   2970 		plog(LLV_ERROR, LOCATION, NULL,
   2971 			"failed to get buffer to send.\n");
   2972 		goto end;
   2973 	}
   2974 
   2975 	ptr = first;
   2976 
   2977 	p = set_isakmp_header1(buf, iph1, ptr->payload_type);
   2978 	if (p == NULL)
   2979 		goto end;
   2980 
   2981 	while (ptr)
   2982 	{
   2983 		p = set_isakmp_payload (p, ptr->payload, ptr->next ? ptr->next->payload_type : ISAKMP_NPTYPE_NONE);
   2984 		first = ptr;
   2985 		ptr = ptr->next;
   2986 		if (first->free_payload)
   2987 			vfree(first->payload);
   2988 		racoon_free (first);
   2989 		/* ptr->prev = NULL; first = NULL; ... omitted.  */
   2990 		n++;
   2991 	}
   2992 
   2993 	*plist = NULL;
   2994 
   2995 	return buf;
   2996 end:
   2997 	if (buf != NULL)
   2998 		vfree(buf);
   2999 	return NULL;
   3000 }
   3001 
   3002 #ifdef ENABLE_FRAG
   3003 int
   3004 frag_handler(struct ph1handle *iph1, vchar_t *msg, struct sockaddr *remote,
   3005     struct sockaddr *local)
   3006 {
   3007 	vchar_t *newmsg;
   3008 
   3009 	if (isakmp_frag_extract(iph1, msg) == 1) {
   3010 		if ((newmsg = isakmp_frag_reassembly(iph1)) == NULL) {
   3011 			plog(LLV_ERROR, LOCATION, remote,
   3012 			    "Packet reassembly failed\n");
   3013 			return -1;
   3014 		}
   3015 		return isakmp_main(newmsg, remote, local);
   3016 	}
   3017 
   3018 	return 0;
   3019 }
   3020 #endif
   3021 
   3022 void
   3023 script_hook(struct ph1handle *iph1, int script)
   3024 {
   3025 #define IP_MAX 40
   3026 #define PORT_MAX 6
   3027 	char addrstr[IP_MAX];
   3028 	char portstr[PORT_MAX];
   3029 	char **envp = NULL;
   3030 	int envc = 1;
   3031 	char **c;
   3032 
   3033 	if (iph1 == NULL ||
   3034 		iph1->rmconf == NULL ||
   3035 		iph1->rmconf->script[script] == NULL)
   3036 		return;
   3037 
   3038 #ifdef ENABLE_HYBRID
   3039 	(void)isakmp_cfg_setenv(iph1, &envp, &envc);
   3040 #endif
   3041 
   3042 	/* local address */
   3043 	GETNAMEINFO(iph1->local, addrstr, portstr);
   3044 
   3045 	if (script_env_append(&envp, &envc, "LOCAL_ADDR", addrstr) != 0) {
   3046 		plog(LLV_ERROR, LOCATION, NULL, "Cannot set LOCAL_ADDR\n");
   3047 		goto out;
   3048 	}
   3049 
   3050 	if (script_env_append(&envp, &envc, "LOCAL_PORT", portstr) != 0) {
   3051 		plog(LLV_ERROR, LOCATION, NULL, "Cannot set LOCAL_PORT\n");
   3052 		goto out;
   3053 	}
   3054 
   3055 	/* Peer address */
   3056 	if (iph1->remote != NULL) {
   3057 		GETNAMEINFO(iph1->remote, addrstr, portstr);
   3058 
   3059 		if (script_env_append(&envp, &envc,
   3060 		    "REMOTE_ADDR", addrstr) != 0) {
   3061 			plog(LLV_ERROR, LOCATION, NULL,
   3062 			    "Cannot set REMOTE_ADDR\n");
   3063 			goto out;
   3064 		}
   3065 
   3066 		if (script_env_append(&envp, &envc,
   3067 		    "REMOTE_PORT", portstr) != 0) {
   3068 			plog(LLV_ERROR, LOCATION, NULL,
   3069 			    "Cannot set REMOTEL_PORT\n");
   3070 			goto out;
   3071 		}
   3072 	}
   3073 
   3074 	/* Peer identity. */
   3075 	if (iph1->id_p != NULL) {
   3076 		if (script_env_append(&envp, &envc, "REMOTE_ID",
   3077 				      ipsecdoi_id2str(iph1->id_p)) != 0) {
   3078 			plog(LLV_ERROR, LOCATION, NULL,
   3079 			     "Cannot set REMOTE_ID\n");
   3080 			goto out;
   3081 		}
   3082 	}
   3083 
   3084 	if (privsep_script_exec(iph1->rmconf->script[script]->v,
   3085 	    script, envp) != 0)
   3086 		plog(LLV_ERROR, LOCATION, NULL,
   3087 		    "Script %s execution failed\n", script_names[script]);
   3088 
   3089 out:
   3090 	for (c = envp; *c; c++)
   3091 		racoon_free(*c);
   3092 
   3093 	racoon_free(envp);
   3094 
   3095 	return;
   3096 }
   3097 
   3098 int
   3099 script_env_append(char ***envp, int *envc, const char *name, char *value)
   3100 {
   3101 	char *envitem;
   3102 	char **newenvp;
   3103 	int newenvc;
   3104 
   3105 	envitem = racoon_malloc(strlen(name) + 1 + strlen(value) + 1);
   3106 	if (envitem == NULL) {
   3107 		plog(LLV_ERROR, LOCATION, NULL,
   3108 		    "Cannot allocate memory: %s\n", strerror(errno));
   3109 		return -1;
   3110 	}
   3111 	sprintf(envitem, "%s=%s", name, value);
   3112 
   3113 	newenvc = (*envc) + 1;
   3114 	newenvp = racoon_realloc(*envp, newenvc * sizeof(char *));
   3115 	if (newenvp == NULL) {
   3116 		plog(LLV_ERROR, LOCATION, NULL,
   3117 		    "Cannot allocate memory: %s\n", strerror(errno));
   3118 		racoon_free(envitem);
   3119 		return -1;
   3120 	}
   3121 
   3122 	newenvp[newenvc - 2] = envitem;
   3123 	newenvp[newenvc - 1] = NULL;
   3124 
   3125 	*envp = newenvp;
   3126 	*envc = newenvc;
   3127 	return 0;
   3128 }
   3129 
   3130 int
   3131 script_exec(char *script, int name, char *const envp[])
   3132 {
   3133 	char *argv[] = { NULL, NULL, NULL };
   3134 
   3135 	argv[0] = script;
   3136 	argv[1] = __UNCONST(script_names[name]);
   3137 	argv[2] = NULL;
   3138 
   3139 	switch (fork()) {
   3140 	case 0:
   3141 		execve(argv[0], argv, envp);
   3142 		plog(LLV_ERROR, LOCATION, NULL,
   3143 		    "execve(\"%s\") failed: %s\n",
   3144 		    argv[0], strerror(errno));
   3145 		_exit(1);
   3146 	case -1:
   3147 		plog(LLV_ERROR, LOCATION, NULL,
   3148 		    "Cannot fork: %s\n", strerror(errno));
   3149 		return -1;
   3150 	default:
   3151 		break;
   3152 	}
   3153 	return 0;
   3154 
   3155 }
   3156 
   3157 void
   3158 purge_remote(struct ph1handle *iph1)
   3159 {
   3160 	vchar_t *buf = NULL;
   3161 	struct sadb_msg *msg, *next, *end;
   3162 	struct sadb_sa *sa;
   3163 	struct sockaddr *src, *dst;
   3164 	caddr_t mhp[SADB_EXT_MAX + 1];
   3165 	u_int proto_id;
   3166 	struct ph2handle *iph2;
   3167 	struct ph1handle *new_iph1;
   3168 
   3169 	plog(LLV_INFO, LOCATION, NULL,
   3170 		 "purging ISAKMP-SA spi=%s.\n",
   3171 		 isakmp_pindex(&(iph1->index), iph1->msgid));
   3172 
   3173 	/* Mark as expired. */
   3174 	iph1->status = PHASE1ST_EXPIRED;
   3175 
   3176 	/* Check if we have another, still valid, phase1 SA. */
   3177 	new_iph1 = getph1(iph1, iph1->local, iph1->remote, GETPH1_F_ESTABLISHED);
   3178 
   3179 	/*
   3180 	 * Delete all orphaned or binded to the deleting ph1handle phase2 SAs.
   3181 	 * Keep all others phase2 SAs.
   3182 	 */
   3183 	buf = pfkey_dump_sadb(SADB_SATYPE_UNSPEC);
   3184 	if (buf == NULL) {
   3185 		plog(LLV_DEBUG, LOCATION, NULL,
   3186 			"pfkey_dump_sadb returned nothing.\n");
   3187 		return;
   3188 	}
   3189 
   3190 	msg = (struct sadb_msg *)buf->v;
   3191 	end = (struct sadb_msg *)(buf->v + buf->l);
   3192 
   3193 	while (msg < end) {
   3194 		if ((msg->sadb_msg_len << 3) < sizeof(*msg))
   3195 			break;
   3196 		next = (struct sadb_msg *)((caddr_t)msg + (msg->sadb_msg_len << 3));
   3197 		if (msg->sadb_msg_type != SADB_DUMP) {
   3198 			msg = next;
   3199 			continue;
   3200 		}
   3201 
   3202 		if (pfkey_align(msg, mhp) || pfkey_check(mhp)) {
   3203 			plog(LLV_ERROR, LOCATION, NULL,
   3204 				"pfkey_check (%s)\n", ipsec_strerror());
   3205 			msg = next;
   3206 			continue;
   3207 		}
   3208 
   3209 		sa = (struct sadb_sa *)(mhp[SADB_EXT_SA]);
   3210 		if (!sa ||
   3211 		    !mhp[SADB_EXT_ADDRESS_SRC] ||
   3212 		    !mhp[SADB_EXT_ADDRESS_DST]) {
   3213 			msg = next;
   3214 			continue;
   3215 		}
   3216 		pk_fixup_sa_addresses(mhp);
   3217 		src = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]);
   3218 		dst = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]);
   3219 
   3220 		if (sa->sadb_sa_state != SADB_SASTATE_LARVAL &&
   3221 		    sa->sadb_sa_state != SADB_SASTATE_MATURE &&
   3222 		    sa->sadb_sa_state != SADB_SASTATE_DYING) {
   3223 			msg = next;
   3224 			continue;
   3225 		}
   3226 
   3227 		/*
   3228 		 * check in/outbound SAs.
   3229 		 * Select only SAs where src == local and dst == remote (outgoing)
   3230 		 * or src == remote and dst == local (incoming).
   3231 		 */
   3232 		if ((cmpsaddr(iph1->local, src) != CMPSADDR_MATCH ||
   3233 		     cmpsaddr(iph1->remote, dst) != CMPSADDR_MATCH) &&
   3234 		    (cmpsaddr(iph1->local, dst) != CMPSADDR_MATCH ||
   3235 		     cmpsaddr(iph1->remote, src) != CMPSADDR_MATCH)) {
   3236 			msg = next;
   3237 			continue;
   3238 		}
   3239 
   3240 		proto_id = pfkey2ipsecdoi_proto(msg->sadb_msg_satype);
   3241 		iph2 = getph2bysaidx(src, dst, proto_id, sa->sadb_sa_spi);
   3242 
   3243 		/* Check if there is another valid ISAKMP-SA */
   3244 		if (new_iph1 != NULL) {
   3245 
   3246 			if (iph2 == NULL) {
   3247 				/* No handler... still send a pfkey_delete message, but log this !*/
   3248 				plog(LLV_INFO, LOCATION, NULL,
   3249 					"Unknown IPsec-SA spi=%u, hmmmm?\n",
   3250 					ntohl(sa->sadb_sa_spi));
   3251 			}else{
   3252 
   3253 				/*
   3254 				 * If we have a new ph1, do not purge IPsec-SAs binded
   3255 				 *  to a different ISAKMP-SA
   3256 				 */
   3257 				if (iph2->ph1 != NULL && iph2->ph1 != iph1){
   3258 					msg = next;
   3259 					continue;
   3260 				}
   3261 
   3262 				/* If the ph2handle is established, do not purge IPsec-SA */
   3263 				if (iph2->status == PHASE2ST_ESTABLISHED ||
   3264 					iph2->status == PHASE2ST_EXPIRED) {
   3265 
   3266 					plog(LLV_INFO, LOCATION, NULL,
   3267 						 "keeping IPsec-SA spi=%u - found valid ISAKMP-SA spi=%s.\n",
   3268 						 ntohl(sa->sadb_sa_spi),
   3269 						 isakmp_pindex(&(new_iph1->index), new_iph1->msgid));
   3270 					msg = next;
   3271 					continue;
   3272 				}
   3273 			}
   3274 		}
   3275 
   3276 
   3277 		pfkey_send_delete(lcconf->sock_pfkey,
   3278 				  msg->sadb_msg_satype,
   3279 				  IPSEC_MODE_ANY,
   3280 				  src, dst, sa->sadb_sa_spi);
   3281 
   3282 		/* delete a relative phase 2 handle. */
   3283 		if (iph2 != NULL) {
   3284 			delete_spd(iph2, 0);
   3285 			remph2(iph2);
   3286 			delph2(iph2);
   3287 		}
   3288 
   3289 		plog(LLV_INFO, LOCATION, NULL,
   3290 			 "purged IPsec-SA spi=%u.\n",
   3291 			 ntohl(sa->sadb_sa_spi));
   3292 
   3293 		msg = next;
   3294 	}
   3295 
   3296 	if (buf)
   3297 		vfree(buf);
   3298 
   3299 	/* Mark the phase1 handler as EXPIRED */
   3300 	plog(LLV_INFO, LOCATION, NULL,
   3301 		 "purged ISAKMP-SA spi=%s.\n",
   3302 		 isakmp_pindex(&(iph1->index), iph1->msgid));
   3303 
   3304 	isakmp_ph1delete(iph1);
   3305 }
   3306 
   3307 void
   3308 delete_spd(struct ph2handle *iph2, u_int64_t created)
   3309 {
   3310 	struct policyindex spidx;
   3311 	struct sockaddr_storage addr;
   3312 	uint8_t pref;
   3313 	struct sockaddr *src;
   3314 	struct sockaddr *dst;
   3315 	int error;
   3316 	int idi2type = 0;/* switch whether copy IDs into id[src,dst]. */
   3317 
   3318 	if (iph2 == NULL)
   3319 		return;
   3320 
   3321 	/* Delete the SPD entry if we generated it
   3322 	 */
   3323 	if (! iph2->generated_spidx )
   3324 		return;
   3325 
   3326 	src = iph2->src;
   3327 	dst = iph2->dst;
   3328 
   3329 	plog(LLV_INFO, LOCATION, NULL,
   3330 		 "deleting a generated policy.\n");
   3331 
   3332 	memset(&spidx, 0, sizeof(spidx));
   3333 	iph2->spidx_gen = (caddr_t )&spidx;
   3334 
   3335 	/* make inbound policy */
   3336 	iph2->src = dst;
   3337 	iph2->dst = src;
   3338 	spidx.dir = IPSEC_DIR_INBOUND;
   3339 	spidx.ul_proto = 0;
   3340 
   3341 	/*
   3342 	 * Note: code from get_proposal_r
   3343 	 */
   3344 
   3345 #define _XIDT(d) ((struct ipsecdoi_id_b *)(d)->v)->type
   3346 
   3347 	/*
   3348 	 * make destination address in spidx from either ID payload
   3349 	 * or phase 1 address into a address in spidx.
   3350 	 */
   3351 	if (iph2->id != NULL
   3352 		&& (_XIDT(iph2->id) == IPSECDOI_ID_IPV4_ADDR
   3353 			|| _XIDT(iph2->id) == IPSECDOI_ID_IPV6_ADDR
   3354 			|| _XIDT(iph2->id) == IPSECDOI_ID_IPV4_ADDR_SUBNET
   3355 			|| _XIDT(iph2->id) == IPSECDOI_ID_IPV6_ADDR_SUBNET)) {
   3356 		/* get a destination address of a policy */
   3357 		error = ipsecdoi_id2sockaddr(iph2->id,
   3358 									 (struct sockaddr *)&spidx.dst,
   3359 									 &spidx.prefd, &spidx.ul_proto);
   3360 		if (error)
   3361 			goto purge;
   3362 
   3363 #ifdef INET6
   3364 		/*
   3365 		 * get scopeid from the SA address.
   3366 		 * note that the phase 1 source address is used as
   3367 		 * a destination address to search for a inbound
   3368 		 * policy entry because rcoon is responder.
   3369 		 */
   3370 		if (_XIDT(iph2->id) == IPSECDOI_ID_IPV6_ADDR) {
   3371 			if ((error =
   3372 				 setscopeid((struct sockaddr *)&spidx.dst,
   3373 							iph2->src)) != 0)
   3374 				goto purge;
   3375 		}
   3376 #endif
   3377 
   3378 		if (_XIDT(iph2->id) == IPSECDOI_ID_IPV4_ADDR
   3379 			|| _XIDT(iph2->id) == IPSECDOI_ID_IPV6_ADDR)
   3380 			idi2type = _XIDT(iph2->id);
   3381 
   3382 	} else {
   3383 
   3384 		plog(LLV_DEBUG, LOCATION, NULL,
   3385 			 "get a destination address of SP index "
   3386 			 "from phase1 address "
   3387 			 "due to no ID payloads found "
   3388 			 "OR because ID type is not address.\n");
   3389 
   3390 		/*
   3391 		 * copy the SOURCE address of IKE into the
   3392 		 * DESTINATION address of the key to search the
   3393 		 * SPD because the direction of policy is inbound.
   3394 		 */
   3395 		memcpy(&spidx.dst, iph2->src, sysdep_sa_len(iph2->src));
   3396 		switch (spidx.dst.ss_family) {
   3397 		case AF_INET:
   3398 			spidx.prefd =
   3399 				sizeof(struct in_addr) << 3;
   3400 			break;
   3401 #ifdef INET6
   3402 		case AF_INET6:
   3403 			spidx.prefd =
   3404 				sizeof(struct in6_addr) << 3;
   3405 			break;
   3406 #endif
   3407 		default:
   3408 			spidx.prefd = 0;
   3409 			break;
   3410 		}
   3411 	}
   3412 
   3413 		/* make source address in spidx */
   3414 	if (iph2->id_p != NULL
   3415 		&& (_XIDT(iph2->id_p) == IPSECDOI_ID_IPV4_ADDR
   3416 			|| _XIDT(iph2->id_p) == IPSECDOI_ID_IPV6_ADDR
   3417 			|| _XIDT(iph2->id_p) == IPSECDOI_ID_IPV4_ADDR_SUBNET
   3418 			|| _XIDT(iph2->id_p) == IPSECDOI_ID_IPV6_ADDR_SUBNET)) {
   3419 		/* get a source address of inbound SA */
   3420 		error = ipsecdoi_id2sockaddr(iph2->id_p,
   3421 					     (struct sockaddr *)&spidx.src,
   3422 					     &spidx.prefs, &spidx.ul_proto);
   3423 		if (error)
   3424 			goto purge;
   3425 
   3426 #ifdef INET6
   3427 		/*
   3428 		 * get scopeid from the SA address.
   3429 		 * for more detail, see above of this function.
   3430 		 */
   3431 		if (_XIDT(iph2->id_p) == IPSECDOI_ID_IPV6_ADDR) {
   3432 			error =
   3433 				setscopeid((struct sockaddr *)&spidx.src,
   3434 						   iph2->dst);
   3435 			if (error)
   3436 				goto purge;
   3437 		}
   3438 #endif
   3439 
   3440 		/* make sa_[src,dst] if both ID types are IP address and same */
   3441 		if (_XIDT(iph2->id_p) == idi2type
   3442 			&& spidx.dst.ss_family == spidx.src.ss_family) {
   3443 			iph2->sa_src =
   3444 				dupsaddr((struct sockaddr *)&spidx.dst);
   3445 			if (iph2->sa_src == NULL) {
   3446 				plog(LLV_ERROR, LOCATION, NULL,
   3447 					 "allocation failed\n");
   3448 				goto purge;
   3449 			}
   3450 			iph2->sa_dst =
   3451 				dupsaddr((struct sockaddr *)&spidx.src);
   3452 			if (iph2->sa_dst == NULL) {
   3453 				plog(LLV_ERROR, LOCATION, NULL,
   3454 					 "allocation failed\n");
   3455 				goto purge;
   3456 			}
   3457 		}
   3458 
   3459 	} else {
   3460 		plog(LLV_DEBUG, LOCATION, NULL,
   3461 			 "get a source address of SP index "
   3462 			 "from phase1 address "
   3463 			 "due to no ID payloads found "
   3464 			 "OR because ID type is not address.\n");
   3465 
   3466 		/* see above comment. */
   3467 		memcpy(&spidx.src, iph2->dst, sysdep_sa_len(iph2->dst));
   3468 		switch (spidx.src.ss_family) {
   3469 		case AF_INET:
   3470 			spidx.prefs =
   3471 				sizeof(struct in_addr) << 3;
   3472 			break;
   3473 #ifdef INET6
   3474 		case AF_INET6:
   3475 			spidx.prefs =
   3476 				sizeof(struct in6_addr) << 3;
   3477 			break;
   3478 #endif
   3479 		default:
   3480 			spidx.prefs = 0;
   3481 			break;
   3482 		}
   3483 	}
   3484 
   3485 #undef _XIDT
   3486 
   3487 	plog(LLV_DEBUG, LOCATION, NULL,
   3488 		 "get a src address from ID payload "
   3489 		 "%s prefixlen=%u ul_proto=%u\n",
   3490 		 saddr2str((struct sockaddr *)&spidx.src),
   3491 		 spidx.prefs, spidx.ul_proto);
   3492 	plog(LLV_DEBUG, LOCATION, NULL,
   3493 		 "get dst address from ID payload "
   3494 		 "%s prefixlen=%u ul_proto=%u\n",
   3495 		 saddr2str((struct sockaddr *)&spidx.dst),
   3496 		 spidx.prefd, spidx.ul_proto);
   3497 
   3498 	/*
   3499 	 * convert the ul_proto if it is 0
   3500 	 * because 0 in ID payload means a wild card.
   3501 	 */
   3502 	if (spidx.ul_proto == 0)
   3503 		spidx.ul_proto = IPSEC_ULPROTO_ANY;
   3504 
   3505 #undef _XIDT
   3506 
   3507 	/* Check if the generated SPD has the same timestamp as the SA.
   3508 	 * If timestamps are different, this means that the SPD entry has been
   3509 	 * refreshed by another SA, and should NOT be deleted with the current SA.
   3510 	 */
   3511 	if( created ){
   3512 		struct secpolicy *p;
   3513 
   3514 		p = getsp(&spidx);
   3515 		if(p != NULL){
   3516 			/* just do no test if p is NULL, because this probably just means
   3517 			 * that the policy has already be deleted for some reason.
   3518 			 */
   3519 			if(p->spidx.created != created)
   3520 				goto purge;
   3521 		}
   3522 	}
   3523 
   3524 	/* End of code from get_proposal_r
   3525 	 */
   3526 
   3527 	if (pk_sendspddelete(iph2) < 0) {
   3528 		plog(LLV_ERROR, LOCATION, NULL,
   3529 			 "pfkey spddelete(inbound) failed.\n");
   3530 	}else{
   3531 		plog(LLV_DEBUG, LOCATION, NULL,
   3532 			 "pfkey spddelete(inbound) sent.\n");
   3533 	}
   3534 
   3535 #ifdef HAVE_POLICY_FWD
   3536 	/* make forward policy if required */
   3537 	if (tunnel_mode_prop(iph2->approval)) {
   3538 		spidx.dir = IPSEC_DIR_FWD;
   3539 		if (pk_sendspddelete(iph2) < 0) {
   3540 			plog(LLV_ERROR, LOCATION, NULL,
   3541 				 "pfkey spddelete(forward) failed.\n");
   3542 		}else{
   3543 			plog(LLV_DEBUG, LOCATION, NULL,
   3544 				 "pfkey spddelete(forward) sent.\n");
   3545 		}
   3546 	}
   3547 #endif
   3548 
   3549 	/* make outbound policy */
   3550 	iph2->src = src;
   3551 	iph2->dst = dst;
   3552 	spidx.dir = IPSEC_DIR_OUTBOUND;
   3553 	addr = spidx.src;
   3554 	spidx.src = spidx.dst;
   3555 	spidx.dst = addr;
   3556 	pref = spidx.prefs;
   3557 	spidx.prefs = spidx.prefd;
   3558 	spidx.prefd = pref;
   3559 
   3560 	if (pk_sendspddelete(iph2) < 0) {
   3561 		plog(LLV_ERROR, LOCATION, NULL,
   3562 			 "pfkey spddelete(outbound) failed.\n");
   3563 	}else{
   3564 		plog(LLV_DEBUG, LOCATION, NULL,
   3565 			 "pfkey spddelete(outbound) sent.\n");
   3566 	}
   3567 purge:
   3568 	iph2->spidx_gen=NULL;
   3569 }
   3570 
   3571 
   3572 #ifdef INET6
   3573 uint32_t
   3574 setscopeid(struct sockaddr *sp_addr0, struct sockaddr *sa_addr0)
   3575 {
   3576 	struct sockaddr_in6 *sp_addr, *sa_addr;
   3577 
   3578 	sp_addr = (struct sockaddr_in6 *)sp_addr0;
   3579 	sa_addr = (struct sockaddr_in6 *)sa_addr0;
   3580 
   3581 	if (!IN6_IS_ADDR_LINKLOCAL(&sp_addr->sin6_addr)
   3582 	 && !IN6_IS_ADDR_SITELOCAL(&sp_addr->sin6_addr)
   3583 	 && !IN6_IS_ADDR_MULTICAST(&sp_addr->sin6_addr))
   3584 		return 0;
   3585 
   3586 	/* this check should not be here ? */
   3587 	if (sa_addr->sin6_family != AF_INET6) {
   3588 		plog(LLV_ERROR, LOCATION, NULL,
   3589 			"can't get scope ID: family mismatch\n");
   3590 		return (uint32_t)-1;
   3591 	}
   3592 
   3593 	if (!IN6_IS_ADDR_LINKLOCAL(&sa_addr->sin6_addr)) {
   3594 		plog(LLV_ERROR, LOCATION, NULL,
   3595 			"scope ID is not supported except of lladdr.\n");
   3596 		return (uint32_t)-1;
   3597 	}
   3598 
   3599 	sp_addr->sin6_scope_id = sa_addr->sin6_scope_id;
   3600 
   3601 	return 0;
   3602 }
   3603 #endif
   3604