]> git.saurik.com Git - apple/xnu.git/blobdiff - bsd/netkey/key.c
xnu-792.6.56.tar.gz
[apple/xnu.git] / bsd / netkey / key.c
index 9db82dcfd084f259596253aea77a061eeee68f5c..2c635da4c53ba3d723e5c78728054bf34a6982d3 100644 (file)
@@ -1,4 +1,5 @@
-/*     $KAME: key.c,v 1.76 2000/03/27 05:11:04 sumikawa Exp $  */
+/*     $FreeBSD: src/sys/netkey/key.c,v 1.16.2.13 2002/07/24 18:17:40 ume Exp $        */
+/*     $KAME: key.c,v 1.191 2001/06/27 10:46:49 sakane Exp $   */
 
 /*
  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
  * This code is referd to RFC 2367
  */
 
-#if (defined(__FreeBSD__) && __FreeBSD__ >= 3) || defined(__NetBSD__)
-#include "opt_inet.h"
-#ifdef __NetBSD__
-#include "opt_ipsec.h"
-#endif
-#endif
-
-/* this is for backward compatibility. we should not touch those. */
-#define ss_len         __ss_len
-#define ss_family      __ss_family
-
 #include <sys/types.h>
 #include <sys/param.h>
 #include <sys/systm.h>
 #include <sys/malloc.h>
 #include <sys/socket.h>
 #include <sys/socketvar.h>
-#if defined(__FreeBSD__) || defined (__APPLE__)
 #include <sys/sysctl.h>
-#endif
 #include <sys/errno.h>
 #include <sys/proc.h>
 #include <sys/queue.h>
+#include <sys/syslog.h>
+
+#include <kern/locks.h>
 
 #include <net/if.h>
 #include <net/route.h>
@@ -80,9 +71,7 @@
 #include <netinet/in_pcb.h>
 #endif
 #if INET6
-#if !(defined(__bsdi__) && _BSDI_VERSION >= 199802)
 #include <netinet6/in6_pcb.h>
-#endif
 #endif /* INET6 */
 
 #include <net/pfkeyv2.h>
 #include <netkey/key.h>
 #include <netkey/keysock.h>
 #include <netkey/key_debug.h>
+#include <stdarg.h>
+
 
 #include <netinet6/ipsec.h>
+#if INET6
+#include <netinet6/ipsec6.h>
+#endif
 #include <netinet6/ah.h>
+#if INET6
+#include <netinet6/ah6.h>
+#endif
 #if IPSEC_ESP
 #include <netinet6/esp.h>
+#if INET6
+#include <netinet6/esp6.h>
+#endif
 #endif
 #include <netinet6/ipcomp.h>
+#if INET6
+#include <netinet6/ipcomp6.h>
+#endif
+
+
+/* randomness */
+#include <sys/random.h>
 
 #include <net/net_osdep.h>
 
+#ifndef satosin
+#define satosin(s) ((struct sockaddr_in *)s)
+#endif
+
+#define FULLMASK       0xff
+
+lck_grp_t         *sadb_mutex_grp;
+lck_grp_attr_t    *sadb_mutex_grp_attr;
+lck_attr_t        *sadb_mutex_attr;
+lck_mtx_t         *sadb_mutex;
+extern lck_mtx_t  *nd6_mutex;
+
 /*
  * Note on SA reference counting:
  * - SAs that are not in DEAD state will have (total external reference + 1)
@@ -120,14 +139,22 @@ static u_int key_int_random = 60; /*interval to initialize randseed,1(m)*/
 static u_int key_larval_lifetime = 30; /* interval to expire acquiring, 30(s)*/
 static int key_blockacq_count = 10;    /* counter for blocking SADB_ACQUIRE.*/
 static int key_blockacq_lifetime = 20; /* lifetime for blocking SADB_ACQUIRE.*/
+static int key_preferred_oldsa = 0;    /* preferred old sa rather than new sa.*/
+static int natt_keepalive_interval = 20;       /* interval between natt keepalives.*/
 
 static u_int32_t acq_seq = 0;
 static int key_tick_init_random = 0;
+__private_extern__ u_int32_t natt_now = 0;
 
 static LIST_HEAD(_sptree, secpolicy) sptree[IPSEC_DIR_MAX];    /* SPD */
 static LIST_HEAD(_sahtree, secashead) sahtree;                 /* SAD */
 static LIST_HEAD(_regtree, secreg) regtree[SADB_SATYPE_MAX + 1];
                                                        /* registed list */
+                                                       
+#define SPIHASHSIZE    128
+#define        SPIHASH(x)      (((x) ^ ((x) >> 16)) % SPIHASHSIZE)
+static LIST_HEAD(_spihash, secasvar) spihash[SPIHASHSIZE];
+
 #ifndef IPSEC_NONBLOCK_ACQUIRE
 static LIST_HEAD(_acqtree, secacq) acqtree;            /* acquiring list */
 #endif
@@ -136,28 +163,75 @@ static LIST_HEAD(_spacqtree, secspacq) spacqtree; /* SP acquiring list */
 struct key_cb key_cb;
 
 /* search order for SAs */
-static u_int saorder_state_valid[] = {
+static const u_int saorder_state_valid_prefer_old[] = {
        SADB_SASTATE_DYING, SADB_SASTATE_MATURE,
-       /*
-        * This order is important because we must select a oldest SA
-        * for outbound processing.  For inbound, This is not important.
-        */
 };
-static u_int saorder_state_alive[] = {
+static const u_int saorder_state_valid_prefer_new[] = {
+       SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
+};
+static const u_int saorder_state_alive[] = {
        /* except DEAD */
        SADB_SASTATE_MATURE, SADB_SASTATE_DYING, SADB_SASTATE_LARVAL
 };
-static u_int saorder_state_any[] = {
+static const u_int saorder_state_any[] = {
        SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
        SADB_SASTATE_LARVAL, SADB_SASTATE_DEAD
 };
 
-#if defined(__FreeBSD__) || defined (__APPLE__)
+static const int minsize[] = {
+       sizeof(struct sadb_msg),        /* SADB_EXT_RESERVED */
+       sizeof(struct sadb_sa),         /* SADB_EXT_SA */
+       sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_CURRENT */
+       sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_HARD */
+       sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_SOFT */
+       sizeof(struct sadb_address),    /* SADB_EXT_ADDRESS_SRC */
+       sizeof(struct sadb_address),    /* SADB_EXT_ADDRESS_DST */
+       sizeof(struct sadb_address),    /* SADB_EXT_ADDRESS_PROXY */
+       sizeof(struct sadb_key),        /* SADB_EXT_KEY_AUTH */
+       sizeof(struct sadb_key),        /* SADB_EXT_KEY_ENCRYPT */
+       sizeof(struct sadb_ident),      /* SADB_EXT_IDENTITY_SRC */
+       sizeof(struct sadb_ident),      /* SADB_EXT_IDENTITY_DST */
+       sizeof(struct sadb_sens),       /* SADB_EXT_SENSITIVITY */
+       sizeof(struct sadb_prop),       /* SADB_EXT_PROPOSAL */
+       sizeof(struct sadb_supported),  /* SADB_EXT_SUPPORTED_AUTH */
+       sizeof(struct sadb_supported),  /* SADB_EXT_SUPPORTED_ENCRYPT */
+       sizeof(struct sadb_spirange),   /* SADB_EXT_SPIRANGE */
+       0,                              /* SADB_X_EXT_KMPRIVATE */
+       sizeof(struct sadb_x_policy),   /* SADB_X_EXT_POLICY */
+       sizeof(struct sadb_x_sa2),      /* SADB_X_SA2 */
+};
+static const int maxsize[] = {
+       sizeof(struct sadb_msg),        /* SADB_EXT_RESERVED */
+       sizeof(struct sadb_sa_2),               /* SADB_EXT_SA */
+       sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_CURRENT */
+       sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_HARD */
+       sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_SOFT */
+       0,                              /* SADB_EXT_ADDRESS_SRC */
+       0,                              /* SADB_EXT_ADDRESS_DST */
+       0,                              /* SADB_EXT_ADDRESS_PROXY */
+       0,                              /* SADB_EXT_KEY_AUTH */
+       0,                              /* SADB_EXT_KEY_ENCRYPT */
+       0,                              /* SADB_EXT_IDENTITY_SRC */
+       0,                              /* SADB_EXT_IDENTITY_DST */
+       0,                              /* SADB_EXT_SENSITIVITY */
+       0,                              /* SADB_EXT_PROPOSAL */
+       0,                              /* SADB_EXT_SUPPORTED_AUTH */
+       0,                              /* SADB_EXT_SUPPORTED_ENCRYPT */
+       sizeof(struct sadb_spirange),   /* SADB_EXT_SPIRANGE */
+       0,                              /* SADB_X_EXT_KMPRIVATE */
+       0,                              /* SADB_X_EXT_POLICY */
+       sizeof(struct sadb_x_sa2),      /* SADB_X_SA2 */
+};
+
+static int ipsec_esp_keymin = 256;
+static int ipsec_esp_auth = 0;
+static int ipsec_ah_keymin = 128;
+
 SYSCTL_DECL(_net_key);
-//#if defined(IPSEC_DEBUG)
+
 SYSCTL_INT(_net_key, KEYCTL_DEBUG_LEVEL,       debug,  CTLFLAG_RW, \
        &key_debug_level,       0,      "");
-//#endif /* defined(IPSEC_DEBUG) */
+
 
 /* max count of trial for the decision of spi value */
 SYSCTL_INT(_net_key, KEYCTL_SPI_TRY,           spi_trycnt,     CTLFLAG_RW, \
@@ -187,7 +261,29 @@ SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_COUNT,        blockacq_count, CTLFLAG_RW, \
 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_LIFETIME, blockacq_lifetime, CTLFLAG_RW, \
        &key_blockacq_lifetime, 0,      "");
 
-#endif /* __FreeBSD__ */
+/* ESP auth */
+SYSCTL_INT(_net_key, KEYCTL_ESP_AUTH,  esp_auth, CTLFLAG_RW, \
+       &ipsec_esp_auth,        0,      "");
+
+/* minimum ESP key length */
+SYSCTL_INT(_net_key, KEYCTL_ESP_KEYMIN,        esp_keymin, CTLFLAG_RW, \
+       &ipsec_esp_keymin,      0,      "");
+
+/* minimum AH key length */
+SYSCTL_INT(_net_key, KEYCTL_AH_KEYMIN, ah_keymin, CTLFLAG_RW, \
+       &ipsec_ah_keymin,       0,      "");
+
+/* perfered old SA rather than new SA */
+SYSCTL_INT(_net_key, KEYCTL_PREFERED_OLDSA,    prefered_oldsa, CTLFLAG_RW,\
+       &key_preferred_oldsa,   0,      "");
+
+/* time between NATT keepalives in seconds, 0 disabled  */
+SYSCTL_INT(_net_key, KEYCTL_NATT_KEEPALIVE_INTERVAL, natt_keepalive_interval, CTLFLAG_RW,\
+       &natt_keepalive_interval,       0,      "");
+
+/* PF_KEY statistics */
+SYSCTL_STRUCT(_net_key, KEYCTL_PFKEYSTAT, pfkeystat, CTLFLAG_RD,\
+       &pfkeystat, pfkeystat, "");
 
 #ifndef LIST_FOREACH
 #define LIST_FOREACH(elm, head, field)                                     \
@@ -209,20 +305,20 @@ do {\
 
 #define KEY_CHKSASTATE(head, sav, name) \
 do { \
-       if ((head) != (sav)) {                                               \
-               printf("%s: state mismatched (TREE=%d SA=%d)\n",             \
-                       (name), (head), (sav));                              \
-               continue;                                                    \
-       }                                                                    \
+       if ((head) != (sav)) {                                          \
+               ipseclog((LOG_DEBUG, "%s: state mismatched (TREE=%d SA=%d)\n", \
+                       (name), (head), (sav)));                        \
+               continue;                                               \
+       }                                                               \
 } while (0)
 
 #define KEY_CHKSPDIR(head, sp, name) \
 do { \
-       if ((head) != (sp)) {                                                \
-               printf("%s: direction mismatched (TREE=%d SP=%d), "          \
-                       "anyway continue.\n",                                \
-                       (name), (head), (sp));                               \
-       }                                                                    \
+       if ((head) != (sp)) {                                           \
+               ipseclog((LOG_DEBUG, "%s: direction mismatched (TREE=%d SP=%d), " \
+                       "anyway continue.\n",                           \
+                       (name), (head), (sp)));                         \
+       }                                                               \
 } while (0)
 
 #if 1
@@ -264,12 +360,12 @@ do { \
  * set parameters into secasindex buffer.
  * Must allocate secasindex buffer before calling this function.
  */
-#define KEY_SETSECASIDX(p, m, s, d, idx) \
+#define KEY_SETSECASIDX(p, m, r, s, d, idx) \
 do { \
        bzero((idx), sizeof(struct secasindex));                             \
        (idx)->proto = (p);                                                  \
-       (idx)->mode = (m)->sadb_msg_mode;                                    \
-       (idx)->reqid = (m)->sadb_msg_reqid;                                  \
+       (idx)->mode = (m);                                                   \
+       (idx)->reqid = (r);                                                  \
        bcopy((s), &(idx)->src, ((struct sockaddr *)(s))->sa_len);           \
        bcopy((d), &(idx)->dst, ((struct sockaddr *)(d))->sa_len);           \
 } while (0)
@@ -279,115 +375,170 @@ struct _keystat {
        u_long getspi_count; /* the avarage of count to try to get new SPI */
 } keystat;
 
-static struct secasvar *key_allocsa_policy __P((struct secasindex *saidx));
-static void key_freesp_so __P((struct secpolicy **sp));
-static struct secasvar *key_do_allocsa_policy __P((struct secashead *sah,
-                                               u_int state));
-static void key_delsp __P((struct secpolicy *sp));
-static struct secpolicy *key_getsp __P((struct secpolicyindex *spidx));
-static struct secpolicy *key_getspbyid __P((u_int32_t id));
-static u_int32_t key_newreqid __P((void));
-static struct sadb_msg *key_spdadd __P((caddr_t *mhp));
-static u_int32_t key_getnewspid __P((void));
-static struct sadb_msg *key_spddelete __P((caddr_t *mhp));
-static struct sadb_msg *key_spddelete2 __P((caddr_t *mhp));
-static int key_spdget __P((caddr_t *mhp, struct socket *so, int target));
-static struct sadb_msg *key_spdflush __P((caddr_t *mhp));
-static int key_spddump __P((caddr_t *mhp, struct socket *so, int target));
-static struct mbuf *key_setdumpsp __P((struct secpolicy *sp,
-                               u_int8_t type, u_int32_t seq, u_int32_t pid));
-static u_int key_getspmsglen __P((struct secpolicy *sp));
-static u_int key_getspreqmsglen __P((struct secpolicy *sp));
-static struct secashead *key_newsah __P((struct secasindex *saidx));
-static void key_delsah __P((struct secashead *sah));
-static struct secasvar *key_newsav __P((caddr_t *mhp, struct secashead *sah));
-static void key_delsav __P((struct secasvar *sav));
-static struct secashead *key_getsah __P((struct secasindex *saidx));
-static struct secasvar *key_checkspidup __P((struct secasindex *saidx,
-                                               u_int32_t spi));
-static struct secasvar *key_getsavbyspi __P((struct secashead *sah,
-                                               u_int32_t spi));
-static int key_setsaval __P((struct secasvar *sav, caddr_t *mhp));
-static u_int key_getmsglen __P((struct secasvar *sav));
-static int key_mature __P((struct secasvar *sav));
-static u_int key_setdumpsa __P((struct sadb_msg *newmsg, struct secasvar *sav,
-                               u_int8_t type, u_int8_t satype,
-                               u_int32_t seq, u_int32_t pid));
-#if 1
-static int key_setsadbmsg_m __P((struct mbuf *, u_int8_t type, int tlen,
-                               u_int8_t satype, u_int32_t seq, pid_t pid,
-                               u_int8_t mode, u_int32_t reqid,
-                               u_int8_t reserved1, u_int32_t reserved2));
-#endif
-static caddr_t key_setsadbmsg __P((caddr_t buf, u_int8_t type, int tlen,
-                               u_int8_t satype, u_int32_t seq, pid_t pid,
-                               u_int8_t mode, u_int32_t reqid,
-                               u_int8_t reserved1, u_int32_t reserved2));
-static caddr_t key_setsadbsa __P((caddr_t buf, struct secasvar *sav));
-#if 1
-static int key_setsadbaddr_m __P((struct mbuf *m, u_int16_t exttype,
-       struct sockaddr *saddr, u_int8_t prefixlen, u_int16_t ul_proto));
+struct sadb_msghdr {
+       struct sadb_msg *msg;
+       struct sadb_ext *ext[SADB_EXT_MAX + 1];
+       int extoff[SADB_EXT_MAX + 1];
+       int extlen[SADB_EXT_MAX + 1];
+};
+
+static struct secasvar *key_allocsa_policy(struct secasindex *);
+static void key_freesp_so(struct secpolicy **);
+static struct secasvar *key_do_allocsa_policy(struct secashead *, u_int);
+static void key_delsp(struct secpolicy *);
+static struct secpolicy *key_getsp(struct secpolicyindex *);
+static struct secpolicy *key_getspbyid(u_int32_t);
+static u_int32_t key_newreqid(void);
+static struct mbuf *key_gather_mbuf(struct mbuf *,
+       const struct sadb_msghdr *, int, int, int *);
+static int key_spdadd(struct socket *, struct mbuf *,
+       const struct sadb_msghdr *);
+static u_int32_t key_getnewspid(void);
+static int key_spddelete(struct socket *, struct mbuf *,
+       const struct sadb_msghdr *);
+static int key_spddelete2(struct socket *, struct mbuf *,
+       const struct sadb_msghdr *);
+static int key_spdget(struct socket *, struct mbuf *,
+       const struct sadb_msghdr *);
+static int key_spdflush(struct socket *, struct mbuf *,
+       const struct sadb_msghdr *);
+static int key_spddump(struct socket *, struct mbuf *,
+       const struct sadb_msghdr *);
+static struct mbuf *key_setdumpsp(struct secpolicy *,
+       u_int8_t, u_int32_t, u_int32_t);
+static u_int key_getspreqmsglen(struct secpolicy *);
+static int key_spdexpire(struct secpolicy *);
+static struct secashead *key_newsah(struct secasindex *);
+static void key_delsah(struct secashead *);
+static struct secasvar *key_newsav(struct mbuf *,
+       const struct sadb_msghdr *, struct secashead *, int *);
+static void key_delsav(struct secasvar *);
+static struct secashead *key_getsah(struct secasindex *);
+static struct secasvar *key_checkspidup(struct secasindex *, u_int32_t);
+static void key_setspi __P((struct secasvar *, u_int32_t));
+static struct secasvar *key_getsavbyspi(struct secashead *, u_int32_t);
+static int key_setsaval(struct secasvar *, struct mbuf *,
+       const struct sadb_msghdr *);
+static int key_mature(struct secasvar *);
+static struct mbuf *key_setdumpsa(struct secasvar *, u_int8_t,
+       u_int8_t, u_int32_t, u_int32_t);
+static struct mbuf *key_setsadbmsg(u_int8_t, u_int16_t, u_int8_t,
+       u_int32_t, pid_t, u_int16_t);
+static struct mbuf *key_setsadbsa(struct secasvar *);
+static struct mbuf *key_setsadbaddr(u_int16_t,
+       struct sockaddr *, u_int8_t, u_int16_t);
+#if 0
+static struct mbuf *key_setsadbident(u_int16_t, u_int16_t, caddr_t,
+       int, u_int64_t);
 #endif
-static caddr_t key_setsadbaddr __P((caddr_t buf, u_int16_t exttype,
-       struct sockaddr *saddr, u_int8_t prefixlen, u_int16_t ul_proto));
-static caddr_t key_setsadbident
-       __P((caddr_t buf, u_int16_t exttype, u_int16_t idtype,
-               caddr_t string, int stringlen, u_int64_t id));
-static caddr_t key_setsadbxpolicy
-       __P((caddr_t buf, u_int16_t type, u_int8_t dir, u_int32_t id));
-static caddr_t key_setsadbext __P((caddr_t p, caddr_t ext));
-static void *key_newbuf __P((void *src, u_int len));
+static struct mbuf *key_setsadbxsa2(u_int8_t, u_int32_t, u_int32_t);
+static struct mbuf *key_setsadbxpolicy(u_int16_t, u_int8_t,
+       u_int32_t);
+static void *key_newbuf(const void *, u_int);
 #if INET6
-static int key_ismyaddr6 __P((caddr_t addr));
-#endif
-#if 0
-static int key_isloopback __P((u_int family, caddr_t addr));
+static int key_ismyaddr6(struct sockaddr_in6 *);
+#endif
+
+/* flags for key_cmpsaidx() */
+#define CMP_HEAD       1       /* protocol, addresses. */
+#define CMP_MODE_REQID 2       /* additionally HEAD, reqid, mode. */
+#define CMP_REQID      3       /* additionally HEAD, reaid. */
+#define CMP_EXACTLY    4       /* all elements. */
+static int key_cmpsaidx(struct secasindex *, struct secasindex *, int);
+
+static int key_cmpspidx_exactly(struct secpolicyindex *,
+                                       struct secpolicyindex *);
+static int key_cmpspidx_withmask(struct secpolicyindex *,
+                                       struct secpolicyindex *);
+static int key_sockaddrcmp(struct sockaddr *, struct sockaddr *, int);
+static int key_bbcmp(caddr_t, caddr_t, u_int);
+static void key_srandom(void);
+static u_int16_t key_satype2proto(u_int8_t);
+static u_int8_t key_proto2satype(u_int16_t);
+
+static int key_getspi(struct socket *, struct mbuf *,
+       const struct sadb_msghdr *);
+static u_int32_t key_do_getnewspi(struct sadb_spirange *, struct secasindex *);
+static int key_update(struct socket *, struct mbuf *,
+       const struct sadb_msghdr *);
+#if IPSEC_DOSEQCHECK
+static struct secasvar *key_getsavbyseq(struct secashead *, u_int32_t);
 #endif
-static int key_cmpsaidx_exactly
-       __P((struct secasindex *saidx0, struct secasindex *saidx1));
-static int key_cmpsaidx_withmode
-       __P((struct secasindex *saidx0, struct secasindex *saidx1));
-static int key_cmpspidx_exactly
-       __P((struct secpolicyindex *spidx0, struct secpolicyindex *spidx1));
-static int key_cmpspidx_withmask
-       __P((struct secpolicyindex *spidx0, struct secpolicyindex *spidx1));
-static int key_bbcmp __P((caddr_t p1, caddr_t p2, u_int bits));
-static u_int16_t key_satype2proto __P((u_int8_t satype));
-static u_int8_t key_proto2satype __P((u_int16_t proto));
-
-static struct sadb_msg *key_getspi __P((caddr_t *mhp));
-static u_int32_t key_do_getnewspi __P((struct sadb_spirange *spirange,
-                                       struct secasindex *saidx));
-static struct sadb_msg *key_update __P((caddr_t *mhp));
-#ifdef IPSEC_DOSEQCHECK
-static struct secasvar *key_getsavbyseq __P((struct secashead *sah,
-                                               u_int32_t seq));
+static int key_add(struct socket *, struct mbuf *, const struct sadb_msghdr *);
+static int key_setident(struct secashead *, struct mbuf *,
+       const struct sadb_msghdr *);
+static struct mbuf *key_getmsgbuf_x1(struct mbuf *, const struct sadb_msghdr *);
+static int key_delete(struct socket *, struct mbuf *,
+       const struct sadb_msghdr *);
+static int key_get(struct socket *, struct mbuf *, const struct sadb_msghdr *);
+
+static void key_getcomb_setlifetime(struct sadb_comb *);
+#if IPSEC_ESP
+static struct mbuf *key_getcomb_esp(void);
 #endif
-static struct sadb_msg *key_add __P((caddr_t *mhp));
-static int key_setident __P((struct secashead *sah, caddr_t *mhp));
-static struct sadb_msg *key_getmsgbuf_x1 __P((caddr_t *mhp));
-static struct sadb_msg *key_delete __P((caddr_t *mhp));
-static struct sadb_msg *key_get __P((caddr_t *mhp));
-static int key_acquire __P((struct secasindex *, struct secpolicy *));
-static struct secacq *key_newacq __P((struct secasindex *saidx));
-static struct secacq *key_getacq __P((struct secasindex *saidx));
-static struct secacq *key_getacqbyseq __P((u_int32_t seq));
-static struct secspacq *key_newspacq __P((struct secpolicyindex *spidx));
-static struct secspacq *key_getspacq __P((struct secpolicyindex *spidx));
-static struct sadb_msg *key_acquire2 __P((caddr_t *mhp));
-static struct sadb_msg *key_register __P((caddr_t *mhp, struct socket *so));
-static int key_expire __P((struct secasvar *sav));
-static struct sadb_msg *key_flush __P((caddr_t *mhp));
-static int key_dump __P((caddr_t *mhp, struct socket *so, int target));
-static void key_promisc __P((caddr_t *mhp, struct socket *so));
-static int key_sendall __P((struct sadb_msg *msg, u_int len));
-static int key_align __P((struct sadb_msg *msg, caddr_t *mhp));
+static struct mbuf *key_getcomb_ah(void);
+static struct mbuf *key_getcomb_ipcomp(void);
+static struct mbuf *key_getprop(const struct secasindex *);
+
+static int key_acquire(struct secasindex *, struct secpolicy *);
+#ifndef IPSEC_NONBLOCK_ACQUIRE
+static struct secacq *key_newacq(struct secasindex *);
+static struct secacq *key_getacq(struct secasindex *);
+static struct secacq *key_getacqbyseq(u_int32_t);
+#endif
+static struct secspacq *key_newspacq(struct secpolicyindex *);
+static struct secspacq *key_getspacq(struct secpolicyindex *);
+static int key_acquire2(struct socket *, struct mbuf *,
+       const struct sadb_msghdr *);
+static int key_register(struct socket *, struct mbuf *,
+       const struct sadb_msghdr *);
+static int key_expire(struct secasvar *);
+static int key_flush(struct socket *, struct mbuf *,
+       const struct sadb_msghdr *);
+static int key_dump(struct socket *, struct mbuf *, const struct sadb_msghdr *);
+static int key_promisc(struct socket *, struct mbuf *,
+       const struct sadb_msghdr *);
+static int key_senderror(struct socket *, struct mbuf *, int);
+static int key_validate_ext(const struct sadb_ext *, int);
+static int key_align(struct mbuf *, struct sadb_msghdr *);
 #if 0
-static const char *key_getfqdn __P((void));
-static const char *key_getuserfqdn __P((void));
+static const char *key_getfqdn(void);
+static const char *key_getuserfqdn(void);
 #endif
-static void key_sa_chgstate __P((struct secasvar *sav, u_int8_t state));
-static caddr_t key_appendmbuf __P((struct mbuf *, int));
+static void key_sa_chgstate(struct secasvar *, u_int8_t);
+static struct mbuf *key_alloc_mbuf(int);
+
+extern int ipsec_bypass;
+void ipsec_send_natt_keepalive(struct secasvar *sav);
+
+
+/*
+ * PF_KEY init
+ * setup locks and call raw_init()
+ *
+ */
+void
+key_init(void)
+{
+
+       int i;
+       
+       sadb_mutex_grp_attr = lck_grp_attr_alloc_init();
+       sadb_mutex_grp = lck_grp_alloc_init("sadb", sadb_mutex_grp_attr);
+       sadb_mutex_attr = lck_attr_alloc_init();
+       lck_attr_setdefault(sadb_mutex_attr);
+
+       if ((sadb_mutex = lck_mtx_alloc_init(sadb_mutex_grp, sadb_mutex_attr)) == NULL) {
+               printf("key_init: can't alloc sadb_mutex\n");
+               return;
+       }
+
+       for (i = 0; i < SPIHASHSIZE; i++)
+               LIST_INIT(&spihash[i]);
+
+       raw_init();
+}
+
 
 /* %%% IPsec policy management */
 /*
@@ -402,8 +553,10 @@ key_allocsp(spidx, dir)
        u_int dir;
 {
        struct secpolicy *sp;
+       struct timeval tv;
        int s;
 
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
        /* sanity check */
        if (spidx == NULL)
                panic("key_allocsp: NULL pointer is passed.\n");
@@ -418,11 +571,6 @@ key_allocsp(spidx, dir)
        }
 
        /* get a SP entry */
-#ifdef __NetBSD__
-       s = splsoftnet();       /*called from softclock()*/
-#else
-       s = splnet();   /*called from softclock()*/
-#endif
        KEYDEBUG(KEYDEBUG_IPSEC_DATA,
                printf("*** objects\n");
                kdebug_secpolicyindex(spidx));
@@ -438,7 +586,6 @@ key_allocsp(spidx, dir)
                        goto found;
        }
 
-       splx(s);
        return NULL;
 
 found:
@@ -446,8 +593,9 @@ found:
        KEY_CHKSPDIR(sp->spidx.dir, dir, "key_allocsp");
 
        /* found a SPD entry */
+       microtime(&tv);
+       sp->lastused = tv.tv_sec;
        sp->refcnt++;
-       splx(s);
        KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
                printf("DP key_allocsp cause refcnt++:%d SP:%p\n",
                        sp->refcnt, sp));
@@ -456,8 +604,81 @@ found:
 }
 
 /*
- * allocating a SA entry for a *OUTBOUND* packet.
- * checking each request entries in SP, and acquire SA if need.
+ * return a policy that matches this particular inbound packet.
+ * XXX slow
+ */
+struct secpolicy *
+key_gettunnel(osrc, odst, isrc, idst)
+       struct sockaddr *osrc, *odst, *isrc, *idst;
+{
+       struct secpolicy *sp;
+       const int dir = IPSEC_DIR_INBOUND;
+       struct timeval tv;
+       int s;
+       struct ipsecrequest *r1, *r2, *p;
+       struct sockaddr *os, *od, *is, *id;
+       struct secpolicyindex spidx;
+
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
+       if (isrc->sa_family != idst->sa_family) {
+               ipseclog((LOG_ERR, "protocol family mismatched %d != %d\n.",
+                       isrc->sa_family, idst->sa_family));
+               return NULL;
+       }
+
+       LIST_FOREACH(sp, &sptree[dir], chain) {
+               if (sp->state == IPSEC_SPSTATE_DEAD)
+                       continue;
+
+               r1 = r2 = NULL;
+               for (p = sp->req; p; p = p->next) {
+                       if (p->saidx.mode != IPSEC_MODE_TUNNEL)
+                               continue;
+
+                       r1 = r2;
+                       r2 = p;
+
+                       if (!r1) {
+                               /* here we look at address matches only */
+                               spidx = sp->spidx;
+                               if (isrc->sa_len > sizeof(spidx.src) ||
+                                   idst->sa_len > sizeof(spidx.dst))
+                                       continue;
+                               bcopy(isrc, &spidx.src, isrc->sa_len);
+                               bcopy(idst, &spidx.dst, idst->sa_len);
+                               if (!key_cmpspidx_withmask(&sp->spidx, &spidx))
+                                       continue;
+                       } else {
+                               is = (struct sockaddr *)&r1->saidx.src;
+                               id = (struct sockaddr *)&r1->saidx.dst;
+                               if (key_sockaddrcmp(is, isrc, 0) ||
+                                   key_sockaddrcmp(id, idst, 0))
+                                       continue;
+                       }
+
+                       os = (struct sockaddr *)&r2->saidx.src;
+                       od = (struct sockaddr *)&r2->saidx.dst;
+                       if (key_sockaddrcmp(os, osrc, 0) ||
+                           key_sockaddrcmp(od, odst, 0))
+                               continue;
+
+                       goto found;
+               }
+       }
+
+       return NULL;
+
+found:
+       microtime(&tv);
+       sp->lastused = tv.tv_sec;
+       sp->refcnt++;
+       return sp;
+}
+
+/*
+ * allocating an SA entry for an *OUTBOUND* packet.
+ * checking each request entries in SP, and acquire an SA if need.
  * OUT:        0: there are valid requests.
  *     ENOENT: policy may be valid, but SA with REQUIRE is on acquiring.
  */
@@ -469,6 +690,8 @@ key_checkrequest(isr, saidx)
        u_int level;
        int error;
 
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        /* sanity check */
        if (isr == NULL || saidx == NULL)
                panic("key_checkrequest: NULL pointer is passed.\n");
@@ -535,11 +758,9 @@ key_checkrequest(isr, saidx)
 
        /* there is no SA */
        if ((error = key_acquire(saidx, isr->sp)) != 0) {
-               /* XXX What I do ? */
-#ifdef IPSEC_DEBUG
-               printf("key_checkrequest: error %d returned "
-                       "from key_acquire.\n", error);
-#endif
+               /* XXX What should I do ? */
+               ipseclog((LOG_DEBUG, "key_checkrequest: error %d returned "
+                       "from key_acquire.\n", error));
                return error;
        }
 
@@ -559,11 +780,15 @@ key_allocsa_policy(saidx)
        struct secashead *sah;
        struct secasvar *sav;
        u_int stateidx, state;
+       const u_int *saorder_state_valid;
+       int arraysize;
+
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
 
        LIST_FOREACH(sah, &sahtree, chain) {
                if (sah->state == SADB_SASTATE_DEAD)
                        continue;
-               if (key_cmpsaidx_withmode(&sah->saidx, saidx))
+               if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID))
                        goto found;
        }
 
@@ -571,10 +796,19 @@ key_allocsa_policy(saidx)
 
     found:
 
-       /* search valid state */
-       for (stateidx = 0;
-            stateidx < _ARRAYLEN(saorder_state_valid);
-            stateidx++) {
+       /*
+        * search a valid state list for outbound packet.
+        * This search order is important.
+        */
+       if (key_preferred_oldsa) {
+               saorder_state_valid = saorder_state_valid_prefer_old;
+               arraysize = _ARRAYLEN(saorder_state_valid_prefer_old);
+       } else {
+               saorder_state_valid = saorder_state_valid_prefer_new;
+               arraysize = _ARRAYLEN(saorder_state_valid_prefer_new);
+       }
+
+       for (stateidx = 0; stateidx < arraysize; stateidx++) {
 
                state = saorder_state_valid[stateidx];
 
@@ -598,12 +832,18 @@ key_do_allocsa_policy(sah, state)
        struct secashead *sah;
        u_int state;
 {
-       struct secasvar *sav, *candidate;
+       struct secasvar *sav, *nextsav, *candidate, *d;
+
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
 
        /* initilize */
        candidate = NULL;
 
-       LIST_FOREACH(sav, &sah->savtree[state], chain) {
+       for (sav = LIST_FIRST(&sah->savtree[state]);
+            sav != NULL;
+            sav = nextsav) {
+
+               nextsav = LIST_NEXT(sav, chain);
 
                /* sanity check */
                KEY_CHKSASTATE(sav->state, state, "key_do_allocsa_policy");
@@ -621,11 +861,82 @@ key_do_allocsa_policy(sah, state)
                        panic("key_do_allocsa_policy: "
                                "lifetime_current is NULL.\n");
 
-               /* XXX What the best method is to compare ? */
-               if (candidate->lft_c->sadb_lifetime_addtime >
+               /* What the best method is to compare ? */
+               if (key_preferred_oldsa) {
+                       if (candidate->lft_c->sadb_lifetime_addtime >
+                                       sav->lft_c->sadb_lifetime_addtime) {
+                               candidate = sav;
+                       }
+                       continue;
+                       /*NOTREACHED*/
+               }
+
+               /* prefered new sa rather than old sa */
+               if (candidate->lft_c->sadb_lifetime_addtime <
                                sav->lft_c->sadb_lifetime_addtime) {
+                       d = candidate;
                        candidate = sav;
-                       continue;
+               } else
+                       d = sav;
+
+               /*
+                * prepared to delete the SA when there is more
+                * suitable candidate and the lifetime of the SA is not
+                * permanent.
+                */
+               if (d->lft_c->sadb_lifetime_addtime != 0) {
+                       struct mbuf *m, *result;
+
+                       key_sa_chgstate(d, SADB_SASTATE_DEAD);
+
+                       m = key_setsadbmsg(SADB_DELETE, 0,
+                           d->sah->saidx.proto, 0, 0, d->refcnt - 1);
+                       if (!m)
+                               goto msgfail;
+                       result = m;
+
+                       /* set sadb_address for saidx's. */
+                       m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
+                               (struct sockaddr *)&d->sah->saidx.src,
+                               d->sah->saidx.src.ss_len << 3,
+                               IPSEC_ULPROTO_ANY);
+                       if (!m)
+                               goto msgfail;
+                       m_cat(result, m);
+
+                       /* set sadb_address for saidx's. */
+                       m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
+                               (struct sockaddr *)&d->sah->saidx.src,
+                               d->sah->saidx.src.ss_len << 3,
+                               IPSEC_ULPROTO_ANY);
+                       if (!m)
+                               goto msgfail;
+                       m_cat(result, m);
+
+                       /* create SA extension */
+                       m = key_setsadbsa(d);
+                       if (!m)
+                               goto msgfail;
+                       m_cat(result, m);
+
+                       if (result->m_len < sizeof(struct sadb_msg)) {
+                               result = m_pullup(result,
+                                               sizeof(struct sadb_msg));
+                               if (result == NULL)
+                                       goto msgfail;
+                       }
+
+                       result->m_pkthdr.len = 0;
+                       for (m = result; m; m = m->m_next)
+                               result->m_pkthdr.len += m->m_len;
+                       mtod(result, struct sadb_msg *)->sadb_msg_len =
+                               PFKEY_UNIT64(result->m_pkthdr.len);
+
+                       if (key_sendup_mbuf(NULL, result,
+                                       KEY_SENDUP_REGISTERED))
+                               goto msgfail;
+                msgfail:
+                       key_freesav(d);
                }
        }
 
@@ -643,7 +954,7 @@ key_do_allocsa_policy(sah, state)
  * allocating a SA entry for a *INBOUND* packet.
  * Must call key_freesav() later.
  * OUT: positive:      pointer to a sav.
- *     NULL:           not found, or error occured.
+ *     NULL:           not found, or error occurred.
  *
  * In the comparison, source address will be ignored for RFC2401 conformance.
  * To quote, from section 4.1:
@@ -651,7 +962,7 @@ key_do_allocsa_policy(sah, state)
  *     of a Security Parameter Index (SPI), an IP Destination Address, and a
  *     security protocol (AH or ESP) identifier.
  * Note that, however, we do need to keep source address in IPsec SA.
- * IPsec SA.  IKE specification and PF_KEY specification do assume that we
+ * IKE specification and PF_KEY specification do assume that we
  * keep source address in IPsec SA.  We see a tricky situation here.
  */
 struct secasvar *
@@ -660,70 +971,150 @@ key_allocsa(family, src, dst, proto, spi)
        caddr_t src, dst;
        u_int32_t spi;
 {
-       struct secashead *sah;
-       struct secasvar *sav;
-       u_int stateidx, state;
+       struct secasvar *sav, *match;
+       u_int stateidx, state, tmpidx, matchidx;
+       struct sockaddr_in sin;
+       struct sockaddr_in6 sin6;
        int s;
+       const u_int *saorder_state_valid;
+       int arraysize;
+
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
 
        /* sanity check */
        if (src == NULL || dst == NULL)
                panic("key_allocsa: NULL pointer is passed.\n");
 
+       /*
+        * when both systems employ similar strategy to use a SA.
+        * the search order is important even in the inbound case.
+        */
+       if (key_preferred_oldsa) {
+               saorder_state_valid = saorder_state_valid_prefer_old;
+               arraysize = _ARRAYLEN(saorder_state_valid_prefer_old);
+       } else {
+               saorder_state_valid = saorder_state_valid_prefer_new;
+               arraysize = _ARRAYLEN(saorder_state_valid_prefer_new);
+       }
+
        /*
         * searching SAD.
         * XXX: to be checked internal IP header somewhere.  Also when
         * IPsec tunnel packet is received.  But ESP tunnel mode is
         * encrypted so we can't check internal IP header.
         */
-#ifdef __NetBSD__
-       s = splsoftnet();       /*called from softclock()*/
-#else
-       s = splnet();   /*called from softclock()*/
-#endif
-       LIST_FOREACH(sah, &sahtree, chain) {
-
-               /* search valid state */
-               for (stateidx = 0;
-                    stateidx < _ARRAYLEN(saorder_state_valid);
-                    stateidx++) {
-
+       /*
+        * search a valid state list for inbound packet.
+        * the search order is not important.
+        */
+       match = NULL;
+       matchidx = arraysize;
+       LIST_FOREACH(sav, &spihash[SPIHASH(spi)], spihash) {
+               if (sav->spi != spi)
+                       continue;
+               if (proto != sav->sah->saidx.proto)
+                       continue;
+               if (family != sav->sah->saidx.src.ss_family ||
+                   family != sav->sah->saidx.dst.ss_family)
+                       continue;
+               tmpidx = arraysize;
+               for (stateidx = 0; stateidx < matchidx; stateidx++) {
                        state = saorder_state_valid[stateidx];
-                       LIST_FOREACH(sav, &sah->savtree[state], chain) {
-
-                               /* sanity check */
-                               KEY_CHKSASTATE(sav->state, state, "key_allocsav");
-                               if (proto != sav->sah->saidx.proto)
-                                       continue;
-                               if (spi != sav->spi)
-                                       continue;
+                       if (sav->state == state) {
+                               tmpidx = stateidx;
+                               break;
+                       }
+               }
+               if (tmpidx >= matchidx)
+                       continue;
 
 #if 0  /* don't check src */
-                               if (!key_bbcmp(src,
-                                    _INADDRBYSA(&sav->sah->saidx.src),
-                                    _INALENBYAF(sav->sah->saidx.src.ss_family) << 3))
-                                       continue;
+               /* check src address */
+               switch (family) {
+               case AF_INET:
+                       bzero(&sin, sizeof(sin));
+                       sin.sin_family = AF_INET;
+                       sin.sin_len = sizeof(sin);
+                       bcopy(src, &sin.sin_addr,
+                           sizeof(sin.sin_addr));
+                       if (key_sockaddrcmp((struct sockaddr*)&sin,
+                           (struct sockaddr *)&sav->sah->saidx.src, 0) != 0)
+                               continue;
+                       break;
+               case AF_INET6:
+                  bzero(&sin6, sizeof(sin6));
+                  sin6.sin6_family = AF_INET6;
+                  sin6.sin6_len = sizeof(sin6);
+                  bcopy(src, &sin6.sin6_addr,
+                          sizeof(sin6.sin6_addr));
+                  if (IN6_IS_SCOPE_LINKLOCAL(&sin6.sin6_addr)) {
+                                  /* kame fake scopeid */
+                                  sin6.sin6_scope_id =
+                                          ntohs(sin6.sin6_addr.s6_addr16[1]);
+                                  sin6.sin6_addr.s6_addr16[1] = 0;
+                  }
+                  if (key_sockaddrcmp((struct sockaddr*)&sin6,
+                           (struct sockaddr *)&sav->sah->saidx.src, 0) != 0)
+                               continue;
+                       break;
+               default:
+                       ipseclog((LOG_DEBUG, "key_allocsa: "
+                           "unknown address family=%d.\n",
+                           family));
+                       continue;
+               }
+
 #endif
-                               if (!key_bbcmp(dst,
-                                    _INADDRBYSA(&sav->sah->saidx.dst),
-                                    _INALENBYAF(sav->sah->saidx.dst.ss_family) << 3))
-                                       continue;
+               /* check dst address */
+               switch (family) {
+               case AF_INET:
+                       bzero(&sin, sizeof(sin));
+                       sin.sin_family = AF_INET;
+                       sin.sin_len = sizeof(sin);
+                       bcopy(dst, &sin.sin_addr,
+                           sizeof(sin.sin_addr));
+                       if (key_sockaddrcmp((struct sockaddr*)&sin,
+                           (struct sockaddr *)&sav->sah->saidx.dst, 0) != 0)
+                               continue;
 
-                               goto found;
-                       }
+                       break;
+               case AF_INET6:
+                  bzero(&sin6, sizeof(sin6));
+                  sin6.sin6_family = AF_INET6;
+                  sin6.sin6_len = sizeof(sin6);
+                  bcopy(dst, &sin6.sin6_addr,
+                          sizeof(sin6.sin6_addr));
+                  if (IN6_IS_SCOPE_LINKLOCAL(&sin6.sin6_addr)) {
+                                  /* kame fake scopeid */
+                                  sin6.sin6_scope_id =
+                                          ntohs(sin6.sin6_addr.s6_addr16[1]);
+                                  sin6.sin6_addr.s6_addr16[1] = 0;
+                  }
+                  if (key_sockaddrcmp((struct sockaddr*)&sin6,
+                           (struct sockaddr *)&sav->sah->saidx.dst, 0) != 0)
+                               continue;
+                       break;
+               default:
+                       ipseclog((LOG_DEBUG, "key_allocsa: "
+                           "unknown address family=%d.\n", family));
+                       continue;
                }
+
+               match = sav;
+               matchidx = tmpidx;
        }
+       if (match)
+               goto found;
 
        /* not found */
-       splx(s);
        return NULL;
 
 found:
-       sav->refcnt++;
-       splx(s);
+       match->refcnt++;        
        KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
                printf("DP allocsa cause refcnt++:%d SA:%p\n",
-                       sav->refcnt, sav));
-       return sav;
+                       match->refcnt, match));
+       return match;
 }
 
 /*
@@ -734,6 +1125,8 @@ void
 key_freesp(sp)
        struct secpolicy *sp;
 {
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        /* sanity check */
        if (sp == NULL)
                panic("key_freesp: NULL pointer is passed.\n");
@@ -749,6 +1142,7 @@ key_freesp(sp)
        return;
 }
 
+#if 0
 /*
  * Must be called after calling key_allocsp().
  * For the packet with socket.
@@ -757,6 +1151,8 @@ void
 key_freeso(so)
        struct socket *so;
 {
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        /* sanity check */
        if (so == NULL)
                panic("key_freeso: NULL pointer is passed.\n");
@@ -768,7 +1164,7 @@ key_freeso(so)
                struct inpcb *pcb = sotoinpcb(so);
 
                /* Does it have a PCB ? */
-               if (pcb == NULL)
+               if (pcb == NULL || pcb->inp_sp == NULL)
                        return;
                key_freesp_so(&pcb->inp_sp->sp_in);
                key_freesp_so(&pcb->inp_sp->sp_out);
@@ -782,7 +1178,7 @@ key_freeso(so)
                struct inpcb *pcb  = sotoinpcb(so);
 
                /* Does it have a PCB ? */
-               if (pcb == NULL)
+               if (pcb == NULL || pcb->inp_sp == NULL)
                        return;
                key_freesp_so(&pcb->inp_sp->sp_in);
                key_freesp_so(&pcb->inp_sp->sp_out);
@@ -790,7 +1186,7 @@ key_freeso(so)
                struct in6pcb *pcb  = sotoin6pcb(so);
 
                /* Does it have a PCB ? */
-               if (pcb == NULL)
+               if (pcb == NULL || pcb->in6p_sp == NULL)
                        return;
                key_freesp_so(&pcb->in6p_sp->sp_in);
                key_freesp_so(&pcb->in6p_sp->sp_out);
@@ -799,20 +1195,22 @@ key_freeso(so)
                break;
 #endif /* INET6 */
        default:
-#if IPSEC_DEBUG
-               printf("key_freeso: unknown address family=%d.\n",
-                       so->so_proto->pr_domain->dom_family);
-#endif
+               ipseclog((LOG_DEBUG, "key_freeso: unknown address family=%d.\n",
+                   so->so_proto->pr_domain->dom_family));
                return;
        }
 
        return;
 }
+#endif
 
 static void
 key_freesp_so(sp)
        struct secpolicy **sp;
 {
+
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        /* sanity check */
        if (sp == NULL || *sp == NULL)
                panic("key_freesp_so: sp == NULL\n");
@@ -843,13 +1241,15 @@ void
 key_freesav(sav)
        struct secasvar *sav;
 {
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        /* sanity check */
        if (sav == NULL)
                panic("key_freesav: NULL pointer is passed.\n");
 
        sav->refcnt--;
        KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
-               printf("DP freesav cause refcnt--:%d SA:%p SPI %d\n",
+               printf("DP freesav cause refcnt--:%d SA:%p SPI %u\n",
                        sav->refcnt, sav, (u_int32_t)ntohl(sav->spi)));
 
        if (sav->refcnt == 0)
@@ -868,6 +1268,8 @@ key_delsp(sp)
 {
        int s;
 
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        /* sanity check */
        if (sp == NULL)
                panic("key_delsp: NULL pointer is passed.\n");
@@ -877,11 +1279,7 @@ key_delsp(sp)
        if (sp->refcnt > 0)
                return; /* can't free */
 
-#if __NetBSD__
-       s = splsoftnet();       /*called from softclock()*/
-#else
        s = splnet();   /*called from softclock()*/
-#endif
        /* remove from SP index */
        if (__LIST_CHAINED(sp))
                LIST_REMOVE(sp, chain);
@@ -922,6 +1320,8 @@ key_getsp(spidx)
 {
        struct secpolicy *sp;
 
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        /* sanity check */
        if (spidx == NULL)
                panic("key_getsp: NULL pointer is passed.\n");
@@ -949,6 +1349,8 @@ key_getspbyid(id)
 {
        struct secpolicy *sp;
 
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        LIST_FOREACH(sp, &sptree[IPSEC_DIR_INBOUND], chain) {
                if (sp->state == IPSEC_SPSTATE_DEAD)
                        continue;
@@ -998,15 +1400,15 @@ key_msg2sp(xpl0, len, error)
 {
        struct secpolicy *newsp;
 
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        /* sanity check */
        if (xpl0 == NULL)
                panic("key_msg2sp: NULL pointer was passed.\n");
        if (len < sizeof(*xpl0))
                panic("key_msg2sp: invalid length.\n");
        if (len != PFKEY_EXTLEN(xpl0)) {
-#if IPSEC_DEBUG
-               printf("key_msg2sp: Invalid msg length.\n");
-#endif
+               ipseclog((LOG_DEBUG, "key_msg2sp: Invalid msg length.\n"));
                *error = EINVAL;
                return NULL;
        }
@@ -1036,9 +1438,8 @@ key_msg2sp(xpl0, len, error)
 
                /* validity check */
                if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) {
-#if IPSEC_DEBUG
-                       printf("key_msg2sp: Invalid msg length.\n");
-#endif
+                       ipseclog((LOG_DEBUG,
+                           "key_msg2sp: Invalid msg length.\n"));
                        key_freesp(newsp);
                        *error = EINVAL;
                        return NULL;
@@ -1051,10 +1452,8 @@ key_msg2sp(xpl0, len, error)
 
                        /* length check */
                        if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) {
-#if IPSEC_DEBUG
-                               printf("key_msg2sp: "
-                                       "invalid ipsecrequest length.\n");
-#endif
+                               ipseclog((LOG_DEBUG, "key_msg2sp: "
+                                       "invalid ipsecrequest length.\n"));
                                key_freesp(newsp);
                                *error = EINVAL;
                                return NULL;
@@ -1063,9 +1462,8 @@ key_msg2sp(xpl0, len, error)
                        /* allocate request buffer */
                        KMALLOC(*p_isr, struct ipsecrequest *, sizeof(**p_isr));
                        if ((*p_isr) == NULL) {
-#if IPSEC_DEBUG
-                               printf("key_msg2sp: No more memory.\n");
-#endif
+                               ipseclog((LOG_DEBUG,
+                                   "key_msg2sp: No more memory.\n"));
                                key_freesp(newsp);
                                *error = ENOBUFS;
                                return NULL;
@@ -1078,15 +1476,12 @@ key_msg2sp(xpl0, len, error)
                        switch (xisr->sadb_x_ipsecrequest_proto) {
                        case IPPROTO_ESP:
                        case IPPROTO_AH:
-#if 1  /*nonstandard*/
                        case IPPROTO_IPCOMP:
-#endif
                                break;
                        default:
-#if IPSEC_DEBUG
-                               printf("key_msg2sp: invalid proto type=%u\n",
-                                       xisr->sadb_x_ipsecrequest_proto);
-#endif
+                               ipseclog((LOG_DEBUG,
+                                   "key_msg2sp: invalid proto type=%u\n",
+                                   xisr->sadb_x_ipsecrequest_proto));
                                key_freesp(newsp);
                                *error = EPROTONOSUPPORT;
                                return NULL;
@@ -1099,10 +1494,9 @@ key_msg2sp(xpl0, len, error)
                                break;
                        case IPSEC_MODE_ANY:
                        default:
-#if IPSEC_DEBUG
-                               printf("key_msg2sp: invalid mode=%u\n",
-                                       xisr->sadb_x_ipsecrequest_mode);
-#endif
+                               ipseclog((LOG_DEBUG,
+                                   "key_msg2sp: invalid mode=%u\n",
+                                   xisr->sadb_x_ipsecrequest_mode));
                                key_freesp(newsp);
                                *error = EINVAL;
                                return NULL;
@@ -1122,12 +1516,10 @@ key_msg2sp(xpl0, len, error)
                                 */
                                if (xisr->sadb_x_ipsecrequest_reqid
                                                > IPSEC_MANUAL_REQID_MAX) {
-#if IPSEC_DEBUG
-                                       printf("key_msg2sp: reqid=%d "
-                                               "range violation, "
-                                               "updated by kernel.\n",
-                                               xisr->sadb_x_ipsecrequest_reqid);
-#endif
+                                       ipseclog((LOG_DEBUG,
+                                           "key_msg2sp: reqid=%d range "
+                                           "violation, updated by kernel.\n",
+                                           xisr->sadb_x_ipsecrequest_reqid));
                                        xisr->sadb_x_ipsecrequest_reqid = 0;
                                }
 
@@ -1149,10 +1541,8 @@ key_msg2sp(xpl0, len, error)
                                break;
 
                        default:
-#if IPSEC_DEBUG
-                               printf("key_msg2sp: invalid level=%u\n",
-                                       xisr->sadb_x_ipsecrequest_level);
-#endif
+                               ipseclog((LOG_DEBUG, "key_msg2sp: invalid level=%u\n",
+                                       xisr->sadb_x_ipsecrequest_level));
                                key_freesp(newsp);
                                *error = EINVAL;
                                return NULL;
@@ -1168,10 +1558,8 @@ key_msg2sp(xpl0, len, error)
                                /* validity check */
                                if (paddr->sa_len
                                    > sizeof((*p_isr)->saidx.src)) {
-#if IPSEC_DEBUG
-                                       printf("key_msg2sp: invalid request "
-                                               "address length.\n");
-#endif
+                                       ipseclog((LOG_DEBUG, "key_msg2sp: invalid request "
+                                               "address length.\n"));
                                        key_freesp(newsp);
                                        *error = EINVAL;
                                        return NULL;
@@ -1185,10 +1573,8 @@ key_msg2sp(xpl0, len, error)
                                /* validity check */
                                if (paddr->sa_len
                                    > sizeof((*p_isr)->saidx.dst)) {
-#if IPSEC_DEBUG
-                                       printf("key_msg2sp: invalid request "
-                                               "address length.\n");
-#endif
+                                       ipseclog((LOG_DEBUG, "key_msg2sp: invalid request "
+                                               "address length.\n"));
                                        key_freesp(newsp);
                                        *error = EINVAL;
                                        return NULL;
@@ -1206,9 +1592,7 @@ key_msg2sp(xpl0, len, error)
 
                        /* validity check */
                        if (tlen < 0) {
-#if IPSEC_DEBUG
-                               printf("key_msg2sp: becoming tlen < 0.\n");
-#endif
+                               ipseclog((LOG_DEBUG, "key_msg2sp: becoming tlen < 0.\n"));
                                key_freesp(newsp);
                                *error = EINVAL;
                                return NULL;
@@ -1220,9 +1604,7 @@ key_msg2sp(xpl0, len, error)
            }
                break;
        default:
-#if IPSEC_DEBUG
-               printf("key_msg2sp: invalid policy type.\n");
-#endif
+               ipseclog((LOG_DEBUG, "key_msg2sp: invalid policy type.\n"));
                key_freesp(newsp);
                *error = EINVAL;
                return NULL;
@@ -1237,6 +1619,8 @@ key_newreqid()
 {
        static u_int32_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
 
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        auto_reqid = (auto_reqid == ~0
                        ? IPSEC_MANUAL_REQID_MAX + 1 : auto_reqid + 1);
 
@@ -1257,27 +1641,18 @@ key_sp2msg(sp)
        caddr_t p;
        struct mbuf *m;
 
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        /* sanity check. */
        if (sp == NULL)
                panic("key_sp2msg: NULL pointer was passed.\n");
 
        tlen = key_getspreqmsglen(sp);
 
-       MGET(m, M_DONTWAIT, MT_DATA);
-       if (m && MLEN < tlen) {
-               MCLGET(m, M_DONTWAIT);
-               if ((m->m_flags & M_EXT) == 0) {
-                       m_free(m);
-                       m = NULL;
-               }
-       }
-       m->m_len = 0;
-       if (!m || M_TRAILINGSPACE(m) < tlen) {
-#if IPSEC_DEBUG
-               printf("key_sp2msg: No more memory.\n");
-#endif
+       m = key_alloc_mbuf(tlen);
+       if (!m || m->m_next) {  /*XXX*/
                if (m)
-                       m_free(m);
+                       m_freem(m);
                return NULL;
        }
 
@@ -1323,57 +1698,142 @@ key_sp2msg(sp)
        return m;
 }
 
+/* m will not be freed nor modified */
+static struct mbuf *
+key_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp,
+       int ndeep, int nitem, int *items)
+{
+       int idx;
+       int i;
+       struct mbuf *result = NULL, *n;
+       int len;
+
+       if (m == NULL || mhp == NULL)
+               panic("null pointer passed to key_gather");
+
+       for (i = 0; i < nitem; i++) {
+               idx = items[i];
+               if (idx < 0 || idx > SADB_EXT_MAX)
+                       goto fail;
+               /* don't attempt to pull empty extension */
+               if (idx == SADB_EXT_RESERVED && mhp->msg == NULL)
+                       continue;
+               if (idx != SADB_EXT_RESERVED  &&
+                   (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0))
+                       continue;
+
+               if (idx == SADB_EXT_RESERVED) {
+                       len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
+#if DIAGNOSTIC
+                       if (len > MHLEN)
+                               panic("assumption failed");
+#endif
+                       MGETHDR(n, M_DONTWAIT, MT_DATA);
+                       if (!n)
+                               goto fail;
+                       n->m_len = len;
+                       n->m_next = NULL;
+                       m_copydata(m, 0, sizeof(struct sadb_msg),
+                           mtod(n, caddr_t));
+               } else if (i < ndeep) {
+                       len = mhp->extlen[idx];
+                       n = key_alloc_mbuf(len);
+                       if (!n || n->m_next) {  /*XXX*/
+                               if (n)
+                                       m_freem(n);
+                               goto fail;
+                       }
+                       m_copydata(m, mhp->extoff[idx], mhp->extlen[idx],
+                           mtod(n, caddr_t));
+               } else {
+                       n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx],
+                           M_DONTWAIT);
+               }
+               if (n == NULL)
+                       goto fail;
+
+               if (result)
+                       m_cat(result, n);
+               else
+                       result = n;
+       }
+
+       if ((result->m_flags & M_PKTHDR) != 0) {
+               result->m_pkthdr.len = 0;
+               for (n = result; n; n = n->m_next)
+                       result->m_pkthdr.len += n->m_len;
+       }
+
+       return result;
+
+fail:
+       m_freem(result);
+       return NULL;
+}
+
 /*
  * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing
  * add a entry to SP database, when received
- *   <base, address(SD), policy>
+ *   <base, address(SD), (lifetime(H),) policy>
  * from the user(?).
  * Adding to SP database,
  * and send
- *   <base, address(SD), policy>
+ *   <base, address(SD), (lifetime(H),) policy>
  * to the socket which was send.
  *
  * SPDADD set a unique policy entry.
  * SPDSETIDX like SPDADD without a part of policy requests.
  * SPDUPDATE replace a unique policy entry.
  *
- * IN: mhp: pointer to the pointer to each header.
- * OUT:        NULL if fail.
- *     other if success, return pointer to the message to send.
- *
+ * m will always be freed.
  */
-static struct sadb_msg *
-key_spdadd(mhp)
-       caddr_t *mhp;
+static int
+key_spdadd(so, m, mhp)
+       struct socket *so;
+       struct mbuf *m;
+       const struct sadb_msghdr *mhp;
 {
-       struct sadb_msg *msg0;
        struct sadb_address *src0, *dst0;
-       struct sadb_x_policy *xpl0;
+       struct sadb_x_policy *xpl0, *xpl;
+       struct sadb_lifetime *lft = NULL;
        struct secpolicyindex spidx;
        struct secpolicy *newsp;
+       struct timeval tv;
        int error;
 
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        /* sanity check */
-       if (mhp == NULL || mhp[0] == NULL)
+       if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
                panic("key_spdadd: NULL pointer is passed.\n");
 
-       msg0 = (struct sadb_msg *)mhp[0];
-
-       if (mhp[SADB_EXT_ADDRESS_SRC] == NULL
-        || mhp[SADB_EXT_ADDRESS_DST] == NULL
-        || mhp[SADB_X_EXT_POLICY] == NULL) {
-#if IPSEC_DEBUG
-               printf("key_spdadd: invalid message is passed.\n");
-#endif
-               msg0->sadb_msg_errno = EINVAL;
-               return NULL;
+       if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
+           mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
+           mhp->ext[SADB_X_EXT_POLICY] == NULL) {
+               ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
+               return key_senderror(so, m, EINVAL);
+       }
+       if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
+           mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
+           mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
+               ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
+               return key_senderror(so, m, EINVAL);
+       }
+       if (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL) {
+               if (mhp->extlen[SADB_EXT_LIFETIME_HARD]
+                       < sizeof(struct sadb_lifetime)) {
+                       ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
+                       return key_senderror(so, m, EINVAL);
+               }
+               lft = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
        }
 
-       src0 = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_SRC];
-       dst0 = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_DST];
-       xpl0 = (struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY];
+       src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
+       dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
+       xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
 
        /* make secindex */
+       /* XXX boundary check against sa_len */
        KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
                        src0 + 1,
                        dst0 + 1,
@@ -1388,75 +1848,58 @@ key_spdadd(mhp)
        case IPSEC_DIR_OUTBOUND:
                break;
        default:
-#if IPSEC_DEBUG
-               printf("key_spdadd: Invalid SP direction.\n");
-#endif
-               msg0->sadb_msg_errno = EINVAL;
-               return NULL;
+               ipseclog((LOG_DEBUG, "key_spdadd: Invalid SP direction.\n"));
+               mhp->msg->sadb_msg_errno = EINVAL;
+               return 0;
        }
 
        /* check policy */
        /* key_spdadd() accepts DISCARD, NONE and IPSEC. */
        if (xpl0->sadb_x_policy_type == IPSEC_POLICY_ENTRUST
         || xpl0->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
-#if IPSEC_DEBUG
-               printf("key_spdadd: Invalid policy type.\n");
-#endif
-               msg0->sadb_msg_errno = EINVAL;
-               return NULL;
+               ipseclog((LOG_DEBUG, "key_spdadd: Invalid policy type.\n"));
+               return key_senderror(so, m, EINVAL);
        }
 
        /* policy requests are mandatory when action is ipsec. */
-        if (msg0->sadb_msg_type != SADB_X_SPDSETIDX
+        if (mhp->msg->sadb_msg_type != SADB_X_SPDSETIDX
         && xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC
-        && PFKEY_EXTLEN(xpl0) <= sizeof(*xpl0)) {
-#if IPSEC_DEBUG
-               printf("key_spdadd: some policy requests part required.\n");
-#endif
-               msg0->sadb_msg_errno = EINVAL;
-               return NULL;
+        && mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) {
+               ipseclog((LOG_DEBUG, "key_spdadd: some policy requests part required.\n"));
+               return key_senderror(so, m, EINVAL);
        }
 
        /*
         * checking there is SP already or not.
-        * If type is SPDUPDATE and no SP found, then error.
-        * If type is either SPDADD or SPDSETIDX and SP found, then error.
+        * SPDUPDATE doesn't depend on whether there is a SP or not.
+        * If the type is either SPDADD or SPDSETIDX AND a SP is found,
+        * then error.
         */
        newsp = key_getsp(&spidx);
-       if (msg0->sadb_msg_type == SADB_X_SPDUPDATE) {
-               if (newsp == NULL) {
-#if IPSEC_DEBUG
-                       printf("key_spdadd: no SP found.\n");
-#endif
-                       msg0->sadb_msg_errno = ENOENT;
-                       return NULL;
+       if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
+               if (newsp) {
+                       newsp->state = IPSEC_SPSTATE_DEAD;
+                       key_freesp(newsp);
                }
-
-               newsp->state = IPSEC_SPSTATE_DEAD;
-               key_freesp(newsp);
        } else {
                if (newsp != NULL) {
                        key_freesp(newsp);
-#if IPSEC_DEBUG
-                       printf("key_spdadd: a SP entry exists already.\n");
-#endif
-                       msg0->sadb_msg_errno = EEXIST;
-                       return NULL;
+                       ipseclog((LOG_DEBUG, "key_spdadd: a SP entry exists already.\n"));
+                       return key_senderror(so, m, EEXIST);
                }
        }
 
        /* allocation new SP entry */
        if ((newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error)) == NULL) {
-               msg0->sadb_msg_errno = error;
-               return NULL;
+               return key_senderror(so, m, error);
        }
 
        if ((newsp->id = key_getnewspid()) == 0) {
-               msg0->sadb_msg_errno = ENOBUFS;
                keydb_delsecpolicy(newsp);
-               return NULL;
+               return key_senderror(so, m, ENOBUFS);
        }
 
+       /* XXX boundary check against sa_len */
        KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
                        src0 + 1,
                        dst0 + 1,
@@ -1468,83 +1911,102 @@ key_spdadd(mhp)
        /* sanity check on addr pair */
        if (((struct sockaddr *)(src0 + 1))->sa_family !=
                        ((struct sockaddr *)(dst0+ 1))->sa_family) {
-               msg0->sadb_msg_errno = EINVAL;
                keydb_delsecpolicy(newsp);
-               return NULL;
+               return key_senderror(so, m, EINVAL);
+       }
+       if (((struct sockaddr *)(src0 + 1))->sa_len !=
+                       ((struct sockaddr *)(dst0+ 1))->sa_len) {
+               keydb_delsecpolicy(newsp);
+               return key_senderror(so, m, EINVAL);
        }
 #if 1
        if (newsp->req && newsp->req->saidx.src.ss_family) {
                struct sockaddr *sa;
                sa = (struct sockaddr *)(src0 + 1);
                if (sa->sa_family != newsp->req->saidx.src.ss_family) {
-                       msg0->sadb_msg_errno = EINVAL;
                        keydb_delsecpolicy(newsp);
-                       return NULL;
+                       return key_senderror(so, m, EINVAL);
                }
        }
        if (newsp->req && newsp->req->saidx.dst.ss_family) {
                struct sockaddr *sa;
                sa = (struct sockaddr *)(dst0 + 1);
                if (sa->sa_family != newsp->req->saidx.dst.ss_family) {
-                       msg0->sadb_msg_errno = EINVAL;
                        keydb_delsecpolicy(newsp);
-                       return NULL;
+                       return key_senderror(so, m, EINVAL);
                }
        }
 #endif
 
+       microtime(&tv);
+       newsp->created = tv.tv_sec;
+       newsp->lastused = tv.tv_sec;
+       newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
+       newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
+
        newsp->refcnt = 1;      /* do not reclaim until I say I do */
        newsp->state = IPSEC_SPSTATE_ALIVE;
-       LIST_INSERT_HEAD(&sptree[newsp->spidx.dir], newsp, chain);
+       LIST_INSERT_TAIL(&sptree[newsp->spidx.dir], newsp, secpolicy, chain);
+
+       /* Turn off the ipsec bypass */
+       if (ipsec_bypass != 0)
+               ipsec_bypass = 0;
 
        /* delete the entry in spacqtree */
-       if (msg0->sadb_msg_type == SADB_X_SPDUPDATE) {
+       if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
                struct secspacq *spacq;
                if ((spacq = key_getspacq(&spidx)) != NULL) {
-                       /* reset counter in order to deletion by timehander. */
-                       spacq->tick = key_blockacq_lifetime;
+                       /* reset counter in order to deletion by timehandler. */
+                       microtime(&tv);
+                       spacq->created = tv.tv_sec;
                        spacq->count = 0;
                }
        }
 
     {
+       struct mbuf *n, *mpolicy;
        struct sadb_msg *newmsg;
-       u_int len;
-       caddr_t p;
+       int off;
 
        /* create new sadb_msg to reply. */
-       len = sizeof(struct sadb_msg)
-           + PFKEY_EXTLEN(mhp[SADB_X_EXT_POLICY])
-           + PFKEY_EXTLEN(mhp[SADB_EXT_ADDRESS_SRC])
-           + PFKEY_EXTLEN(mhp[SADB_EXT_ADDRESS_DST]);
-
-       KMALLOC(newmsg, struct sadb_msg *, len);
-       if (newmsg == NULL) {
-#if IPSEC_DEBUG
-               printf("key_spdadd: No more memory.\n");
-#endif
-               /* newsp persists in the kernel */
-               msg0->sadb_msg_errno = ENOBUFS;
-               return NULL;
+       if (lft) {
+               int     mbufItems[] = {SADB_EXT_RESERVED, SADB_X_EXT_POLICY,
+                                          SADB_EXT_LIFETIME_HARD, SADB_EXT_ADDRESS_SRC,
+                                          SADB_EXT_ADDRESS_DST};
+               n = key_gather_mbuf(m, mhp, 2, sizeof(mbufItems)/sizeof(int), mbufItems);
+       } else {
+               int     mbufItems[] = {SADB_EXT_RESERVED, SADB_X_EXT_POLICY,
+                                          SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST};
+               n = key_gather_mbuf(m, mhp, 2, sizeof(mbufItems)/sizeof(int), mbufItems);
        }
-       bzero((caddr_t)newmsg, len);
+       if (!n)
+               return key_senderror(so, m, ENOBUFS);
 
-       bcopy((caddr_t)msg0, (caddr_t)newmsg, sizeof(*msg0));
+       if (n->m_len < sizeof(*newmsg)) {
+               n = m_pullup(n, sizeof(*newmsg));
+               if (!n)
+                       return key_senderror(so, m, ENOBUFS);
+       }
+       newmsg = mtod(n, struct sadb_msg *);
        newmsg->sadb_msg_errno = 0;
-       newmsg->sadb_msg_len = PFKEY_UNIT64(len);
-       p = (caddr_t)newmsg + sizeof(*msg0);
+       newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
 
-       /*
-        * reqid may had been updated at key_msg2sp() if reqid's
-        * range violation.
-        */
-       ((struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY])->sadb_x_policy_id = newsp->id;
-       p = key_setsadbext(p, mhp[SADB_X_EXT_POLICY]);
-
-       p = key_setsadbext(p, mhp[SADB_EXT_ADDRESS_SRC]);
-       p = key_setsadbext(p, mhp[SADB_EXT_ADDRESS_DST]);
+       off = 0;
+       mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
+           sizeof(*xpl), &off);
+       if (mpolicy == NULL) {
+               /* n is already freed */
+               return key_senderror(so, m, ENOBUFS);
+       }
+       xpl = (struct sadb_x_policy *)(mtod(mpolicy, caddr_t) + off);
+       if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
+               m_freem(n);
+               return key_senderror(so, m, EINVAL);
+       }
+       xpl->sadb_x_policy_id = newsp->id;
 
-       return newmsg;
+       m_freem(m);
+       return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
     }
 }
 
@@ -1561,9 +2023,11 @@ key_getnewspid()
        int count = key_spi_trycnt;     /* XXX */
        struct secpolicy *sp;
 
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        /* when requesting to allocate spi ranged */
        while (count--) {
-               newid = (policy_id = (policy_id == ~0 ? 1 : ++policy_id));
+               newid = (policy_id = (policy_id == ~0 ? 1 : policy_id + 1));
 
                if ((sp = key_getspbyid(newid)) == NULL)
                        break;
@@ -1572,9 +2036,7 @@ key_getnewspid()
        }
 
        if (count == 0 || newid == 0) {
-#if IPSEC_DEBUG
-               printf("key_getnewspid: to allocate policy id is failed.\n");
-#endif
+               ipseclog((LOG_DEBUG, "key_getnewspid: to allocate policy id is failed.\n"));
                return 0;
        }
 
@@ -1591,41 +2053,44 @@ key_getnewspid()
  * to the ikmpd.
  * policy(*) including direction of policy.
  *
- * IN: mhp: pointer to the pointer to each header.
- * OUT:        other if success, return pointer to the message to send.
- *     0 if fail.
+ * m will always be freed.
  */
-static struct sadb_msg *
-key_spddelete(mhp)
-       caddr_t *mhp;
+static int
+key_spddelete(so, m, mhp)
+       struct socket *so;
+       struct mbuf *m;
+       const struct sadb_msghdr *mhp;
 {
-       struct sadb_msg *msg0;
        struct sadb_address *src0, *dst0;
        struct sadb_x_policy *xpl0;
        struct secpolicyindex spidx;
        struct secpolicy *sp;
 
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        /* sanity check */
-       if (mhp == NULL || mhp[0] == NULL)
+       if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
                panic("key_spddelete: NULL pointer is passed.\n");
 
-       msg0 = (struct sadb_msg *)mhp[0];
-
-       if (mhp[SADB_EXT_ADDRESS_SRC] == NULL
-        || mhp[SADB_EXT_ADDRESS_DST] == NULL
-        || mhp[SADB_X_EXT_POLICY] == NULL) {
-#if IPSEC_DEBUG
-               printf("key_spddelete: invalid message is passed.\n");
-#endif
-               msg0->sadb_msg_errno = EINVAL;
-               return NULL;
+       if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
+           mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
+           mhp->ext[SADB_X_EXT_POLICY] == NULL) {
+               ipseclog((LOG_DEBUG, "key_spddelete: invalid message is passed.\n"));
+               return key_senderror(so, m, EINVAL);
+       }
+       if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
+           mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
+           mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
+               ipseclog((LOG_DEBUG, "key_spddelete: invalid message is passed.\n"));
+               return key_senderror(so, m, EINVAL);
        }
 
-       src0 = (struct sadb_address *)(mhp[SADB_EXT_ADDRESS_SRC]);
-       dst0 = (struct sadb_address *)(mhp[SADB_EXT_ADDRESS_DST]);
-       xpl0 = (struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY];
+       src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
+       dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
+       xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
 
        /* make secindex */
+       /* XXX boundary check against sa_len */
        KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
                        src0 + 1,
                        dst0 + 1,
@@ -1640,20 +2105,14 @@ key_spddelete(mhp)
        case IPSEC_DIR_OUTBOUND:
                break;
        default:
-#if IPSEC_DEBUG
-               printf("key_spddelete: Invalid SP direction.\n");
-#endif
-               msg0->sadb_msg_errno = EINVAL;
-               return NULL;
+               ipseclog((LOG_DEBUG, "key_spddelete: Invalid SP direction.\n"));
+               return key_senderror(so, m, EINVAL);
        }
 
        /* Is there SP in SPD ? */
        if ((sp = key_getsp(&spidx)) == NULL) {
-#if IPSEC_DEBUG
-               printf("key_spddelete: no SP found.\n");
-#endif
-               msg0->sadb_msg_errno = ENOENT;
-               return NULL;
+               ipseclog((LOG_DEBUG, "key_spddelete: no SP found.\n"));
+               return key_senderror(so, m, EINVAL);
        }
 
        /* save policy id to buffer to be returned. */
@@ -1663,36 +2122,22 @@ key_spddelete(mhp)
        key_freesp(sp);
 
     {
+       struct mbuf *n;
        struct sadb_msg *newmsg;
-       u_int len;
-       caddr_t p;
+       int     mbufItems[] = {SADB_EXT_RESERVED, SADB_X_EXT_POLICY,
+                                       SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST};
 
        /* create new sadb_msg to reply. */
-       len = sizeof(struct sadb_msg)
-           + PFKEY_EXTLEN(mhp[SADB_X_EXT_POLICY])
-           + PFKEY_EXTLEN(mhp[SADB_EXT_ADDRESS_SRC])
-           + PFKEY_EXTLEN(mhp[SADB_EXT_ADDRESS_DST]);
-
-       KMALLOC(newmsg, struct sadb_msg *, len);
-       if (newmsg == NULL) {
-#if IPSEC_DEBUG
-               printf("key_spddelete: No more memory.\n");
-#endif
-               msg0->sadb_msg_errno = ENOBUFS;
-               return NULL;
-       }
-       bzero((caddr_t)newmsg, len);
+       n = key_gather_mbuf(m, mhp, 1, sizeof(mbufItems)/sizeof(int), mbufItems);
+       if (!n)
+               return key_senderror(so, m, ENOBUFS);
 
-       bcopy((caddr_t)mhp[0], (caddr_t)newmsg, sizeof(*msg0));
+       newmsg = mtod(n, struct sadb_msg *);
        newmsg->sadb_msg_errno = 0;
-       newmsg->sadb_msg_len = PFKEY_UNIT64(len);
-       p = (caddr_t)newmsg + sizeof(*msg0);
-
-       p = key_setsadbext(p, mhp[SADB_X_EXT_POLICY]);
-       p = key_setsadbext(p, mhp[SADB_EXT_ADDRESS_SRC]);
-       p = key_setsadbext(p, mhp[SADB_EXT_ADDRESS_DST]);
+       newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
 
-       return newmsg;
+       m_freem(m);
+       return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
     }
 }
 
@@ -1706,73 +2151,91 @@ key_spddelete(mhp)
  * to the ikmpd.
  * policy(*) including direction of policy.
  *
- * IN: mhp: pointer to the pointer to each header.
- * OUT:        other if success, return pointer to the message to send.
- *     0 if fail.
+ * m will always be freed.
  */
-static struct sadb_msg *
-key_spddelete2(mhp)
-       caddr_t *mhp;
+static int
+key_spddelete2(so, m, mhp)
+       struct socket *so;
+       struct mbuf *m;
+       const struct sadb_msghdr *mhp;
 {
-       struct sadb_msg *msg0;
        u_int32_t id;
        struct secpolicy *sp;
 
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        /* sanity check */
-       if (mhp == NULL || mhp[0] == NULL)
+       if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
                panic("key_spddelete2: NULL pointer is passed.\n");
 
-       msg0 = (struct sadb_msg *)mhp[0];
-
-       if (mhp[SADB_X_EXT_POLICY] == NULL) {
-#if IPSEC_DEBUG
-               printf("key_spddelete2: invalid message is passed.\n");
-#endif
-               msg0->sadb_msg_errno = EINVAL;
-               return NULL;
+       if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
+           mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
+               ipseclog((LOG_DEBUG, "key_spddelete2: invalid message is passed.\n"));
+               key_senderror(so, m, EINVAL);
+               return 0;
        }
 
-       id = ((struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY])->sadb_x_policy_id;
+       id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
 
        /* Is there SP in SPD ? */
        if ((sp = key_getspbyid(id)) == NULL) {
-#if IPSEC_DEBUG
-               printf("key_spddelete2: no SP found id:%u.\n", id);
-#endif
-               msg0->sadb_msg_errno = ENOENT;
-               return NULL;
+               ipseclog((LOG_DEBUG, "key_spddelete2: no SP found id:%u.\n", id));
+               key_senderror(so, m, EINVAL);
        }
 
        sp->state = IPSEC_SPSTATE_DEAD;
        key_freesp(sp);
 
     {
+       struct mbuf *n, *nn;
        struct sadb_msg *newmsg;
-       u_int len;
-       caddr_t p;
+       int off, len;
 
        /* create new sadb_msg to reply. */
-       len = sizeof(struct sadb_msg)
-           + PFKEY_EXTLEN(mhp[SADB_X_EXT_POLICY]);
+       len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
+
+       if (len > MCLBYTES)
+               return key_senderror(so, m, ENOBUFS);
+       MGETHDR(n, M_DONTWAIT, MT_DATA);
+       if (n && len > MHLEN) {
+               MCLGET(n, M_DONTWAIT);
+               if ((n->m_flags & M_EXT) == 0) {
+                       m_freem(n);
+                       n = NULL;
+               }
+       }
+       if (!n)
+               return key_senderror(so, m, ENOBUFS);
+
+       n->m_len = len;
+       n->m_next = NULL;
+       off = 0;
 
-       KMALLOC(newmsg, struct sadb_msg *, len);
-       if (newmsg == NULL) {
-#if IPSEC_DEBUG
-               printf("key_spddelete2: No more memory.\n");
+       m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
+       off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
+
+#if DIAGNOSTIC
+       if (off != len)
+               panic("length inconsistency in key_spddelete2");
 #endif
-               msg0->sadb_msg_errno = ENOBUFS;
-               return NULL;
+
+       n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
+           mhp->extlen[SADB_X_EXT_POLICY], M_DONTWAIT);
+       if (!n->m_next) {
+               m_freem(n);
+               return key_senderror(so, m, ENOBUFS);
        }
-       bzero((caddr_t)newmsg, len);
 
-       bcopy((caddr_t)mhp[0], (caddr_t)newmsg, sizeof(*msg0));
-       newmsg->sadb_msg_errno = 0;
-       newmsg->sadb_msg_len = PFKEY_UNIT64(len);
-       p = (caddr_t)newmsg + sizeof(*msg0);
+       n->m_pkthdr.len = 0;
+       for (nn = n; nn; nn = nn->m_next)
+               n->m_pkthdr.len += nn->m_len;
 
-       p = key_setsadbext(p, mhp[SADB_X_EXT_POLICY]);
+       newmsg = mtod(n, struct sadb_msg *);
+       newmsg->sadb_msg_errno = 0;
+       newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
 
-       return newmsg;
+       m_freem(m);
+       return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
     }
 }
 
@@ -1786,49 +2249,44 @@ key_spddelete2(mhp)
  * to the ikmpd.
  * policy(*) including direction of policy.
  *
- * IN: mhp: pointer to the pointer to each header.
- * OUT:        other if success, return pointer to the message to send.
- *     0 if fail.
+ * m will always be freed.
  */
 static int
-key_spdget(mhp, so, target)
-       caddr_t *mhp;
+key_spdget(so, m, mhp)
        struct socket *so;
-       int target;
+       struct mbuf *m;
+       const struct sadb_msghdr *mhp;
 {
-       struct sadb_msg *msg0;
        u_int32_t id;
        struct secpolicy *sp;
-       struct mbuf *m;
+       struct mbuf *n;
+
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
 
        /* sanity check */
-       if (mhp == NULL || mhp[0] == NULL)
+       if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
                panic("key_spdget: NULL pointer is passed.\n");
 
-       msg0 = (struct sadb_msg *)mhp[0];
-
-       if (mhp[SADB_X_EXT_POLICY] == NULL) {
-#if IPSEC_DEBUG
-               printf("key_spdget: invalid message is passed.\n");
-#endif
-               return EINVAL;
+       if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
+           mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
+               ipseclog((LOG_DEBUG, "key_spdget: invalid message is passed.\n"));
+               return key_senderror(so, m, EINVAL);
        }
 
-       id = ((struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY])->sadb_x_policy_id;
+       id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
 
        /* Is there SP in SPD ? */
        if ((sp = key_getspbyid(id)) == NULL) {
-#if IPSEC_DEBUG
-               printf("key_spdget: no SP found id:%u.\n", id);
-#endif
-               return ENOENT;
+               ipseclog((LOG_DEBUG, "key_spdget: no SP found id:%u.\n", id));
+               return key_senderror(so, m, ENOENT);
        }
 
-       m = key_setdumpsp(sp, SADB_X_SPDGET, 0, msg0->sadb_msg_pid);
-       if (m != NULL)
-               key_sendup_mbuf(so, m, target);
-
-       return 0;
+       n = key_setdumpsp(sp, SADB_X_SPDGET, 0, mhp->msg->sadb_msg_pid);
+       if (n != NULL) {
+               m_freem(m);
+               return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
+       } else
+               return key_senderror(so, m, ENOBUFS);
 }
 
 /*
@@ -1837,7 +2295,7 @@ key_spdget(mhp, so, target)
  * send
  *   <base, policy(*)>
  * to KMD, and expect to receive
- *   <base> with SADB_X_SPDACQUIRE if error occured,
+ *   <base> with SADB_X_SPDACQUIRE if error occurred,
  * or
  *   <base, policy>
  * with SADB_X_SPDUPDATE from KMD by PF_KEY.
@@ -1850,9 +2308,12 @@ int
 key_spdacquire(sp)
        struct secpolicy *sp;
 {
+       struct mbuf *result = NULL, *m;
        struct secspacq *newspacq;
        int error;
 
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        /* sanity check */
        if (sp == NULL)
                panic("key_spdacquire: NULL pointer is passed.\n");
@@ -1880,69 +2341,27 @@ key_spdacquire(sp)
                LIST_INSERT_HEAD(&spacqtree, newspacq, chain);
        }
 
-    {
-       struct sadb_msg *newmsg = NULL;
-       union sadb_x_ident_id id;
-       u_int len;
-       caddr_t p;
-
        /* create new sadb_msg to reply. */
-       len = sizeof(struct sadb_msg)
-               + sizeof(struct sadb_ident)
-               + PFKEY_ALIGN8(sp->spidx.src.ss_len)
-               + sizeof(struct sadb_ident)
-               + PFKEY_ALIGN8(sp->spidx.dst.ss_len);
-
-       KMALLOC(newmsg, struct sadb_msg *, len);
-       if (newmsg == 0) {
-#if IPSEC_DEBUG
-               printf("key_spdacquire: No more memory.\n");
-#endif
-               return ENOBUFS;
+       m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
+       if (!m) {
+               error = ENOBUFS;
+               goto fail;
        }
-       bzero((caddr_t)newmsg, len);
+       result = m;
 
-       newmsg->sadb_msg_version = PF_KEY_V2;
-       newmsg->sadb_msg_type = SADB_X_SPDACQUIRE;
-       newmsg->sadb_msg_errno = 0;
-       newmsg->sadb_msg_satype = 0;
-       newmsg->sadb_msg_len = PFKEY_UNIT64(len);
-       newmsg->sadb_msg_mode = 0;
-       newmsg->sadb_msg_reqid = 0;
-       newmsg->sadb_msg_seq = 0;
-       newmsg->sadb_msg_pid = 0;
-       p = (caddr_t)newmsg + sizeof(struct sadb_msg);
-
-       /* set sadb_address for spidx's. */
-       bzero(&id, sizeof(id));
-       id.sadb_x_ident_id_addr.prefix = sp->spidx.prefs;
-       id.sadb_x_ident_id_addr.ul_proto = sp->spidx.ul_proto;
-       p = key_setsadbident(p,
-                           SADB_EXT_IDENTITY_SRC,
-                           SADB_X_IDENTTYPE_ADDR,
-                           (caddr_t)&sp->spidx.src,
-                           sp->spidx.src.ss_len,
-                           *(u_int64_t *)&id);
-
-       bzero(&id, sizeof(id));
-       id.sadb_x_ident_id_addr.prefix = sp->spidx.prefd;
-       id.sadb_x_ident_id_addr.ul_proto = sp->spidx.ul_proto;
-       p = key_setsadbident(p,
-                           SADB_EXT_IDENTITY_DST,
-                           SADB_X_IDENTTYPE_ADDR,
-                           (caddr_t)&sp->spidx.dst,
-                           sp->spidx.dst.ss_len,
-                           *(u_int64_t *)&id);
-
-       error = key_sendall(newmsg, len);
-#if IPSEC_DEBUG
-       if (error != 0)
-               printf("key_spdacquire: key_sendall returned %d\n", error);
-#endif
-       return error;
-    }
+       result->m_pkthdr.len = 0;
+       for (m = result; m; m = m->m_next)
+               result->m_pkthdr.len += m->m_len;
 
-       return 0;
+       mtod(result, struct sadb_msg *)->sadb_msg_len =
+           PFKEY_UNIT64(result->m_pkthdr.len);
+
+       return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
+
+fail:
+       if (result)
+               m_freem(result);
+       return error;
 }
 
 /*
@@ -1955,23 +2374,26 @@ key_spdacquire(sp)
  * to the user.
  * NOTE: what to do is only marking SADB_SASTATE_DEAD.
  *
- * IN: mhp: pointer to the pointer to each header.
- * OUT:        other if success, return pointer to the message to send.
- *     0 if fail.
+ * m will always be freed.
  */
-static struct sadb_msg *
-key_spdflush(mhp)
-       caddr_t *mhp;
+static int
+key_spdflush(so, m, mhp)
+       struct socket *so;
+       struct mbuf *m;
+       const struct sadb_msghdr *mhp;
 {
-       struct sadb_msg *msg0;
+       struct sadb_msg *newmsg;
        struct secpolicy *sp;
        u_int dir;
 
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        /* sanity check */
-       if (mhp == NULL || mhp[0] == NULL)
+       if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
                panic("key_spdflush: NULL pointer is passed.\n");
 
-       msg0 = (struct sadb_msg *)mhp[0];
+       if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
+               return key_senderror(so, m, EINVAL);
 
        for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
                LIST_FOREACH(sp, &sptree[dir], chain) {
@@ -1979,29 +2401,20 @@ key_spdflush(mhp)
                }
        }
 
-    {
-       struct sadb_msg *newmsg;
-       u_int len;
-
-       /* create new sadb_msg to reply. */
-       len = sizeof(struct sadb_msg);
-
-       KMALLOC(newmsg, struct sadb_msg *, len);
-       if (newmsg == NULL) {
-#if IPSEC_DEBUG
-               printf("key_spdflush: No more memory.\n");
-#endif
-               msg0->sadb_msg_errno = ENOBUFS;
-               return NULL;
+       if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
+               ipseclog((LOG_DEBUG, "key_spdflush: No more memory.\n"));
+               return key_senderror(so, m, ENOBUFS);
        }
-       bzero((caddr_t)newmsg, len);
 
-       bcopy((caddr_t)mhp[0], (caddr_t)newmsg, sizeof(*msg0));
+       if (m->m_next)
+               m_freem(m->m_next);
+       m->m_next = NULL;
+       m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
+       newmsg = mtod(m, struct sadb_msg *);
        newmsg->sadb_msg_errno = 0;
-       newmsg->sadb_msg_len = PFKEY_UNIT64(len);
+       newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
 
-       return(newmsg);
-    }
+       return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
 }
 
 /*
@@ -2013,28 +2426,25 @@ key_spdflush(mhp)
  *   <base> .....
  * to the ikmpd.
  *
- * IN: mhp: pointer to the pointer to each header.
- * OUT:        other if success, return pointer to the message to send.
- *     0 if fail.
+ * m will always be freed.
  */
 static int
-key_spddump(mhp, so, target)
-       caddr_t *mhp;
+key_spddump(so, m, mhp)
        struct socket *so;
-       int target;
+       struct mbuf *m;
+       const struct sadb_msghdr *mhp;
 {
-       struct sadb_msg *msg0;
        struct secpolicy *sp;
        int cnt;
        u_int dir;
-       struct mbuf *m;
+       struct mbuf *n;
+
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
 
        /* sanity check */
-       if (mhp == NULL || mhp[0] == NULL)
+       if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
                panic("key_spddump: NULL pointer is passed.\n");
 
-       msg0 = (struct sadb_msg *)mhp[0];
-
        /* search SPD entry and get buffer size. */
        cnt = 0;
        for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
@@ -2044,19 +2454,20 @@ key_spddump(mhp, so, target)
        }
 
        if (cnt == 0)
-               return ENOENT;
+               return key_senderror(so, m, ENOENT);
 
        for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
                LIST_FOREACH(sp, &sptree[dir], chain) {
                        --cnt;
-                       m = key_setdumpsp(sp, SADB_X_SPDDUMP,
-                                           cnt, msg0->sadb_msg_pid);
+                       n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt,
+                           mhp->msg->sadb_msg_pid);
 
-                       if (m)
-                               key_sendup_mbuf(so, m, target);
+                       if (n)
+                               key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
                }
        }
 
+       m_freem(m);
        return 0;
 }
 
@@ -2066,108 +2477,55 @@ key_setdumpsp(sp, type, seq, pid)
        u_int8_t type;
        u_int32_t seq, pid;
 {
-       struct mbuf *m;
-       u_int tlen;
-
-       /* XXX it would be better to avoid pre-computing length */
-       tlen = key_getspmsglen(sp);
+       struct mbuf *result = NULL, *m;
 
-       /* XXX maybe it's a wrong idea to insist on cluster? */
-       MGETHDR(m, M_DONTWAIT, MT_DATA);
-       if (m != NULL) {
-               MCLGET(m, M_DONTWAIT);
-               if ((m->m_flags & M_EXT) == 0) {
-                       m_freem(m);
-                       m = NULL;
-               }
-       }
-       if (m == NULL)
-               return NULL;    /*ENOBUFS*/
-
-       m->m_pkthdr.len = m->m_len = 0;
-       m->m_next = NULL;
-
-       /* sadb_msg->sadb_msg_len must be filled afterwards */
-       if (key_setsadbmsg_m(m, type, 0, SADB_SATYPE_UNSPEC, seq, pid,
-                   IPSEC_MODE_ANY, 0, 0, sp->refcnt) != 0) {
-               m_freem(m);
-               return NULL;
-       }
-
-       if (key_setsadbaddr_m(m, SADB_EXT_ADDRESS_SRC,
-                   (struct sockaddr *)&sp->spidx.src, sp->spidx.prefs,
-                   sp->spidx.ul_proto) != 0) {
-               m_freem(m);
-               return NULL;
-       }
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
 
-       if (key_setsadbaddr_m(m, SADB_EXT_ADDRESS_DST,
-                   (struct sockaddr *)&sp->spidx.dst, sp->spidx.prefd,
-                   sp->spidx.ul_proto) != 0) {
-               m_freem(m);
-               return NULL;
-       }
+       m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid, sp->refcnt);
+       if (!m)
+               goto fail;
+       result = m;
 
-    {
-       struct mbuf *n;
-       struct sadb_x_policy *tmp;
+       m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
+           (struct sockaddr *)&sp->spidx.src, sp->spidx.prefs,
+           sp->spidx.ul_proto);
+       if (!m)
+               goto fail;
+       m_cat(result, m);
 
-       n = key_sp2msg(sp);
-       if (!n || n->m_len < sizeof(*tmp)) {
-#if IPSEC_DEBUG
-               printf("key_setdumpsp: No more memory.\n");
-#endif
-               m_freem(m);
-               if (n)
-                       m_freem(n);
-               return NULL;
-       }
+       m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
+           (struct sockaddr *)&sp->spidx.dst, sp->spidx.prefd,
+           sp->spidx.ul_proto);
+       if (!m)
+               goto fail;
+       m_cat(result, m);
 
-       tmp = mtod(n, struct sadb_x_policy *);
+       m = key_sp2msg(sp);
+       if (!m)
+               goto fail;
+       m_cat(result, m);
 
-       /* validity check */
-       if (key_getspreqmsglen(sp) != PFKEY_UNUNIT64(tmp->sadb_x_policy_len)
-        || n->m_len != PFKEY_UNUNIT64(tmp->sadb_x_policy_len))
-               panic("key_setdumpsp: length mismatch."
-                     "sp:%d msg:%d\n",
-                       key_getspreqmsglen(sp),
-                       PFKEY_UNUNIT64(tmp->sadb_x_policy_len));
-       
-       m_cat(m, n);
-       m->m_pkthdr.len += n->m_len;
-    }
+       if ((result->m_flags & M_PKTHDR) == 0)
+               goto fail;
 
-       if (m->m_len < sizeof(struct sadb_msg)) {
-               m = m_pullup(m, sizeof(struct sadb_msg));
-               if (m == NULL)
-                       return NULL;
+       if (result->m_len < sizeof(struct sadb_msg)) {
+               result = m_pullup(result, sizeof(struct sadb_msg));
+               if (result == NULL)
+                       goto fail;
        }
-       mtod(m, struct sadb_msg *)->sadb_msg_len =
-           PFKEY_UNIT64(m->m_pkthdr.len);
-
-       return m;
-}
-
-/* get sadb message length for a SP. */
-static u_int
-key_getspmsglen(sp)
-       struct secpolicy *sp;
-{
-       u_int tlen;
 
-       /* sanity check */
-       if (sp == NULL)
-               panic("key_getspmsglen: NULL pointer is passed.\n");
+       result->m_pkthdr.len = 0;
+       for (m = result; m; m = m->m_next)
+               result->m_pkthdr.len += m->m_len;
 
-       tlen = (sizeof(struct sadb_msg)
-               + sizeof(struct sadb_address)
-               + PFKEY_ALIGN8(_SALENBYAF(sp->spidx.src.ss_family))
-               + sizeof(struct sadb_address)
-               + PFKEY_ALIGN8(_SALENBYAF(sp->spidx.dst.ss_family)));
+       mtod(result, struct sadb_msg *)->sadb_msg_len =
+           PFKEY_UNIT64(result->m_pkthdr.len);
 
-       tlen += key_getspreqmsglen(sp);
+       return result;
 
-       return tlen;
+fail:
+       m_freem(result);
+       return NULL;
 }
 
 /*
@@ -2179,6 +2537,8 @@ key_getspreqmsglen(sp)
 {
        u_int tlen;
 
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        tlen = sizeof(struct sadb_x_policy);
 
        /* if is the policy for ipsec ? */
@@ -2202,38 +2562,155 @@ key_getspreqmsglen(sp)
        return tlen;
 }
 
-/* %%% SAD management */
 /*
- * allocating a memory for new SA head, and copy from the values of mhp.
- * OUT:        NULL    : failure due to the lack of memory.
- *     others  : pointer to new SA head.
+ * SADB_SPDEXPIRE processing
+ * send
+ *   <base, address(SD), lifetime(CH), policy>
+ * to KMD by PF_KEY.
+ *
+ * OUT:        0       : succeed
+ *     others  : error number
  */
-static struct secashead *
-key_newsah(saidx)
-       struct secasindex *saidx;
+static int
+key_spdexpire(sp)
+       struct secpolicy *sp;
 {
-       struct secashead *newsah;
+       int s;
+       struct mbuf *result = NULL, *m;
+       int len;
+       int error = -1;
+       struct sadb_lifetime *lt;
+
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
 
        /* sanity check */
-       if (saidx == NULL)
-               panic("key_newsaidx: NULL pointer is passed.\n");
+       if (sp == NULL)
+               panic("key_spdexpire: NULL pointer is passed.\n");
 
-       newsah = keydb_newsecashead();
-       if (newsah == NULL)
-               return NULL;
+       /* set msg header */
+       m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
+       if (!m) {
+               error = ENOBUFS;
+               goto fail;
+       }
+       result = m;
 
-       bcopy(saidx, &newsah->saidx, sizeof(newsah->saidx));
+       /* create lifetime extension (current and hard) */
+       len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
+       m = key_alloc_mbuf(len);
+       if (!m || m->m_next) {  /*XXX*/
+               if (m)
+                       m_freem(m);
+               error = ENOBUFS;
+               goto fail;
+       }
+       bzero(mtod(m, caddr_t), len);
+       lt = mtod(m, struct sadb_lifetime *);
+       lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
+       lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
+       lt->sadb_lifetime_allocations = 0;
+       lt->sadb_lifetime_bytes = 0;
+       lt->sadb_lifetime_addtime = sp->created;
+       lt->sadb_lifetime_usetime = sp->lastused;
+       lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
+       lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
+       lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
+       lt->sadb_lifetime_allocations = 0;
+       lt->sadb_lifetime_bytes = 0;
+       lt->sadb_lifetime_addtime = sp->lifetime;
+       lt->sadb_lifetime_usetime = sp->validtime;
+       m_cat(result, m);
 
-       /* add to saidxtree */
-       newsah->state = SADB_SASTATE_MATURE;
-       LIST_INSERT_HEAD(&sahtree, newsah, chain);
+       /* set sadb_address for source */
+       m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
+           (struct sockaddr *)&sp->spidx.src,
+           sp->spidx.prefs, sp->spidx.ul_proto);
+       if (!m) {
+               error = ENOBUFS;
+               goto fail;
+       }
+       m_cat(result, m);
 
-       return(newsah);
-}
+       /* set sadb_address for destination */
+       m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
+           (struct sockaddr *)&sp->spidx.dst,
+           sp->spidx.prefd, sp->spidx.ul_proto);
+       if (!m) {
+               error = ENOBUFS;
+               goto fail;
+       }
+       m_cat(result, m);
 
-/*
- * delete SA index and all SA registerd.
- */
+       /* set secpolicy */
+       m = key_sp2msg(sp);
+       if (!m) {
+               error = ENOBUFS;
+               goto fail;
+       }
+       m_cat(result, m);
+
+       if ((result->m_flags & M_PKTHDR) == 0) {
+               error = EINVAL;
+               goto fail;
+       }
+
+       if (result->m_len < sizeof(struct sadb_msg)) {
+               result = m_pullup(result, sizeof(struct sadb_msg));
+               if (result == NULL) {
+                       error = ENOBUFS;
+                       goto fail;
+               }
+       }
+
+       result->m_pkthdr.len = 0;
+       for (m = result; m; m = m->m_next)
+               result->m_pkthdr.len += m->m_len;
+
+       mtod(result, struct sadb_msg *)->sadb_msg_len =
+           PFKEY_UNIT64(result->m_pkthdr.len);
+
+       return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
+
+ fail:
+       if (result)
+               m_freem(result);
+       return error;
+}
+
+/* %%% SAD management */
+/*
+ * allocating a memory for new SA head, and copy from the values of mhp.
+ * OUT:        NULL    : failure due to the lack of memory.
+ *     others  : pointer to new SA head.
+ */
+static struct secashead *
+key_newsah(saidx)
+       struct secasindex *saidx;
+{
+       struct secashead *newsah;
+
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
+       /* sanity check */
+       if (saidx == NULL)
+               panic("key_newsaidx: NULL pointer is passed.\n");
+
+       newsah = keydb_newsecashead();
+       if (newsah == NULL)
+               return NULL;
+
+       bcopy(saidx, &newsah->saidx, sizeof(newsah->saidx));
+
+       /* add to saidxtree */
+       newsah->state = SADB_SASTATE_MATURE;
+       LIST_INSERT_HEAD(&sahtree, newsah, chain);
+
+       return(newsah);
+}
+
+/*
+ * delete SA index and all SA registerd.
+ */
 static void
 key_delsah(sah)
        struct secashead *sah;
@@ -2243,15 +2720,13 @@ key_delsah(sah)
        int s;
        int zombie = 0;
 
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        /* sanity check */
        if (sah == NULL)
                panic("key_delsah: NULL pointer is passed.\n");
 
-#ifdef __NetBSD__
-       s = splsoftnet();       /*called from softclock()*/
-#else
        s = splnet();   /*called from softclock()*/
-#endif
 
        /* searching all SA registerd in the secindex. */
        for (stateidx = 0;
@@ -2289,7 +2764,7 @@ key_delsah(sah)
        }
 
        if (sah->sa_route.ro_rt) {
-               RTFREE(sah->sa_route.ro_rt);
+               rtfree(sah->sa_route.ro_rt);
                sah->sa_route.ro_rt = (struct rtentry *)NULL;
        }
 
@@ -2312,75 +2787,84 @@ key_delsah(sah)
  *     not to call key_setsava().
  * OUT:        NULL    : fail
  *     others  : pointer to new secasvar.
+ *
+ * does not modify mbuf.  does not free mbuf on error.
  */
 static struct secasvar *
-key_newsav(mhp, sah)
-       caddr_t *mhp;
+key_newsav(m, mhp, sah, errp)
+       struct mbuf *m;
+       const struct sadb_msghdr *mhp;
        struct secashead *sah;
+       int *errp;
 {
        struct secasvar *newsav;
-       struct sadb_msg *msg0;
+       const struct sadb_sa *xsa;
+
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
 
        /* sanity check */
-       if (mhp == NULL || mhp[0] == NULL || sah == NULL)
+       if (m == NULL || mhp == NULL || mhp->msg == NULL || sah == NULL)
                panic("key_newsa: NULL pointer is passed.\n");
 
-       msg0 = (struct sadb_msg *)mhp[0];
-
        KMALLOC(newsav, struct secasvar *, sizeof(struct secasvar));
        if (newsav == NULL) {
-#if IPSEC_DEBUG
-               printf("key_newsa: No more memory.\n");
-#endif
-               msg0->sadb_msg_errno = ENOBUFS;
+               ipseclog((LOG_DEBUG, "key_newsa: No more memory.\n"));
+               *errp = ENOBUFS;
                return NULL;
        }
        bzero((caddr_t)newsav, sizeof(struct secasvar));
 
-       switch (msg0->sadb_msg_type) {
+       switch (mhp->msg->sadb_msg_type) {
        case SADB_GETSPI:
-               newsav->spi = 0;
+               key_setspi(newsav, 0);
 
 #if IPSEC_DOSEQCHECK
                /* sync sequence number */
-               if (msg0->sadb_msg_seq == 0)
+               if (mhp->msg->sadb_msg_seq == 0)
                        newsav->seq =
                                (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
                else
 #endif
-                       newsav->seq = msg0->sadb_msg_seq;
+                       newsav->seq = mhp->msg->sadb_msg_seq;
                break;
 
        case SADB_ADD:
                /* sanity check */
-               if (mhp[SADB_EXT_SA] == NULL) {
+               if (mhp->ext[SADB_EXT_SA] == NULL) {
                        KFREE(newsav);
-#if IPSEC_DEBUG
-                       printf("key_newsa: invalid message is passed.\n");
-#endif
-                       msg0->sadb_msg_errno = EINVAL;
+                       ipseclog((LOG_DEBUG, "key_newsa: invalid message is passed.\n"));
+                       *errp = EINVAL;
                        return NULL;
                }
-               newsav->spi = ((struct sadb_sa *)mhp[SADB_EXT_SA])->sadb_sa_spi;
-               newsav->seq = msg0->sadb_msg_seq;
+               xsa = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
+               key_setspi(newsav, xsa->sadb_sa_spi);
+               newsav->seq = mhp->msg->sadb_msg_seq;
                break;
        default:
                KFREE(newsav);
-               msg0->sadb_msg_errno = EINVAL;
+               *errp = EINVAL;
                return NULL;
        }
 
        /* copy sav values */
-       if (msg0->sadb_msg_type != SADB_GETSPI && key_setsaval(newsav, mhp)) {
-               KFREE(newsav);
-               /* msg0->sadb_msg_errno is set at key_setsaval. */
-               return NULL;
+       if (mhp->msg->sadb_msg_type != SADB_GETSPI) {
+               *errp = key_setsaval(newsav, m, mhp);
+               if (*errp) {
+                       if (newsav->spihash.le_prev || newsav->spihash.le_next)
+                               LIST_REMOVE(newsav, spihash);
+                       KFREE(newsav);
+                       return NULL;
+               }
        }
 
-       /* reset tick */
-       newsav->tick = 0;
+       /* reset created */
+    {
+       struct timeval tv;
+       microtime(&tv);
+       newsav->created = tv.tv_sec;
+    }
 
-       newsav->pid = msg0->sadb_msg_pid;
+       newsav->pid = mhp->msg->sadb_msg_pid;
 
        /* add to satree */
        newsav->sah = sah;
@@ -2399,6 +2883,8 @@ static void
 key_delsav(sav)
        struct secasvar *sav;
 {
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        /* sanity check */
        if (sav == NULL)
                panic("key_delsav: NULL pointer is passed.\n");
@@ -2409,29 +2895,45 @@ key_delsav(sav)
        /* remove from SA header */
        if (__LIST_CHAINED(sav))
                LIST_REMOVE(sav, chain);
+               
+       if (sav->spihash.le_prev || sav->spihash.le_next)
+               LIST_REMOVE(sav, spihash);
 
-       if (sav->key_auth != NULL)
+       if (sav->key_auth != NULL) {
+               bzero(_KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth));
                KFREE(sav->key_auth);
-       if (sav->key_enc != NULL)
+               sav->key_auth = NULL;
+       }
+       if (sav->key_enc != NULL) {
+               bzero(_KEYBUF(sav->key_enc), _KEYLEN(sav->key_enc));
                KFREE(sav->key_enc);
-       if (sav->replay != NULL)
+               sav->key_enc = NULL;
+       }
+       if (sav->sched) {
+               bzero(sav->sched, sav->schedlen);
+               KFREE(sav->sched);
+               sav->sched = NULL;
+       }
+       if (sav->replay != NULL) {
                keydb_delsecreplay(sav->replay);
-       if (sav->lft_c != NULL)
+               sav->replay = NULL;
+       }
+       if (sav->lft_c != NULL) {
                KFREE(sav->lft_c);
-       if (sav->lft_h != NULL)
+               sav->lft_c = NULL;
+       }
+       if (sav->lft_h != NULL) {
                KFREE(sav->lft_h);
-       if (sav->lft_s != NULL)
+               sav->lft_h = NULL;
+       }
+       if (sav->lft_s != NULL) {
                KFREE(sav->lft_s);
-       if (sav->iv != NULL)
+               sav->lft_s = NULL;
+       }
+       if (sav->iv != NULL) {
                KFREE(sav->iv);
-#if notyet
-       if (sav->misc1 != NULL)
-               KFREE(sav->misc1);
-       if (sav->misc2 != NULL)
-               KFREE(sav->misc2);
-       if (sav->misc3 != NULL)
-               KFREE(sav->misc3);
-#endif
+               sav->iv = NULL;
+       }
 
        KFREE(sav);
 
@@ -2450,11 +2952,13 @@ key_getsah(saidx)
 {
        struct secashead *sah;
 
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        LIST_FOREACH(sah, &sahtree, chain) {
                if (sah->state == SADB_SASTATE_DEAD)
                        continue;
-               if (key_cmpsaidx_exactly(&sah->saidx, saidx))
-                       return(sah);
+               if (key_cmpsaidx(&sah->saidx, saidx, CMP_REQID))
+                       return sah;
        }
 
        return NULL;
@@ -2472,30 +2976,47 @@ key_checkspidup(saidx, spi)
        struct secasindex *saidx;
        u_int32_t spi;
 {
-       struct secashead *sah;
        struct secasvar *sav;
+       u_int stateidx, state;
+       
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
 
        /* check address family */
        if (saidx->src.ss_family != saidx->dst.ss_family) {
-#if IPSEC_DEBUG
-               printf("key_checkspidup: address family mismatched.\n");
-#endif
+               ipseclog((LOG_DEBUG, "key_checkspidup: address family mismatched.\n"));
                return NULL;
        }
 
        /* check all SAD */
-       LIST_FOREACH(sah, &sahtree, chain) {
-               if (!key_ismyaddr(sah->saidx.dst.ss_family,
-                                 _INADDRBYSA(&sah->saidx.dst)))
+       LIST_FOREACH(sav, &spihash[SPIHASH(spi)], spihash) {
+               if (sav->spi != spi)
                        continue;
-               sav = key_getsavbyspi(sah, spi);
-               if (sav != NULL)
-                       return sav;
+               for (stateidx = 0;
+                    stateidx < _ARRAYLEN(saorder_state_alive);
+                    stateidx++) {
+                       state = saorder_state_alive[stateidx];
+                       if (sav->state == state &&
+                           key_ismyaddr((struct sockaddr *)&sav->sah->saidx.dst))
+                               return sav;
+               }
        }
 
        return NULL;
 }
 
+static void
+key_setspi(sav, spi)
+       struct secasvar *sav;
+       u_int32_t spi;
+{
+
+       sav->spi = spi;
+       if (sav->spihash.le_prev || sav->spihash.le_next)
+               LIST_REMOVE(sav, spihash);
+       LIST_INSERT_HEAD(&spihash[SPIHASH(spi)], sav, spihash);
+}
+
+
 /*
  * search SAD litmited alive SA, protocol, SPI.
  * OUT:
@@ -2507,375 +3028,326 @@ key_getsavbyspi(sah, spi)
        struct secashead *sah;
        u_int32_t spi;
 {
-       struct secasvar *sav;
-       u_int stateidx, state;
-
-       /* search all status */
-       for (stateidx = 0;
-            stateidx < _ARRAYLEN(saorder_state_alive);
-            stateidx++) {
-
-               state = saorder_state_alive[stateidx];
-               LIST_FOREACH(sav, &sah->savtree[state], chain) {
-
-                       /* sanity check */
-                       if (sav->state != state) {
-#if IPSEC_DEBUG
-                               printf("key_getsavbyspi: "
-                                       "invalid sav->state "
-                                       "(queue: %d SA: %d)\n",
-                                       state, sav->state);
-#endif
-                               continue;
+       struct secasvar *sav, *match;
+       u_int stateidx, state, matchidx;
+                       
+       match = NULL;
+       matchidx = _ARRAYLEN(saorder_state_alive);
+       LIST_FOREACH(sav, &spihash[SPIHASH(spi)], spihash) {
+               if (sav->spi != spi)
+                       continue;
+               if (sav->sah != sah)
+                       continue;
+               for (stateidx = 0; stateidx < matchidx; stateidx++) {
+                       state = saorder_state_alive[stateidx];
+                       if (sav->state == state) {
+                               match = sav;
+                               matchidx = stateidx;
+                               break;
                        }
-
-                       if (sav->spi == spi)
-                               return sav;
                }
        }
 
-       return NULL;
+       return match;
 }
 
 /*
  * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
  * You must update these if need.
  * OUT:        0:      success.
- *     1:      failure. set errno to (mhp[0])->sadb_msg_errno.
+ *     !0:     failure.
+ *
+ * does not modify mbuf.  does not free mbuf on error.
  */
 static int
-key_setsaval(sav, mhp)
+key_setsaval(sav, m, mhp)
        struct secasvar *sav;
-       caddr_t *mhp;
+       struct mbuf *m;
+       const struct sadb_msghdr *mhp;
 {
-       struct sadb_msg *msg0;
+#if IPSEC_ESP
+       const struct esp_algorithm *algo;
+#endif
        int error = 0;
+       struct timeval tv;
+
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
 
        /* sanity check */
-       if (mhp == NULL || mhp[0] == NULL)
+       if (m == NULL || mhp == NULL || mhp->msg == NULL)
                panic("key_setsaval: NULL pointer is passed.\n");
 
-       msg0 = (struct sadb_msg *)mhp[0];
-
        /* initialization */
        sav->replay = NULL;
        sav->key_auth = NULL;
        sav->key_enc = NULL;
+       sav->sched = NULL;
+       sav->schedlen = 0;
        sav->iv = NULL;
        sav->lft_c = NULL;
        sav->lft_h = NULL;
        sav->lft_s = NULL;
-#if notyet
-       sav->misc1 = NULL;
-       sav->misc2 = NULL;
-       sav->misc3 = NULL;
-#endif
+       sav->remote_ike_port = 0;
+       sav->natt_last_activity = natt_now;
 
        /* SA */
-       if (mhp[SADB_EXT_SA] != NULL) {
-               struct sadb_sa *sa0 = (struct sadb_sa *)mhp[SADB_EXT_SA];
+       if (mhp->ext[SADB_EXT_SA] != NULL) {
+               const struct sadb_sa *sa0;
+
+               sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
+               if (mhp->extlen[SADB_EXT_SA] < sizeof(*sa0)) {
+                       ipseclog((LOG_DEBUG, "key_setsaval: invalid message size.\n"));
+                       error = EINVAL;
+                       goto fail;
+               }
 
                sav->alg_auth = sa0->sadb_sa_auth;
                sav->alg_enc = sa0->sadb_sa_encrypt;
                sav->flags = sa0->sadb_sa_flags;
+               
+               /*
+                * Verify that a nat-traversal port was specified if
+                * the nat-traversal flag is set.
+                */
+               if ((sav->flags & SADB_X_EXT_NATT) != 0) {
+                       if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa_2) ||
+                                ((struct sadb_sa_2*)(sa0))->sadb_sa_natt_port == 0) {
+                               ipseclog((LOG_DEBUG, "key_setsaval: natt port not set.\n"));
+                               error = EINVAL;
+                               goto fail;
+                       }
+                       sav->remote_ike_port = ((struct sadb_sa_2*)(sa0))->sadb_sa_natt_port;
+               }
 
                /* replay window */
                if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) {
                        sav->replay = keydb_newsecreplay(sa0->sadb_sa_replay);
                        if (sav->replay == NULL) {
-#if IPSEC_DEBUG
-                               printf("key_setsaval: No more memory.\n");
-#endif
+                               ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
                                error = ENOBUFS;
-                               goto err;
+                               goto fail;
                        }
                }
        }
 
        /* Authentication keys */
-       if (mhp[SADB_EXT_KEY_AUTH] != NULL) {
-               struct sadb_key *key0;
-               u_int len;
+       if (mhp->ext[SADB_EXT_KEY_AUTH] != NULL) {
+               const struct sadb_key *key0;
+               int len;
 
-               key0 = (struct sadb_key *)mhp[SADB_EXT_KEY_AUTH];
-               len = PFKEY_UNUNIT64(key0->sadb_key_len);
+               key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
+               len = mhp->extlen[SADB_EXT_KEY_AUTH];
 
                error = 0;
-               if (len < sizeof(struct sadb_key))
+               if (len < sizeof(*key0)) {
+                       ipseclog((LOG_DEBUG, "key_setsaval: invalid auth key ext len. len = %d\n", len));
                        error = EINVAL;
-               switch (msg0->sadb_msg_satype) {
+                       goto fail;
+               }
+               switch (mhp->msg->sadb_msg_satype) {
                case SADB_SATYPE_AH:
                case SADB_SATYPE_ESP:
-                       if (len == sizeof(struct sadb_key)
-                        && sav->alg_auth != SADB_AALG_NULL) {
+                       if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
+                           sav->alg_auth != SADB_X_AALG_NULL)
                                error = EINVAL;
-                       }
                        break;
                case SADB_X_SATYPE_IPCOMP:
-                       error = EINVAL;
-                       break;
                default:
                        error = EINVAL;
                        break;
                }
                if (error) {
-#if IPSEC_DEBUG
-                       printf("key_setsaval: invalid key_auth values.\n");
-#endif
-                       goto err;
+                       ipseclog((LOG_DEBUG, "key_setsaval: invalid key_auth values.\n"));
+                       goto fail;
                }
 
                sav->key_auth = (struct sadb_key *)key_newbuf(key0, len);
                if (sav->key_auth == NULL) {
-#if IPSEC_DEBUG
-                       printf("key_setsaval: No more memory.\n");
-#endif
+                       ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
                        error = ENOBUFS;
-                       goto err;
+                       goto fail;
                }
-
-               /* make length shift up for kernel*/
-               sav->key_auth->sadb_key_len = len;
        }
 
        /* Encryption key */
-       if (mhp[SADB_EXT_KEY_ENCRYPT] != NULL) {
-               struct sadb_key *key0;
-               u_int len;
+       if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) {
+               const struct sadb_key *key0;
+               int len;
 
-               key0 = (struct sadb_key *)mhp[SADB_EXT_KEY_ENCRYPT];
-               len = PFKEY_UNUNIT64(key0->sadb_key_len);
+               key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
+               len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
 
                error = 0;
-               if (len < sizeof(struct sadb_key))
+               if (len < sizeof(*key0)) {
+                       ipseclog((LOG_DEBUG, "key_setsaval: invalid encryption key ext len. len = %d\n", len));
                        error = EINVAL;
-               switch (msg0->sadb_msg_satype) {
+                       goto fail;
+               }
+               switch (mhp->msg->sadb_msg_satype) {
                case SADB_SATYPE_ESP:
-                       if (len == sizeof(struct sadb_key)
-                        && sav->alg_enc != SADB_EALG_NULL) {
+                       if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
+                           sav->alg_enc != SADB_EALG_NULL) {
+                           ipseclog((LOG_DEBUG, "key_setsaval: invalid ESP algorithm.\n"));
                                error = EINVAL;
+                               break;
+                       }
+                       sav->key_enc = (struct sadb_key *)key_newbuf(key0, len);
+                       if (sav->key_enc == NULL) {
+                               ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
+                               error = ENOBUFS;
+                               goto fail;
                        }
-                       break;
-               case SADB_SATYPE_AH:
-                       error = EINVAL;
                        break;
                case SADB_X_SATYPE_IPCOMP:
+                       if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
+                               error = EINVAL;
+                       sav->key_enc = NULL;    /*just in case*/
                        break;
+               case SADB_SATYPE_AH:
                default:
                        error = EINVAL;
                        break;
                }
                if (error) {
-#if IPSEC_DEBUG
-                       printf("key_setsatval: invalid key_enc value.\n");
-#endif
-                       goto err;
-               }
-
-               sav->key_enc = (struct sadb_key *)key_newbuf(key0, len);
-               if (sav->key_enc == NULL) {
-#if IPSEC_DEBUG
-                       printf("key_setsaval: No more memory.\n");
-#endif
-                       error = ENOBUFS;
-                       goto err;
+                       ipseclog((LOG_DEBUG, "key_setsaval: invalid key_enc value.\n"));
+                       goto fail;
                }
-
-               /* make length shift up for kernel*/
-               sav->key_enc->sadb_key_len = len;
        }
 
        /* set iv */
        sav->ivlen = 0;
 
-       switch (msg0->sadb_msg_satype) {
+       switch (mhp->msg->sadb_msg_satype) {
        case SADB_SATYPE_ESP:
 #if IPSEC_ESP
-           {
-               struct esp_algorithm *algo;
-
-               algo = &esp_algorithms[sav->alg_enc];
+               algo = esp_algorithm_lookup(sav->alg_enc);
                if (algo && algo->ivlen)
-                       sav->ivlen = (*algo->ivlen)(sav);
+                       sav->ivlen = (*algo->ivlen)(algo, sav);
+               if (sav->ivlen == 0)
+                       break;
                KMALLOC(sav->iv, caddr_t, sav->ivlen);
                if (sav->iv == 0) {
-#if IPSEC_DEBUG
-                       printf("key_setsaval: No more memory.\n");
-#endif
+                       ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
                        error = ENOBUFS;
-                       goto err;
+                       goto fail;
                }
-               /* initialize ? */
-               break;
-           }
-#else
-               break;
+
+               /* initialize */
+               key_randomfill(sav->iv, sav->ivlen);
 #endif
+               break;
        case SADB_SATYPE_AH:
-#if 1  /*nonstandard*/
        case SADB_X_SATYPE_IPCOMP:
-#endif
                break;
        default:
-#if IPSEC_DEBUG
-               printf("key_setsaval: invalid SA type.\n");
-#endif
+               ipseclog((LOG_DEBUG, "key_setsaval: invalid SA type.\n"));
                error = EINVAL;
-               goto err;
+               goto fail;
        }
 
-       /* reset tick */
-       sav->tick = 0;
+       /* reset created */
+       microtime(&tv);
+       sav->created = tv.tv_sec;
 
        /* make lifetime for CURRENT */
-    {
-       struct timeval tv;
-
        KMALLOC(sav->lft_c, struct sadb_lifetime *,
-               sizeof(struct sadb_lifetime));
+           sizeof(struct sadb_lifetime));
        if (sav->lft_c == NULL) {
-#if IPSEC_DEBUG
-               printf("key_setsaval: No more memory.\n");
-#endif
+               ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
                error = ENOBUFS;
-               goto err;
+               goto fail;
        }
 
        microtime(&tv);
 
        sav->lft_c->sadb_lifetime_len =
-               PFKEY_UNIT64(sizeof(struct sadb_lifetime));
+           PFKEY_UNIT64(sizeof(struct sadb_lifetime));
        sav->lft_c->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
        sav->lft_c->sadb_lifetime_allocations = 0;
        sav->lft_c->sadb_lifetime_bytes = 0;
        sav->lft_c->sadb_lifetime_addtime = tv.tv_sec;
        sav->lft_c->sadb_lifetime_usetime = 0;
-    }
 
        /* lifetimes for HARD and SOFT */
     {
-       struct sadb_lifetime *lft0;
+       const struct sadb_lifetime *lft0;
 
-       lft0 = (struct sadb_lifetime *)mhp[SADB_EXT_LIFETIME_HARD];
+       lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
        if (lft0 != NULL) {
+               if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) {
+                       ipseclog((LOG_DEBUG, "key_setsaval: invalid hard lifetime ext len.\n"));
+                       error = EINVAL;
+                       goto fail;
+               }
                sav->lft_h = (struct sadb_lifetime *)key_newbuf(lft0,
-                               sizeof(*lft0));
+                   sizeof(*lft0));
                if (sav->lft_h == NULL) {
-#if IPSEC_DEBUG
-                       printf("key_setsaval: No more memory.\n");
-#endif
+                       ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
                        error = ENOBUFS;
-                       goto err;
+                       goto fail;
                }
                /* to be initialize ? */
        }
 
-       lft0 = (struct sadb_lifetime *)mhp[SADB_EXT_LIFETIME_SOFT];
+       lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_SOFT];
        if (lft0 != NULL) {
+               if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) {
+                       ipseclog((LOG_DEBUG, "key_setsaval: invalid soft lifetime ext len.\n"));
+                       error = EINVAL;
+                       goto fail;
+               }
                sav->lft_s = (struct sadb_lifetime *)key_newbuf(lft0,
-                               sizeof(*lft0));
+                   sizeof(*lft0));
                if (sav->lft_s == NULL) {
-#if IPSEC_DEBUG
-                       printf("key_setsaval: No more memory.\n");
-#endif
+                       ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
                        error = ENOBUFS;
-                       goto err;
+                       goto fail;
                }
                /* to be initialize ? */
        }
     }
 
-#if notyet
-       /* pre-processing for DES */
-       switch (sav->alg_enc) {
-       case SADB_EALG_DESCBC:
-               if (des_key_sched((C_Block *)_KEYBUF(sav->key_enc),
-                                 (des_key_schedule)sav->misc1) != 0) {
-#if IPSEC_DEBUG
-                       printf("key_setsaval: error des_key_sched.\n");
-#endif
-                       sav->misc1 = NULL;
-                       /* THROUGH */
-               }
-               break;
-       case SADB_EALG_3DESCBC:
-               if (des_key_sched((C_Block *)_KEYBUF(sav->key_enc),
-                                 (des_key_schedule)sav->misc1) != 0
-                || des_key_sched((C_Block *)(_KEYBUF(sav->key_enc) + 8),
-                                 (des_key_schedule)sav->misc2) != 0
-                || des_key_sched((C_Block *)(_KEYBUF(sav->key_enc) + 16),
-                                 (des_key_schedule)sav->misc3) != 0) {
-#if IPSEC_DEBUG
-                       printf("key_setsaval: error des_key_sched.\n");
-#endif
-                       sav->misc1 = NULL;
-                       sav->misc2 = NULL;
-                       sav->misc3 = NULL;
-                       /* THROUGH */
-               }
-       }
-#endif
-
-       msg0->sadb_msg_errno = 0;
        return 0;
 
   err:
fail:
        /* initialization */
-       if (sav->replay != NULL)
+       if (sav->replay != NULL) {
                keydb_delsecreplay(sav->replay);
-       if (sav->key_auth != NULL)
+               sav->replay = NULL;
+       }
+       if (sav->key_auth != NULL) {
+               bzero(_KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth));
                KFREE(sav->key_auth);
-       if (sav->key_enc != NULL)
+               sav->key_auth = NULL;
+       }
+       if (sav->key_enc != NULL) {
+               bzero(_KEYBUF(sav->key_enc), _KEYLEN(sav->key_enc));
                KFREE(sav->key_enc);
-       if (sav->iv != NULL)
+               sav->key_enc = NULL;
+       }
+       if (sav->sched) {
+               bzero(sav->sched, sav->schedlen);
+               KFREE(sav->sched);
+               sav->sched = NULL;
+       }
+       if (sav->iv != NULL) {
                KFREE(sav->iv);
-       if (sav->lft_c != NULL)
+               sav->iv = NULL;
+       }
+       if (sav->lft_c != NULL) {
                KFREE(sav->lft_c);
-       if (sav->lft_h != NULL)
+               sav->lft_c = NULL;
+       }
+       if (sav->lft_h != NULL) {
                KFREE(sav->lft_h);
-       if (sav->lft_s != NULL)
+               sav->lft_h = NULL;
+       }
+       if (sav->lft_s != NULL) {
                KFREE(sav->lft_s);
-#if notyet
-       if (sav->misc1 != NULL)
-               KFREE(sav->misc1);
-       if (sav->misc2 != NULL)
-               KFREE(sav->misc2);
-       if (sav->misc3 != NULL)
-               KFREE(sav->misc3);
-#endif
-
-       msg0->sadb_msg_errno = error;
-       return 1;
-}
+               sav->lft_s = NULL;
+       }
 
-/*
- * get message buffer length.
- */
-static u_int
-key_getmsglen(sav)
-       struct secasvar *sav;
-{
-       int len = sizeof(struct sadb_msg);
-
-       len += sizeof(struct sadb_sa);
-       len += (sizeof(struct sadb_address)
-               + PFKEY_ALIGN8(_SALENBYAF(sav->sah->saidx.src.ss_family)));
-       len += (sizeof(struct sadb_address)
-               + PFKEY_ALIGN8(_SALENBYAF(sav->sah->saidx.dst.ss_family)));
-
-       if (sav->key_auth != NULL)
-               len += sav->key_auth->sadb_key_len;
-       if (sav->key_enc != NULL)
-               len += sav->key_enc->sadb_key_len;
-
-       if (sav->lft_c != NULL)
-               len += sizeof(struct sadb_lifetime);
-       if (sav->lft_h != NULL)
-               len += sizeof(struct sadb_lifetime);
-       if (sav->lft_s != NULL)
-               len += sizeof(struct sadb_lifetime);
-
-       return len;
+       return error;
 }
 
 /*
@@ -2893,12 +3365,19 @@ key_mature(sav)
 
        mature = 0;
 
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        /* check SPI value */
-       if (ntohl(sav->spi) >= 0 && ntohl(sav->spi) <= 255) {
-#if IPSEC_DEBUG
-               printf("key_mature: illegal range of SPI %d.\n", sav->spi);
-#endif
-               return EINVAL;
+       switch (sav->sah->saidx.proto) {
+       case IPPROTO_ESP:
+       case IPPROTO_AH:
+               if (ntohl(sav->spi) >= 0 && ntohl(sav->spi) <= 255) {
+                       ipseclog((LOG_DEBUG,
+                           "key_mature: illegal range of SPI %u.\n",
+                           (u_int32_t)ntohl(sav->spi)));
+                       return EINVAL;
+               }
+               break;
        }
 
        /* check satype */
@@ -2907,96 +3386,72 @@ key_mature(sav)
                /* check flags */
                if ((sav->flags & SADB_X_EXT_OLD)
                 && (sav->flags & SADB_X_EXT_DERIV)) {
-#if IPSEC_DEBUG
-                       printf("key_mature: "
-                               "invalid flag (derived) given to old-esp.\n");
-#endif
+                       ipseclog((LOG_DEBUG, "key_mature: "
+                           "invalid flag (derived) given to old-esp.\n"));
                        return EINVAL;
                }
-               checkmask = 3;
+               if (sav->alg_auth == SADB_AALG_NONE)
+                       checkmask = 1;
+               else
+                       checkmask = 3;
                mustmask = 1;
                break;
        case IPPROTO_AH:
                /* check flags */
                if (sav->flags & SADB_X_EXT_DERIV) {
-#if IPSEC_DEBUG
-                       printf("key_mature: "
-                               "invalid flag (derived) given to AH SA.\n");
-#endif
+                       ipseclog((LOG_DEBUG, "key_mature: "
+                           "invalid flag (derived) given to AH SA.\n"));
                        return EINVAL;
                }
                if (sav->alg_enc != SADB_EALG_NONE) {
-#if IPSEC_DEBUG
-                       printf("key_mature: "
-                               "protocol and algorithm mismated.\n");
-#endif
+                       ipseclog((LOG_DEBUG, "key_mature: "
+                           "protocol and algorithm mismated.\n"));
                        return(EINVAL);
                }
                checkmask = 2;
                mustmask = 2;
                break;
-#if 1  /*nonstandard*/
        case IPPROTO_IPCOMP:
                if (sav->alg_auth != SADB_AALG_NONE) {
-#if IPSEC_DEBUG
-                       printf("key_mature: "
-                               "protocol and algorithm mismated.\n");
-#endif
+                       ipseclog((LOG_DEBUG, "key_mature: "
+                               "protocol and algorithm mismated.\n"));
                        return(EINVAL);
                }
                if ((sav->flags & SADB_X_EXT_RAWCPI) == 0
                 && ntohl(sav->spi) >= 0x10000) {
-#if IPSEC_DEBUG
-                       printf("key_mature: invalid cpi for IPComp.\n");
-#endif
+                       ipseclog((LOG_DEBUG, "key_mature: invalid cpi for IPComp.\n"));
                        return(EINVAL);
                }
                checkmask = 4;
                mustmask = 4;
                break;
-#endif
        default:
-#if IPSEC_DEBUG
-               printf("key_mature: Invalid satype.\n");
-#endif
+               ipseclog((LOG_DEBUG, "key_mature: Invalid satype.\n"));
                return EPROTONOSUPPORT;
        }
 
        /* check authentication algorithm */
        if ((checkmask & 2) != 0) {
-               struct ah_algorithm *algo;
+               const struct ah_algorithm *algo;
                int keylen;
 
-               /* XXX: should use algorithm map to check. */
-               switch (sav->alg_auth) {
-               case SADB_AALG_NONE:
-               case SADB_AALG_MD5HMAC:
-               case SADB_AALG_SHA1HMAC:
-               case SADB_AALG_MD5:
-               case SADB_AALG_SHA:
-               case SADB_AALG_NULL:
-                       break;
-               default:
-#if IPSEC_DEBUG
-                       printf("key_mature: "
-                               "unknown authentication algorithm.\n");
-#endif
+               algo = ah_algorithm_lookup(sav->alg_auth);
+               if (!algo) {
+                       ipseclog((LOG_DEBUG,"key_mature: "
+                           "unknown authentication algorithm.\n"));
                        return EINVAL;
                }
 
                /* algorithm-dependent check */
-               algo = &ah_algorithms[sav->alg_auth];
-
                if (sav->key_auth)
                        keylen = sav->key_auth->sadb_key_bits;
                else
                        keylen = 0;
                if (keylen < algo->keymin || algo->keymax < keylen) {
-#if IPSEC_DEBUG
-                       printf("key_mature: invalid AH key length %d "
-                               "(%d-%d allowed)\n", keylen,
-                               algo->keymin, algo->keymax);
-#endif
+                       ipseclog((LOG_DEBUG,
+                           "key_mature: invalid AH key length %d "
+                           "(%d-%d allowed)\n",
+                           keylen, algo->keymin, algo->keymax));
                        return EINVAL;
                }
 
@@ -3009,9 +3464,7 @@ key_mature(sav)
                }
 
                if ((mustmask & 2) != 0 &&  mature != SADB_SATYPE_AH) {
-#if IPSEC_DEBUG
-                       printf("key_mature: no satisfy algorithm for AH\n");
-#endif
+                       ipseclog((LOG_DEBUG, "key_mature: no satisfy algorithm for AH\n"));
                        return EINVAL;
                }
        }
@@ -3019,38 +3472,25 @@ key_mature(sav)
        /* check encryption algorithm */
        if ((checkmask & 1) != 0) {
 #if IPSEC_ESP
-               struct esp_algorithm *algo;
+               const struct esp_algorithm *algo;
                int keylen;
 
-               switch (sav->alg_enc) {
-               case SADB_EALG_NONE:
-               case SADB_EALG_DESCBC:
-               case SADB_EALG_3DESCBC:
-               case SADB_EALG_NULL:
-               case SADB_EALG_BLOWFISHCBC:
-               case SADB_EALG_CAST128CBC:
-               case SADB_EALG_RC5CBC:
-                       break;
-               default:
-#if IPSEC_DEBUG
-                       printf("key_mature: unknown encryption algorithm.\n");
-#endif
+               algo = esp_algorithm_lookup(sav->alg_enc);
+               if (!algo) {
+                       ipseclog((LOG_DEBUG, "key_mature: unknown encryption algorithm.\n"));
                        return EINVAL;
                }
 
                /* algorithm-dependent check */
-               algo = &esp_algorithms[sav->alg_enc];
-
                if (sav->key_enc)
                        keylen = sav->key_enc->sadb_key_bits;
                else
                        keylen = 0;
                if (keylen < algo->keymin || algo->keymax < keylen) {
-#if IPSEC_DEBUG
-                       printf("key_mature: invalid ESP key length %d "
-                               "(%d-%d allowed)\n", keylen,
-                               algo->keymin, algo->keymax);
-#endif
+                       ipseclog((LOG_DEBUG,
+                           "key_mature: invalid ESP key length %d "
+                           "(%d-%d allowed)\n",
+                           keylen, algo->keymin, algo->keymax));
                        return EINVAL;
                }
 
@@ -3063,44 +3503,23 @@ key_mature(sav)
                }
 
                if ((mustmask & 1) != 0 &&  mature != SADB_SATYPE_ESP) {
-#if IPSEC_DEBUG
-                       printf("key_mature: no satisfy algorithm for ESP\n");
-#endif
+                       ipseclog((LOG_DEBUG, "key_mature: no satisfy algorithm for ESP\n"));
                        return EINVAL;
                }
 #else /*IPSEC_ESP*/
-#if IPSEC_DEBUG
-               printf("key_mature: ESP not supported in this configuration\n");
-#endif
+               ipseclog((LOG_DEBUG, "key_mature: ESP not supported in this configuration\n"));
                return EINVAL;
 #endif
        }
 
        /* check compression algorithm */
        if ((checkmask & 4) != 0) {
-               struct ipcomp_algorithm *algo;
-
-               switch (sav->alg_enc) {
-               case SADB_X_CALG_NONE:
-               case SADB_X_CALG_OUI:
-               case SADB_X_CALG_DEFLATE:
-               case SADB_X_CALG_LZS:
-                       break;
-               default:
-#if IPSEC_DEBUG
-                       printf("key_mature: unknown compression algorithm.\n");
-#endif
-                       return EINVAL;
-               }
+               const struct ipcomp_algorithm *algo;
 
                /* algorithm-dependent check */
-               algo = &ipcomp_algorithms[sav->alg_enc];
-
-               if (!(algo->compress && algo->decompress)) {
-#if IPSEC_DEBUG
-                       printf("key_mature: "
-                               "unsupported compression algorithm.\n");
-#endif
+               algo = ipcomp_algorithm_lookup(sav->alg_enc);
+               if (!algo) {
+                       ipseclog((LOG_DEBUG, "key_mature: unknown compression algorithm.\n"));
                        return EINVAL;
                }
        }
@@ -3112,148 +3531,187 @@ key_mature(sav)
 
 /*
  * subroutine for SADB_GET and SADB_DUMP.
- * the buf must be allocated sufficent space.
  */
-static u_int
-key_setdumpsa(newmsg, sav, type, satype, seq, pid)
-       struct sadb_msg *newmsg;
+static struct mbuf *
+key_setdumpsa(sav, type, satype, seq, pid)
        struct secasvar *sav;
        u_int8_t type, satype;
        u_int32_t seq, pid;
 {
-       u_int tlen;
-       caddr_t p;
+       struct mbuf *result = NULL, *tres = NULL, *m;
+       int l = 0;
        int i;
+       void *p;
+       int dumporder[] = {
+               SADB_EXT_SA, SADB_X_EXT_SA2,
+               SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
+               SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
+               SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
+               SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
+               SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
+       };
+
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
+       m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
+       if (m == NULL)
+               goto fail;
+       result = m;
 
-       tlen = key_getmsglen(sav);
-
-       p = key_setsadbmsg((caddr_t)newmsg, type, tlen,
-                          satype, seq, pid,
-                          sav->sah->saidx.mode, sav->sah->saidx.reqid,
-                          0, sav->refcnt);
-
-       for (i = 1; i <= SADB_EXT_MAX; i++) {
-               switch (i) {
+       for (i = sizeof(dumporder)/sizeof(dumporder[0]) - 1; i >= 0; i--) {
+               m = NULL;
+               p = NULL;
+               switch (dumporder[i]) {
                case SADB_EXT_SA:
-                       p = key_setsadbsa(p, sav);
+                       m = key_setsadbsa(sav);
+                       if (!m)
+                               goto fail;
+                       break;
+
+               case SADB_X_EXT_SA2:
+                       m = key_setsadbxsa2(sav->sah->saidx.mode,
+                                       sav->replay ? sav->replay->count : 0,
+                                       sav->sah->saidx.reqid);
+                       if (!m)
+                               goto fail;
                        break;
 
                case SADB_EXT_ADDRESS_SRC:
-                       p = key_setsadbaddr(p,
-                             SADB_EXT_ADDRESS_SRC,
-                             (struct sockaddr *)&sav->sah->saidx.src,
-                             _INALENBYAF(sav->sah->saidx.src.ss_family) << 3,
-                             IPSEC_ULPROTO_ANY);
+                       m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
+                           (struct sockaddr *)&sav->sah->saidx.src,
+                           FULLMASK, IPSEC_ULPROTO_ANY);
+                       if (!m)
+                               goto fail;
                        break;
 
                case SADB_EXT_ADDRESS_DST:
-                       p = key_setsadbaddr(p,
-                             SADB_EXT_ADDRESS_DST,
-                             (struct sockaddr *)&sav->sah->saidx.dst,
-                             _INALENBYAF(sav->sah->saidx.dst.ss_family) << 3,
-                             IPSEC_ULPROTO_ANY);
+                       m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
+                           (struct sockaddr *)&sav->sah->saidx.dst,
+                           FULLMASK, IPSEC_ULPROTO_ANY);
+                       if (!m)
+                               goto fail;
                        break;
 
                case SADB_EXT_KEY_AUTH:
-                   {
-                       u_int len;
-                       if (sav->key_auth == NULL) break;
-                       len = sav->key_auth->sadb_key_len; /* real length */
-                       bcopy((caddr_t)sav->key_auth, p, len);
-                       ((struct sadb_ext *)p)->sadb_ext_len = PFKEY_UNIT64(len);
-                       p += len;
-                   }
+                       if (!sav->key_auth)
+                               continue;
+                       l = PFKEY_UNUNIT64(sav->key_auth->sadb_key_len);
+                       p = sav->key_auth;
                        break;
 
                case SADB_EXT_KEY_ENCRYPT:
-                   {
-                       u_int len;
-                       if (sav->key_enc == NULL) break;
-                       len = sav->key_enc->sadb_key_len; /* real length */
-                       bcopy((caddr_t)sav->key_enc, p, len);
-                       ((struct sadb_ext *)p)->sadb_ext_len = PFKEY_UNIT64(len);
-                       p += len;
-                   }
-                       break;;
+                       if (!sav->key_enc)
+                               continue;
+                       l = PFKEY_UNUNIT64(sav->key_enc->sadb_key_len);
+                       p = sav->key_enc;
+                       break;
 
                case SADB_EXT_LIFETIME_CURRENT:
-                       if (sav->lft_c == NULL) break;
-                       p = key_setsadbext(p, (caddr_t)sav->lft_c);
+                       if (!sav->lft_c)
+                               continue;
+                       l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_c)->sadb_ext_len);
+                       p = sav->lft_c;
                        break;
 
                case SADB_EXT_LIFETIME_HARD:
-                       if (sav->lft_h == NULL) break;
-                       p = key_setsadbext(p, (caddr_t)sav->lft_h);
+                       if (!sav->lft_h)
+                               continue;
+                       l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_h)->sadb_ext_len);
+                       p = sav->lft_h;
                        break;
 
                case SADB_EXT_LIFETIME_SOFT:
-                       if (sav->lft_s == NULL) break;
-                       p = key_setsadbext(p, (caddr_t)sav->lft_s);
+                       if (!sav->lft_s)
+                               continue;
+                       l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_s)->sadb_ext_len);
+                       p = sav->lft_s;
                        break;
 
+               case SADB_EXT_ADDRESS_PROXY:
                case SADB_EXT_IDENTITY_SRC:
                case SADB_EXT_IDENTITY_DST:
                        /* XXX: should we brought from SPD ? */
                case SADB_EXT_SENSITIVITY:
                default:
-                       break;
+                       continue;
                }
+
+               if ((!m && !p) || (m && p))
+                       goto fail;
+               if (p && tres) {
+                       M_PREPEND(tres, l, M_DONTWAIT);
+                       if (!tres)
+                               goto fail;
+                       bcopy(p, mtod(tres, caddr_t), l);
+                       continue;
+               }
+               if (p) {
+                       m = key_alloc_mbuf(l);
+                       if (!m)
+                               goto fail;
+                       m_copyback(m, 0, l, p);
+               }
+
+               if (tres)
+                       m_cat(m, tres);
+               tres = m;
        }
 
-       return tlen;
-}
+       m_cat(result, tres);
 
-#if 1
-static int
-key_setsadbmsg_m(m, type, tlen, satype, seq, pid, mode, reqid,
-               reserved1, reserved2)
-       struct mbuf *m;
-       u_int8_t type, satype;
-       u_int16_t tlen;
-       u_int32_t seq;
-       pid_t pid;
-       u_int8_t mode;
-       u_int32_t reqid;
-       u_int8_t reserved1;
-       u_int32_t reserved2;
-{
-       caddr_t p;
-       const size_t len = sizeof(struct sadb_msg);
+       if (result->m_len < sizeof(struct sadb_msg)) {
+               result = m_pullup(result, sizeof(struct sadb_msg));
+               if (result == NULL)
+                       goto fail;
+       }
 
-       p = key_appendmbuf(m, len);
-       if (p == NULL)
-               return ENOBUFS;
+       result->m_pkthdr.len = 0;
+       for (m = result; m; m = m->m_next)
+               result->m_pkthdr.len += m->m_len;
 
-       if (key_setsadbmsg(p, type, tlen, satype, seq, pid, mode, reqid,
-                       reserved1, reserved2))
-               return 0;
-       else
-               return EINVAL;
+       mtod(result, struct sadb_msg *)->sadb_msg_len =
+           PFKEY_UNIT64(result->m_pkthdr.len);
+
+       return result;
+
+fail:
+       m_freem(result);
+       m_freem(tres);
+       return NULL;
 }
-#endif
 
 /*
  * set data into sadb_msg.
- * `buf' must has been allocated sufficiently.
  */
-static caddr_t
-key_setsadbmsg(buf, type, tlen, satype, seq, pid, mode, reqid,
-               reserved1, reserved2)
-       caddr_t buf;
+static struct mbuf *
+key_setsadbmsg(type, tlen, satype, seq, pid, reserved)
        u_int8_t type, satype;
        u_int16_t tlen;
        u_int32_t seq;
        pid_t pid;
-       u_int8_t mode;
-       u_int32_t reqid;
-       u_int8_t reserved1;
-       u_int32_t reserved2;
+       u_int16_t reserved;
 {
+       struct mbuf *m;
        struct sadb_msg *p;
-       u_int len;
+       int len;
+
+       len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
+       if (len > MCLBYTES)
+               return NULL;
+       MGETHDR(m, M_DONTWAIT, MT_DATA);
+       if (m && len > MHLEN) {
+               MCLGET(m, M_DONTWAIT);
+               if ((m->m_flags & M_EXT) == 0) {
+                       m_freem(m);
+                       m = NULL;
+               }
+       }
+       if (!m)
+               return NULL;
+       m->m_pkthdr.len = m->m_len = len;
+       m->m_next = NULL;
 
-       p = (struct sadb_msg *)buf;
-       len = sizeof(struct sadb_msg);
+       p = mtod(m, struct sadb_msg *);
 
        bzero(p, len);
        p->sadb_msg_version = PF_KEY_V2;
@@ -3261,30 +3719,33 @@ key_setsadbmsg(buf, type, tlen, satype, seq, pid, mode, reqid,
        p->sadb_msg_errno = 0;
        p->sadb_msg_satype = satype;
        p->sadb_msg_len = PFKEY_UNIT64(tlen);
-       p->sadb_msg_mode = mode;
-       p->sadb_msg_reserved1 = reserved1;
+       p->sadb_msg_reserved = reserved;
        p->sadb_msg_seq = seq;
        p->sadb_msg_pid = (u_int32_t)pid;
-       p->sadb_msg_reqid = reqid;
-       p->sadb_msg_reserved2 = reserved2;
 
-       return(buf + len);
+       return m;
 }
 
 /*
  * copy secasvar data into sadb_address.
- * `buf' must has been allocated sufficiently.
  */
-static caddr_t
-key_setsadbsa(buf, sav)
-       caddr_t buf;
+static struct mbuf *
+key_setsadbsa(sav)
        struct secasvar *sav;
 {
+       struct mbuf *m;
        struct sadb_sa *p;
-       u_int len;
+       int len;
+
+       len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
+       m = key_alloc_mbuf(len);
+       if (!m || m->m_next) {  /*XXX*/
+               if (m)
+                       m_freem(m);
+               return NULL;
+       }
 
-       p = (struct sadb_sa *)buf;
-       len = sizeof(struct sadb_sa);
+       p = mtod(m, struct sadb_sa *);
 
        bzero(p, len);
        p->sadb_sa_len = PFKEY_UNIT64(len);
@@ -3296,80 +3757,84 @@ key_setsadbsa(buf, sav)
        p->sadb_sa_encrypt = sav->alg_enc;
        p->sadb_sa_flags = sav->flags;
 
-       return(buf + len);
-}
-
-#if 1
-static int
-key_setsadbaddr_m(m, exttype, saddr, prefixlen, ul_proto)
-       struct mbuf *m;
-       u_int16_t exttype;
-       struct sockaddr *saddr;
-       u_int8_t prefixlen;
-       u_int16_t ul_proto;
-{
-       caddr_t p;
-       const size_t len =
-           sizeof(struct sadb_address) + PFKEY_ALIGN8(saddr->sa_len);
-
-       p = key_appendmbuf(m, len);
-       if (p == NULL)
-               return ENOBUFS;
-
-       if (key_setsadbaddr(p, exttype, saddr, prefixlen, ul_proto))
-               return 0;
-       else
-               return EINVAL;
+       return m;
 }
-#endif
 
 /*
  * set data into sadb_address.
- * `buf' must has been allocated sufficiently.
  */
-static caddr_t
-key_setsadbaddr(buf, exttype, saddr, prefixlen, ul_proto)
-       caddr_t buf;
+static struct mbuf *
+key_setsadbaddr(exttype, saddr, prefixlen, ul_proto)
        u_int16_t exttype;
        struct sockaddr *saddr;
        u_int8_t prefixlen;
        u_int16_t ul_proto;
 {
+       struct mbuf *m;
        struct sadb_address *p;
        size_t len;
 
-       p = (struct sadb_address *)buf;
-       len = sizeof(struct sadb_address) + PFKEY_ALIGN8(saddr->sa_len);
+       len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
+           PFKEY_ALIGN8(saddr->sa_len);
+       m = key_alloc_mbuf(len);
+       if (!m || m->m_next) {  /*XXX*/
+               if (m)
+                       m_freem(m);
+               return NULL;
+       }
+
+       p = mtod(m, struct sadb_address *);
 
        bzero(p, len);
        p->sadb_address_len = PFKEY_UNIT64(len);
        p->sadb_address_exttype = exttype;
        p->sadb_address_proto = ul_proto;
+       if (prefixlen == FULLMASK) {
+               switch (saddr->sa_family) {
+               case AF_INET:
+                       prefixlen = sizeof(struct in_addr) << 3;
+                       break;
+               case AF_INET6:
+                       prefixlen = sizeof(struct in6_addr) << 3;
+                       break;
+               default:
+                       ; /*XXX*/
+               }
+       }
        p->sadb_address_prefixlen = prefixlen;
        p->sadb_address_reserved = 0;
 
-       bcopy(saddr, p + 1, saddr->sa_len);
+       bcopy(saddr,
+           mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
+           saddr->sa_len);
 
-       return(buf + len);
+       return m;
 }
 
+#if 0
 /*
  * set data into sadb_ident.
- * `buf' must has been allocated sufficiently.
  */
-static caddr_t
-key_setsadbident(buf, exttype, idtype, string, stringlen, id)
-       caddr_t buf;
+static struct mbuf *
+key_setsadbident(exttype, idtype, string, stringlen, id)
        u_int16_t exttype, idtype;
        caddr_t string;
        int stringlen;
        u_int64_t id;
 {
+       struct mbuf *m;
        struct sadb_ident *p;
-       u_int len;
+       size_t len;
+
+       len = PFKEY_ALIGN8(sizeof(struct sadb_ident)) + PFKEY_ALIGN8(stringlen);
+       m = key_alloc_mbuf(len);
+       if (!m || m->m_next) {  /*XXX*/
+               if (m)
+                       m_freem(m);
+               return NULL;
+       }
 
-       p = (struct sadb_ident *)buf;
-       len = sizeof(struct sadb_ident) + PFKEY_ALIGN8(stringlen);
+       p = mtod(m, struct sadb_ident *);
 
        bzero(p, len);
        p->sadb_ident_len = PFKEY_UNIT64(len);
@@ -3378,27 +3843,70 @@ key_setsadbident(buf, exttype, idtype, string, stringlen, id)
        p->sadb_ident_reserved = 0;
        p->sadb_ident_id = id;
 
-       bcopy(string, p + 1, stringlen);
+       bcopy(string,
+           mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_ident)),
+           stringlen);
+
+       return m;
+}
+#endif
+
+/*
+ * set data into sadb_x_sa2.
+ */
+static struct mbuf *
+key_setsadbxsa2(mode, seq, reqid)
+       u_int8_t mode;
+       u_int32_t seq, reqid;
+{
+       struct mbuf *m;
+       struct sadb_x_sa2 *p;
+       size_t len;
+
+       len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
+       m = key_alloc_mbuf(len);
+       if (!m || m->m_next) {  /*XXX*/
+               if (m)
+                       m_freem(m);
+               return NULL;
+       }
+
+       p = mtod(m, struct sadb_x_sa2 *);
 
-       return(buf + len);
+       bzero(p, len);
+       p->sadb_x_sa2_len = PFKEY_UNIT64(len);
+       p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
+       p->sadb_x_sa2_mode = mode;
+       p->sadb_x_sa2_reserved1 = 0;
+       p->sadb_x_sa2_reserved2 = 0;
+       p->sadb_x_sa2_sequence = seq;
+       p->sadb_x_sa2_reqid = reqid;
+
+       return m;
 }
 
 /*
  * set data into sadb_x_policy
- * `buf' must has been allocated sufficiently.
  */
-static caddr_t
-key_setsadbxpolicy(buf, type, dir, id)
-       caddr_t buf;
+static struct mbuf *
+key_setsadbxpolicy(type, dir, id)
        u_int16_t type;
        u_int8_t dir;
        u_int32_t id;
 {
+       struct mbuf *m;
        struct sadb_x_policy *p;
-       u_int len;
+       size_t len;
+
+       len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
+       m = key_alloc_mbuf(len);
+       if (!m || m->m_next) {  /*XXX*/
+               if (m)
+                       m_freem(m);
+               return NULL;
+       }
 
-       p = (struct sadb_x_policy *)buf;
-       len = sizeof(struct sadb_x_policy);
+       p = mtod(m, struct sadb_x_policy *);
 
        bzero(p, len);
        p->sadb_x_policy_len = PFKEY_UNIT64(len);
@@ -3407,25 +3915,7 @@ key_setsadbxpolicy(buf, type, dir, id)
        p->sadb_x_policy_dir = dir;
        p->sadb_x_policy_id = id;
 
-       return(buf + len);
-}
-
-/*
- * copy buffer of any sadb extension type into sadb_ext.
- * assume that sadb_ext_len shifted down >> 3.
- * i.e. shift length up when setting length of extension.
- */
-static caddr_t
-key_setsadbext(p, ext)
-       caddr_t p, ext;
-{
-       u_int len;
-
-       len = PFKEY_UNUNIT64(((struct sadb_ext *)ext)->sadb_ext_len);
-
-       bcopy(ext, p, len);
-
-       return(p + len);
+       return m;
 }
 
 /* %%% utilities */
@@ -3434,19 +3924,17 @@ key_setsadbext(p, ext)
  */
 static void *
 key_newbuf(src, len)
-       void *src;
+       const void *src;
        u_int len;
 {
        caddr_t new;
 
        KMALLOC(new, caddr_t, len);
        if (new == NULL) {
-#if IPSEC_DEBUG
-               printf("key_newbuf: No more memory.\n");
-#endif
+               ipseclog((LOG_DEBUG, "key_newbuf: No more memory.\n"));
                return NULL;
        }
-       bcopy((caddr_t)src, new, len);
+       bcopy(src, new, len);
 
        return new;
 }
@@ -3456,36 +3944,40 @@ key_newbuf(src, len)
  *     0: false
  */
 int
-key_ismyaddr(family, addr)
-       u_int family;
-       caddr_t addr;
+key_ismyaddr(sa)
+       struct sockaddr *sa;
 {
+#if INET
+       struct sockaddr_in *sin;
+       struct in_ifaddr *ia;
+#endif
+
        /* sanity check */
-       if (addr == NULL)
+       if (sa == NULL)
                panic("key_ismyaddr: NULL pointer is passed.\n");
 
-       switch (family) {
+       switch (sa->sa_family) {
+#if INET
        case AF_INET:
-       {
-               struct in_ifaddr *ia;
-
-#ifdef __NetBSD__
-               for (ia = in_ifaddr.tqh_first; ia; ia = ia->ia_list.tqe_next)
-#elif defined(__FreeBSD__) && __FreeBSD__ >= 3 || defined (__APPLE__)
+               lck_mtx_lock(rt_mtx);
+               sin = (struct sockaddr_in *)sa;
                for (ia = in_ifaddrhead.tqh_first; ia;
                     ia = ia->ia_link.tqe_next)
-#else
-               for (ia = in_ifaddr; ia; ia = ia->ia_next)
-#endif
-                       if (bcmp(addr,
-                               (caddr_t)&ia->ia_addr.sin_addr,
-                               _INALENBYAF(family)) == 0)
+               {
+                       if (sin->sin_family == ia->ia_addr.sin_family &&
+                           sin->sin_len == ia->ia_addr.sin_len &&
+                           sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
+                       {
+                               lck_mtx_unlock(rt_mtx);
                                return 1;
-       }
+                       }
+               }
+               lck_mtx_unlock(rt_mtx);
                break;
+#endif
 #if INET6
        case AF_INET6:
-               return key_ismyaddr6(addr);
+               return key_ismyaddr6((struct sockaddr_in6 *)sa);
 #endif
        }
 
@@ -3502,132 +3994,59 @@ key_ismyaddr(family, addr)
 #include <netinet6/in6_var.h>
 
 static int
-key_ismyaddr6(addr)
-       caddr_t addr;
+key_ismyaddr6(sin6)
+       struct sockaddr_in6 *sin6;
 {
-       struct in6_addr *a = (struct in6_addr *)addr;
        struct in6_ifaddr *ia;
+       struct in6_multi *in6m;
 
-       for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
-               if (bcmp(addr, (caddr_t)&ia->ia_addr.sin6_addr,
-                               _INALENBYAF(AF_INET6)) == 0) {
+       lck_mtx_lock(nd6_mutex);
+       for (ia = in6_ifaddrs; ia; ia = ia->ia_next) {
+               if (key_sockaddrcmp((struct sockaddr *)&sin6,
+                   (struct sockaddr *)&ia->ia_addr, 0) == 0) {
+                       lck_mtx_unlock(nd6_mutex);
                        return 1;
                }
 
-               /* XXX Multicast */
-           {
-               struct  in6_multi *in6m = 0;
-
-#if defined(__FreeBSD__) && __FreeBSD__ >= 3 || defined (__APPLE__)
-               IN6_LOOKUP_MULTI(*(struct in6_addr *)addr, ia->ia_ifp, in6m);
-#else
-               for ((in6m) = ia->ia6_multiaddrs.lh_first;
-                    (in6m) != NULL &&
-                    !IN6_ARE_ADDR_EQUAL(&(in6m)->in6m_addr, a);
-                    (in6m) = in6m->in6m_entry.le_next)
-                       continue;
-#endif
-               if (in6m)
+               /*
+                * XXX Multicast
+                * XXX why do we care about multlicast here while we don't care
+                * about IPv4 multicast??
+                * XXX scope
+                */
+               in6m = NULL;
+               IN6_LOOKUP_MULTI(sin6->sin6_addr, ia->ia_ifp, in6m);
+               if (in6m) {
+                       lck_mtx_unlock(nd6_mutex);
                        return 1;
-           }
+               }
        }
+       lck_mtx_unlock(nd6_mutex);
 
        /* loopback, just for safety */
-       if (IN6_IS_ADDR_LOOPBACK(a))
-               return 1;
-
-#if 0
-       /* FAITH */
-       if (ip6_keepfaith &&
-           (a->s6_addr32[0] == ip6_faith_prefix.s6_addr32[0] &&
-            a->s6_addr32[1] == ip6_faith_prefix.s6_addr32[1] &&
-            a->s6_addr32[2] == ip6_faith_prefix.s6_addr32[2]))
+       if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
                return 1;
-#endif
-
-       /* XXX anycast */
 
        return 0;
 }
 #endif /*INET6*/
 
-#if 0
-/* checking address is whether loopback or not.
- * OUT:        1:      true
- *     0:      false
- */
-static int
-key_isloopback(family, addr)
-       u_int family;
-       caddr_t addr;
-{
-       switch (family) {
-       case PF_INET:
-               if (((caddr_t)addr)[0] == IN_LOOPBACKNET)
-                       return 1;
-               break;
-#if INET6
-       case PF_INET6:
-               if (IN6_IS_ADDR_LOOPBACK((struct in6_addr *)addr))
-                       return 1;
-               break;
-#endif /* INET6 */
-       default:
-#if IPSEC_DEBUG
-               printf("key_isloopback: unknown address family=%d.\n", family);
-#endif
-               return 0;
-       }
-
-       return 0;
-}
-#endif
-
-/*
- * compare two secasindex structure exactly.
- * IN:
- *     saidx0: source, it can be in SAD.
- *     saidx1: object.
- * OUT:
- *     1 : equal
- *     0 : not equal
- */
-static int
-key_cmpsaidx_exactly(saidx0, saidx1)
-       struct secasindex *saidx0, *saidx1;
-{
-       /* sanity */
-       if (saidx0 == NULL && saidx1 == NULL)
-               return 1;
-
-       if (saidx0 == NULL || saidx1 == NULL)
-               return 0;
-
-       if (saidx0->proto != saidx1->proto
-        || saidx0->mode != saidx1->mode
-        || saidx0->reqid != saidx1->reqid)
-               return 0;
-
-       if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.ss_len) != 0
-        || bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.ss_len) != 0)
-               return 0;
-
-       return 1;
-}
-
 /*
- * compare two secasindex structure with consideration mode.
+ * compare two secasindex structure.
+ * flag can specify to compare 2 saidxes.
+ * compare two secasindex structure without both mode and reqid.
  * don't compare port.
- * IN:
- *     saidx0: source, it is often in SAD.
- *     saidx1: object, it is often from SPD.
- * OUT:
- *     1 : equal
- *     0 : not equal
+ * IN:  
+ *      saidx0: source, it can be in SAD.
+ *      saidx1: object.
+ * OUT: 
+ *      1 : equal
+ *      0 : not equal
  */
 static int
-key_cmpsaidx_withmode(saidx0, saidx1)
+key_cmpsaidx(saidx0, saidx1, flag)
        struct secasindex *saidx0, *saidx1;
+       int flag;
 {
        /* sanity */
        if (saidx0 == NULL && saidx1 == NULL)
@@ -3636,30 +4055,45 @@ key_cmpsaidx_withmode(saidx0, saidx1)
        if (saidx0 == NULL || saidx1 == NULL)
                return 0;
 
-       if (saidx0->proto != saidx1->proto
-        || saidx0->src.ss_family != saidx1->src.ss_family
-        || saidx0->dst.ss_family != saidx1->dst.ss_family)
+       if (saidx0->proto != saidx1->proto)
                return 0;
 
-       /*
-        * If reqid of SPD is non-zero, unique SA is required.
-        * The result must be of same reqid in this case.
-        */
-       if (saidx1->reqid != 0
-        && saidx0->reqid != saidx1->reqid)
-               return 0;
+       if (flag == CMP_EXACTLY) {
+               if (saidx0->mode != saidx1->mode)
+                       return 0;
+               if (saidx0->reqid != saidx1->reqid)
+                       return 0;
+               if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.ss_len) != 0 ||
+                   bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.ss_len) != 0)
+                       return 0;
+       } else {
 
-       if (saidx0->mode != IPSEC_MODE_ANY
-        && saidx0->mode != saidx1->mode)
-               return 0;
+               /* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
+               if (flag == CMP_MODE_REQID
+                 ||flag == CMP_REQID) {
+                       /*
+                        * If reqid of SPD is non-zero, unique SA is required.
+                        * The result must be of same reqid in this case.
+                        */
+                       if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
+                               return 0;
+               }
 
-    {
-       int sa_len = _INALENBYAF(saidx0->src.ss_family);
+               if (flag == CMP_MODE_REQID) {
+                       if (saidx0->mode != IPSEC_MODE_ANY
+                        && saidx0->mode != saidx1->mode)
+                               return 0;
+               }
 
-       if (bcmp(_INADDRBYSA(&saidx0->src), _INADDRBYSA(&saidx1->src), sa_len)
-        || bcmp(_INADDRBYSA(&saidx0->dst), _INADDRBYSA(&saidx1->dst), sa_len))
-               return 0;
-    }
+               if (key_sockaddrcmp((struct sockaddr *)&saidx0->src,
+                               (struct sockaddr *)&saidx1->src, 0) != 0) {
+                       return 0;
+               }
+               if (key_sockaddrcmp((struct sockaddr *)&saidx0->dst,
+                               (struct sockaddr *)&saidx1->dst, 0) != 0) {
+                       return 0;
+               }
+       }
 
        return 1;
 }
@@ -3689,9 +4123,14 @@ key_cmpspidx_exactly(spidx0, spidx1)
         || spidx0->ul_proto != spidx1->ul_proto)
                return 0;
 
-       if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.ss_len) != 0
-        || bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.ss_len) != 0)
+       if (key_sockaddrcmp((struct sockaddr *)&spidx0->src,
+           (struct sockaddr *)&spidx1->src, 1) != 0) {
+               return 0;
+       }
+       if (key_sockaddrcmp((struct sockaddr *)&spidx0->dst,
+           (struct sockaddr *)&spidx1->dst, 1) != 0) {
                return 0;
+       }
 
        return 1;
 }
@@ -3716,8 +4155,10 @@ key_cmpspidx_withmask(spidx0, spidx1)
        if (spidx0 == NULL || spidx1 == NULL)
                return 0;
 
-       if (spidx0->src.ss_family != spidx1->src.ss_family
-        || spidx0->dst.ss_family != spidx1->dst.ss_family)
+       if (spidx0->src.ss_family != spidx1->src.ss_family ||
+           spidx0->dst.ss_family != spidx1->dst.ss_family ||
+           spidx0->src.ss_len != spidx1->src.ss_len ||
+           spidx0->dst.ss_len != spidx1->dst.ss_len)
                return 0;
 
        /* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
@@ -3725,27 +4166,124 @@ key_cmpspidx_withmask(spidx0, spidx1)
         && spidx0->ul_proto != spidx1->ul_proto)
                return 0;
 
-       if (_INPORTBYSA(&spidx0->src) != IPSEC_PORT_ANY
-        && _INPORTBYSA(&spidx0->src) != _INPORTBYSA(&spidx1->src))
-               return 0;
-
-       if (_INPORTBYSA(&spidx0->dst) != IPSEC_PORT_ANY
-        && _INPORTBYSA(&spidx0->dst) != _INPORTBYSA(&spidx1->dst))
-               return 0;
-
-       if (!key_bbcmp(_INADDRBYSA(&spidx0->src),
-                      _INADDRBYSA(&spidx1->src),
-                      spidx0->prefs))
-               return 0;
-
-       if (!key_bbcmp(_INADDRBYSA(&spidx0->dst),
-                      _INADDRBYSA(&spidx1->dst),
-                      spidx0->prefd))
-               return 0;
-
-       /* XXX Do we check other field ?  e.g. flowinfo, scope_id. */
-
-       return 1;
+       switch (spidx0->src.ss_family) {
+       case AF_INET:
+               if (satosin(&spidx0->src)->sin_port != IPSEC_PORT_ANY
+                && satosin(&spidx0->src)->sin_port !=
+                   satosin(&spidx1->src)->sin_port)
+                       return 0;
+               if (!key_bbcmp((caddr_t)&satosin(&spidx0->src)->sin_addr,
+                   (caddr_t)&satosin(&spidx1->src)->sin_addr, spidx0->prefs))
+                       return 0;
+               break;
+       case AF_INET6:
+               if (satosin6(&spidx0->src)->sin6_port != IPSEC_PORT_ANY
+                && satosin6(&spidx0->src)->sin6_port !=
+                   satosin6(&spidx1->src)->sin6_port)
+                       return 0;
+               /*
+                * scope_id check. if sin6_scope_id is 0, we regard it
+                * as a wildcard scope, which matches any scope zone ID. 
+                */
+               if (satosin6(&spidx0->src)->sin6_scope_id &&
+                   satosin6(&spidx1->src)->sin6_scope_id &&
+                   satosin6(&spidx0->src)->sin6_scope_id !=
+                   satosin6(&spidx1->src)->sin6_scope_id)
+                       return 0;
+               if (!key_bbcmp((caddr_t)&satosin6(&spidx0->src)->sin6_addr,
+                   (caddr_t)&satosin6(&spidx1->src)->sin6_addr, spidx0->prefs))
+                       return 0;
+               break;
+       default:
+               /* XXX */
+               if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.ss_len) != 0)
+                       return 0;
+               break;
+       }
+
+       switch (spidx0->dst.ss_family) {
+       case AF_INET:
+               if (satosin(&spidx0->dst)->sin_port != IPSEC_PORT_ANY
+                && satosin(&spidx0->dst)->sin_port !=
+                   satosin(&spidx1->dst)->sin_port)
+                       return 0;
+               if (!key_bbcmp((caddr_t)&satosin(&spidx0->dst)->sin_addr,
+                   (caddr_t)&satosin(&spidx1->dst)->sin_addr, spidx0->prefd))
+                       return 0;
+               break;
+       case AF_INET6:
+               if (satosin6(&spidx0->dst)->sin6_port != IPSEC_PORT_ANY
+                && satosin6(&spidx0->dst)->sin6_port !=
+                   satosin6(&spidx1->dst)->sin6_port)
+                       return 0;
+               /*
+                * scope_id check. if sin6_scope_id is 0, we regard it
+                * as a wildcard scope, which matches any scope zone ID. 
+                */
+               if (satosin6(&spidx0->src)->sin6_scope_id &&
+                   satosin6(&spidx1->src)->sin6_scope_id &&
+                   satosin6(&spidx0->dst)->sin6_scope_id !=
+                   satosin6(&spidx1->dst)->sin6_scope_id)
+                       return 0;
+               if (!key_bbcmp((caddr_t)&satosin6(&spidx0->dst)->sin6_addr,
+                   (caddr_t)&satosin6(&spidx1->dst)->sin6_addr, spidx0->prefd))
+                       return 0;
+               break;
+       default:
+               /* XXX */
+               if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.ss_len) != 0)
+                       return 0;
+               break;
+       }
+
+       /* XXX Do we check other field ?  e.g. flowinfo */
+
+       return 1;
+}
+
+/* returns 0 on match */
+static int
+key_sockaddrcmp(sa1, sa2, port)
+       struct sockaddr *sa1;
+       struct sockaddr *sa2;
+       int port;
+{
+       if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
+               return 1;
+
+       switch (sa1->sa_family) {
+       case AF_INET:
+               if (sa1->sa_len != sizeof(struct sockaddr_in))
+                       return 1;
+               if (satosin(sa1)->sin_addr.s_addr !=
+                   satosin(sa2)->sin_addr.s_addr) {
+                       return 1;
+               }
+               if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
+                       return 1;
+               break;
+       case AF_INET6:
+               if (sa1->sa_len != sizeof(struct sockaddr_in6))
+                       return 1;       /*EINVAL*/
+               if (satosin6(sa1)->sin6_scope_id !=
+                   satosin6(sa2)->sin6_scope_id) {
+                       return 1;
+               }
+               if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
+                   &satosin6(sa2)->sin6_addr)) {
+                       return 1;
+               }
+               if (port &&
+                   satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
+                       return 1;
+               }
+       default:
+               if (bcmp(sa1, sa2, sa1->sa_len) != 0)
+                       return 1;
+               break;
+       }
+
+       return 0;
 }
 
 /*
@@ -3760,8 +4298,8 @@ key_cmpspidx_withmask(spidx0, spidx1)
  */
 static int
 key_bbcmp(p1, p2, bits)
-       register caddr_t p1, p2;
-       register u_int bits;
+       caddr_t p1, p2;
+       u_int bits;
 {
        u_int8_t mask;
 
@@ -3790,20 +4328,19 @@ key_bbcmp(p1, p2, bits)
  * time handler.
  * scanning SPD and SAD to check status for each entries,
  * and do to remove or to expire.
+ * XXX: year 2038 problem may remain.
  */
+
 void
 key_timehandler(void)
 {
        u_int dir;
        int s;
+       struct timeval tv;
 
-       thread_funnel_set(network_flock, TRUE);
-#if __NetBSD__
-       s = splsoftnet();       /*called from softclock()*/
-#else
-       s = splnet();   /*called from softclock()*/
-#endif
+       microtime(&tv);
 
+       lck_mtx_lock(sadb_mutex);
        /* SPD */
     {
        struct secpolicy *sp, *nextsp;
@@ -3815,8 +4352,23 @@ key_timehandler(void)
 
                        nextsp = LIST_NEXT(sp, chain);
 
-                       if (sp->state == IPSEC_SPSTATE_DEAD)
+                       if (sp->state == IPSEC_SPSTATE_DEAD) {
                                key_freesp(sp);
+                               continue;
+                       }
+
+                       if (sp->lifetime == 0 && sp->validtime == 0)
+                               continue;
+
+                       /* the deletion will occur next time */
+                       if ((sp->lifetime
+                         && tv.tv_sec - sp->created > sp->lifetime)
+                        || (sp->validtime
+                         && tv.tv_sec - sp->lastused > sp->validtime)) {
+                               sp->state = IPSEC_SPSTATE_DEAD;
+                               key_spdexpire(sp);
+                               continue;
+                       }
                }
        }
     }
@@ -3845,13 +4397,27 @@ key_timehandler(void)
 
                        nextsav = LIST_NEXT(sav, chain);
 
-                       sav->tick++;
-
-                       if (key_larval_lifetime < sav->tick) {
+                       if (tv.tv_sec - sav->created > key_larval_lifetime) {
                                key_freesav(sav);
                        }
                }
-
+               
+               /*
+                * If this is a NAT traversal SA with no activity,
+                * we need to send a keep alive.
+                *
+                * Performed outside of the loop before so we will
+                * only ever send one keepalive. The first SA on
+                * the list is the one that will be used for sending
+                * traffic, so this is the one we use for determining
+                * when to send the keepalive.
+                */
+               sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_MATURE]);
+               if (natt_keepalive_interval && sav && (sav->flags & SADB_X_EXT_NATT_KEEPALIVE) != 0 &&
+                       (natt_now - sav->natt_last_activity) >= natt_keepalive_interval) {
+                       ipsec_send_natt_keepalive(sav);
+               }
+               
                /*
                 * check MATURE entry to start to send expire message
                 * whether or not.
@@ -3862,27 +4428,24 @@ key_timehandler(void)
 
                        nextsav = LIST_NEXT(sav, chain);
 
-                       sav->tick++;
-
                        /* we don't need to check. */
                        if (sav->lft_s == NULL)
                                continue;
 
                        /* sanity check */
                        if (sav->lft_c == NULL) {
-#if IPSEC_DEBUG
-                               printf("key_timehandler: "
-                                       "There is no CURRENT time, why?\n");
-#endif
+                               ipseclog((LOG_DEBUG,"key_timehandler: "
+                                       "There is no CURRENT time, why?\n"));
                                continue;
                        }
 
-                       /* compare SOFT lifetime and tick */
+                       /* check SOFT lifetime */
                        if (sav->lft_s->sadb_lifetime_addtime != 0
-                        && sav->lft_s->sadb_lifetime_addtime < sav->tick) {
+                        && tv.tv_sec - sav->created > sav->lft_s->sadb_lifetime_addtime) {
                                /*
-                                * check SA to be used whether or not.
-                                * when SA hasn't been used, delete it.
+                                * check the SA if it has been used.
+                                * when it hasn't been used, delete it.
+                                * i don't think such SA will be used.
                                 */
                                if (sav->lft_c->sadb_lifetime_usetime == 0) {
                                        key_sa_chgstate(sav, SADB_SASTATE_DEAD);
@@ -3898,6 +4461,7 @@ key_timehandler(void)
                                        key_expire(sav);
                                }
                        }
+
                        /* check SOFT lifetime by bytes */
                        /*
                         * XXX I don't know the way to delete this SA
@@ -3924,24 +4488,19 @@ key_timehandler(void)
 
                        nextsav = LIST_NEXT(sav, chain);
 
-                       sav->tick++;
-
                        /* we don't need to check. */
                        if (sav->lft_h == NULL)
                                continue;
 
                        /* sanity check */
                        if (sav->lft_c == NULL) {
-#if IPSEC_DEBUG
-                               printf("key_timehandler: "
-                                       "There is no CURRENT time, why?\n");
-#endif
+                               ipseclog((LOG_DEBUG, "key_timehandler: "
+                                       "There is no CURRENT time, why?\n"));
                                continue;
                        }
 
-                       /* compare HARD lifetime and tick */
                        if (sav->lft_h->sadb_lifetime_addtime != 0
-                        && sav->lft_h->sadb_lifetime_addtime < sav->tick) {
+                        && tv.tv_sec - sav->created > sav->lft_h->sadb_lifetime_addtime) {
                                key_sa_chgstate(sav, SADB_SASTATE_DEAD);
                                key_freesav(sav);
                                sav = NULL;
@@ -3949,7 +4508,7 @@ key_timehandler(void)
 #if 0  /* XXX Should we keep to send expire message until HARD lifetime ? */
                        else if (sav->lft_s != NULL
                              && sav->lft_s->sadb_lifetime_addtime != 0
-                             && sav->lft_s->sadb_lifetime_addtime < sav->tick) {
+                             && tv.tv_sec - sav->created > sav->lft_s->sadb_lifetime_addtime) {
                                /*
                                 * XXX: should be checked to be
                                 * installed the valid SA.
@@ -3980,13 +4539,11 @@ key_timehandler(void)
 
                        /* sanity check */
                        if (sav->state != SADB_SASTATE_DEAD) {
-#if IPSEC_DEBUG
-                               printf("key_timehandler: "
+                               ipseclog((LOG_DEBUG, "key_timehandler: "
                                        "invalid sav->state "
                                        "(queue: %d SA: %d): "
                                        "kill it anyway\n",
-                                       SADB_SASTATE_DEAD, sav->state);
-#endif
+                                       SADB_SASTATE_DEAD, sav->state));
                        }
 
                        /*
@@ -4010,9 +4567,8 @@ key_timehandler(void)
 
                nextacq = LIST_NEXT(acq, chain);
 
-               acq->tick++;
-
-               if (key_blockacq_lifetime < acq->tick && __LIST_CHAINED(acq)) {
+               if (tv.tv_sec - acq->created > key_blockacq_lifetime
+                && __LIST_CHAINED(acq)) {
                        LIST_REMOVE(acq, chain);
                        KFREE(acq);
                }
@@ -4030,9 +4586,8 @@ key_timehandler(void)
 
                nextacq = LIST_NEXT(acq, chain);
 
-               acq->tick++;
-
-               if (key_blockacq_lifetime < acq->tick && __LIST_CHAINED(acq)) {
+               if (tv.tv_sec - acq->created > key_blockacq_lifetime
+                && __LIST_CHAINED(acq)) {
                        LIST_REMOVE(acq, chain);
                        KFREE(acq);
                }
@@ -4044,43 +4599,77 @@ key_timehandler(void)
                key_tick_init_random = 0;
                key_srandom();
        }
+       
+       natt_now++;
 
+       lck_mtx_unlock(sadb_mutex);
 #ifndef IPSEC_DEBUG2
        /* do exchange to tick time !! */
-       (void)timeout((void *)key_timehandler, (void *)0, 100);
+       (void)timeout((void *)key_timehandler, (void *)0, hz);
 #endif /* IPSEC_DEBUG2 */
 
-       splx(s);
-       thread_funnel_set(network_funnel, FALSE);
        return;
 }
 
 /*
  * to initialize a seed for random()
  */
-void
+static void
 key_srandom()
 {
+#ifdef __APPLE__
+       /* Our PRNG is based on Yarrow and doesn't need to be seeded */
+       random();
+#else
        struct timeval tv;
-#ifdef __bsdi__
-       extern long randseed; /* it's defined at i386/i386/random.s */
-#endif /* __bsdi__ */
 
        microtime(&tv);
 
-#if defined(__FreeBSD__)
        srandom(tv.tv_usec);
-#endif /* __FreeBSD__ */
-#if defined(__APPLE__)
-       random();
 #endif
-#ifdef __bsdi__
-       randseed = tv.tv_usec;
-#endif /* __bsdi__ */
 
        return;
 }
 
+u_long
+key_random()
+{
+       u_long value;
+
+       key_randomfill(&value, sizeof(value));
+       return value;
+}
+
+void
+key_randomfill(p, l)
+       void *p;
+       size_t l;
+{
+       size_t n;
+       u_long v;
+       static int warn = 1;
+#ifdef __APPLE__
+
+       read_random(p, (u_int)l);
+#else
+       n = 0;
+       n = (size_t)read_random(p, (u_int)l);
+       /* last resort */
+       while (n < l) {
+               v = random();
+               bcopy(&v, (u_int8_t *)p + n,
+                   l - n < sizeof(v) ? l - n : sizeof(v));
+               n += sizeof(v);
+
+               if (warn) {
+                       printf("WARNING: pseudo-random number generator "
+                           "used for IPsec processing\n");
+                       warn = 0;
+               }
+       }
+#endif
+}
+
 /*
  * map SADB_SATYPE_* to IPPROTO_*.
  * if satype == SADB_SATYPE then satype is mapped to ~0.
@@ -4098,11 +4687,9 @@ key_satype2proto(satype)
                return IPPROTO_AH;
        case SADB_SATYPE_ESP:
                return IPPROTO_ESP;
-#if 1  /*nonstandard*/
        case SADB_X_SATYPE_IPCOMP:
                return IPPROTO_IPCOMP;
                break;
-#endif
        default:
                return 0;
        }
@@ -4123,11 +4710,9 @@ key_proto2satype(proto)
                return SADB_SATYPE_AH;
        case IPPROTO_ESP:
                return SADB_SATYPE_ESP;
-#if 1  /*nonstandard*/
        case IPPROTO_IPCOMP:
                return SADB_X_SATYPE_IPCOMP;
                break;
-#endif
        default:
                return 0;
        }
@@ -4137,7 +4722,7 @@ key_proto2satype(proto)
 /* %%% PF_KEY */
 /*
  * SADB_GETSPI processing is to receive
- *     <base, src address, dst address, (SPI range)>
+ *     <base, (SA2), src address, dst address, (SPI range)>
  * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
  * tree with the status of LARVAL, and send
  *     <base, SA(*), address(SD)>
@@ -4147,130 +4732,198 @@ key_proto2satype(proto)
  * OUT:        NULL if fail.
  *     other if success, return pointer to the message to send.
  */
-static struct sadb_msg *
-key_getspi(mhp)
-       caddr_t *mhp;
+static int
+key_getspi(so, m, mhp)
+       struct socket *so;
+       struct mbuf *m;
+       const struct sadb_msghdr *mhp;
 {
-       struct sadb_msg *msg0;
        struct sadb_address *src0, *dst0;
        struct secasindex saidx;
        struct secashead *newsah;
        struct secasvar *newsav;
        u_int8_t proto;
        u_int32_t spi;
+       u_int8_t mode;
+       u_int32_t reqid;
+       int error;
+
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
 
        /* sanity check */
-       if (mhp == NULL || mhp[0] == NULL)
+       if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
                panic("key_getspi: NULL pointer is passed.\n");
 
-       msg0 = (struct sadb_msg *)mhp[0];
-
-       if (mhp[SADB_EXT_ADDRESS_SRC] == NULL
-        || mhp[SADB_EXT_ADDRESS_DST] == NULL) {
-#if IPSEC_DEBUG
-               printf("key_getspi: invalid message is passed.\n");
-#endif
-               msg0->sadb_msg_errno = EINVAL;
-               return NULL;
+       if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
+           mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
+               ipseclog((LOG_DEBUG, "key_getspi: invalid message is passed.\n"));
+               return key_senderror(so, m, EINVAL);
+       }
+       if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
+           mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
+               ipseclog((LOG_DEBUG, "key_getspi: invalid message is passed.\n"));
+               return key_senderror(so, m, EINVAL);
+       }
+       if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
+               mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
+               reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
+       } else {
+               mode = IPSEC_MODE_ANY;
+               reqid = 0;
        }
 
-       src0 = (struct sadb_address *)(mhp[SADB_EXT_ADDRESS_SRC]);
-       dst0 = (struct sadb_address *)(mhp[SADB_EXT_ADDRESS_DST]);
+       src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
+       dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
 
        /* map satype to proto */
-       if ((proto = key_satype2proto(msg0->sadb_msg_satype)) == 0) {
-#if IPSEC_DEBUG
-               printf("key_getspi: invalid satype is passed.\n");
-#endif
-               msg0->sadb_msg_errno = EINVAL;
-               return NULL;
+       if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
+               ipseclog((LOG_DEBUG, "key_getspi: invalid satype is passed.\n"));
+               return key_senderror(so, m, EINVAL);
+       }
+
+       /* make sure if port number is zero. */
+       switch (((struct sockaddr *)(src0 + 1))->sa_family) {
+       case AF_INET:
+               if (((struct sockaddr *)(src0 + 1))->sa_len !=
+                   sizeof(struct sockaddr_in))
+                       return key_senderror(so, m, EINVAL);
+               ((struct sockaddr_in *)(src0 + 1))->sin_port = 0;
+               break;
+       case AF_INET6:
+               if (((struct sockaddr *)(src0 + 1))->sa_len !=
+                   sizeof(struct sockaddr_in6))
+                       return key_senderror(so, m, EINVAL);
+               ((struct sockaddr_in6 *)(src0 + 1))->sin6_port = 0;
+               break;
+       default:
+               ; /*???*/
+       }
+       switch (((struct sockaddr *)(dst0 + 1))->sa_family) {
+       case AF_INET:
+               if (((struct sockaddr *)(dst0 + 1))->sa_len !=
+                   sizeof(struct sockaddr_in))
+                       return key_senderror(so, m, EINVAL);
+               ((struct sockaddr_in *)(dst0 + 1))->sin_port = 0;
+               break;
+       case AF_INET6:
+               if (((struct sockaddr *)(dst0 + 1))->sa_len !=
+                   sizeof(struct sockaddr_in6))
+                       return key_senderror(so, m, EINVAL);
+               ((struct sockaddr_in6 *)(dst0 + 1))->sin6_port = 0;
+               break;
+       default:
+               ; /*???*/
        }
 
-       KEY_SETSECASIDX(proto, msg0, src0+1, dst0+1, &saidx);
+       /* XXX boundary check against sa_len */
+       KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
 
        /* SPI allocation */
-       spi = key_do_getnewspi((struct sadb_spirange *)mhp[SADB_EXT_SPIRANGE],
+       spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
                               &saidx);
-       if (spi == 0) {
-               msg0->sadb_msg_errno = EEXIST;
-               return NULL;
-       }
+       if (spi == 0)
+               return key_senderror(so, m, EINVAL);
 
        /* get a SA index */
        if ((newsah = key_getsah(&saidx)) == NULL) {
-
                /* create a new SA index */
                if ((newsah = key_newsah(&saidx)) == NULL) {
-#if IPSEC_DEBUG
-                       printf("key_getspi: No more memory.\n");
-#endif
-                       msg0->sadb_msg_errno = ENOBUFS;
-                       return NULL;
+                       ipseclog((LOG_DEBUG, "key_getspi: No more memory.\n"));
+                       return key_senderror(so, m, ENOBUFS);
                }
        }
 
        /* get a new SA */
-       if ((newsav = key_newsav(mhp, newsah)) == NULL) {
-               msg0->sadb_msg_errno = ENOBUFS;
+       /* XXX rewrite */
+       newsav = key_newsav(m, mhp, newsah, &error);
+       if (newsav == NULL) {
                /* XXX don't free new SA index allocated in above. */
-               return NULL;
+               return key_senderror(so, m, error);
        }
 
        /* set spi */
-       newsav->spi = htonl(spi);
+       key_setspi(newsav, htonl(spi));
 
 #ifndef IPSEC_NONBLOCK_ACQUIRE
        /* delete the entry in acqtree */
-       if (msg0->sadb_msg_seq != 0) {
+       if (mhp->msg->sadb_msg_seq != 0) {
                struct secacq *acq;
-               if ((acq = key_getacqbyseq(msg0->sadb_msg_seq)) != NULL) {
-                       /* reset counter in order to deletion by timehander. */
-                       acq->tick = key_blockacq_lifetime;
+               if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
+                       /* reset counter in order to deletion by timehandler. */
+                       struct timeval tv;
+                       microtime(&tv);
+                       acq->created = tv.tv_sec;
                        acq->count = 0;
                }
        }
 #endif
 
     {
+       struct mbuf *n, *nn;
+       struct sadb_sa *m_sa;
        struct sadb_msg *newmsg;
-       u_int len;
-       caddr_t p;
+       int off, len;
 
        /* create new sadb_msg to reply. */
-       len = sizeof(struct sadb_msg)
-           + sizeof(struct sadb_sa)
-           + PFKEY_EXTLEN(mhp[SADB_EXT_ADDRESS_SRC])
-           + PFKEY_EXTLEN(mhp[SADB_EXT_ADDRESS_DST]);
-
-       KMALLOC(newmsg, struct sadb_msg *, len);
-       if (newmsg == NULL) {
-#if IPSEC_DEBUG
-               printf("key_getspi: No more memory.\n");
-#endif
-               msg0->sadb_msg_errno = ENOBUFS;
-               return NULL;
+       len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
+           PFKEY_ALIGN8(sizeof(struct sadb_sa));
+       if (len > MCLBYTES)
+               return key_senderror(so, m, ENOBUFS);
+
+       MGETHDR(n, M_DONTWAIT, MT_DATA);
+       if (len > MHLEN) {
+               MCLGET(n, M_DONTWAIT);
+               if ((n->m_flags & M_EXT) == 0) {
+                       m_freem(n);
+                       n = NULL;
+               }
        }
-       bzero((caddr_t)newmsg, len);
+       if (!n)
+               return key_senderror(so, m, ENOBUFS);
 
-       bcopy((caddr_t)mhp[0], (caddr_t)newmsg, sizeof(*msg0));
-       newmsg->sadb_msg_seq = newsav->seq;
-       newmsg->sadb_msg_errno = 0;
-       newmsg->sadb_msg_len = PFKEY_UNIT64(len);
-       p = (caddr_t)newmsg + sizeof(*msg0);
+       n->m_len = len;
+       n->m_next = NULL;
+       off = 0;
 
-      {
-       struct sadb_sa *m_sa;
-       m_sa = (struct sadb_sa *)p;
+       m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
+       off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
+
+       m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
        m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
        m_sa->sadb_sa_exttype = SADB_EXT_SA;
        m_sa->sadb_sa_spi = htonl(spi);
-       p += sizeof(struct sadb_sa);
-      }
+       off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
+
+#if DIAGNOSTIC
+       if (off != len)
+               panic("length inconsistency in key_getspi");
+#endif
+       {
+       int mbufItems[] = {SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST};
+       n->m_next = key_gather_mbuf(m, mhp, 0, sizeof(mbufItems)/sizeof(int), mbufItems);
+       if (!n->m_next) {
+               m_freem(n);
+               return key_senderror(so, m, ENOBUFS);
+       }
+       }
+
+       if (n->m_len < sizeof(struct sadb_msg)) {
+               n = m_pullup(n, sizeof(struct sadb_msg));
+               if (n == NULL)
+                       return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
+       }
 
-       p = key_setsadbext(p, mhp[SADB_EXT_ADDRESS_SRC]);
-       p = key_setsadbext(p, mhp[SADB_EXT_ADDRESS_DST]);
+       n->m_pkthdr.len = 0;
+       for (nn = n; nn; nn = nn->m_next)
+               n->m_pkthdr.len += nn->m_len;
 
-       return newmsg;
+       newmsg = mtod(n, struct sadb_msg *);
+       newmsg->sadb_msg_seq = newsav->seq;
+       newmsg->sadb_msg_errno = 0;
+       newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
+
+       m_freem(m);
+       return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
     }
 }
 
@@ -4290,6 +4943,8 @@ key_do_getnewspi(spirange, saidx)
        u_int32_t min, max;
        int count = key_spi_trycnt;
 
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        /* set spi range to allocate */
        if (spirange != NULL) {
                min = spirange->sadb_spirange_min;
@@ -4312,9 +4967,7 @@ key_do_getnewspi(spirange, saidx)
 
        if (min == max) {
                if (key_checkspidup(saidx, min) != NULL) {
-#if IPSEC_DEBUG
-                       printf("key_do_getnewspi: SPI %u exists already.\n", min);
-#endif
+                       ipseclog((LOG_DEBUG, "key_do_getnewspi: SPI %u exists already.\n", min));
                        return 0;
                }
 
@@ -4329,16 +4982,14 @@ key_do_getnewspi(spirange, saidx)
                /* when requesting to allocate spi ranged */
                while (count--) {
                        /* generate pseudo-random SPI value ranged. */
-                       newspi = min + (random() % ( max - min + 1 ));
+                       newspi = min + (key_random() % (max - min + 1));
 
                        if (key_checkspidup(saidx, newspi) == NULL)
                                break;
                }
 
                if (count == 0 || newspi == 0) {
-#if IPSEC_DEBUG
-                       printf("key_do_getnewspi: to allocate spi is failed.\n");
-#endif
+                       ipseclog((LOG_DEBUG, "key_do_getnewspi: to allocate spi is failed.\n"));
                        return 0;
                }
        }
@@ -4353,157 +5004,158 @@ key_do_getnewspi(spirange, saidx)
 /*
  * SADB_UPDATE processing
  * receive
- *   <base, SA, (lifetime(HSC),) address(SD), (address(P),)
+ *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
  *       key(AE), (identity(SD),) (sensitivity)>
  * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
  * and send
- *   <base, SA, (lifetime(HSC),) address(SD), (address(P),)
+ *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
  *       (identity(SD),) (sensitivity)>
  * to the ikmpd.
  *
- * IN: mhp: pointer to the pointer to each header.
- * OUT:        NULL if fail.
- *     other if success, return pointer to the message to send.
+ * m will always be freed.
  */
-static struct sadb_msg *
-key_update(mhp)
-       caddr_t *mhp;
+static int
+key_update(so, m, mhp)
+       struct socket *so;
+       struct mbuf *m;
+       const struct sadb_msghdr *mhp;
 {
-       struct sadb_msg *msg0;
        struct sadb_sa *sa0;
        struct sadb_address *src0, *dst0;
        struct secasindex saidx;
        struct secashead *sah;
        struct secasvar *sav;
        u_int16_t proto;
+       u_int8_t mode;
+       u_int32_t reqid;
+       int error;
+
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
 
        /* sanity check */
-       if (mhp == NULL || mhp[0] == NULL)
+       if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
                panic("key_update: NULL pointer is passed.\n");
 
-       msg0 = (struct sadb_msg *)mhp[0];
-
        /* map satype to proto */
-       if ((proto = key_satype2proto(msg0->sadb_msg_satype)) == 0) {
-#if IPSEC_DEBUG
-               printf("key_update: invalid satype is passed.\n");
-#endif
-               msg0->sadb_msg_errno = EINVAL;
-               return NULL;
-       }
-
-       if (mhp[SADB_EXT_SA] == NULL
-        || mhp[SADB_EXT_ADDRESS_SRC] == NULL
-        || mhp[SADB_EXT_ADDRESS_DST] == NULL
-        || (msg0->sadb_msg_satype == SADB_SATYPE_ESP
-         && mhp[SADB_EXT_KEY_ENCRYPT] == NULL)
-        || (msg0->sadb_msg_satype == SADB_SATYPE_AH
-         && mhp[SADB_EXT_KEY_AUTH] == NULL)
-        || (mhp[SADB_EXT_LIFETIME_HARD] != NULL
-         && mhp[SADB_EXT_LIFETIME_SOFT] == NULL)
-        || (mhp[SADB_EXT_LIFETIME_HARD] == NULL
-         && mhp[SADB_EXT_LIFETIME_SOFT] != NULL)) {
-#if IPSEC_DEBUG
-               printf("key_update: invalid message is passed.\n");
-#endif
-               msg0->sadb_msg_errno = EINVAL;
-               return NULL;
+       if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
+               ipseclog((LOG_DEBUG, "key_update: invalid satype is passed.\n"));
+               return key_senderror(so, m, EINVAL);
+       }
+
+       if (mhp->ext[SADB_EXT_SA] == NULL ||
+           mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
+           mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
+           (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
+            mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
+           (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
+            mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
+           (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
+            mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
+           (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
+            mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
+               ipseclog((LOG_DEBUG, "key_update: invalid message is passed.\n"));
+               return key_senderror(so, m, EINVAL);
+       }
+       if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
+           mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
+           mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
+               ipseclog((LOG_DEBUG, "key_update: invalid message is passed.\n"));
+               return key_senderror(so, m, EINVAL);
+       }
+       if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
+               mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
+               reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
+       } else {
+               mode = IPSEC_MODE_ANY;
+               reqid = 0;
        }
+       /* XXX boundary checking for other extensions */
 
-       sa0 = (struct sadb_sa *)mhp[SADB_EXT_SA];
-       src0 = (struct sadb_address *)(mhp[SADB_EXT_ADDRESS_SRC]);
-       dst0 = (struct sadb_address *)(mhp[SADB_EXT_ADDRESS_DST]);
+       sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
+       src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
+       dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
 
-       KEY_SETSECASIDX(proto, msg0, src0+1, dst0+1, &saidx);
+       /* XXX boundary check against sa_len */
+       KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
 
        /* get a SA header */
        if ((sah = key_getsah(&saidx)) == NULL) {
-#if IPSEC_DEBUG
-               printf("key_update: no SA index found.\n");
-#endif
-               msg0->sadb_msg_errno = ENOENT;
-               return NULL;
+               ipseclog((LOG_DEBUG, "key_update: no SA index found.\n"));
+               return key_senderror(so, m, ENOENT);
        }
 
        /* set spidx if there */
-       if (key_setident(sah, mhp) < 0)
-               return NULL;
+       /* XXX rewrite */
+       error = key_setident(sah, m, mhp);
+       if (error)
+               return key_senderror(so, m, error);
 
        /* find a SA with sequence number. */
 #if IPSEC_DOSEQCHECK
-       if (msg0->sadb_msg_seq != 0
-        && (sav = key_getsavbyseq(sah, msg0->sadb_msg_seq)) == NULL) {
-#if IPSEC_DEBUG
-               printf("key_update: no larval SA with sequence %u exists.\n",
-                       msg0->sadb_msg_seq);
-#endif
-               msg0->sadb_msg_errno = ENOENT;
-               return NULL;
+       if (mhp->msg->sadb_msg_seq != 0
+        && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
+               ipseclog((LOG_DEBUG,
+                   "key_update: no larval SA with sequence %u exists.\n",
+                   mhp->msg->sadb_msg_seq));
+               return key_senderror(so, m, ENOENT);
        }
 #else
        if ((sav = key_getsavbyspi(sah, sa0->sadb_sa_spi)) == NULL) {
-#if IPSEC_DEBUG
-               printf("key_update: no such a SA found (spi:%u)\n",
-                       (u_int32_t)ntohl(sa0->sadb_sa_spi));
-#endif
-               msg0->sadb_msg_errno = EINVAL;
-               return NULL;
+               ipseclog((LOG_DEBUG,
+                   "key_update: no such a SA found (spi:%u)\n",
+                   (u_int32_t)ntohl(sa0->sadb_sa_spi)));
+               return key_senderror(so, m, EINVAL);
        }
 #endif
 
        /* validity check */
        if (sav->sah->saidx.proto != proto) {
-#if IPSEC_DEBUG
-               printf("key_update: protocol mismatched (DB=%u param=%u)\n",
-                       sav->sah->saidx.proto, proto);
-#endif
-               msg0->sadb_msg_errno = EINVAL;
-               return NULL;
+               ipseclog((LOG_DEBUG,
+                   "key_update: protocol mismatched (DB=%u param=%u)\n",
+                   sav->sah->saidx.proto, proto));
+               return key_senderror(so, m, EINVAL);
        }
 #if IPSEC_DOSEQCHECK
        if (sav->spi != sa0->sadb_sa_spi) {
-#if IPSEC_DEBUG
-               printf("key_update: SPI mismatched (DB:%u param:%u)\n",
-                       (u_int32_t)ntohl(sav->spi),
-                       (u_int32_t)ntohl(sa0->sadb_sa_spi));
-#endif
-               msg0->sadb_msg_errno = EINVAL;
-               return NULL;
+               ipseclog((LOG_DEBUG,
+                   "key_update: SPI mismatched (DB:%u param:%u)\n",
+                   (u_int32_t)ntohl(sav->spi),
+                   (u_int32_t)ntohl(sa0->sadb_sa_spi)));
+               return key_senderror(so, m, EINVAL);
        }
 #endif
-       if (sav->pid != msg0->sadb_msg_pid) {
-#if IPSEC_DEBUG
-               printf("key_update: pid mismatched (DB:%u param:%u)\n",
-                       sav->pid, msg0->sadb_msg_pid);
-#endif
-               msg0->sadb_msg_errno = EINVAL;
-               return NULL;
+       if (sav->pid != mhp->msg->sadb_msg_pid) {
+               ipseclog((LOG_DEBUG,
+                   "key_update: pid mismatched (DB:%u param:%u)\n",
+                   sav->pid, mhp->msg->sadb_msg_pid));
+               return key_senderror(so, m, EINVAL);
        }
 
        /* copy sav values */
-       if (key_setsaval(sav, mhp)) {
+       error = key_setsaval(sav, m, mhp);
+       if (error) {
                key_freesav(sav);
-               return NULL;
+               return key_senderror(so, m, error);
        }
 
        /* check SA values to be mature. */
-       if ((msg0->sadb_msg_errno = key_mature(sav)) != 0) {
+       if ((error = key_mature(sav)) != 0) {
                key_freesav(sav);
-               return NULL;
+               return key_senderror(so, m, error);
        }
 
     {
-       struct sadb_msg *newmsg;
+       struct mbuf *n;
 
        /* set msg buf from mhp */
-       if ((newmsg = key_getmsgbuf_x1(mhp)) == NULL) {
-#if IPSEC_DEBUG
-               printf("key_update: No more memory.\n");
-#endif
-               msg0->sadb_msg_errno = ENOBUFS;
-               return NULL;
+       n = key_getmsgbuf_x1(m, mhp);
+       if (n == NULL) {
+               ipseclog((LOG_DEBUG, "key_update: No more memory.\n"));
+               return key_senderror(so, m, ENOBUFS);
        }
-       return newmsg;
+
+       m_freem(m);
+       return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
     }
 }
 
@@ -4523,6 +5175,8 @@ key_getsavbyseq(sah, seq)
        struct secasvar *sav;
        u_int state;
 
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        state = SADB_SASTATE_LARVAL;
 
        /* search SAD with sequence number ? */
@@ -4547,104 +5201,113 @@ key_getsavbyseq(sah, seq)
 /*
  * SADB_ADD processing
  * add a entry to SA database, when received
- *   <base, SA, (lifetime(HSC),) address(SD), (address(P),)
+ *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
  *       key(AE), (identity(SD),) (sensitivity)>
  * from the ikmpd,
  * and send
- *   <base, SA, (lifetime(HSC),) address(SD), (address(P),)
+ *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
  *       (identity(SD),) (sensitivity)>
  * to the ikmpd.
  *
  * IGNORE identity and sensitivity messages.
  *
- * IN: mhp: pointer to the pointer to each header.
- * OUT:        NULL if fail.
- *     other if success, return pointer to the message to send.
+ * m will always be freed.
  */
-static struct sadb_msg *
-key_add(mhp)
-       caddr_t *mhp;
+static int
+key_add(so, m, mhp)
+       struct socket *so;
+       struct mbuf *m;
+       const struct sadb_msghdr *mhp;
 {
-       struct sadb_msg *msg0;
        struct sadb_sa *sa0;
        struct sadb_address *src0, *dst0;
        struct secasindex saidx;
        struct secashead *newsah;
        struct secasvar *newsav;
        u_int16_t proto;
+       u_int8_t mode;
+       u_int32_t reqid;
+       int error;
+
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
 
        /* sanity check */
-       if (mhp == NULL || mhp[0] == NULL)
+       if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
                panic("key_add: NULL pointer is passed.\n");
 
-       msg0 = (struct sadb_msg *)mhp[0];
-
        /* map satype to proto */
-       if ((proto = key_satype2proto(msg0->sadb_msg_satype)) == 0) {
-#if IPSEC_DEBUG
-               printf("key_add: invalid satype is passed.\n");
-#endif
-               msg0->sadb_msg_errno = EINVAL;
-               return NULL;
-       }
-
-       if (mhp[SADB_EXT_SA] == NULL
-        || mhp[SADB_EXT_ADDRESS_SRC] == NULL
-        || mhp[SADB_EXT_ADDRESS_DST] == NULL
-        || (msg0->sadb_msg_satype == SADB_SATYPE_ESP
-         && mhp[SADB_EXT_KEY_ENCRYPT] == NULL)
-        || (msg0->sadb_msg_satype == SADB_SATYPE_AH
-         && mhp[SADB_EXT_KEY_AUTH] == NULL)
-        || (mhp[SADB_EXT_LIFETIME_HARD] != NULL
-         && mhp[SADB_EXT_LIFETIME_SOFT] == NULL)
-        || (mhp[SADB_EXT_LIFETIME_HARD] == NULL
-         && mhp[SADB_EXT_LIFETIME_SOFT] != NULL)) {
-#if IPSEC_DEBUG
-               printf("key_add: invalid message is passed.\n");
-#endif
-               msg0->sadb_msg_errno = EINVAL;
-               return NULL;
+       if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
+               ipseclog((LOG_DEBUG, "key_add: invalid satype is passed.\n"));
+               return key_senderror(so, m, EINVAL);
+       }
+
+       if (mhp->ext[SADB_EXT_SA] == NULL ||
+           mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
+           mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
+           (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
+            mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
+           (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
+            mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
+           (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
+            mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
+           (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
+            mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
+               ipseclog((LOG_DEBUG, "key_add: invalid message is passed.\n"));
+               return key_senderror(so, m, EINVAL);
+       }
+       if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
+           mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
+           mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
+               /* XXX need more */
+               ipseclog((LOG_DEBUG, "key_add: invalid message is passed.\n"));
+               return key_senderror(so, m, EINVAL);
+       }
+       if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
+               mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
+               reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
+       } else {
+               mode = IPSEC_MODE_ANY;
+               reqid = 0;
        }
 
-       sa0 = (struct sadb_sa *)mhp[SADB_EXT_SA];
-       src0 = (struct sadb_address *)(mhp[SADB_EXT_ADDRESS_SRC]);
-       dst0 = (struct sadb_address *)(mhp[SADB_EXT_ADDRESS_DST]);
+       sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
+       src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
+       dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
 
-       KEY_SETSECASIDX(proto, msg0, src0+1, dst0+1, &saidx);
+       /* XXX boundary check against sa_len */
+       KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
 
        /* get a SA header */
        if ((newsah = key_getsah(&saidx)) == NULL) {
-
                /* create a new SA header */
                if ((newsah = key_newsah(&saidx)) == NULL) {
-#if IPSEC_DEBUG
-                       printf("key_add: No more memory.\n");
-#endif
-                       msg0->sadb_msg_errno = ENOBUFS;
-                       return NULL;
+                       ipseclog((LOG_DEBUG, "key_add: No more memory.\n"));
+                       return key_senderror(so, m, ENOBUFS);
                }
        }
 
        /* set spidx if there */
-       if (key_setident(newsah, mhp) < 0)
-               return NULL;
+       /* XXX rewrite */
+       error = key_setident(newsah, m, mhp);
+       if (error) {
+               return key_senderror(so, m, error);
+       }
 
        /* create new SA entry. */
        /* We can create new SA only if SPI is differenct. */
        if (key_getsavbyspi(newsah, sa0->sadb_sa_spi)) {
-#if IPSEC_DEBUG
-               printf("key_add: SA already exists.\n");
-#endif
-               msg0->sadb_msg_errno = EEXIST;
-               return NULL;
+               ipseclog((LOG_DEBUG, "key_add: SA already exists.\n"));
+               return key_senderror(so, m, EEXIST);
+       }
+       newsav = key_newsav(m, mhp, newsah, &error);
+       if (newsav == NULL) {
+               return key_senderror(so, m, error);
        }
-       if ((newsav = key_newsav(mhp, newsah)) == NULL)
-               return NULL;
 
        /* check SA values to be mature. */
-       if ((msg0->sadb_msg_errno = key_mature(newsav)) != NULL) {
+       if ((error = key_mature(newsav)) != 0) {
                key_freesav(newsav);
-               return NULL;
+               return key_senderror(so, m, error);
        }
 
        /*
@@ -4653,100 +5316,62 @@ key_add(mhp)
         */
 
     {
-       struct sadb_msg *newmsg;
+       struct mbuf *n;
 
        /* set msg buf from mhp */
-       if ((newmsg = key_getmsgbuf_x1(mhp)) == NULL) {
-#if IPSEC_DEBUG
-               printf("key_add: No more memory.\n");
-#endif
-               msg0->sadb_msg_errno = ENOBUFS;
-               return NULL;
+       n = key_getmsgbuf_x1(m, mhp);
+       if (n == NULL) {
+               ipseclog((LOG_DEBUG, "key_update: No more memory.\n"));
+               return key_senderror(so, m, ENOBUFS);
        }
 
-       return newmsg;
+       m_freem(m);
+       return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
     }
 }
 
+/* m is retained */
 static int
-key_setident(sah, mhp)
+key_setident(sah, m, mhp)
        struct secashead *sah;
-       caddr_t *mhp;
+       struct mbuf *m;
+       const struct sadb_msghdr *mhp;
 {
-       struct sadb_msg *msg0;
-       struct sadb_ident *idsrc, *iddst;
+       const struct sadb_ident *idsrc, *iddst;
        int idsrclen, iddstlen;
 
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        /* sanity check */
-       if (sah == NULL || mhp == NULL || mhp[0] == NULL)
+       if (sah == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
                panic("key_setident: NULL pointer is passed.\n");
 
-       msg0 = (struct sadb_msg *)mhp[0];
-
        /* don't make buffer if not there */
-       if (mhp[SADB_EXT_IDENTITY_SRC] == NULL
-        && mhp[SADB_EXT_IDENTITY_DST] == NULL) {
+       if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
+           mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
                sah->idents = NULL;
                sah->identd = NULL;
                return 0;
        }
        
-       if (mhp[SADB_EXT_IDENTITY_SRC] == NULL
-        || mhp[SADB_EXT_IDENTITY_DST] == NULL) {
-#if IPSEC_DEBUG
-               printf("key_setident: invalid identity.\n");
-#endif
-               msg0->sadb_msg_errno = EINVAL;
-               return -1;
+       if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
+           mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
+               ipseclog((LOG_DEBUG, "key_setident: invalid identity.\n"));
+               return EINVAL;
        }
 
-       idsrc = (struct sadb_ident *)mhp[SADB_EXT_IDENTITY_SRC];
-       iddst = (struct sadb_ident *)mhp[SADB_EXT_IDENTITY_DST];
-       idsrclen = PFKEY_UNUNIT64(idsrc->sadb_ident_len);
-       iddstlen = PFKEY_UNUNIT64(idsrc->sadb_ident_len);
+       idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
+       iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
+       idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
+       iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
 
        /* validity check */
        if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
-#if IPSEC_DEBUG
-               printf("key_setident: ident type mismatch.\n");
-#endif
-               msg0->sadb_msg_errno = EINVAL;
-               return -1;
+               ipseclog((LOG_DEBUG, "key_setident: ident type mismatch.\n"));
+               return EINVAL;
        }
 
        switch (idsrc->sadb_ident_type) {
-       case SADB_X_IDENTTYPE_ADDR:
-               if (idsrclen !=
-                   sizeof(*idsrc) + ((struct sockaddr *)(idsrc + 1))->sa_len
-                || iddstlen !=
-                   sizeof(*iddst) + ((struct sockaddr *)(iddst + 1))->sa_len) {
-#if IPSEC_DEBUG
-                       printf("key_setident: invalid length is passed.\n");
-#endif
-                       msg0->sadb_msg_errno = EINVAL;
-                       return -1;
-               }
-               if (((struct sockaddr *)(idsrc + 1))->sa_len >
-                               sizeof(struct sockaddr_storage)
-                || ((struct sockaddr *)(iddst + 1))->sa_len >
-                               sizeof(struct sockaddr_storage)) {
-#if IPSEC_DEBUG
-                       printf("key_setident: invalid sa_len is passed.\n");
-#endif
-                       msg0->sadb_msg_errno = EINVAL;
-                       return -1;
-               }
-#define __IDENTXID(a) ((union sadb_x_ident_id *)&(a)->sadb_ident_id)
-               if (__IDENTXID(idsrc)->sadb_x_ident_id_addr.ul_proto
-                != __IDENTXID(iddst)->sadb_x_ident_id_addr.ul_proto) {
-#if IPSEC_DEBUG
-                       printf("key_setident: ul_proto mismatch.\n");
-#endif
-                       msg0->sadb_msg_errno = EINVAL;
-                       return -1;
-               }
-#undef __IDENTXID(a)
-               break;
        case SADB_IDENTTYPE_PREFIX:
        case SADB_IDENTTYPE_FQDN:
        case SADB_IDENTTYPE_USERFQDN:
@@ -4760,20 +5385,15 @@ key_setident(sah, mhp)
        /* make structure */
        KMALLOC(sah->idents, struct sadb_ident *, idsrclen);
        if (sah->idents == NULL) {
-#if IPSEC_DEBUG
-               printf("key_setident: No more memory.\n");
-#endif
-               msg0->sadb_msg_errno = ENOBUFS;
-               return -1;
+               ipseclog((LOG_DEBUG, "key_setident: No more memory.\n"));
+               return ENOBUFS;
        }
        KMALLOC(sah->identd, struct sadb_ident *, iddstlen);
        if (sah->identd == NULL) {
                KFREE(sah->idents);
-#if IPSEC_DEBUG
-               printf("key_setident: No more memory.\n");
-#endif
-               msg0->sadb_msg_errno = ENOBUFS;
-               return -1;
+               sah->idents = NULL;
+               ipseclog((LOG_DEBUG, "key_setident: No more memory.\n"));
+               return ENOBUFS;
        }
        bcopy(idsrc, sah->idents, idsrclen);
        bcopy(iddst, sah->identd, iddstlen);
@@ -4781,63 +5401,46 @@ key_setident(sah, mhp)
        return 0;
 }
 
-static struct sadb_msg *
-key_getmsgbuf_x1(mhp)
-       caddr_t *mhp;
+/*
+ * m will not be freed on return.
+ * it is caller's responsibility to free the result. 
+ */
+static struct mbuf *
+key_getmsgbuf_x1(m, mhp)
+       struct mbuf *m;
+       const struct sadb_msghdr *mhp;
 {
-       struct sadb_msg *msg0;
-       struct sadb_msg *newmsg;
-       u_int len;
-       caddr_t p;
+       struct mbuf *n;
+       int mbufItems[] = {SADB_EXT_RESERVED, SADB_EXT_SA,
+                                       SADB_X_EXT_SA2, SADB_EXT_ADDRESS_SRC,
+                                       SADB_EXT_ADDRESS_DST, SADB_EXT_LIFETIME_HARD,
+                                       SADB_EXT_LIFETIME_SOFT, SADB_EXT_IDENTITY_SRC,
+                                       SADB_EXT_IDENTITY_DST};
 
        /* sanity check */
-       if (mhp == NULL || mhp[0] == NULL)
+       if (m == NULL || mhp == NULL || mhp->msg == NULL)
                panic("key_getmsgbuf_x1: NULL pointer is passed.\n");
 
-       msg0 = (struct sadb_msg *)mhp[0];
-
        /* create new sadb_msg to reply. */
-       len = sizeof(struct sadb_msg)
-           + sizeof(struct sadb_sa)
-           + PFKEY_EXTLEN(mhp[SADB_EXT_ADDRESS_SRC])
-           + PFKEY_EXTLEN(mhp[SADB_EXT_ADDRESS_DST])
-           + (mhp[SADB_EXT_LIFETIME_HARD] == NULL
-               ? 0 : sizeof(struct sadb_lifetime))
-           + (mhp[SADB_EXT_LIFETIME_SOFT] == NULL
-               ? 0 : sizeof(struct sadb_lifetime))
-           + (mhp[SADB_EXT_IDENTITY_SRC] == NULL
-               ? 0 : PFKEY_EXTLEN(mhp[SADB_EXT_IDENTITY_SRC]))
-           + (mhp[SADB_EXT_IDENTITY_DST] == NULL
-               ? 0 : PFKEY_EXTLEN(mhp[SADB_EXT_IDENTITY_DST]));
-
-       KMALLOC(newmsg, struct sadb_msg *, len);
-       if (newmsg == NULL)
+       n = key_gather_mbuf(m, mhp, 1, sizeof(mbufItems)/sizeof(int), mbufItems);
+       if (!n)
                return NULL;
-       bzero((caddr_t)newmsg, len);
 
-       bcopy((caddr_t)mhp[0], (caddr_t)newmsg, sizeof(*msg0));
-       newmsg->sadb_msg_errno = 0;
-       newmsg->sadb_msg_len = PFKEY_UNIT64(len);
-       p = (caddr_t)newmsg + sizeof(*msg0);
-
-       p = key_setsadbext(p, mhp[SADB_EXT_SA]);
-       p = key_setsadbext(p, mhp[SADB_EXT_ADDRESS_SRC]);
-       p = key_setsadbext(p, mhp[SADB_EXT_ADDRESS_DST]);
-
-       if (mhp[SADB_EXT_LIFETIME_HARD] != NULL)
-               p = key_setsadbext(p, mhp[SADB_EXT_LIFETIME_HARD]);
-
-       if (mhp[SADB_EXT_LIFETIME_SOFT] != NULL)
-               p = key_setsadbext(p, mhp[SADB_EXT_LIFETIME_SOFT]);
-
-       if (mhp[SADB_EXT_IDENTITY_SRC] != NULL)
-               p = key_setsadbext(p, mhp[SADB_EXT_IDENTITY_SRC]);
-       if (mhp[SADB_EXT_IDENTITY_DST] != NULL)
-               p = key_setsadbext(p, mhp[SADB_EXT_IDENTITY_DST]);
+       if (n->m_len < sizeof(struct sadb_msg)) {
+               n = m_pullup(n, sizeof(struct sadb_msg));
+               if (n == NULL)
+                       return NULL;
+       }
+       mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
+       mtod(n, struct sadb_msg *)->sadb_msg_len =
+           PFKEY_UNIT64(n->m_pkthdr.len);
 
-       return newmsg;
+       return n;
 }
 
+static int key_delete_all(struct socket *, struct mbuf *,
+       const struct sadb_msghdr *, u_int16_t);
+
 /*
  * SADB_DELETE processing
  * receive
@@ -4847,69 +5450,80 @@ key_getmsgbuf_x1(mhp)
  *   <base, SA(*), address(SD)>
  * to the ikmpd.
  *
- * IN: mhp: pointer to the pointer to each header.
- * OUT:        NULL if fail.
- *     other if success, return pointer to the message to send.
+ * m will always be freed.
  */
-static struct sadb_msg *
-key_delete(mhp)
-       caddr_t *mhp;
+static int
+key_delete(so, m, mhp)
+       struct socket *so;
+       struct mbuf *m;
+       const struct sadb_msghdr *mhp;
 {
-       struct sadb_msg *msg0;
        struct sadb_sa *sa0;
        struct sadb_address *src0, *dst0;
        struct secasindex saidx;
        struct secashead *sah;
-       struct secasvar *sav;
+       struct secasvar *sav = NULL;
        u_int16_t proto;
 
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        /* sanity check */
-       if (mhp == NULL || mhp[0] == NULL)
+       if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
                panic("key_delete: NULL pointer is passed.\n");
 
-       msg0 = (struct sadb_msg *)mhp[0];
-
        /* map satype to proto */
-       if ((proto = key_satype2proto(msg0->sadb_msg_satype)) == 0) {
-#if IPSEC_DEBUG
-               printf("key_delete: invalid satype is passed.\n");
-#endif
-               msg0->sadb_msg_errno = EINVAL;
-               return NULL;
+       if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
+               ipseclog((LOG_DEBUG, "key_delete: invalid satype is passed.\n"));
+               return key_senderror(so, m, EINVAL);
        }
 
-       if (mhp[SADB_EXT_SA] == NULL
-        || mhp[SADB_EXT_ADDRESS_SRC] == NULL
-        || mhp[SADB_EXT_ADDRESS_DST] == NULL) {
-#if IPSEC_DEBUG
-               printf("key_delete: invalid message is passed.\n");
-#endif
-               msg0->sadb_msg_errno = EINVAL;
-               return NULL;
+       if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
+           mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
+               ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
+               return key_senderror(so, m, EINVAL);
        }
-       sa0 = (struct sadb_sa *)mhp[SADB_EXT_SA];
-       src0 = (struct sadb_address *)(mhp[SADB_EXT_ADDRESS_SRC]);
-       dst0 = (struct sadb_address *)(mhp[SADB_EXT_ADDRESS_DST]);
 
-       KEY_SETSECASIDX(proto, msg0, src0+1, dst0+1, &saidx);
+       if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
+           mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
+               ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
+               return key_senderror(so, m, EINVAL);
+       }
 
-       /* get a SA header */
-       if ((sah = key_getsah(&saidx)) == NULL) {
-#if IPSEC_DEBUG
-               printf("key_delete: no SA found.\n");
-#endif
-               msg0->sadb_msg_errno = ENOENT;
-               return NULL;
+       if (mhp->ext[SADB_EXT_SA] == NULL) {
+               /*
+                * Caller wants us to delete all non-LARVAL SAs
+                * that match the src/dst.  This is used during
+                * IKE INITIAL-CONTACT.
+                */
+               ipseclog((LOG_DEBUG, "key_delete: doing delete all.\n"));
+               return key_delete_all(so, m, mhp, proto);
+       } else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
+               ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
+               return key_senderror(so, m, EINVAL);
        }
 
-       /* get a SA with SPI. */
-       sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
-       if (sav == NULL) {
-#if IPSEC_DEBUG
-               printf("key_delete: no alive SA found.\n");
-#endif
-               msg0->sadb_msg_errno = ENOENT;
-               return NULL;
+       sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
+       src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
+       dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
+
+       /* XXX boundary check against sa_len */
+       KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
+
+       /* get a SA header */
+       LIST_FOREACH(sah, &sahtree, chain) {
+               if (sah->state == SADB_SASTATE_DEAD)
+                       continue;
+               if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
+                       continue;
+
+               /* get a SA with SPI. */
+               sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
+               if (sav)
+                       break;
+       }
+       if (sah == NULL) {
+               ipseclog((LOG_DEBUG, "key_delete: no SA found.\n"));
+               return key_senderror(so, m, ENOENT);
        }
 
        key_sa_chgstate(sav, SADB_SASTATE_DEAD);
@@ -4917,36 +5531,106 @@ key_delete(mhp)
        sav = NULL;
 
     {
+       struct mbuf *n;
        struct sadb_msg *newmsg;
-       u_int len;
-       caddr_t p;
+       int mbufItems[] = {SADB_EXT_RESERVED, SADB_EXT_SA,
+                                               SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST};
 
        /* create new sadb_msg to reply. */
-       len = sizeof(struct sadb_msg)
-           + sizeof(struct sadb_sa)
-           + PFKEY_EXTLEN(mhp[SADB_EXT_ADDRESS_SRC])
-           + PFKEY_EXTLEN(mhp[SADB_EXT_ADDRESS_DST]);
-
-       KMALLOC(newmsg, struct sadb_msg *, len);
-       if (newmsg == NULL) {
-#if IPSEC_DEBUG
-               printf("key_delete: No more memory.\n");
-#endif
-               msg0->sadb_msg_errno = ENOBUFS;
-               return NULL;
-       }
-       bzero((caddr_t)newmsg, len);
+       n = key_gather_mbuf(m, mhp, 1, sizeof(mbufItems)/sizeof(int), mbufItems);
+       if (!n)
+               return key_senderror(so, m, ENOBUFS);
 
-       bcopy((caddr_t)mhp[0], (caddr_t)newmsg, sizeof(*msg0));
+       if (n->m_len < sizeof(struct sadb_msg)) {
+               n = m_pullup(n, sizeof(struct sadb_msg));
+               if (n == NULL)
+                       return key_senderror(so, m, ENOBUFS);
+       }
+       newmsg = mtod(n, struct sadb_msg *);
        newmsg->sadb_msg_errno = 0;
-       newmsg->sadb_msg_len = PFKEY_UNIT64(len);
-       p = (caddr_t)newmsg + sizeof(*msg0);
+       newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
 
-       p = key_setsadbext(p, mhp[SADB_EXT_SA]);
-       p = key_setsadbext(p, mhp[SADB_EXT_ADDRESS_SRC]);
-       p = key_setsadbext(p, mhp[SADB_EXT_ADDRESS_DST]);
+       m_freem(m);
+       return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
+    }
+}
+
+/*
+ * delete all SAs for src/dst.  Called from key_delete().
+ */
+static int
+key_delete_all(so, m, mhp, proto)
+       struct socket *so;
+       struct mbuf *m;
+       const struct sadb_msghdr *mhp;
+       u_int16_t proto;
+{
+       struct sadb_address *src0, *dst0;
+       struct secasindex saidx;
+       struct secashead *sah;
+       struct secasvar *sav, *nextsav;
+       u_int stateidx, state;
+
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
+       src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
+       dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
+
+       /* XXX boundary check against sa_len */
+       KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
 
-       return newmsg;
+       LIST_FOREACH(sah, &sahtree, chain) {
+               if (sah->state == SADB_SASTATE_DEAD)
+                       continue;
+               if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
+                       continue;
+
+               /* Delete all non-LARVAL SAs. */
+               for (stateidx = 0;
+                    stateidx < _ARRAYLEN(saorder_state_alive);
+                    stateidx++) {
+                       state = saorder_state_alive[stateidx];
+                       if (state == SADB_SASTATE_LARVAL)
+                               continue;
+                       for (sav = LIST_FIRST(&sah->savtree[state]);
+                            sav != NULL; sav = nextsav) {
+                               nextsav = LIST_NEXT(sav, chain);
+                               /* sanity check */
+                               if (sav->state != state) {
+                                       ipseclog((LOG_DEBUG, "key_delete_all: "
+                                              "invalid sav->state "
+                                              "(queue: %d SA: %d)\n",
+                                              state, sav->state));
+                                       continue;
+                               }
+                               
+                               key_sa_chgstate(sav, SADB_SASTATE_DEAD);
+                               key_freesav(sav);
+                       }
+               }
+       }
+    {
+       struct mbuf *n;
+       struct sadb_msg *newmsg;
+       int mbufItems[] = {SADB_EXT_RESERVED, SADB_EXT_ADDRESS_SRC,
+                                               SADB_EXT_ADDRESS_DST};
+
+       /* create new sadb_msg to reply. */
+       n = key_gather_mbuf(m, mhp, 1, sizeof(mbufItems)/sizeof(int), mbufItems);
+       if (!n)
+               return key_senderror(so, m, ENOBUFS);
+
+       if (n->m_len < sizeof(struct sadb_msg)) {
+               n = m_pullup(n, sizeof(struct sadb_msg));
+               if (n == NULL)
+                       return key_senderror(so, m, ENOBUFS);
+       }
+       newmsg = mtod(n, struct sadb_msg *);
+       newmsg->sadb_msg_errno = 0;
+       newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
+
+       m_freem(m);
+       return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
     }
 }
 
@@ -4960,117 +5644,358 @@ key_delete(mhp)
  *       (identity(SD),) (sensitivity)>
  * to the ikmpd.
  *
- * IN: mhp: pointer to the pointer to each header.
- * OUT:        NULL if fail.
- *     other if success, return pointer to the message to send.
+ * m will always be freed.
  */
-static struct sadb_msg *
-key_get(mhp)
-       caddr_t *mhp;
+static int
+key_get(so, m, mhp)
+       struct socket *so;
+       struct mbuf *m;
+       const struct sadb_msghdr *mhp;
 {
-       struct sadb_msg *msg0;
        struct sadb_sa *sa0;
        struct sadb_address *src0, *dst0;
        struct secasindex saidx;
        struct secashead *sah;
-       struct secasvar *sav;
+       struct secasvar *sav = NULL;
        u_int16_t proto;
 
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        /* sanity check */
-       if (mhp == NULL || mhp[0] == NULL)
+       if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
                panic("key_get: NULL pointer is passed.\n");
 
-       msg0 = (struct sadb_msg *)mhp[0];
-
        /* map satype to proto */
-       if ((proto = key_satype2proto(msg0->sadb_msg_satype)) == 0) {
-#if IPSEC_DEBUG
-               printf("key_get: invalid satype is passed.\n");
-#endif
-               msg0->sadb_msg_errno = EINVAL;
-               return NULL;
+       if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
+               ipseclog((LOG_DEBUG, "key_get: invalid satype is passed.\n"));
+               return key_senderror(so, m, EINVAL);
        }
 
-       if (mhp[SADB_EXT_SA] == NULL
-        || mhp[SADB_EXT_ADDRESS_SRC] == NULL
-        || mhp[SADB_EXT_ADDRESS_DST] == NULL) {
-#if IPSEC_DEBUG
-               printf("key_get: invalid message is passed.\n");
-#endif
-               msg0->sadb_msg_errno = EINVAL;
-               return NULL;
+       if (mhp->ext[SADB_EXT_SA] == NULL ||
+           mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
+           mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
+               ipseclog((LOG_DEBUG, "key_get: invalid message is passed.\n"));
+               return key_senderror(so, m, EINVAL);
+       }
+       if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
+           mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
+           mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
+               ipseclog((LOG_DEBUG, "key_get: invalid message is passed.\n"));
+               return key_senderror(so, m, EINVAL);
        }
-       sa0 = (struct sadb_sa *)mhp[SADB_EXT_SA];
-       src0 = (struct sadb_address *)(mhp[SADB_EXT_ADDRESS_SRC]);
-       dst0 = (struct sadb_address *)(mhp[SADB_EXT_ADDRESS_DST]);
 
-       KEY_SETSECASIDX(proto, msg0, src0+1, dst0+1, &saidx);
+       sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
+       src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
+       dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
+
+       /* XXX boundary check against sa_len */
+       KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
 
        /* get a SA header */
-       if ((sah = key_getsah(&saidx)) == NULL) {
-#if IPSEC_DEBUG
-               printf("key_get: no SA found.\n");
-#endif
-               msg0->sadb_msg_errno = ENOENT;
-               return NULL;
-       }
+       LIST_FOREACH(sah, &sahtree, chain) {
+               if (sah->state == SADB_SASTATE_DEAD)
+                       continue;
+               if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
+                       continue;
 
-       /* get a SA with SPI. */
-       sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
-       if (sav == NULL) {
-#if IPSEC_DEBUG
-               printf("key_get: no SA with state of mature found.\n");
-#endif
-               msg0->sadb_msg_errno = ENOENT;
-               return NULL;
+               /* get a SA with SPI. */
+               sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
+               if (sav)
+                       break;
+       }
+       if (sah == NULL) {
+               ipseclog((LOG_DEBUG, "key_get: no SA found.\n"));
+               return key_senderror(so, m, ENOENT);
        }
 
     {
-       struct sadb_msg *newmsg;
-       u_int len;
+       struct mbuf *n;
        u_int8_t satype;
 
        /* map proto to satype */
        if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
-#if IPSEC_DEBUG
-               printf("key_get: there was invalid proto in SAD.\n");
+               ipseclog((LOG_DEBUG, "key_get: there was invalid proto in SAD.\n"));
+               return key_senderror(so, m, EINVAL);
+       }
+
+       /* create new sadb_msg to reply. */
+       n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
+           mhp->msg->sadb_msg_pid);
+       if (!n)
+               return key_senderror(so, m, ENOBUFS);
+
+       m_freem(m);
+       return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
+    }
+}
+
+/* XXX make it sysctl-configurable? */
+static void
+key_getcomb_setlifetime(comb)
+       struct sadb_comb *comb;
+{
+
+       comb->sadb_comb_soft_allocations = 1;
+       comb->sadb_comb_hard_allocations = 1;
+       comb->sadb_comb_soft_bytes = 0;
+       comb->sadb_comb_hard_bytes = 0;
+       comb->sadb_comb_hard_addtime = 86400;   /* 1 day */
+       comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
+       comb->sadb_comb_soft_usetime = 28800;   /* 8 hours */
+       comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
+}
+
+#if IPSEC_ESP
+/*
+ * XXX reorder combinations by preference
+ * XXX no idea if the user wants ESP authentication or not
+ */
+static struct mbuf *
+key_getcomb_esp()
+{
+       struct sadb_comb *comb;
+       const struct esp_algorithm *algo;
+       struct mbuf *result = NULL, *m, *n;
+       int encmin;
+       int i, off, o;
+       int totlen;
+       const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
+
+       m = NULL;
+       for (i = 1; i <= SADB_EALG_MAX; i++) {
+               algo = esp_algorithm_lookup(i);
+               if (!algo)
+                       continue;
+
+               if (algo->keymax < ipsec_esp_keymin)
+                       continue;
+               if (algo->keymin < ipsec_esp_keymin)
+                       encmin = ipsec_esp_keymin;
+               else
+                       encmin = algo->keymin;
+
+               if (ipsec_esp_auth)
+                       m = key_getcomb_ah();
+               else {
+#if DIAGNOSTIC
+                       if (l > MLEN)
+                               panic("assumption failed in key_getcomb_esp");
+#endif
+                       MGET(m, M_DONTWAIT, MT_DATA);
+                       if (m) {
+                               M_ALIGN(m, l);
+                               m->m_len = l;
+                               m->m_next = NULL;
+                               bzero(mtod(m, caddr_t), m->m_len);
+                       }
+               }
+               if (!m)
+                       goto fail;
+
+               totlen = 0;
+               for (n = m; n; n = n->m_next)
+                       totlen += n->m_len;
+#if DIAGNOSTIC
+               if (totlen % l)
+                       panic("assumption failed in key_getcomb_esp");
+#endif
+
+               for (off = 0; off < totlen; off += l) {
+                       n = m_pulldown(m, off, l, &o);
+                       if (!n) {
+                               /* m is already freed */
+                               goto fail;
+                       }
+                       comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
+                       bzero(comb, sizeof(*comb));
+                       key_getcomb_setlifetime(comb);
+                       comb->sadb_comb_encrypt = i;
+                       comb->sadb_comb_encrypt_minbits = encmin;
+                       comb->sadb_comb_encrypt_maxbits = algo->keymax;
+               }
+
+               if (!result)
+                       result = m;
+               else
+                       m_cat(result, m);
+       }
+
+       return result;
+
+ fail:
+       if (result)
+               m_freem(result);
+       return NULL;
+}
 #endif
-               msg0->sadb_msg_errno = EINVAL;
-               return NULL;
+
+/*
+ * XXX reorder combinations by preference
+ */
+static struct mbuf *
+key_getcomb_ah()
+{
+       struct sadb_comb *comb;
+       const struct ah_algorithm *algo;
+       struct mbuf *m;
+       int min;
+       int i;
+       const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
+
+       m = NULL;
+       for (i = 1; i <= SADB_AALG_MAX; i++) {
+#if 1
+               /* we prefer HMAC algorithms, not old algorithms */
+               if (i != SADB_AALG_SHA1HMAC && i != SADB_AALG_MD5HMAC)
+                       continue;
+#endif
+               algo = ah_algorithm_lookup(i);
+               if (!algo)
+                       continue;
+
+               if (algo->keymax < ipsec_ah_keymin)
+                       continue;
+               if (algo->keymin < ipsec_ah_keymin)
+                       min = ipsec_ah_keymin;
+               else
+                       min = algo->keymin;
+
+               if (!m) {
+#if DIAGNOSTIC
+                       if (l > MLEN)
+                               panic("assumption failed in key_getcomb_ah");
+#endif
+                       MGET(m, M_DONTWAIT, MT_DATA);
+                       if (m) {
+                               M_ALIGN(m, l);
+                               m->m_len = l;
+                               m->m_next = NULL;
+                       }
+               } else
+                       M_PREPEND(m, l, M_DONTWAIT);
+               if (!m)
+                       return NULL;
+
+               comb = mtod(m, struct sadb_comb *);
+               bzero(comb, sizeof(*comb));
+               key_getcomb_setlifetime(comb);
+               comb->sadb_comb_auth = i;
+               comb->sadb_comb_auth_minbits = min;
+               comb->sadb_comb_auth_maxbits = algo->keymax;
        }
 
-       /* calculate a length of message buffer */
-       len = key_getmsglen(sav);
+       return m;
+}
 
-       KMALLOC(newmsg, struct sadb_msg *, len);
-       if (newmsg == NULL) {
-#if IPSEC_DEBUG
-               printf("key_get: No more memory.\n");
+/*
+ * not really an official behavior.  discussed in pf_key@inner.net in Sep2000.
+ * XXX reorder combinations by preference
+ */
+static struct mbuf *
+key_getcomb_ipcomp()
+{
+       struct sadb_comb *comb;
+       const struct ipcomp_algorithm *algo;
+       struct mbuf *m;
+       int i;
+       const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
+
+       m = NULL;
+       for (i = 1; i <= SADB_X_CALG_MAX; i++) {
+               algo = ipcomp_algorithm_lookup(i);
+               if (!algo)
+                       continue;
+
+               if (!m) {
+#if DIAGNOSTIC
+                       if (l > MLEN)
+                               panic("assumption failed in key_getcomb_ipcomp");
+#endif
+                       MGET(m, M_DONTWAIT, MT_DATA);
+                       if (m) {
+                               M_ALIGN(m, l);
+                               m->m_len = l;
+                               m->m_next = NULL;
+                       }
+               } else
+                       M_PREPEND(m, l, M_DONTWAIT);
+               if (!m)
+                       return NULL;
+
+               comb = mtod(m, struct sadb_comb *);
+               bzero(comb, sizeof(*comb));
+               key_getcomb_setlifetime(comb);
+               comb->sadb_comb_encrypt = i;
+               /* what should we set into sadb_comb_*_{min,max}bits? */
+       }
+
+       return m;
+}
+
+/*
+ * XXX no way to pass mode (transport/tunnel) to userland
+ * XXX replay checking?
+ * XXX sysctl interface to ipsec_{ah,esp}_keymin
+ */
+static struct mbuf *
+key_getprop(saidx)
+       const struct secasindex *saidx;
+{
+       struct sadb_prop *prop;
+       struct mbuf *m, *n;
+       const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
+       int totlen;
+
+       switch (saidx->proto)  {
+#if IPSEC_ESP
+       case IPPROTO_ESP:
+               m = key_getcomb_esp();
+               break;
 #endif
-               msg0->sadb_msg_errno = ENOBUFS;
+       case IPPROTO_AH:
+               m = key_getcomb_ah();
+               break;
+       case IPPROTO_IPCOMP:
+               m = key_getcomb_ipcomp();
+               break;
+       default:
                return NULL;
        }
 
-       /* create new sadb_msg to reply. */
-       (void)key_setdumpsa(newmsg, sav, SADB_GET,
-                           satype, msg0->sadb_msg_seq, msg0->sadb_msg_pid);
+       if (!m)
+               return NULL;
+       M_PREPEND(m, l, M_DONTWAIT);
+       if (!m)
+               return NULL;
 
-       return newmsg;
-    }
+       totlen = 0;
+       for (n = m; n; n = n->m_next)
+               totlen += n->m_len;
+
+       prop = mtod(m, struct sadb_prop *);
+       bzero(prop, sizeof(*prop));
+       prop->sadb_prop_len = PFKEY_UNIT64(totlen);
+       prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
+       prop->sadb_prop_replay = 32;    /* XXX */
+
+       return m;
 }
 
 /*
  * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
  * send
- *   <base, SA, address(SD), (address(P)),
+ *   <base, SA, address(SD), (address(P)), x_policy,
  *       (identity(SD),) (sensitivity,) proposal>
  * to KMD, and expect to receive
- *   <base> with SADB_ACQUIRE if error occured,
+ *   <base> with SADB_ACQUIRE if error occurred,
  * or
  *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
  * from KMD by PF_KEY.
  *
- * sensitivity is not supported.
+ * XXX x_policy is outside of RFC2367 (KAME extension).
+ * XXX sensitivity is not supported.
+ * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
+ * see comment for key_getcomb_ipcomp().
  *
  * OUT:
  *    0     : succeed
@@ -5081,21 +6006,22 @@ key_acquire(saidx, sp)
        struct secasindex *saidx;
        struct secpolicy *sp;
 {
+       struct mbuf *result = NULL, *m;
 #ifndef IPSEC_NONBLOCK_ACQUIRE
        struct secacq *newacq;
 #endif
-       struct secpolicyindex *spidx = NULL;
        u_int8_t satype;
-       int error;
+       int error = -1;
+       u_int32_t seq;
+
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
 
        /* sanity check */
-       if (saidx == NULL || sp == NULL)
+       if (saidx == NULL)
                panic("key_acquire: NULL pointer is passed.\n");
        if ((satype = key_proto2satype(saidx->proto)) == 0)
                panic("key_acquire: invalid proto is passed.\n");
 
-       spidx = &sp->spidx;
-
 #ifndef IPSEC_NONBLOCK_ACQUIRE
        /*
         * We never do anything about acquirng SA.  There is anather
@@ -5118,129 +6044,55 @@ key_acquire(saidx, sp)
                if ((newacq = key_newacq(saidx)) == NULL)
                        return ENOBUFS;
 
-               /* add to acqtree */
-               LIST_INSERT_HEAD(&acqtree, newacq, chain);
-       }
-#endif
-
-    {
-       struct sadb_msg *newmsg = NULL;
-       union sadb_x_ident_id id;
-       u_int len;
-       caddr_t p;
-
-       /* create new sadb_msg to reply. */
-       len = sizeof(struct sadb_msg)
-               + sizeof(struct sadb_address)
-               + PFKEY_ALIGN8(saidx->src.ss_len)
-               + sizeof(struct sadb_address)
-               + PFKEY_ALIGN8(saidx->dst.ss_len)
-               + sizeof(struct sadb_x_policy)
-               + sizeof(struct sadb_ident)
-               + PFKEY_ALIGN8(spidx->src.ss_len)
-               + sizeof(struct sadb_ident)
-               + PFKEY_ALIGN8(spidx->dst.ss_len)
-               + sizeof(struct sadb_prop)
-               + sizeof(struct sadb_comb); /* XXX to be multiple */
-
-       KMALLOC(newmsg, struct sadb_msg *, len);
-       if (newmsg == 0) {
-#if IPSEC_DEBUG
-               printf("key_acquire: No more memory.\n");
-#endif
-               return ENOBUFS;
+               /* add to acqtree */
+               LIST_INSERT_HEAD(&acqtree, newacq, chain);
        }
-       bzero((caddr_t)newmsg, len);
+#endif
 
-       newmsg->sadb_msg_version = PF_KEY_V2;
-       newmsg->sadb_msg_type = SADB_ACQUIRE;
-       newmsg->sadb_msg_errno = 0;
-       newmsg->sadb_msg_satype = satype;
-       newmsg->sadb_msg_len = PFKEY_UNIT64(len);
-       newmsg->sadb_msg_mode = saidx->mode;
-       newmsg->sadb_msg_reqid = saidx->reqid;
 
 #ifndef IPSEC_NONBLOCK_ACQUIRE
-       newmsg->sadb_msg_seq = newacq->seq;
+       seq = newacq->seq;
 #else
-       newmsg->sadb_msg_seq = (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
+       seq = (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
 #endif
-
-       newmsg->sadb_msg_pid = 0;
-
-       p = (caddr_t)newmsg + sizeof(struct sadb_msg);
+       m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
+       if (!m) {
+               error = ENOBUFS;
+               goto fail;
+       }
+       result = m;
 
        /* set sadb_address for saidx's. */
-       p = key_setsadbaddr(p,
-                           SADB_EXT_ADDRESS_SRC,
-                           (struct sockaddr *)&saidx->src,
-                           _INALENBYAF(saidx->src.ss_family) << 3,
-                           IPSEC_ULPROTO_ANY);
-       p = key_setsadbaddr(p,
-                           SADB_EXT_ADDRESS_DST,
-                           (struct sockaddr *)&saidx->dst,
-                           _INALENBYAF(saidx->dst.ss_family) << 3,
-                           IPSEC_ULPROTO_ANY);
+       m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
+           (struct sockaddr *)&saidx->src, FULLMASK, IPSEC_ULPROTO_ANY);
+       if (!m) {
+               error = ENOBUFS;
+               goto fail;
+       }
+       m_cat(result, m);
 
-       /* set sadb_x_policy */
-       p = key_setsadbxpolicy(p, sp->policy, sp->spidx.dir, sp->id);
-
-       /* set sadb_address for spidx's. */
-       bzero(&id, sizeof(id));
-       id.sadb_x_ident_id_addr.prefix = spidx->prefs;
-       id.sadb_x_ident_id_addr.ul_proto = spidx->ul_proto;
-       p = key_setsadbident(p,
-                           SADB_EXT_IDENTITY_SRC,
-                           SADB_X_IDENTTYPE_ADDR,
-                           (caddr_t)&spidx->src,
-                           spidx->src.ss_len,
-                           *(u_int64_t *)&id);
-
-       bzero(&id, sizeof(id));
-       id.sadb_x_ident_id_addr.prefix = spidx->prefd;
-       id.sadb_x_ident_id_addr.ul_proto = spidx->ul_proto;
-       p = key_setsadbident(p,
-                           SADB_EXT_IDENTITY_DST,
-                           SADB_X_IDENTTYPE_ADDR,
-                           (caddr_t)&spidx->dst,
-                           spidx->dst.ss_len,
-                           *(u_int64_t *)&id);
-
-       /* create proposal extension */
-       /* set combination extension */
-       /* XXX: to be defined by proposal database */
-    {
-       struct sadb_prop *prop;
-       struct sadb_comb *comb;
+       m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
+           (struct sockaddr *)&saidx->dst, FULLMASK, IPSEC_ULPROTO_ANY);
+       if (!m) {
+               error = ENOBUFS;
+               goto fail;
+       }
+       m_cat(result, m);
 
-       prop = (struct sadb_prop *)p;
-       prop->sadb_prop_len = PFKEY_UNIT64(sizeof(*prop) + sizeof(*comb));
-               /* XXX to be multiple */
-       prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
-       prop->sadb_prop_replay = 32;    /* XXX be variable ? */
-       p += sizeof(struct sadb_prop);
-
-       comb = (struct sadb_comb *)p;
-       comb->sadb_comb_auth = SADB_AALG_SHA1HMAC; /* XXX ??? */
-       comb->sadb_comb_encrypt = SADB_EALG_DESCBC; /* XXX ??? */
-       comb->sadb_comb_flags = 0;
-       comb->sadb_comb_auth_minbits = 8; /* XXX */
-       comb->sadb_comb_auth_maxbits = 1024; /* XXX */
-       comb->sadb_comb_encrypt_minbits = 64; /* XXX */
-       comb->sadb_comb_encrypt_maxbits = 64; /* XXX */
-       comb->sadb_comb_soft_allocations = 0;
-       comb->sadb_comb_hard_allocations = 0;
-       comb->sadb_comb_soft_bytes = 0;
-       comb->sadb_comb_hard_bytes = 0;
-       comb->sadb_comb_soft_addtime = 0;
-       comb->sadb_comb_hard_addtime = 0;
-       comb->sadb_comb_soft_usetime = 0;
-       comb->sadb_comb_hard_usetime = 0;
+       /* XXX proxy address (optional) */
 
-       p += sizeof(*comb);
-    }
+       /* set sadb_x_policy */
+       if (sp) {
+               m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
+               if (!m) {
+                       error = ENOBUFS;
+                       goto fail;
+               }
+               m_cat(result, m);
+       }
 
-#if 0 /* XXX Do it ?*/
+       /* XXX identity (optional) */
+#if 0
        if (idexttype && fqdn) {
                /* create identity extension (FQDN) */
                struct sadb_ident *id;
@@ -5280,15 +6132,55 @@ key_acquire(saidx, sp)
        }
 #endif
 
-       error = key_sendall(newmsg, len);
-#if IPSEC_DEBUG
-       if (error != 0)
-               printf("key_acquire: key_sendall returned %d\n", error);
+       /* XXX sensitivity (optional) */
+
+       /* create proposal/combination extension */
+       m = key_getprop(saidx);
+#if 0
+       /*
+        * spec conformant: always attach proposal/combination extension,
+        * the problem is that we have no way to attach it for ipcomp,
+        * due to the way sadb_comb is declared in RFC2367.
+        */
+       if (!m) {
+               error = ENOBUFS;
+               goto fail;
+       }
+       m_cat(result, m);
+#else
+       /*
+        * outside of spec; make proposal/combination extension optional.
+        */
+       if (m)
+               m_cat(result, m);
 #endif
-       return error;
-    }
 
-       return 0;
+       if ((result->m_flags & M_PKTHDR) == 0) {
+               error = EINVAL;
+               goto fail;
+       }
+
+       if (result->m_len < sizeof(struct sadb_msg)) {
+               result = m_pullup(result, sizeof(struct sadb_msg));
+               if (result == NULL) {
+                       error = ENOBUFS;
+                       goto fail;
+               }
+       }
+
+       result->m_pkthdr.len = 0;
+       for (m = result; m; m = m->m_next)
+               result->m_pkthdr.len += m->m_len;
+
+       mtod(result, struct sadb_msg *)->sadb_msg_len =
+           PFKEY_UNIT64(result->m_pkthdr.len);
+
+       return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
+
+ fail:
+       if (result)
+               m_freem(result);
+       return error;
 }
 
 #ifndef IPSEC_NONBLOCK_ACQUIRE
@@ -5297,13 +6189,12 @@ key_newacq(saidx)
        struct secasindex *saidx;
 {
        struct secacq *newacq;
+       struct timeval tv;
 
        /* get new entry */
        KMALLOC(newacq, struct secacq *, sizeof(struct secacq));
        if (newacq == NULL) {
-#if IPSEC_DEBUG
-               printf("key_newacq: No more memory.\n");
-#endif
+               ipseclog((LOG_DEBUG, "key_newacq: No more memory.\n"));
                return NULL;
        }
        bzero(newacq, sizeof(*newacq));
@@ -5311,7 +6202,8 @@ key_newacq(saidx)
        /* copy secindex */
        bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx));
        newacq->seq = (acq_seq == ~0 ? 1 : ++acq_seq);
-       newacq->tick = 0;
+       microtime(&tv);
+       newacq->created = tv.tv_sec;
        newacq->count = 0;
 
        return newacq;
@@ -5323,8 +6215,10 @@ key_getacq(saidx)
 {
        struct secacq *acq;
 
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        LIST_FOREACH(acq, &acqtree, chain) {
-               if (key_cmpsaidx_exactly(saidx, &acq->saidx))
+               if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
                        return acq;
        }
 
@@ -5337,6 +6231,8 @@ key_getacqbyseq(seq)
 {
        struct secacq *acq;
 
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        LIST_FOREACH(acq, &acqtree, chain) {
                if (acq->seq == seq)
                        return acq;
@@ -5351,20 +6247,20 @@ key_newspacq(spidx)
        struct secpolicyindex *spidx;
 {
        struct secspacq *acq;
+       struct timeval tv;
 
        /* get new entry */
        KMALLOC(acq, struct secspacq *, sizeof(struct secspacq));
        if (acq == NULL) {
-#if IPSEC_DEBUG
-               printf("key_newspacq: No more memory.\n");
-#endif
+               ipseclog((LOG_DEBUG, "key_newspacq: No more memory.\n"));
                return NULL;
        }
        bzero(acq, sizeof(*acq));
 
        /* copy secindex */
        bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
-       acq->tick = 0;
+       microtime(&tv);
+       acq->created = tv.tv_sec;
        acq->count = 0;
 
        return acq;
@@ -5376,6 +6272,8 @@ key_getspacq(spidx)
 {
        struct secspacq *acq;
 
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        LIST_FOREACH(acq, &spacqtree, chain) {
                if (key_cmpspidx_exactly(spidx, &acq->spidx))
                        return acq;
@@ -5396,59 +6294,60 @@ key_getspacq(spidx)
  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
  * to the socket.
  *
- * IN: mhp: pointer to the pointer to each header.
- * OUT:        NULL if fail.
- *     other if success, return pointer to the message to send.
+ * m will always be freed.
  */
-static struct sadb_msg *
-key_acquire2(mhp)
-       caddr_t *mhp;
+static int
+key_acquire2(so, m, mhp)
+       struct socket *so;
+       struct mbuf *m;
+       const struct sadb_msghdr *mhp;
 {
-       struct sadb_msg *msg0;
-       struct sadb_address *src0, *dst0;
+       const struct sadb_address *src0, *dst0;
        struct secasindex saidx;
        struct secashead *sah;
        u_int16_t proto;
+       int error;
+
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
 
        /* sanity check */
-       if (mhp == NULL || mhp[0] == NULL)
+       if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
                panic("key_acquire2: NULL pointer is passed.\n");
 
-       msg0 = (struct sadb_msg *)mhp[0];
-
        /*
         * Error message from KMd.
-        * We assume that if error was occured in IKEd, the length of PFKEY
+        * We assume that if error was occurred in IKEd, the length of PFKEY
         * message is equal to the size of sadb_msg structure.
-        * We return ~0 even if error occured in this function.
+        * We do not raise error even if error occurred in this function.
         */
-       if (msg0->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
-
+       if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
 #ifndef IPSEC_NONBLOCK_ACQUIRE
                struct secacq *acq;
+               struct timeval tv;
 
                /* check sequence number */
-               if (msg0->sadb_msg_seq == 0) {
-#if IPSEC_DEBUG
-                       printf("key_acquire2: must specify sequence number.\n");
-#endif
-                       return (struct sadb_msg *)~0;
+               if (mhp->msg->sadb_msg_seq == 0) {
+                       ipseclog((LOG_DEBUG, "key_acquire2: must specify sequence number.\n"));
+                       m_freem(m);
+                       return 0;
                }
 
-               if ((acq = key_getacqbyseq(msg0->sadb_msg_seq)) == NULL) {
-#if IPSEC_DEBUG
-                       printf("key_acquire2: "
-                               "invalid sequence number is passed.\n");
-#endif
-                       return (struct sadb_msg *)~0;
+               if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
+                       /*
+                        * the specified larval SA is already gone, or we got
+                        * a bogus sequence number.  we can silently ignore it.
+                        */
+                       m_freem(m);
+                       return 0;
                }
 
                /* reset acq counter in order to deletion by timehander. */
-               acq->tick = key_blockacq_lifetime;
+               microtime(&tv);
+               acq->created = tv.tv_sec;
                acq->count = 0;
 #endif
-               return (struct sadb_msg *)~0;
-               /* NOTREACHED */
+               m_freem(m);
+               return 0;
        }
 
        /*
@@ -5456,68 +6355,52 @@ key_acquire2(mhp)
         */
 
        /* map satype to proto */
-       if ((proto = key_satype2proto(msg0->sadb_msg_satype)) == 0) {
-#if IPSEC_DEBUG
-               printf("key_acquire2: invalid satype is passed.\n");
-#endif
-               msg0->sadb_msg_errno = EINVAL;
-               return NULL;
+       if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
+               ipseclog((LOG_DEBUG, "key_acquire2: invalid satype is passed.\n"));
+               return key_senderror(so, m, EINVAL);
        }
 
-       if (mhp[SADB_EXT_ADDRESS_SRC] == NULL
-        || mhp[SADB_EXT_ADDRESS_DST] == NULL
-        || mhp[SADB_EXT_PROPOSAL] == NULL) {
+       if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
+           mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
+           mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
                /* error */
-#if IPSEC_DEBUG
-               printf("key_acquire2: invalid message is passed.\n");
-#endif
-               msg0->sadb_msg_errno = EINVAL;
-               return NULL;
+               ipseclog((LOG_DEBUG, "key_acquire2: invalid message is passed.\n"));
+               return key_senderror(so, m, EINVAL);
+       }
+       if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
+           mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
+           mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
+               /* error */
+               ipseclog((LOG_DEBUG, "key_acquire2: invalid message is passed.\n"));
+               return key_senderror(so, m, EINVAL);
        }
-       src0 = (struct sadb_address *)(mhp[SADB_EXT_ADDRESS_SRC]);
-       dst0 = (struct sadb_address *)(mhp[SADB_EXT_ADDRESS_DST]);
 
-       KEY_SETSECASIDX(proto, msg0, src0+1, dst0+1, &saidx);
+       src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
+       dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
+
+       /* XXX boundary check against sa_len */
+       KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
 
        /* get a SA index */
-       if ((sah = key_getsah(&saidx)) != NULL) {
-#if IPSEC_DEBUG
-               printf("key_acquire2: a SA exists already.\n");
-#endif
-               msg0->sadb_msg_errno = EEXIST;
-               return NULL;
+       LIST_FOREACH(sah, &sahtree, chain) {
+               if (sah->state == SADB_SASTATE_DEAD)
+                       continue;
+               if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
+                       break;
        }
-
-       msg0->sadb_msg_errno = key_acquire(&saidx, NULL);
-       if (msg0->sadb_msg_errno != 0) {
-#if IPSEC_DEBUG
-               printf("key_acquire2: error %d returned "
-                       "from key_acquire.\n", msg0->sadb_msg_errno);
-#endif
-               return NULL;
+       if (sah != NULL) {
+               ipseclog((LOG_DEBUG, "key_acquire2: a SA exists already.\n"));
+               return key_senderror(so, m, EEXIST);
        }
 
-    {
-       struct sadb_msg *newmsg;
-       u_int len;
-
-       /* create new sadb_msg to reply. */
-       len = PFKEY_UNUNIT64(msg0->sadb_msg_len);
-
-       KMALLOC(newmsg, struct sadb_msg *, len);
-       if (newmsg == NULL) {
-#if IPSEC_DEBUG
-               printf("key_acquire2: No more memory.\n");
-#endif
-               msg0->sadb_msg_errno = ENOBUFS;
-               return NULL;
+       error = key_acquire(&saidx, NULL);
+       if (error != 0) {
+               ipseclog((LOG_DEBUG, "key_acquire2: error %d returned "
+                       "from key_acquire.\n", mhp->msg->sadb_msg_errno));
+               return key_senderror(so, m, error);
        }
-       bzero((caddr_t)newmsg, len);
-
-       bcopy(mhp[0], (caddr_t)newmsg, len);
 
-       return newmsg;
-    }
+       return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
 }
 
 /*
@@ -5530,155 +6413,171 @@ key_acquire2(mhp)
  *   <base, supported>
  * to KMD by PF_KEY.
  * If socket is detached, must free from regnode.
- * OUT:
- *    0     : succeed
- *    others: error number
+ *
+ * m will always be freed.
  */
-static struct sadb_msg *
-key_register(mhp, so)
-       caddr_t *mhp;
+static int
+key_register(so, m, mhp)
        struct socket *so;
+       struct mbuf *m;
+       const struct sadb_msghdr *mhp;
 {
-       struct sadb_msg *msg0;
        struct secreg *reg, *newreg = 0;
 
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        /* sanity check */
-       if (mhp == NULL || so == NULL || mhp[0] == NULL)
+       if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
                panic("key_register: NULL pointer is passed.\n");
 
-       msg0 = (struct sadb_msg *)mhp[0];
-
        /* check for invalid register message */
-       if (msg0->sadb_msg_satype >= sizeof(regtree)/sizeof(regtree[0])) {
-               msg0->sadb_msg_errno = EINVAL;
-               return NULL;
-       }
+       if (mhp->msg->sadb_msg_satype >= sizeof(regtree)/sizeof(regtree[0]))
+               return key_senderror(so, m, EINVAL);
 
        /* When SATYPE_UNSPEC is specified, only return sabd_supported. */
-       if (msg0->sadb_msg_satype == SADB_SATYPE_UNSPEC)
+       if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
                goto setmsg;
 
        /* check whether existing or not */
-       LIST_FOREACH(reg, &regtree[msg0->sadb_msg_satype], chain) {
+       LIST_FOREACH(reg, &regtree[mhp->msg->sadb_msg_satype], chain) {
                if (reg->so == so) {
-#if IPSEC_DEBUG
-                       printf("key_register: socket exists already.\n");
-#endif
-                       msg0->sadb_msg_errno = EEXIST;
-                       return NULL;
+                       ipseclog((LOG_DEBUG, "key_register: socket exists already.\n"));
+                       return key_senderror(so, m, EEXIST);
                }
        }
 
        /* create regnode */
-       KMALLOC(newreg, struct secreg *, sizeof(struct secreg));
+       KMALLOC(newreg, struct secreg *, sizeof(*newreg));
        if (newreg == NULL) {
-#if IPSEC_DEBUG
-               printf("key_register: No more memory.\n");
-#endif
-               msg0->sadb_msg_errno = ENOBUFS;
-               return NULL;
+               ipseclog((LOG_DEBUG, "key_register: No more memory.\n"));
+               return key_senderror(so, m, ENOBUFS);
        }
-       bzero((caddr_t)newreg, sizeof(struct secreg));
+       bzero((caddr_t)newreg, sizeof(*newreg));
 
+       socket_lock(so, 1);
        newreg->so = so;
        ((struct keycb *)sotorawcb(so))->kp_registered++;
+       socket_unlock(so, 1);
 
        /* add regnode to regtree. */
-       LIST_INSERT_HEAD(&regtree[msg0->sadb_msg_satype], newreg, chain);
+       LIST_INSERT_HEAD(&regtree[mhp->msg->sadb_msg_satype], newreg, chain);
 
   setmsg:
-  {
+    {
+       struct mbuf *n;
        struct sadb_msg *newmsg;
        struct sadb_supported *sup;
        u_int len, alen, elen;
-       caddr_t p;
+       int off;
+       int i;
+       struct sadb_alg *alg;
 
        /* create new sadb_msg to reply. */
-       alen = sizeof(struct sadb_supported)
-               + ((SADB_AALG_MAX - 1) * sizeof(struct sadb_alg));
-
-#if IPSEC_ESP
-       elen = sizeof(struct sadb_supported)
-               + ((SADB_EALG_MAX - 1) * sizeof(struct sadb_alg));
-#else
+       alen = 0;
+       for (i = 1; i <= SADB_AALG_MAX; i++) {
+               if (ah_algorithm_lookup(i))
+                       alen += sizeof(struct sadb_alg);
+       }
+       if (alen)
+               alen += sizeof(struct sadb_supported);
        elen = 0;
+#if IPSEC_ESP
+       for (i = 1; i <= SADB_EALG_MAX; i++) {
+               if (esp_algorithm_lookup(i))
+                       elen += sizeof(struct sadb_alg);
+       }
+       if (elen)
+               elen += sizeof(struct sadb_supported);
 #endif
 
-       len = sizeof(struct sadb_msg)
-               + alen
-               + elen;
+       len = sizeof(struct sadb_msg) + alen + elen;
 
-       KMALLOC(newmsg, struct sadb_msg *, len);
-       if (newmsg == NULL) {
-#if IPSEC_DEBUG
-               printf("key_register: No more memory.\n");
-#endif
-               msg0->sadb_msg_errno = ENOBUFS;
-               return NULL;
+       if (len > MCLBYTES)
+               return key_senderror(so, m, ENOBUFS);
+
+       MGETHDR(n, M_DONTWAIT, MT_DATA);
+       if (len > MHLEN) {
+               MCLGET(n, M_DONTWAIT);
+               if ((n->m_flags & M_EXT) == 0) {
+                       m_freem(n);
+                       n = NULL;
+               }
        }
-       bzero((caddr_t)newmsg, len);
+       if (!n)
+               return key_senderror(so, m, ENOBUFS);
+
+       n->m_pkthdr.len = n->m_len = len;
+       n->m_next = NULL;
+       off = 0;
 
-       bcopy((caddr_t)mhp[0], (caddr_t)newmsg, sizeof(*msg0));
+       m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
+       newmsg = mtod(n, struct sadb_msg *);
        newmsg->sadb_msg_errno = 0;
        newmsg->sadb_msg_len = PFKEY_UNIT64(len);
-       p = (caddr_t)newmsg + sizeof(*msg0);
+       off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
 
        /* for authentication algorithm */
-       sup = (struct sadb_supported *)p;
-       sup->sadb_supported_len = PFKEY_UNIT64(alen);
-       sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
-       p += sizeof(*sup);
+       if (alen) {
+               sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
+               sup->sadb_supported_len = PFKEY_UNIT64(alen);
+               sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
+               off += PFKEY_ALIGN8(sizeof(*sup));
 
-    {
-       int i;
-       struct sadb_alg *alg;
-       struct ah_algorithm *algo;
+               for (i = 1; i <= SADB_AALG_MAX; i++) {
+                       const struct ah_algorithm *aalgo;
 
-       for (i = 1; i < SADB_AALG_MAX; i++) {
-               algo = &ah_algorithms[i];
-               alg = (struct sadb_alg *)p;
-               alg->sadb_alg_id = i;
-               alg->sadb_alg_ivlen = 0;
-               alg->sadb_alg_minbits = algo->keymin;
-               alg->sadb_alg_maxbits = algo->keymax;
-               p += sizeof(struct sadb_alg);
+                       aalgo = ah_algorithm_lookup(i);
+                       if (!aalgo)
+                               continue;
+                       alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
+                       alg->sadb_alg_id = i;
+                       alg->sadb_alg_ivlen = 0;
+                       alg->sadb_alg_minbits = aalgo->keymin;
+                       alg->sadb_alg_maxbits = aalgo->keymax;
+                       off += PFKEY_ALIGN8(sizeof(*alg));
+               }
        }
-    }
 
 #if IPSEC_ESP
        /* for encryption algorithm */
-       sup = (struct sadb_supported *)p;
-       sup->sadb_supported_len = PFKEY_UNIT64(elen);
-       sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
-       p += sizeof(*sup);
-
-    {
-       int i;
-       struct sadb_alg *alg;
-       struct esp_algorithm *algo;
+       if (elen) {
+               sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
+               sup->sadb_supported_len = PFKEY_UNIT64(elen);
+               sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
+               off += PFKEY_ALIGN8(sizeof(*sup));
 
-       for (i = 1; i < SADB_EALG_MAX; i++) {
-               algo = &esp_algorithms[i];
+               for (i = 1; i <= SADB_EALG_MAX; i++) {
+                       const struct esp_algorithm *ealgo;
 
-               alg = (struct sadb_alg *)p;
-               alg->sadb_alg_id = i;
-               if (algo && algo->ivlen) {
-                       /*
-                        * give NULL to get the value preferred by algorithm
-                        * XXX SADB_X_EXT_DERIV ?
-                        */
-                       alg->sadb_alg_ivlen = (*algo->ivlen)(NULL);
-               } else
-                       alg->sadb_alg_ivlen = 0;
-               alg->sadb_alg_minbits = algo->keymin;
-               alg->sadb_alg_maxbits = algo->keymax;
-               p += sizeof(struct sadb_alg);
+                       ealgo = esp_algorithm_lookup(i);
+                       if (!ealgo)
+                               continue;
+                       alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
+                       alg->sadb_alg_id = i;
+                       if (ealgo && ealgo->ivlen) {
+                               /*
+                                * give NULL to get the value preferred by
+                                * algorithm XXX SADB_X_EXT_DERIV ?
+                                */
+                               alg->sadb_alg_ivlen =
+                                   (*ealgo->ivlen)(ealgo, NULL);
+                       } else
+                               alg->sadb_alg_ivlen = 0;
+                       alg->sadb_alg_minbits = ealgo->keymin;
+                       alg->sadb_alg_maxbits = ealgo->keymax;
+                       off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
+               }
        }
-    }
 #endif
 
-       return newmsg;
-  }
+#if DIGAGNOSTIC
+       if (off != len)
+               panic("length assumption failed in key_register");
+#endif
+
+       m_freem(m);
+       return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
+    }
 }
 
 /*
@@ -5692,6 +6591,8 @@ key_freereg(so)
        struct secreg *reg;
        int i;
 
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        /* sanity check */
        if (so == NULL)
                panic("key_freereg: NULL pointer is passed.\n");
@@ -5718,7 +6619,7 @@ key_freereg(so)
 /*
  * SADB_EXPIRE processing
  * send
- *   <base, SA, lifetime(C and one of HS), address(SD)>
+ *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
  * to KMD by PF_KEY.
  * NOTE: We send only soft lifetime extension.
  *
@@ -5731,13 +6632,12 @@ key_expire(sav)
 {
        int s;
        int satype;
+       struct mbuf *result = NULL, *m;
+       int len;
+       int error = -1;
+       struct sadb_lifetime *lt;
 
-       /* XXX: Why do we lock ? */
-#ifdef __NetBSD__
-       s = splsoftnet();       /*called from softclock()*/
-#else
-       s = splnet();   /*called from softclock()*/
-#endif
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
 
        /* sanity check */
        if (sav == NULL)
@@ -5747,76 +6647,101 @@ key_expire(sav)
        if ((satype = key_proto2satype(sav->sah->saidx.proto)) == 0)
                panic("key_expire: invalid proto is passed.\n");
 
-    {
-       struct sadb_msg *newmsg = NULL;
-       u_int len;
-       caddr_t p;
-       int error;
-
-       /* create new sadb_msg to reply. */
-       len = sizeof(struct sadb_msg)
-               + sizeof(struct sadb_sa)
-               + sizeof(struct sadb_lifetime)
-               + sizeof(struct sadb_lifetime)
-               + sizeof(struct sadb_address)
-               + PFKEY_ALIGN8(sav->sah->saidx.src.ss_len)
-               + sizeof(struct sadb_address)
-               + PFKEY_ALIGN8(sav->sah->saidx.dst.ss_len);
-
-       KMALLOC(newmsg, struct sadb_msg *, len);
-       if (newmsg == NULL) {
-#if IPSEC_DEBUG
-               printf("key_expire: No more memory.\n");
-#endif
-               splx(s);
-               return ENOBUFS;
+       /* set msg header */
+       m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
+       if (!m) {
+               error = ENOBUFS;
+               goto fail;
        }
-       bzero((caddr_t)newmsg, len);
+       result = m;
 
-       /* set msg header */
-       p = key_setsadbmsg((caddr_t)newmsg, SADB_EXPIRE, len,
-                          satype, sav->seq, 0,
-                          sav->sah->saidx.mode, sav->sah->saidx.reqid,
-                          0, sav->refcnt);
+       /* create SA extension */
+       m = key_setsadbsa(sav);
+       if (!m) {
+               error = ENOBUFS;
+               goto fail;
+       }
+       m_cat(result, m);
 
        /* create SA extension */
-       p = key_setsadbsa(p, sav);
+       m = key_setsadbxsa2(sav->sah->saidx.mode,
+                       sav->replay ? sav->replay->count : 0,
+                       sav->sah->saidx.reqid);
+       if (!m) {
+               error = ENOBUFS;
+               goto fail;
+       }
+       m_cat(result, m);
 
-       /* create lifetime extension */
-    {
-       struct sadb_lifetime *m_lt = (struct sadb_lifetime *)p;
-
-       m_lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
-       m_lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
-       m_lt->sadb_lifetime_allocations = sav->lft_c->sadb_lifetime_allocations;
-       m_lt->sadb_lifetime_bytes = sav->lft_c->sadb_lifetime_bytes;
-       m_lt->sadb_lifetime_addtime = sav->lft_c->sadb_lifetime_addtime;
-       m_lt->sadb_lifetime_usetime = sav->lft_c->sadb_lifetime_usetime;
-       p += sizeof(struct sadb_lifetime);
-
-       /* copy SOFT lifetime extension. */
-       bcopy(sav->lft_s, p, sizeof(struct sadb_lifetime));
-       p += sizeof(struct sadb_lifetime);
-    }
+       /* create lifetime extension (current and soft) */
+       len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
+       m = key_alloc_mbuf(len);
+       if (!m || m->m_next) {  /*XXX*/
+               if (m)
+                       m_freem(m);
+               error = ENOBUFS;
+               goto fail;
+       }
+       bzero(mtod(m, caddr_t), len);
+       lt = mtod(m, struct sadb_lifetime *);
+       lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
+       lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
+       lt->sadb_lifetime_allocations = sav->lft_c->sadb_lifetime_allocations;
+       lt->sadb_lifetime_bytes = sav->lft_c->sadb_lifetime_bytes;
+       lt->sadb_lifetime_addtime = sav->lft_c->sadb_lifetime_addtime;
+       lt->sadb_lifetime_usetime = sav->lft_c->sadb_lifetime_usetime;
+       lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
+       bcopy(sav->lft_s, lt, sizeof(*lt));
+       m_cat(result, m);
 
        /* set sadb_address for source */
-       p = key_setsadbaddr(p,
-                           SADB_EXT_ADDRESS_SRC,
-                           (struct sockaddr *)&sav->sah->saidx.src,
-                           _INALENBYAF(sav->sah->saidx.src.ss_family) << 3,
-                           IPSEC_ULPROTO_ANY);
+       m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
+           (struct sockaddr *)&sav->sah->saidx.src,
+           FULLMASK, IPSEC_ULPROTO_ANY);
+       if (!m) {
+               error = ENOBUFS;
+               goto fail;
+       }
+       m_cat(result, m);
 
        /* set sadb_address for destination */
-       p = key_setsadbaddr(p,
-                           SADB_EXT_ADDRESS_DST,
-                           (struct sockaddr *)&sav->sah->saidx.dst,
-                           _INALENBYAF(sav->sah->saidx.dst.ss_family) << 3,
-                           IPSEC_ULPROTO_ANY);
+       m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
+           (struct sockaddr *)&sav->sah->saidx.dst,
+           FULLMASK, IPSEC_ULPROTO_ANY);
+       if (!m) {
+               error = ENOBUFS;
+               goto fail;
+       }
+       m_cat(result, m);
+
+       if ((result->m_flags & M_PKTHDR) == 0) {
+               error = EINVAL;
+               goto fail;
+       }
+
+       if (result->m_len < sizeof(struct sadb_msg)) {
+               result = m_pullup(result, sizeof(struct sadb_msg));
+               if (result == NULL) {
+                       error = ENOBUFS;
+                       goto fail;
+               }
+       }
+
+       result->m_pkthdr.len = 0;
+       for (m = result; m; m = m->m_next)
+               result->m_pkthdr.len += m->m_len;
 
-       error = key_sendall(newmsg, len);
+       mtod(result, struct sadb_msg *)->sadb_msg_len =
+           PFKEY_UNIT64(result->m_pkthdr.len);
+
+       splx(s);
+       return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
+
+ fail:
+       if (result)
+               m_freem(result);
        splx(s);
        return error;
-    }
 }
 
 /*
@@ -5829,51 +6754,46 @@ key_expire(sav)
  * to the ikmpd.
  * NOTE: to do is only marking SADB_SASTATE_DEAD.
  *
- * IN: mhp: pointer to the pointer to each header.
- * OUT:        NULL if fail.
- *     other if success, return pointer to the message to send.
+ * m will always be freed.
  */
-static struct sadb_msg *
-key_flush(mhp)
-       caddr_t *mhp;
+static int
+key_flush(so, m, mhp)
+       struct socket *so;
+       struct mbuf *m;
+       const struct sadb_msghdr *mhp;
 {
-       struct sadb_msg *msg0;
+       struct sadb_msg *newmsg;
        struct secashead *sah, *nextsah;
        struct secasvar *sav, *nextsav;
        u_int16_t proto;
        u_int8_t state;
        u_int stateidx;
 
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        /* sanity check */
-       if (mhp == NULL || mhp[0] == NULL)
+       if (so == NULL || mhp == NULL || mhp->msg == NULL)
                panic("key_flush: NULL pointer is passed.\n");
 
-       msg0 = (struct sadb_msg *)mhp[0];
-
        /* map satype to proto */
-       if ((proto = key_satype2proto(msg0->sadb_msg_satype)) == 0) {
-#if IPSEC_DEBUG
-               printf("key_flush: invalid satype is passed.\n");
-#endif
-               msg0->sadb_msg_errno = EINVAL;
-               return NULL;
+       if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
+               ipseclog((LOG_DEBUG, "key_flush: invalid satype is passed.\n"));
+               return key_senderror(so, m, EINVAL);
        }
 
        /* no SATYPE specified, i.e. flushing all SA. */
        for (sah = LIST_FIRST(&sahtree);
             sah != NULL;
             sah = nextsah) {
-
                nextsah = LIST_NEXT(sah, chain);
 
-               if (msg0->sadb_msg_satype != SADB_SATYPE_UNSPEC
+               if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
                 && proto != sah->saidx.proto)
                        continue;
 
                for (stateidx = 0;
                     stateidx < _ARRAYLEN(saorder_state_alive);
                     stateidx++) {
-
                        state = saorder_state_any[stateidx];
                        for (sav = LIST_FIRST(&sah->savtree[state]);
                             sav != NULL;
@@ -5889,29 +6809,21 @@ key_flush(mhp)
                sah->state = SADB_SASTATE_DEAD;
        }
 
-    {
-       struct sadb_msg *newmsg;
-       u_int len;
-
-       /* create new sadb_msg to reply. */
-       len = sizeof(struct sadb_msg);
-
-       KMALLOC(newmsg, struct sadb_msg *, len);
-       if (newmsg == NULL) {
-#if IPSEC_DEBUG
-               printf("key_flush: No more memory.\n");
-#endif
-               msg0->sadb_msg_errno = ENOBUFS;
-               return NULL;
+       if (m->m_len < sizeof(struct sadb_msg) ||
+           sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
+               ipseclog((LOG_DEBUG, "key_flush: No more memory.\n"));
+               return key_senderror(so, m, ENOBUFS);
        }
-       bzero((caddr_t)newmsg, len);
 
-       bcopy((caddr_t)mhp[0], (caddr_t)newmsg, sizeof(*msg0));
+       if (m->m_next)
+               m_freem(m->m_next);
+       m->m_next = NULL;
+       m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
+       newmsg = mtod(m, struct sadb_msg *);
        newmsg->sadb_msg_errno = 0;
-       newmsg->sadb_msg_len = PFKEY_UNIT64(len);
+       newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
 
-       return newmsg;
-    }
+       return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
 }
 
 /*
@@ -5924,52 +6836,46 @@ key_flush(mhp)
  *   <base> .....
  * to the ikmpd.
  *
- * IN: mhp: pointer to the pointer to each header.
- * OUT:        error code.  0 on success.
+ * m will always be freed.
  */
 static int
-key_dump(mhp, so, target)
-       caddr_t *mhp;
+key_dump(so, m, mhp)
        struct socket *so;
-       int target;
+       struct mbuf *m;
+       const struct sadb_msghdr *mhp;
 {
-       struct sadb_msg *msg0;
        struct secashead *sah;
        struct secasvar *sav;
        u_int16_t proto;
        u_int stateidx;
        u_int8_t satype;
        u_int8_t state;
-       int len, cnt;
+       int cnt;
        struct sadb_msg *newmsg;
+       struct mbuf *n;
+
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
 
        /* sanity check */
-       if (mhp == NULL || mhp[0] == NULL)
+       if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
                panic("key_dump: NULL pointer is passed.\n");
 
-       msg0 = (struct sadb_msg *)mhp[0];
-
        /* map satype to proto */
-       if ((proto = key_satype2proto(msg0->sadb_msg_satype)) == 0) {
-#if IPSEC_DEBUG
-               printf("key_dump: invalid satype is passed.\n");
-#endif
-               msg0->sadb_msg_errno = EINVAL;
-               return NULL;
+       if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
+               ipseclog((LOG_DEBUG, "key_dump: invalid satype is passed.\n"));
+               return key_senderror(so, m, EINVAL);
        }
 
        /* count sav entries to be sent to the userland. */
        cnt = 0;
        LIST_FOREACH(sah, &sahtree, chain) {
-
-               if (msg0->sadb_msg_satype != SADB_SATYPE_UNSPEC
+               if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
                 && proto != sah->saidx.proto)
                        continue;
 
                for (stateidx = 0;
                     stateidx < _ARRAYLEN(saorder_state_any);
                     stateidx++) {
-
                        state = saorder_state_any[stateidx];
                        LIST_FOREACH(sav, &sah->savtree[state], chain) {
                                cnt++;
@@ -5978,160 +6884,126 @@ key_dump(mhp, so, target)
        }
 
        if (cnt == 0)
-               return ENOENT;
+               return key_senderror(so, m, ENOENT);
 
        /* send this to the userland, one at a time. */
        newmsg = NULL;
        LIST_FOREACH(sah, &sahtree, chain) {
-
-               if (msg0->sadb_msg_satype != SADB_SATYPE_UNSPEC
+               if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
                 && proto != sah->saidx.proto)
                        continue;
 
                /* map proto to satype */
                if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
-#if IPSEC_DEBUG
-                       printf("key_dump: there was invalid proto in SAD.\n");
-#endif
-                       msg0->sadb_msg_errno = EINVAL;
-                       return NULL;
+                       ipseclog((LOG_DEBUG, "key_dump: there was invalid proto in SAD.\n"));
+                       return key_senderror(so, m, EINVAL);
                }
 
                for (stateidx = 0;
                     stateidx < _ARRAYLEN(saorder_state_any);
                     stateidx++) {
-
                        state = saorder_state_any[stateidx];
                        LIST_FOREACH(sav, &sah->savtree[state], chain) {
+                               n = key_setdumpsa(sav, SADB_DUMP, satype,
+                                   --cnt, mhp->msg->sadb_msg_pid);
+                               if (!n)
+                                       return key_senderror(so, m, ENOBUFS);
 
-                               len = key_getmsglen(sav);
-                               KMALLOC(newmsg, struct sadb_msg *, len);
-                               if (newmsg == NULL) {
-#if IPSEC_DEBUG
-                                       printf("key_dump: No more memory.\n");
-#endif
-                                       return ENOBUFS;
-                               }
-                               bzero((caddr_t)newmsg, len);
-
-                               --cnt;
-                               (void)key_setdumpsa(newmsg, sav, SADB_DUMP,
-                                              satype, cnt, msg0->sadb_msg_pid);
-
-                               key_sendup(so, newmsg, len, target);
-                               KFREE(newmsg);
-                               newmsg = NULL;
+                               key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
                        }
                }
        }
 
+       m_freem(m);
        return 0;
 }
 
 /*
  * SADB_X_PROMISC processing
+ *
+ * m will always be freed.
  */
-static void
-key_promisc(mhp, so)
-       caddr_t *mhp;
+static int
+key_promisc(so, m, mhp)
        struct socket *so;
+       struct mbuf *m;
+       const struct sadb_msghdr *mhp;
 {
-       struct sadb_msg *msg0;
        int olen;
 
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        /* sanity check */
-       if (mhp == NULL || mhp[0] == NULL)
+       if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
                panic("key_promisc: NULL pointer is passed.\n");
 
-       msg0 = (struct sadb_msg *)mhp[0];
-       olen = PFKEY_UNUNIT64(msg0->sadb_msg_len);
+       olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
 
        if (olen < sizeof(struct sadb_msg)) {
-               return;
+#if 1
+               return key_senderror(so, m, EINVAL);
+#else
+               m_freem(m);
+               return 0;
+#endif
        } else if (olen == sizeof(struct sadb_msg)) {
                /* enable/disable promisc mode */
                struct keycb *kp;
-               int target = 0;
-
-               target = KEY_SENDUP_ONE;
-
-               if (so == NULL) {
-                       return;
-               }
-               if ((kp = (struct keycb *)sotorawcb(so)) == NULL) {
-                       msg0->sadb_msg_errno = EINVAL;
-                       goto sendorig;
-               }
-               msg0->sadb_msg_errno = 0;
-               if (msg0->sadb_msg_satype == 1 || msg0->sadb_msg_satype == 0) {
-                       kp->kp_promisc = msg0->sadb_msg_satype;
-               } else {
-                       msg0->sadb_msg_errno = EINVAL;
-                       goto sendorig;
+               
+               socket_lock(so, 1);
+               if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
+                       return key_senderror(so, m, EINVAL);
+               mhp->msg->sadb_msg_errno = 0;
+               switch (mhp->msg->sadb_msg_satype) {
+               case 0:
+               case 1:
+                       kp->kp_promisc = mhp->msg->sadb_msg_satype;
+                       break;
+               default:
+                       socket_unlock(so, 1);
+                       return key_senderror(so, m, EINVAL);
                }
+               socket_unlock(so, 1);
 
                /* send the original message back to everyone */
-               msg0->sadb_msg_errno = 0;
-               target = KEY_SENDUP_ALL;
-sendorig:
-               key_sendup(so, msg0, PFKEY_UNUNIT64(msg0->sadb_msg_len), target);
+               mhp->msg->sadb_msg_errno = 0;
+               return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
        } else {
                /* send packet as is */
-               struct sadb_msg *msg;
-               int len;
 
-               len = olen - sizeof(struct sadb_msg);
-               KMALLOC(msg, struct sadb_msg *, len);
-               if (msg == NULL) {
-                       msg0->sadb_msg_errno = ENOBUFS;
-                       key_sendup(so, msg0, PFKEY_UNUNIT64(msg0->sadb_msg_len),
-                               KEY_SENDUP_ONE);        /*XXX*/
-               }
+               m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
 
-               /* XXX if sadb_msg_seq is specified, send to specific pid */
-               key_sendup(so, msg, len, KEY_SENDUP_ALL);
-               KFREE(msg);
+               /* TODO: if sadb_msg_seq is specified, send to specific pid */
+               return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
        }
 }
 
-/*
- * send message to the socket.
- * OUT:
- *     0       : success
- *     others  : fail
- */
-static int
-key_sendall(msg, len)
-       struct sadb_msg *msg;
-       u_int len;
-{
-       struct secreg *reg;
-       int error = 0;
-
-       /* sanity check */
-       if (msg == NULL)
-               panic("key_sendall: NULL pointer is passed.\n");
-
-       /* search table registerd socket to send a message. */
-       LIST_FOREACH(reg, &regtree[msg->sadb_msg_satype], chain) {
-               error = key_sendup(reg->so, msg, len, KEY_SENDUP_ONE);
-               if (error != 0) {
-#if IPSEC_DEBUG
-                       if (error == ENOBUFS)
-                               printf("key_sendall: No more memory.\n");
-                       else {
-                               printf("key_sendall: key_sendup returned %d\n",
-                                       error);
-                       }
-#endif
-                       KFREE(msg);
-                       return error;
-               }
-       }
-
-       KFREE(msg);
-       return 0;
-}
+static int (*key_typesw[])(struct socket *, struct mbuf *,
+               const struct sadb_msghdr *) = {
+       NULL,           /* SADB_RESERVED */
+       key_getspi,     /* SADB_GETSPI */
+       key_update,     /* SADB_UPDATE */
+       key_add,        /* SADB_ADD */
+       key_delete,     /* SADB_DELETE */
+       key_get,        /* SADB_GET */
+       key_acquire2,   /* SADB_ACQUIRE */
+       key_register,   /* SADB_REGISTER */
+       NULL,           /* SADB_EXPIRE */
+       key_flush,      /* SADB_FLUSH */
+       key_dump,       /* SADB_DUMP */
+       key_promisc,    /* SADB_X_PROMISC */
+       NULL,           /* SADB_X_PCHANGE */
+       key_spdadd,     /* SADB_X_SPDUPDATE */
+       key_spdadd,     /* SADB_X_SPDADD */
+       key_spddelete,  /* SADB_X_SPDDELETE */
+       key_spdget,     /* SADB_X_SPDGET */
+       NULL,           /* SADB_X_SPDACQUIRE */
+       key_spddump,    /* SADB_X_SPDDUMP */
+       key_spdflush,   /* SADB_X_SPDFLUSH */
+       key_spdadd,     /* SADB_X_SPDSETIDX */
+       NULL,           /* SADB_X_SPDEXPIRE */
+       key_spddelete2, /* SADB_X_SPDDELETE2 */
+};
 
 /*
  * parse sadb_msg buffer to process PFKEYv2,
@@ -6145,57 +7017,101 @@ key_sendall(msg, len)
  *    length for buffer to send to user process.
  */
 int
-key_parse(msgp, so, targetp)
-       struct sadb_msg **msgp;
+key_parse(m, so)
+       struct mbuf *m;
        struct socket *so;
-       int *targetp;
 {
-       struct sadb_msg *msg = *msgp, *newmsg = NULL;
-       caddr_t mhp[SADB_EXT_MAX + 1];
+       struct sadb_msg *msg;
+       struct sadb_msghdr mh;
        u_int orglen;
        int error;
+       int target;
+
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
 
        /* sanity check */
-       if (msg == NULL || so == NULL)
+       if (m == NULL || so == NULL)
                panic("key_parse: NULL pointer is passed.\n");
 
+#if 0  /*kdebug_sadb assumes msg in linear buffer*/
        KEYDEBUG(KEYDEBUG_KEY_DUMP,
-               printf("key_parse: passed sadb_msg\n");
+               ipseclog((LOG_DEBUG, "key_parse: passed sadb_msg\n"));
                kdebug_sadb(msg));
+#endif
 
+       if (m->m_len < sizeof(struct sadb_msg)) {
+               m = m_pullup(m, sizeof(struct sadb_msg));
+               if (!m)
+                       return ENOBUFS;
+       }
+       msg = mtod(m, struct sadb_msg *);
        orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
+       target = KEY_SENDUP_ONE;
 
-       if (targetp)
-               *targetp = KEY_SENDUP_ONE;
+       if ((m->m_flags & M_PKTHDR) == 0 ||
+           m->m_pkthdr.len != m->m_pkthdr.len) {
+               ipseclog((LOG_DEBUG, "key_parse: invalid message length.\n"));
+               pfkeystat.out_invlen++;
+               error = EINVAL;
+               goto senderror;
+       }
 
-       /* check version */
        if (msg->sadb_msg_version != PF_KEY_V2) {
-#if IPSEC_DEBUG
-               printf("key_parse: PF_KEY version %u is mismatched.\n",
-                   msg->sadb_msg_version);
-#endif
+               ipseclog((LOG_DEBUG,
+                   "key_parse: PF_KEY version %u is mismatched.\n",
+                   msg->sadb_msg_version));
                pfkeystat.out_invver++;
-               msg->sadb_msg_errno = EINVAL;
-               return orglen;
+               error = EINVAL;
+               goto senderror;
        }
 
-       /* check type */
        if (msg->sadb_msg_type > SADB_MAX) {
-#if IPSEC_DEBUG
-               printf("key_parse: invalid type %u is passed.\n",
-                   msg->sadb_msg_type);
-#endif
-               msg->sadb_msg_errno = EINVAL;
+               ipseclog((LOG_DEBUG, "key_parse: invalid type %u is passed.\n",
+                   msg->sadb_msg_type));
                pfkeystat.out_invmsgtype++;
-               return orglen;
+               error = EINVAL;
+               goto senderror;
+       }
+
+       /* for old-fashioned code - should be nuked */
+       if (m->m_pkthdr.len > MCLBYTES) {
+               m_freem(m);
+               return ENOBUFS;
+       }
+       if (m->m_next) {
+               struct mbuf *n;
+
+               MGETHDR(n, M_DONTWAIT, MT_DATA);
+               if (n && m->m_pkthdr.len > MHLEN) {
+                       MCLGET(n, M_DONTWAIT);
+                       if ((n->m_flags & M_EXT) == 0) {
+                               m_free(n);
+                               n = NULL;
+                       }
+               }
+               if (!n) {
+                       m_freem(m);
+                       return ENOBUFS;
+               }
+               m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
+               n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
+               n->m_next = NULL;
+               m_freem(m);
+               m = n;
        }
 
-       /* align message. */
-       if (key_align(msg, mhp) != 0) {
-               msg->sadb_msg_errno = EINVAL;
-               return orglen;
+       /* align the mbuf chain so that extensions are in contiguous region. */
+       error = key_align(m, &mh);
+       if (error)
+               return error;
+
+       if (m->m_next) {        /*XXX*/
+               m_freem(m);
+               return ENOBUFS;
        }
 
+       msg = mh.msg;
+
        /* check SA type */
        switch (msg->sadb_msg_satype) {
        case SADB_SATYPE_UNSPEC:
@@ -6207,21 +7123,16 @@ key_parse(msgp, so, targetp)
                case SADB_GET:
                case SADB_ACQUIRE:
                case SADB_EXPIRE:
-#if IPSEC_DEBUG
-                       printf("key_parse: must specify satype "
-                               "when msg type=%u.\n",
-                               msg->sadb_msg_type);
-#endif
-                       msg->sadb_msg_errno = EINVAL;
+                       ipseclog((LOG_DEBUG, "key_parse: must specify satype "
+                           "when msg type=%u.\n", msg->sadb_msg_type));
                        pfkeystat.out_invsatype++;
-                       return orglen;
+                       error = EINVAL;
+                       goto senderror;
                }
                break;
        case SADB_SATYPE_AH:
        case SADB_SATYPE_ESP:
-#if 1 /*nonstandard*/
        case SADB_X_SATYPE_IPCOMP:
-#endif
                switch (msg->sadb_msg_type) {
                case SADB_X_SPDADD:
                case SADB_X_SPDDELETE:
@@ -6231,94 +7142,113 @@ key_parse(msgp, so, targetp)
                case SADB_X_SPDSETIDX:
                case SADB_X_SPDUPDATE:
                case SADB_X_SPDDELETE2:
-#if IPSEC_DEBUG
-                       printf("key_parse: illegal satype=%u\n",
-                           msg->sadb_msg_type);
-#endif
-                       msg->sadb_msg_errno = EINVAL;
+                       ipseclog((LOG_DEBUG, "key_parse: illegal satype=%u\n",
+                           msg->sadb_msg_type));
                        pfkeystat.out_invsatype++;
-                       return orglen;
+                       error = EINVAL;
+                       goto senderror;
                }
                break;
        case SADB_SATYPE_RSVP:
        case SADB_SATYPE_OSPFV2:
        case SADB_SATYPE_RIPV2:
        case SADB_SATYPE_MIP:
-#if IPSEC_DEBUG
-               printf("key_parse: type %u isn't supported.\n",
-                   msg->sadb_msg_satype);
-#endif
-               msg->sadb_msg_errno = EOPNOTSUPP;
+               ipseclog((LOG_DEBUG, "key_parse: type %u isn't supported.\n",
+                   msg->sadb_msg_satype));
                pfkeystat.out_invsatype++;
-               return orglen;
-       case 1: /* XXX: What does it do ? */
+               error = EOPNOTSUPP;
+               goto senderror;
+       case 1: /* XXX: What does it do? */
                if (msg->sadb_msg_type == SADB_X_PROMISC)
                        break;
                /*FALLTHROUGH*/
        default:
-#if IPSEC_DEBUG
-               printf("key_parse: invalid type %u is passed.\n",
-                   msg->sadb_msg_satype);
-#endif
-               msg->sadb_msg_errno = EINVAL;
+               ipseclog((LOG_DEBUG, "key_parse: invalid type %u is passed.\n",
+                   msg->sadb_msg_satype));
                pfkeystat.out_invsatype++;
-               return orglen;
+               error = EINVAL;
+               goto senderror;
        }
 
        /* check field of upper layer protocol and address family */
-       if (mhp[SADB_EXT_ADDRESS_SRC] != NULL
-        && mhp[SADB_EXT_ADDRESS_DST] != NULL) {
+       if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
+        && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
                struct sadb_address *src0, *dst0;
-               u_int prefix;
+               u_int plen;
 
-               src0 = (struct sadb_address *)(mhp[SADB_EXT_ADDRESS_SRC]);
-               dst0 = (struct sadb_address *)(mhp[SADB_EXT_ADDRESS_DST]);
+               src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
+               dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
 
                /* check upper layer protocol */
                if (src0->sadb_address_proto != dst0->sadb_address_proto) {
-#if IPSEC_DEBUG
-                       printf("key_parse: upper layer protocol mismatched.\n");
-#endif
-                       msg->sadb_msg_errno = EINVAL;
+                       ipseclog((LOG_DEBUG, "key_parse: upper layer protocol mismatched.\n"));
                        pfkeystat.out_invaddr++;
-                       return orglen;
+                       error = EINVAL;
+                       goto senderror;
                }
 
                /* check family */
-               if (PFKEY_ADDR_SADDR(src0)->sa_family
-                != PFKEY_ADDR_SADDR(dst0)->sa_family) {
-#if IPSEC_DEBUG
-                       printf("key_parse: address family mismatched.\n");
-#endif
-                       msg->sadb_msg_errno = EINVAL;
+               if (PFKEY_ADDR_SADDR(src0)->sa_family !=
+                   PFKEY_ADDR_SADDR(dst0)->sa_family) {
+                       ipseclog((LOG_DEBUG, "key_parse: address family mismatched.\n"));
                        pfkeystat.out_invaddr++;
-                       return orglen;
+                       error = EINVAL;
+                       goto senderror;
+               }
+               if (PFKEY_ADDR_SADDR(src0)->sa_len !=
+                   PFKEY_ADDR_SADDR(dst0)->sa_len) {
+                       ipseclog((LOG_DEBUG,
+                           "key_parse: address struct size mismatched.\n"));
+                       pfkeystat.out_invaddr++;
+                       error = EINVAL;
+                       goto senderror;
                }
 
-               prefix = _INALENBYAF(PFKEY_ADDR_SADDR(src0)->sa_family) << 3;
-
-               /* check max prefixlen */
-               if (prefix < src0->sadb_address_prefixlen
-                || prefix < dst0->sadb_address_prefixlen) {
-#if IPSEC_DEBUG
-                       printf("key_parse: illegal prefixlen.\n");
-#endif
-                       msg->sadb_msg_errno = EINVAL;
+               switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
+               case AF_INET:
+                       if (PFKEY_ADDR_SADDR(src0)->sa_len !=
+                           sizeof(struct sockaddr_in)) {
+                               pfkeystat.out_invaddr++;
+                               error = EINVAL;
+                               goto senderror;
+                       }
+                       break;
+               case AF_INET6:
+                       if (PFKEY_ADDR_SADDR(src0)->sa_len !=
+                           sizeof(struct sockaddr_in6)) {
+                               pfkeystat.out_invaddr++;
+                               error = EINVAL;
+                               goto senderror;
+                       }
+                       break;
+               default:
+                       ipseclog((LOG_DEBUG,
+                           "key_parse: unsupported address family.\n"));
                        pfkeystat.out_invaddr++;
-                       return orglen;
+                       error = EAFNOSUPPORT;
+                       goto senderror;
                }
 
                switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
                case AF_INET:
+                       plen = sizeof(struct in_addr) << 3;
+                       break;
                case AF_INET6:
+                       plen = sizeof(struct in6_addr) << 3;
                        break;
                default:
-#if IPSEC_DEBUG
-                       printf("key_parse: invalid address family.\n");
-#endif
-                       msg->sadb_msg_errno = EINVAL;
+                       plen = 0;       /*fool gcc*/
+                       break;
+               }
+
+               /* check max prefix length */
+               if (src0->sadb_address_prefixlen > plen ||
+                   dst0->sadb_address_prefixlen > plen) {
+                       ipseclog((LOG_DEBUG,
+                           "key_parse: illegal prefixlen.\n"));
                        pfkeystat.out_invaddr++;
-                       return orglen;
+                       error = EINVAL;
+                       goto senderror;
                }
 
                /*
@@ -6327,221 +7257,85 @@ key_parse(msgp, so, targetp)
                 */
        }
 
-       switch (msg->sadb_msg_type) {
-       case SADB_GETSPI:
-               if ((newmsg = key_getspi(mhp)) == NULL)
-                       return orglen;
-               if (targetp)
-                       *targetp = KEY_SENDUP_ALL;
-               break;
-
-       case SADB_UPDATE:
-               if ((newmsg = key_update(mhp)) == NULL)
-                       return orglen;
-               if (targetp)
-                       *targetp = KEY_SENDUP_ALL;
-               break;
-
-       case SADB_ADD:
-               if ((newmsg = key_add(mhp)) == NULL)
-                       return orglen;
-               if (targetp)
-                       *targetp = KEY_SENDUP_ALL;
-               break;
-
-       case SADB_DELETE:
-               if ((newmsg = key_delete(mhp)) == NULL)
-                       return orglen;
-               if (targetp)
-                       *targetp = KEY_SENDUP_ALL;
-               break;
-
-       case SADB_GET:
-               if ((newmsg = key_get(mhp)) == NULL)
-                       return orglen;
-               break;
-
-       case SADB_ACQUIRE:
-               if ((newmsg = key_acquire2(mhp)) == NULL)
-                       return orglen;
-
-               if (newmsg == (struct sadb_msg *)~0) {
-                       /*
-                        * It's not need to reply because of the message
-                        * that was reporting an error occured from the KMd.
-                        */
-                       KFREE(msg);
-                       return 0;
-               }
-               break;
-
-       case SADB_REGISTER:
-               if ((newmsg = key_register(mhp, so)) == NULL)
-                       return orglen;
-#if 1
-               if (targetp)
-                       *targetp = KEY_SENDUP_REGISTERED;
-#else
-               /* send result to all registered sockets */
-               KFREE(msg);
-               key_sendall(newmsg, PFKEY_UNUNIT64(newmsg->sadb_msg_len));
-               return 0;
-#endif
-               break;
-
-       case SADB_EXPIRE:
-#if IPSEC_DEBUG
-               printf("key_parse: why is SADB_EXPIRE received ?\n");
-#endif
-               msg->sadb_msg_errno = EINVAL;
-               if (targetp)
-                       *targetp = KEY_SENDUP_ALL;
-               pfkeystat.out_invmsgtype++;
-               return orglen;
-
-       case SADB_FLUSH:
-               if ((newmsg = key_flush(mhp)) == NULL)
-                       return orglen;
-               if (targetp)
-                       *targetp = KEY_SENDUP_ALL;
-               break;
-
-       case SADB_DUMP:
-               /* key_dump will call key_sendup() on her own */
-               error = key_dump(mhp, so, KEY_SENDUP_ONE);
-               if (error) {
-                       msg->sadb_msg_errno = error;
-                       return orglen;
-               } else {
-                       KFREE(msg);
-                       return 0;
-               }
-               break;
-
-       case SADB_X_PROMISC:
-               /* everything is handled in key_promisc() */
-               key_promisc(mhp, so);
-               KFREE(msg);
-               return 0;       /*nothing to reply*/
-
-       case SADB_X_PCHANGE:
-#if IPSEC_DEBUG
-               printf("key_parse: SADB_X_PCHANGE isn't supported.\n");
-#endif
-               msg->sadb_msg_errno = EINVAL;
+       if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
+           key_typesw[msg->sadb_msg_type] == NULL) {
                pfkeystat.out_invmsgtype++;
-               return orglen;
-#if 0
-               if (targetp)
-                       *targetp = KEY_SENDUP_REGISTERED;
-#endif
+               error = EINVAL;
+               goto senderror;
+       }
 
-       case SADB_X_SPDADD:
-       case SADB_X_SPDSETIDX:
-       case SADB_X_SPDUPDATE:
-               if ((newmsg = key_spdadd(mhp)) == NULL)
-                       return orglen;
-               if (targetp)
-                       *targetp = KEY_SENDUP_ALL;
-               break;
-
-       case SADB_X_SPDDELETE:
-               if ((newmsg = key_spddelete(mhp)) == NULL)
-                       return orglen;
-               if (targetp)
-                       *targetp = KEY_SENDUP_ALL;
-               break;
-
-       case SADB_X_SPDDELETE2:
-               if ((newmsg = key_spddelete2(mhp)) == NULL)
-                       return orglen;
-               if (targetp)
-                       *targetp = KEY_SENDUP_ALL;
-               break;
-
-       case SADB_X_SPDGET:
-               /* key_spdget will call key_sendup() on her own */
-               error = key_spdget(mhp, so, KEY_SENDUP_ONE);
-               if (error) {
-                       msg->sadb_msg_errno = error;
-                       return orglen;
-               } else {
-                       KFREE(msg);
-                       return 0;
-               }
-               break;
+       return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
 
-       case SADB_X_SPDDUMP:
-               /* key_spddump will call key_sendup() on her own */
-               error = key_spddump(mhp, so, KEY_SENDUP_ONE);
-               if (error) {
-                       msg->sadb_msg_errno = error;
-                       return orglen;
-               } else {
-                       KFREE(msg);
-                       return 0;
-               }
-               break;
+senderror:
+       msg->sadb_msg_errno = error;
+       return key_sendup_mbuf(so, m, target);
+}
 
-       case SADB_X_SPDFLUSH:
-               if ((newmsg = key_spdflush(mhp)) == NULL)
-                       return orglen;
-               if (targetp)
-                       *targetp = KEY_SENDUP_ALL;
-               break;
+static int
+key_senderror(so, m, code)
+       struct socket *so;
+       struct mbuf *m;
+       int code;
+{
+       struct sadb_msg *msg;
 
-       default:
-               msg->sadb_msg_errno = EOPNOTSUPP;
-               return orglen;
-       }
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
 
-       /* switch from old sadb_msg to new one if success. */
-       KFREE(msg);
-       *msgp = newmsg;
+       if (m->m_len < sizeof(struct sadb_msg))
+               panic("invalid mbuf passed to key_senderror");
 
-       return PFKEY_UNUNIT64((*msgp)->sadb_msg_len);
+       msg = mtod(m, struct sadb_msg *);
+       msg->sadb_msg_errno = code;
+       return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
 }
 
 /*
  * set the pointer to each header into message buffer.
- * IN: msg: pointer to message buffer.
- *     mhp: pointer to the buffer allocated like below:
- *             caddr_t mhp[SADB_EXT_MAX + 1];
- * OUT: 0:
- *      EINVAL:
+ * m will be freed on error.
+ * XXX larger-than-MCLBYTES extension?
  */
 static int
-key_align(msg, mhp)
-       struct sadb_msg *msg;
-       caddr_t *mhp;
+key_align(m, mhp)
+       struct mbuf *m;
+       struct sadb_msghdr *mhp;
 {
+       struct mbuf *n;
        struct sadb_ext *ext;
-       int tlen, extlen;
-       int i;
+       size_t off, end;
+       int extlen;
+       int toff;
 
        /* sanity check */
-       if (msg == NULL || mhp == NULL)
+       if (m == NULL || mhp == NULL)
                panic("key_align: NULL pointer is passed.\n");
+       if (m->m_len < sizeof(struct sadb_msg))
+               panic("invalid mbuf passed to key_align");
 
        /* initialize */
-       for (i = 0; i < SADB_EXT_MAX + 1; i++)
-               mhp[i] = NULL;
+       bzero(mhp, sizeof(*mhp));
 
-       mhp[0] = (caddr_t)msg;
+       mhp->msg = mtod(m, struct sadb_msg *);
+       mhp->ext[0] = (struct sadb_ext *)mhp->msg;      /*XXX backward compat */
 
-       tlen = PFKEY_UNUNIT64(msg->sadb_msg_len) - sizeof(struct sadb_msg);
-       ext = (struct sadb_ext *)((caddr_t)msg + sizeof(struct sadb_msg));
+       end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
+       extlen = end;   /*just in case extlen is not updated*/
+       for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
+               n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
+               if (!n) {
+                       /* m is already freed */
+                       return ENOBUFS;
+               }
+               ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
 
-       while (tlen > 0) {
                /* set pointer */
                switch (ext->sadb_ext_type) {
                case SADB_EXT_SA:
-               case SADB_EXT_LIFETIME_CURRENT:
-               case SADB_EXT_LIFETIME_HARD:
-               case SADB_EXT_LIFETIME_SOFT:
                case SADB_EXT_ADDRESS_SRC:
                case SADB_EXT_ADDRESS_DST:
                case SADB_EXT_ADDRESS_PROXY:
+               case SADB_EXT_LIFETIME_CURRENT:
+               case SADB_EXT_LIFETIME_HARD:
+               case SADB_EXT_LIFETIME_SOFT:
                case SADB_EXT_KEY_AUTH:
                case SADB_EXT_KEY_ENCRYPT:
                case SADB_EXT_IDENTITY_SRC:
@@ -6552,41 +7346,120 @@ key_align(msg, mhp)
                case SADB_EXT_SUPPORTED_ENCRYPT:
                case SADB_EXT_SPIRANGE:
                case SADB_X_EXT_POLICY:
+               case SADB_X_EXT_SA2:
                        /* duplicate check */
                        /*
                         * XXX Are there duplication payloads of either
                         * KEY_AUTH or KEY_ENCRYPT ?
                         */
-                       if (mhp[ext->sadb_ext_type] != NULL) {
-#if IPSEC_DEBUG
-                               printf("key_align: duplicate ext_type %u "
-                                       "is passed.\n",
-                                       ext->sadb_ext_type);
-#endif
+                       if (mhp->ext[ext->sadb_ext_type] != NULL) {
+                               ipseclog((LOG_DEBUG,
+                                   "key_align: duplicate ext_type %u "
+                                   "is passed.\n", ext->sadb_ext_type));
+                               m_freem(m);
                                pfkeystat.out_dupext++;
                                return EINVAL;
                        }
-                       mhp[ext->sadb_ext_type] = (caddr_t)ext;
                        break;
                default:
-#if IPSEC_DEBUG
-                       printf("key_align: invalid ext_type %u is passed.\n",
-                               ext->sadb_ext_type);
-#endif
+                       ipseclog((LOG_DEBUG,
+                           "key_align: invalid ext_type %u is passed.\n",
+                           ext->sadb_ext_type));
+                       m_freem(m);
                        pfkeystat.out_invexttype++;
                        return EINVAL;
                }
 
                extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
-               tlen -= extlen;
-               ext = (struct sadb_ext *)((caddr_t)ext + extlen);
+
+               if (key_validate_ext(ext, extlen)) {
+                       m_freem(m);
+                       pfkeystat.out_invlen++;
+                       return EINVAL;
+               }
+
+               n = m_pulldown(m, off, extlen, &toff);
+               if (!n) {
+                       /* m is already freed */
+                       return ENOBUFS;
+               }
+               ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
+
+               mhp->ext[ext->sadb_ext_type] = ext;
+               mhp->extoff[ext->sadb_ext_type] = off;
+               mhp->extlen[ext->sadb_ext_type] = extlen;
+       }
+
+       if (off != end) {
+               m_freem(m);
+               pfkeystat.out_invlen++;
+               return EINVAL;
+       }
+
+       return 0;
+}
+
+static int
+key_validate_ext(ext, len)
+       const struct sadb_ext *ext;
+       int len;
+{
+       struct sockaddr *sa;
+       enum { NONE, ADDR } checktype = NONE;
+       int baselen;
+       const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
+
+       if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
+               return EINVAL;
+
+       /* if it does not match minimum/maximum length, bail */
+       if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
+           ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
+               return EINVAL;
+       if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
+               return EINVAL;
+       if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
+               return EINVAL;
+
+       /* more checks based on sadb_ext_type XXX need more */
+       switch (ext->sadb_ext_type) {
+       case SADB_EXT_ADDRESS_SRC:
+       case SADB_EXT_ADDRESS_DST:
+       case SADB_EXT_ADDRESS_PROXY:
+               baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
+               checktype = ADDR;
+               break;
+       case SADB_EXT_IDENTITY_SRC:
+       case SADB_EXT_IDENTITY_DST:
+               if (((struct sadb_ident *)ext)->sadb_ident_type ==
+                   SADB_X_IDENTTYPE_ADDR) {
+                       baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
+                       checktype = ADDR;
+               } else
+                       checktype = NONE;
+               break;
+       default:
+               checktype = NONE;
+               break;
+       }
+
+       switch (checktype) {
+       case NONE:
+               break;
+       case ADDR:
+               sa = (struct sockaddr *)((caddr_t)ext + baselen);
+               if (len < baselen + sal)
+                       return EINVAL;
+               if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
+                       return EINVAL;
+               break;
        }
 
        return 0;
 }
 
 void
-key_init()
+key_domain_init()
 {
        int i;
 
@@ -6608,8 +7481,10 @@ key_init()
        LIST_INIT(&spacqtree);
 
        /* system default */
+#if INET
        ip4_def_policy.policy = IPSEC_POLICY_NONE;
        ip4_def_policy.refcnt++;        /*never reclaim this*/
+#endif
 #if INET6
        ip6_def_policy.policy = IPSEC_POLICY_NONE;
        ip6_def_policy.refcnt++;        /*never reclaim this*/
@@ -6622,7 +7497,9 @@ key_init()
        /* initialize key statistics */
        keystat.getspi_count = 1;
 
+#ifndef __APPLE__
        printf("IPsec: Initialized Security Association Processing.\n");
+#endif
 
        return;
 }
@@ -6642,6 +7519,8 @@ key_checktunnelsanity(sav, family, src, dst)
        caddr_t src;
        caddr_t dst;
 {
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        /* sanity check */
        if (sav->sah == NULL)
                panic("sav->sah == NULL at key_checktunnelsanity");
@@ -6652,9 +7531,7 @@ key_checktunnelsanity(sav, family, src, dst)
 }
 
 #if 0
-#ifdef __FreeBSD__
 #define hostnamelen    strlen(hostname)
-#endif
 
 /*
  * Get FQDN for the host.
@@ -6723,6 +7600,8 @@ key_sa_recordxfer(sav, m)
        struct secasvar *sav;
        struct mbuf *m;
 {
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        if (!sav)
                panic("key_sa_recordxfer called with sav == NULL");
        if (!m)
@@ -6774,14 +7653,16 @@ key_sa_routechange(dst)
        struct secashead *sah;
        struct route *ro;
 
+       lck_mtx_lock(sadb_mutex);
        LIST_FOREACH(sah, &sahtree, chain) {
                ro = &sah->sa_route;
                if (ro->ro_rt && dst->sa_len == ro->ro_dst.sa_len
                 && bcmp(dst, &ro->ro_dst, dst->sa_len) == 0) {
-                       RTFREE(ro->ro_rt);
+                       rtfree(ro->ro_rt);
                        ro->ro_rt = (struct rtentry *)NULL;
                }
        }
+       lck_mtx_unlock(sadb_mutex);
 
        return;
 }
@@ -6791,6 +7672,8 @@ key_sa_chgstate(sav, state)
        struct secasvar *sav;
        u_int8_t state;
 {
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
+
        if (sav == NULL)
                panic("key_sa_chgstate called with sav == NULL");
 
@@ -6804,96 +7687,53 @@ key_sa_chgstate(sav, state)
        LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
 }
 
-/* returns NULL on error, m0 will be left unchanged */
-static caddr_t
-key_appendmbuf(m0, len)
-       struct mbuf *m0;
-       int len;
+void
+key_sa_stir_iv(sav)
+       struct secasvar *sav;
 {
-       caddr_t p;
-       struct mbuf *m;
-       struct mbuf *n;
-
-       if (!m0 || (m0->m_flags & M_PKTHDR) == 0)
-               return NULL;    /*EINVAL*/
-       if (len > MCLBYTES)
-               return NULL;    /*EINVAL*/
-
-       for (m = m0; m && m->m_next; m = m->m_next)
-               ;
-       if (len <= M_TRAILINGSPACE(m)) {
-               p = mtod(m, caddr_t) + m->m_len;
-               m->m_len += len;
-               m0->m_pkthdr.len += len;
 
-               return p;
-       }
-       MGET(n, M_DONTWAIT, m->m_type);
-       if (n != NULL) {
-               MCLGET(n, M_DONTWAIT);
-               if ((n->m_flags & M_EXT) == 0) {
-                       m_freem(n);
-                       n = NULL;
-               }
-       }
-       if (n == NULL)
-               return NULL;    /*ENOBUFS*/
-       n->m_next = NULL;
-       m->m_next = n;
-       n->m_len = len;
-       m0->m_pkthdr.len += len;
+       lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
 
-       return mtod(n, caddr_t);
+       if (!sav->iv)
+               panic("key_sa_stir_iv called with sav == NULL");
+       key_randomfill(sav->iv, sav->ivlen);
 }
 
-#ifdef __bsdi__
-#include <sys/user.h>
-#include <sys/sysctl.h>
-
-int *key_sysvars[] = KEYCTL_VARS;
-
-int
-key_sysctl(name, namelen, oldp, oldlenp, newp, newlen)
-       int *name;
-       u_int namelen;
-       void *oldp;
-       size_t *oldlenp;
-       void *newp;
-       size_t newlen;
+/* XXX too much? */
+static struct mbuf *
+key_alloc_mbuf(l)
+       int l;
 {
-       if (name[0] >= KEYCTL_MAXID)
-               return EOPNOTSUPP;
-       switch (name[0]) {
-       default:
-               return sysctl_int_arr(key_sysvars, name, namelen,
-                       oldp, oldlenp, newp, newlen);
-       }
-}
-#endif /*__bsdi__*/
+       struct mbuf *m = NULL, *n;
+       int len, t;
+
+       len = l;
+       while (len > 0) {
+               MGET(n, M_DONTWAIT, MT_DATA);
+               if (n && len > MLEN)
+                       MCLGET(n, M_DONTWAIT);
+               if (!n) {
+                       m_freem(m);
+                       return NULL;
+               }
 
-#ifdef __NetBSD__
-#include <vm/vm.h>
-#include <sys/sysctl.h>
+               n->m_next = NULL;
+               n->m_len = 0;
+               n->m_len = M_TRAILINGSPACE(n);
+               /* use the bottom of mbuf, hoping we can prepend afterwards */
+               if (n->m_len > len) {
+                       t = (n->m_len - len) & ~(sizeof(long) - 1);
+                       n->m_data += t;
+                       n->m_len = len;
+               }
 
-static int *key_sysvars[] = KEYCTL_VARS;
+               len -= n->m_len;
 
-int
-key_sysctl(name, namelen, oldp, oldlenp, newp, newlen)
-       int *name;
-       u_int namelen;
-       void *oldp;
-       size_t *oldlenp;
-       void *newp;
-       size_t newlen;
-{
-       if (name[0] >= KEYCTL_MAXID)
-               return EOPNOTSUPP;
-       if (!key_sysvars[name[0]])
-               return EOPNOTSUPP;
-       switch (name[0]) {
-       default:
-               return sysctl_int(oldp, oldlenp, newp, newlen,
-                       key_sysvars[name[0]]);
+               if (m)
+                       m_cat(m, n);
+               else
+                       m = n;
        }
+
+       return m;
 }
-#endif /*__NetBSD__*/