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