Home | History | Annotate | Line # | Download | only in netinet
ip_encap.c revision 1.39.30.8
      1 /*	$NetBSD: ip_encap.c,v 1.39.30.8 2017/08/28 17:53:12 skrll Exp $	*/
      2 /*	$KAME: ip_encap.c,v 1.73 2001/10/02 08:30:58 itojun Exp $	*/
      3 
      4 /*
      5  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
      6  * All rights reserved.
      7  *
      8  * Redistribution and use in source and binary forms, with or without
      9  * modification, are permitted provided that the following conditions
     10  * are met:
     11  * 1. Redistributions of source code must retain the above copyright
     12  *    notice, this list of conditions and the following disclaimer.
     13  * 2. Redistributions in binary form must reproduce the above copyright
     14  *    notice, this list of conditions and the following disclaimer in the
     15  *    documentation and/or other materials provided with the distribution.
     16  * 3. Neither the name of the project nor the names of its contributors
     17  *    may be used to endorse or promote products derived from this software
     18  *    without specific prior written permission.
     19  *
     20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
     21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
     24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     30  * SUCH DAMAGE.
     31  */
     32 /*
     33  * My grandfather said that there's a devil inside tunnelling technology...
     34  *
     35  * We have surprisingly many protocols that want packets with IP protocol
     36  * #4 or #41.  Here's a list of protocols that want protocol #41:
     37  *	RFC1933 configured tunnel
     38  *	RFC1933 automatic tunnel
     39  *	RFC2401 IPsec tunnel
     40  *	RFC2473 IPv6 generic packet tunnelling
     41  *	RFC2529 6over4 tunnel
     42  *	RFC3056 6to4 tunnel
     43  *	isatap tunnel
     44  *	mobile-ip6 (uses RFC2473)
     45  * Here's a list of protocol that want protocol #4:
     46  *	RFC1853 IPv4-in-IPv4 tunnelling
     47  *	RFC2003 IPv4 encapsulation within IPv4
     48  *	RFC2344 reverse tunnelling for mobile-ip4
     49  *	RFC2401 IPsec tunnel
     50  * Well, what can I say.  They impose different en/decapsulation mechanism
     51  * from each other, so they need separate protocol handler.  The only one
     52  * we can easily determine by protocol # is IPsec, which always has
     53  * AH/ESP/IPComp header right after outer IP header.
     54  *
     55  * So, clearly good old protosw does not work for protocol #4 and #41.
     56  * The code will let you match protocol via src/dst address pair.
     57  */
     58 /* XXX is M_NETADDR correct? */
     59 
     60 /*
     61  * With USE_RADIX the code will use radix table for tunnel lookup, for
     62  * tunnels registered with encap_attach() with a addr/mask pair.
     63  * Faster on machines with thousands of tunnel registerations (= interfaces).
     64  *
     65  * The code assumes that radix table code can handle non-continuous netmask,
     66  * as it will pass radix table memory region with (src + dst) sockaddr pair.
     67  */
     68 #define USE_RADIX
     69 
     70 #include <sys/cdefs.h>
     71 __KERNEL_RCSID(0, "$NetBSD: ip_encap.c,v 1.39.30.8 2017/08/28 17:53:12 skrll Exp $");
     72 
     73 #ifdef _KERNEL_OPT
     74 #include "opt_mrouting.h"
     75 #include "opt_inet.h"
     76 #include "opt_net_mpsafe.h"
     77 #endif
     78 
     79 #include <sys/param.h>
     80 #include <sys/systm.h>
     81 #include <sys/socket.h>
     82 #include <sys/sockio.h>
     83 #include <sys/mbuf.h>
     84 #include <sys/errno.h>
     85 #include <sys/queue.h>
     86 #include <sys/kmem.h>
     87 #include <sys/mutex.h>
     88 #include <sys/condvar.h>
     89 #include <sys/psref.h>
     90 #include <sys/pslist.h>
     91 
     92 #include <net/if.h>
     93 
     94 #include <netinet/in.h>
     95 #include <netinet/in_systm.h>
     96 #include <netinet/ip.h>
     97 #include <netinet/ip_var.h>
     98 #include <netinet/ip_encap.h>
     99 #ifdef MROUTING
    100 #include <netinet/ip_mroute.h>
    101 #endif /* MROUTING */
    102 
    103 #ifdef INET6
    104 #include <netinet/ip6.h>
    105 #include <netinet6/ip6_var.h>
    106 #include <netinet6/ip6protosw.h> /* for struct ip6ctlparam */
    107 #include <netinet6/in6_var.h>
    108 #include <netinet6/in6_pcb.h>
    109 #include <netinet/icmp6.h>
    110 #endif
    111 
    112 #include <net/net_osdep.h>
    113 
    114 #ifdef NET_MPSAFE
    115 #define ENCAP_MPSAFE	1
    116 #endif
    117 
    118 enum direction { INBOUND, OUTBOUND };
    119 
    120 #ifdef INET
    121 static struct encaptab *encap4_lookup(struct mbuf *, int, int, enum direction,
    122     struct psref *);
    123 #endif
    124 #ifdef INET6
    125 static struct encaptab *encap6_lookup(struct mbuf *, int, int, enum direction,
    126     struct psref *);
    127 #endif
    128 static int encap_add(struct encaptab *);
    129 static int encap_remove(struct encaptab *);
    130 static int encap_afcheck(int, const struct sockaddr *, const struct sockaddr *);
    131 #ifdef USE_RADIX
    132 static struct radix_node_head *encap_rnh(int);
    133 static int mask_matchlen(const struct sockaddr *);
    134 #else
    135 static int mask_match(const struct encaptab *, const struct sockaddr *,
    136 		const struct sockaddr *);
    137 #endif
    138 static void encap_fillarg(struct mbuf *, const struct encaptab *);
    139 
    140 /*
    141  * In encap[46]_lookup(), ep->func can sleep(e.g. rtalloc1) while walking
    142  * encap_table. So, it cannot use pserialize_read_enter()
    143  */
    144 static struct {
    145 	struct pslist_head	list;
    146 	pserialize_t		psz;
    147 	struct psref_class	*elem_class; /* for the element of et_list */
    148 } encaptab  __cacheline_aligned = {
    149 	.list = PSLIST_INITIALIZER,
    150 };
    151 #define encap_table encaptab.list
    152 
    153 static struct {
    154 	kmutex_t	lock;
    155 	kcondvar_t	cv;
    156 	struct lwp	*busy;
    157 } encap_whole __cacheline_aligned;
    158 
    159 #ifdef USE_RADIX
    160 struct radix_node_head *encap_head[2];	/* 0 for AF_INET, 1 for AF_INET6 */
    161 static bool encap_head_updating = false;
    162 #endif
    163 
    164 static bool encap_initialized = false;
    165 /*
    166  * must be done before other encap interfaces initialization.
    167  */
    168 void
    169 encapinit(void)
    170 {
    171 
    172 	if (encap_initialized)
    173 		return;
    174 
    175 	encaptab.psz = pserialize_create();
    176 	encaptab.elem_class = psref_class_create("encapelem", IPL_SOFTNET);
    177 
    178 	mutex_init(&encap_whole.lock, MUTEX_DEFAULT, IPL_NONE);
    179 	cv_init(&encap_whole.cv, "ip_encap cv");
    180 	encap_whole.busy = NULL;
    181 
    182 	encap_initialized = true;
    183 }
    184 
    185 void
    186 encap_init(void)
    187 {
    188 	static int initialized = 0;
    189 
    190 	if (initialized)
    191 		return;
    192 	initialized++;
    193 #if 0
    194 	/*
    195 	 * we cannot use LIST_INIT() here, since drivers may want to call
    196 	 * encap_attach(), on driver attach.  encap_init() will be called
    197 	 * on AF_INET{,6} initialization, which happens after driver
    198 	 * initialization - using LIST_INIT() here can nuke encap_attach()
    199 	 * from drivers.
    200 	 */
    201 	PSLIST_INIT(&encap_table);
    202 #endif
    203 
    204 #ifdef USE_RADIX
    205 	/*
    206 	 * initialize radix lookup table when the radix subsystem is inited.
    207 	 */
    208 	rn_delayedinit((void *)&encap_head[0],
    209 	    sizeof(struct sockaddr_pack) << 3);
    210 #ifdef INET6
    211 	rn_delayedinit((void *)&encap_head[1],
    212 	    sizeof(struct sockaddr_pack) << 3);
    213 #endif
    214 #endif
    215 }
    216 
    217 #ifdef INET
    218 static struct encaptab *
    219 encap4_lookup(struct mbuf *m, int off, int proto, enum direction dir,
    220     struct psref *match_psref)
    221 {
    222 	struct ip *ip;
    223 	struct ip_pack4 pack;
    224 	struct encaptab *ep, *match;
    225 	int prio, matchprio;
    226 	int s;
    227 #ifdef USE_RADIX
    228 	struct radix_node_head *rnh = encap_rnh(AF_INET);
    229 	struct radix_node *rn;
    230 #endif
    231 
    232 	KASSERT(m->m_len >= sizeof(*ip));
    233 
    234 	ip = mtod(m, struct ip *);
    235 
    236 	memset(&pack, 0, sizeof(pack));
    237 	pack.p.sp_len = sizeof(pack);
    238 	pack.mine.sin_family = pack.yours.sin_family = AF_INET;
    239 	pack.mine.sin_len = pack.yours.sin_len = sizeof(struct sockaddr_in);
    240 	if (dir == INBOUND) {
    241 		pack.mine.sin_addr = ip->ip_dst;
    242 		pack.yours.sin_addr = ip->ip_src;
    243 	} else {
    244 		pack.mine.sin_addr = ip->ip_src;
    245 		pack.yours.sin_addr = ip->ip_dst;
    246 	}
    247 
    248 	match = NULL;
    249 	matchprio = 0;
    250 
    251 	s = pserialize_read_enter();
    252 #ifdef USE_RADIX
    253 	if (encap_head_updating) {
    254 		/*
    255 		 * Update in progress. Do nothing.
    256 		 */
    257 		pserialize_read_exit(s);
    258 		return NULL;
    259 	}
    260 
    261 	rn = rnh->rnh_matchaddr((void *)&pack, rnh);
    262 	if (rn && (rn->rn_flags & RNF_ROOT) == 0) {
    263 		struct encaptab *encapp = (struct encaptab *)rn;
    264 
    265 		psref_acquire(match_psref, &encapp->psref,
    266 		    encaptab.elem_class);
    267 		match = encapp;
    268 		matchprio = mask_matchlen(match->srcmask) +
    269 		    mask_matchlen(match->dstmask);
    270 	}
    271 #endif
    272 	PSLIST_READER_FOREACH(ep, &encap_table, struct encaptab, chain) {
    273 		struct psref elem_psref;
    274 
    275 		if (ep->af != AF_INET)
    276 			continue;
    277 		if (ep->proto >= 0 && ep->proto != proto)
    278 			continue;
    279 
    280 		psref_acquire(&elem_psref, &ep->psref,
    281 		    encaptab.elem_class);
    282 		if (ep->func) {
    283 			pserialize_read_exit(s);
    284 			/* ep->func is sleepable. e.g. rtalloc1 */
    285 			prio = (*ep->func)(m, off, proto, ep->arg);
    286 			s = pserialize_read_enter();
    287 		} else {
    288 #ifdef USE_RADIX
    289 			psref_release(&elem_psref, &ep->psref,
    290 			    encaptab.elem_class);
    291 			continue;
    292 #else
    293 			prio = mask_match(ep, (struct sockaddr *)&pack.mine,
    294 			    (struct sockaddr *)&pack.yours);
    295 #endif
    296 		}
    297 
    298 		/*
    299 		 * We prioritize the matches by using bit length of the
    300 		 * matches.  mask_match() and user-supplied matching function
    301 		 * should return the bit length of the matches (for example,
    302 		 * if both src/dst are matched for IPv4, 64 should be returned).
    303 		 * 0 or negative return value means "it did not match".
    304 		 *
    305 		 * The question is, since we have two "mask" portion, we
    306 		 * cannot really define total order between entries.
    307 		 * For example, which of these should be preferred?
    308 		 * mask_match() returns 48 (32 + 16) for both of them.
    309 		 *	src=3ffe::/16, dst=3ffe:501::/32
    310 		 *	src=3ffe:501::/32, dst=3ffe::/16
    311 		 *
    312 		 * We need to loop through all the possible candidates
    313 		 * to get the best match - the search takes O(n) for
    314 		 * n attachments (i.e. interfaces).
    315 		 *
    316 		 * For radix-based lookup, I guess source takes precedence.
    317 		 * See rn_{refines,lexobetter} for the correct answer.
    318 		 */
    319 		if (prio <= 0) {
    320 			psref_release(&elem_psref, &ep->psref,
    321 			    encaptab.elem_class);
    322 			continue;
    323 		}
    324 		if (prio > matchprio) {
    325 			/* release last matched ep */
    326 			if (match != NULL)
    327 				psref_release(match_psref, &match->psref,
    328 				    encaptab.elem_class);
    329 
    330 			psref_copy(match_psref, &elem_psref,
    331 			    encaptab.elem_class);
    332 			matchprio = prio;
    333 			match = ep;
    334 		}
    335 		KASSERTMSG((match == NULL) || psref_held(&match->psref,
    336 			encaptab.elem_class),
    337 		    "current match = %p, but not hold its psref", match);
    338 
    339 		psref_release(&elem_psref, &ep->psref,
    340 		    encaptab.elem_class);
    341 	}
    342 	pserialize_read_exit(s);
    343 
    344 	return match;
    345 }
    346 
    347 void
    348 encap4_input(struct mbuf *m, ...)
    349 {
    350 	int off, proto;
    351 	va_list ap;
    352 	const struct encapsw *esw;
    353 	struct encaptab *match;
    354 	struct psref match_psref;
    355 
    356 	va_start(ap, m);
    357 	off = va_arg(ap, int);
    358 	proto = va_arg(ap, int);
    359 	va_end(ap);
    360 
    361 	match = encap4_lookup(m, off, proto, INBOUND, &match_psref);
    362 	if (match) {
    363 		/* found a match, "match" has the best one */
    364 		esw = match->esw;
    365 		if (esw && esw->encapsw4.pr_input) {
    366 			encap_fillarg(m, match);
    367 			(*esw->encapsw4.pr_input)(m, off, proto);
    368 			psref_release(&match_psref, &match->psref,
    369 			    encaptab.elem_class);
    370 		} else {
    371 			psref_release(&match_psref, &match->psref,
    372 			    encaptab.elem_class);
    373 			m_freem(m);
    374 		}
    375 		return;
    376 	}
    377 
    378 	/* last resort: inject to raw socket */
    379 	rip_input(m, off, proto);
    380 }
    381 #endif
    382 
    383 #ifdef INET6
    384 static struct encaptab *
    385 encap6_lookup(struct mbuf *m, int off, int proto, enum direction dir,
    386     struct psref *match_psref)
    387 {
    388 	struct ip6_hdr *ip6;
    389 	struct ip_pack6 pack;
    390 	int prio, matchprio;
    391 	int s;
    392 	struct encaptab *ep, *match;
    393 #ifdef USE_RADIX
    394 	struct radix_node_head *rnh = encap_rnh(AF_INET6);
    395 	struct radix_node *rn;
    396 #endif
    397 
    398 	KASSERT(m->m_len >= sizeof(*ip6));
    399 
    400 	ip6 = mtod(m, struct ip6_hdr *);
    401 
    402 	memset(&pack, 0, sizeof(pack));
    403 	pack.p.sp_len = sizeof(pack);
    404 	pack.mine.sin6_family = pack.yours.sin6_family = AF_INET6;
    405 	pack.mine.sin6_len = pack.yours.sin6_len = sizeof(struct sockaddr_in6);
    406 	if (dir == INBOUND) {
    407 		pack.mine.sin6_addr = ip6->ip6_dst;
    408 		pack.yours.sin6_addr = ip6->ip6_src;
    409 	} else {
    410 		pack.mine.sin6_addr = ip6->ip6_src;
    411 		pack.yours.sin6_addr = ip6->ip6_dst;
    412 	}
    413 
    414 	match = NULL;
    415 	matchprio = 0;
    416 
    417 	s = pserialize_read_enter();
    418 #ifdef USE_RADIX
    419 	if (encap_head_updating) {
    420 		/*
    421 		 * Update in progress. Do nothing.
    422 		 */
    423 		pserialize_read_exit(s);
    424 		return NULL;
    425 	}
    426 
    427 	rn = rnh->rnh_matchaddr((void *)&pack, rnh);
    428 	if (rn && (rn->rn_flags & RNF_ROOT) == 0) {
    429 		struct encaptab *encapp = (struct encaptab *)rn;
    430 
    431 		psref_acquire(match_psref, &encapp->psref,
    432 		    encaptab.elem_class);
    433 		match = encapp;
    434 		matchprio = mask_matchlen(match->srcmask) +
    435 		    mask_matchlen(match->dstmask);
    436 	}
    437 #endif
    438 	PSLIST_READER_FOREACH(ep, &encap_table, struct encaptab, chain) {
    439 		struct psref elem_psref;
    440 
    441 		if (ep->af != AF_INET6)
    442 			continue;
    443 		if (ep->proto >= 0 && ep->proto != proto)
    444 			continue;
    445 
    446 		psref_acquire(&elem_psref, &ep->psref,
    447 		    encaptab.elem_class);
    448 
    449 		if (ep->func) {
    450 			pserialize_read_exit(s);
    451 			/* ep->func is sleepable. e.g. rtalloc1 */
    452 			prio = (*ep->func)(m, off, proto, ep->arg);
    453 			s = pserialize_read_enter();
    454 		} else {
    455 #ifdef USE_RADIX
    456 			psref_release(&elem_psref, &ep->psref,
    457 			    encaptab.elem_class);
    458 			continue;
    459 #else
    460 			prio = mask_match(ep, (struct sockaddr *)&pack.mine,
    461 			    (struct sockaddr *)&pack.yours);
    462 #endif
    463 		}
    464 
    465 		/* see encap4_lookup() for issues here */
    466 		if (prio <= 0) {
    467 			psref_release(&elem_psref, &ep->psref,
    468 			    encaptab.elem_class);
    469 			continue;
    470 		}
    471 		if (prio > matchprio) {
    472 			/* release last matched ep */
    473 			if (match != NULL)
    474 				psref_release(match_psref, &match->psref,
    475 				    encaptab.elem_class);
    476 
    477 			psref_copy(match_psref, &elem_psref,
    478 			    encaptab.elem_class);
    479 			matchprio = prio;
    480 			match = ep;
    481 		}
    482 		KASSERTMSG((match == NULL) || psref_held(&match->psref,
    483 			encaptab.elem_class),
    484 		    "current match = %p, but not hold its psref", match);
    485 
    486 		psref_release(&elem_psref, &ep->psref,
    487 		    encaptab.elem_class);
    488 	}
    489 	pserialize_read_exit(s);
    490 
    491 	return match;
    492 }
    493 
    494 int
    495 encap6_input(struct mbuf **mp, int *offp, int proto)
    496 {
    497 	struct mbuf *m = *mp;
    498 	const struct encapsw *esw;
    499 	struct encaptab *match;
    500 	struct psref match_psref;
    501 
    502 	match = encap6_lookup(m, *offp, proto, INBOUND, &match_psref);
    503 
    504 	if (match) {
    505 		/* found a match */
    506 		esw = match->esw;
    507 		if (esw && esw->encapsw6.pr_input) {
    508 			int ret;
    509 			encap_fillarg(m, match);
    510 			ret = (*esw->encapsw6.pr_input)(mp, offp, proto);
    511 			psref_release(&match_psref, &match->psref,
    512 			    encaptab.elem_class);
    513 			return ret;
    514 		} else {
    515 			psref_release(&match_psref, &match->psref,
    516 			    encaptab.elem_class);
    517 			m_freem(m);
    518 			return IPPROTO_DONE;
    519 		}
    520 	}
    521 
    522 	/* last resort: inject to raw socket */
    523 	return rip6_input(mp, offp, proto);
    524 }
    525 #endif
    526 
    527 /*
    528  * XXX
    529  * The encaptab list and the rnh radix tree must be manipulated atomically.
    530  */
    531 static int
    532 encap_add(struct encaptab *ep)
    533 {
    534 #ifdef USE_RADIX
    535 	struct radix_node_head *rnh = encap_rnh(ep->af);
    536 #endif
    537 
    538 	KASSERT(encap_lock_held());
    539 
    540 #ifdef USE_RADIX
    541 	if (!ep->func && rnh) {
    542 		/* Disable access to the radix tree for reader. */
    543 		encap_head_updating = true;
    544 		/* Wait for all readers to drain. */
    545 		pserialize_perform(encaptab.psz);
    546 
    547 		if (!rnh->rnh_addaddr((void *)ep->addrpack,
    548 		    (void *)ep->maskpack, rnh, ep->nodes)) {
    549 			encap_head_updating = false;
    550 			return EEXIST;
    551 		}
    552 
    553 		/*
    554 		 * The ep added to the radix tree must be skipped while
    555 		 * encap[46]_lookup walks encaptab list. In other words,
    556 		 * encap_add() does not need to care whether the ep has
    557 		 * been added encaptab list or not yet.
    558 		 * So, we can re-enable access to the radix tree for now.
    559 		 */
    560 		encap_head_updating = false;
    561 	}
    562 #endif
    563 	PSLIST_WRITER_INSERT_HEAD(&encap_table, ep, chain);
    564 
    565 	return 0;
    566 }
    567 
    568 /*
    569  * XXX
    570  * The encaptab list and the rnh radix tree must be manipulated atomically.
    571  */
    572 static int
    573 encap_remove(struct encaptab *ep)
    574 {
    575 #ifdef USE_RADIX
    576 	struct radix_node_head *rnh = encap_rnh(ep->af);
    577 #endif
    578 	int error = 0;
    579 
    580 	KASSERT(encap_lock_held());
    581 
    582 #ifdef USE_RADIX
    583 	if (!ep->func && rnh) {
    584 		/* Disable access to the radix tree for reader. */
    585 		encap_head_updating = true;
    586 		/* Wait for all readers to drain. */
    587 		pserialize_perform(encaptab.psz);
    588 
    589 		if (!rnh->rnh_deladdr((void *)ep->addrpack,
    590 		    (void *)ep->maskpack, rnh))
    591 			error = ESRCH;
    592 
    593 		/*
    594 		 * The ep added to the radix tree must be skipped while
    595 		 * encap[46]_lookup walks encaptab list. In other words,
    596 		 * encap_add() does not need to care whether the ep has
    597 		 * been added encaptab list or not yet.
    598 		 * So, we can re-enable access to the radix tree for now.
    599 		 */
    600 		encap_head_updating = false;
    601 	}
    602 #endif
    603 	PSLIST_WRITER_REMOVE(ep, chain);
    604 
    605 	return error;
    606 }
    607 
    608 static int
    609 encap_afcheck(int af, const struct sockaddr *sp, const struct sockaddr *dp)
    610 {
    611 	if (sp && dp) {
    612 		if (sp->sa_len != dp->sa_len)
    613 			return EINVAL;
    614 		if (af != sp->sa_family || af != dp->sa_family)
    615 			return EINVAL;
    616 	} else if (!sp && !dp)
    617 		;
    618 	else
    619 		return EINVAL;
    620 
    621 	switch (af) {
    622 	case AF_INET:
    623 		if (sp && sp->sa_len != sizeof(struct sockaddr_in))
    624 			return EINVAL;
    625 		if (dp && dp->sa_len != sizeof(struct sockaddr_in))
    626 			return EINVAL;
    627 		break;
    628 #ifdef INET6
    629 	case AF_INET6:
    630 		if (sp && sp->sa_len != sizeof(struct sockaddr_in6))
    631 			return EINVAL;
    632 		if (dp && dp->sa_len != sizeof(struct sockaddr_in6))
    633 			return EINVAL;
    634 		break;
    635 #endif
    636 	default:
    637 		return EAFNOSUPPORT;
    638 	}
    639 
    640 	return 0;
    641 }
    642 
    643 /*
    644  * sp (src ptr) is always my side, and dp (dst ptr) is always remote side.
    645  * length of mask (sm and dm) is assumed to be same as sp/dp.
    646  * Return value will be necessary as input (cookie) for encap_detach().
    647  */
    648 const struct encaptab *
    649 encap_attach(int af, int proto,
    650     const struct sockaddr *sp, const struct sockaddr *sm,
    651     const struct sockaddr *dp, const struct sockaddr *dm,
    652     const struct encapsw *esw, void *arg)
    653 {
    654 	struct encaptab *ep;
    655 	int error;
    656 	int pss;
    657 	size_t l;
    658 	struct ip_pack4 *pack4;
    659 #ifdef INET6
    660 	struct ip_pack6 *pack6;
    661 #endif
    662 #ifndef ENCAP_MPSAFE
    663 	int s;
    664 
    665 	s = splsoftnet();
    666 #endif
    667 	/* sanity check on args */
    668 	error = encap_afcheck(af, sp, dp);
    669 	if (error)
    670 		goto fail;
    671 
    672 	/* check if anyone have already attached with exactly same config */
    673 	pss = pserialize_read_enter();
    674 	PSLIST_READER_FOREACH(ep, &encap_table, struct encaptab, chain) {
    675 		if (ep->af != af)
    676 			continue;
    677 		if (ep->proto != proto)
    678 			continue;
    679 		if (ep->func)
    680 			continue;
    681 
    682 		KASSERT(ep->src != NULL);
    683 		KASSERT(ep->dst != NULL);
    684 		KASSERT(ep->srcmask != NULL);
    685 		KASSERT(ep->dstmask != NULL);
    686 
    687 		if (ep->src->sa_len != sp->sa_len ||
    688 		    memcmp(ep->src, sp, sp->sa_len) != 0 ||
    689 		    memcmp(ep->srcmask, sm, sp->sa_len) != 0)
    690 			continue;
    691 		if (ep->dst->sa_len != dp->sa_len ||
    692 		    memcmp(ep->dst, dp, dp->sa_len) != 0 ||
    693 		    memcmp(ep->dstmask, dm, dp->sa_len) != 0)
    694 			continue;
    695 
    696 		error = EEXIST;
    697 		pserialize_read_exit(pss);
    698 		goto fail;
    699 	}
    700 	pserialize_read_exit(pss);
    701 
    702 	switch (af) {
    703 	case AF_INET:
    704 		l = sizeof(*pack4);
    705 		break;
    706 #ifdef INET6
    707 	case AF_INET6:
    708 		l = sizeof(*pack6);
    709 		break;
    710 #endif
    711 	default:
    712 		goto fail;
    713 	}
    714 
    715 	/* M_NETADDR ok? */
    716 	ep = kmem_zalloc(sizeof(*ep), KM_NOSLEEP);
    717 	if (ep == NULL) {
    718 		error = ENOBUFS;
    719 		goto fail;
    720 	}
    721 	ep->addrpack = kmem_zalloc(l, KM_NOSLEEP);
    722 	if (ep->addrpack == NULL) {
    723 		error = ENOBUFS;
    724 		goto gc;
    725 	}
    726 	ep->maskpack = kmem_zalloc(l, KM_NOSLEEP);
    727 	if (ep->maskpack == NULL) {
    728 		error = ENOBUFS;
    729 		goto gc;
    730 	}
    731 
    732 	ep->af = af;
    733 	ep->proto = proto;
    734 	ep->addrpack->sa_len = l & 0xff;
    735 	ep->maskpack->sa_len = l & 0xff;
    736 	switch (af) {
    737 	case AF_INET:
    738 		pack4 = (struct ip_pack4 *)ep->addrpack;
    739 		ep->src = (struct sockaddr *)&pack4->mine;
    740 		ep->dst = (struct sockaddr *)&pack4->yours;
    741 		pack4 = (struct ip_pack4 *)ep->maskpack;
    742 		ep->srcmask = (struct sockaddr *)&pack4->mine;
    743 		ep->dstmask = (struct sockaddr *)&pack4->yours;
    744 		break;
    745 #ifdef INET6
    746 	case AF_INET6:
    747 		pack6 = (struct ip_pack6 *)ep->addrpack;
    748 		ep->src = (struct sockaddr *)&pack6->mine;
    749 		ep->dst = (struct sockaddr *)&pack6->yours;
    750 		pack6 = (struct ip_pack6 *)ep->maskpack;
    751 		ep->srcmask = (struct sockaddr *)&pack6->mine;
    752 		ep->dstmask = (struct sockaddr *)&pack6->yours;
    753 		break;
    754 #endif
    755 	}
    756 
    757 	memcpy(ep->src, sp, sp->sa_len);
    758 	memcpy(ep->srcmask, sm, sp->sa_len);
    759 	memcpy(ep->dst, dp, dp->sa_len);
    760 	memcpy(ep->dstmask, dm, dp->sa_len);
    761 	ep->esw = esw;
    762 	ep->arg = arg;
    763 	psref_target_init(&ep->psref, encaptab.elem_class);
    764 
    765 	error = encap_add(ep);
    766 	if (error)
    767 		goto gc;
    768 
    769 	error = 0;
    770 #ifndef ENCAP_MPSAFE
    771 	splx(s);
    772 #endif
    773 	return ep;
    774 
    775 gc:
    776 	if (ep->addrpack)
    777 		kmem_free(ep->addrpack, l);
    778 	if (ep->maskpack)
    779 		kmem_free(ep->maskpack, l);
    780 	if (ep)
    781 		kmem_free(ep, sizeof(*ep));
    782 fail:
    783 #ifndef ENCAP_MPSAFE
    784 	splx(s);
    785 #endif
    786 	return NULL;
    787 }
    788 
    789 const struct encaptab *
    790 encap_attach_func(int af, int proto,
    791     int (*func)(struct mbuf *, int, int, void *),
    792     const struct encapsw *esw, void *arg)
    793 {
    794 	struct encaptab *ep;
    795 	int error;
    796 #ifndef ENCAP_MPSAFE
    797 	int s;
    798 
    799 	s = splsoftnet();
    800 #endif
    801 	/* sanity check on args */
    802 	if (!func) {
    803 		error = EINVAL;
    804 		goto fail;
    805 	}
    806 
    807 	error = encap_afcheck(af, NULL, NULL);
    808 	if (error)
    809 		goto fail;
    810 
    811 	ep = kmem_alloc(sizeof(*ep), KM_NOSLEEP);	/*XXX*/
    812 	if (ep == NULL) {
    813 		error = ENOBUFS;
    814 		goto fail;
    815 	}
    816 	memset(ep, 0, sizeof(*ep));
    817 
    818 	ep->af = af;
    819 	ep->proto = proto;
    820 	ep->func = func;
    821 	ep->esw = esw;
    822 	ep->arg = arg;
    823 	psref_target_init(&ep->psref, encaptab.elem_class);
    824 
    825 	error = encap_add(ep);
    826 	if (error)
    827 		goto fail;
    828 
    829 	error = 0;
    830 #ifndef ENCAP_MPSAFE
    831 	splx(s);
    832 #endif
    833 	return ep;
    834 
    835 fail:
    836 #ifndef ENCAP_MPSAFE
    837 	splx(s);
    838 #endif
    839 	return NULL;
    840 }
    841 
    842 /* XXX encap4_ctlinput() is necessary if we set DF=1 on outer IPv4 header */
    843 
    844 #ifdef INET6
    845 void *
    846 encap6_ctlinput(int cmd, const struct sockaddr *sa, void *d0)
    847 {
    848 	void *d = d0;
    849 	struct ip6_hdr *ip6;
    850 	struct mbuf *m;
    851 	int off;
    852 	struct ip6ctlparam *ip6cp = NULL;
    853 	int nxt;
    854 	int s;
    855 	struct encaptab *ep;
    856 	const struct encapsw *esw;
    857 
    858 	if (sa->sa_family != AF_INET6 ||
    859 	    sa->sa_len != sizeof(struct sockaddr_in6))
    860 		return NULL;
    861 
    862 	if ((unsigned)cmd >= PRC_NCMDS)
    863 		return NULL;
    864 	if (cmd == PRC_HOSTDEAD)
    865 		d = NULL;
    866 	else if (cmd == PRC_MSGSIZE)
    867 		; /* special code is present, see below */
    868 	else if (inet6ctlerrmap[cmd] == 0)
    869 		return NULL;
    870 
    871 	/* if the parameter is from icmp6, decode it. */
    872 	if (d != NULL) {
    873 		ip6cp = (struct ip6ctlparam *)d;
    874 		m = ip6cp->ip6c_m;
    875 		ip6 = ip6cp->ip6c_ip6;
    876 		off = ip6cp->ip6c_off;
    877 		nxt = ip6cp->ip6c_nxt;
    878 
    879 		if (ip6 && cmd == PRC_MSGSIZE) {
    880 			int valid = 0;
    881 			struct encaptab *match;
    882 			struct psref elem_psref;
    883 
    884 			/*
    885 		 	* Check to see if we have a valid encap configuration.
    886 		 	*/
    887 			match = encap6_lookup(m, off, nxt, OUTBOUND,
    888 			    &elem_psref);
    889 			if (match)
    890 				valid++;
    891 			psref_release(&elem_psref, &match->psref,
    892 			    encaptab.elem_class);
    893 
    894 			/*
    895 		 	* Depending on the value of "valid" and routing table
    896 		 	* size (mtudisc_{hi,lo}wat), we will:
    897 		 	* - recalcurate the new MTU and create the
    898 		 	*   corresponding routing entry, or
    899 		 	* - ignore the MTU change notification.
    900 		 	*/
    901 			icmp6_mtudisc_update((struct ip6ctlparam *)d, valid);
    902 		}
    903 	} else {
    904 		m = NULL;
    905 		ip6 = NULL;
    906 		nxt = -1;
    907 	}
    908 
    909 	/* inform all listeners */
    910 
    911 	s = pserialize_read_enter();
    912 	PSLIST_READER_FOREACH(ep, &encap_table, struct encaptab, chain) {
    913 		struct psref elem_psref;
    914 
    915 		if (ep->af != AF_INET6)
    916 			continue;
    917 		if (ep->proto >= 0 && ep->proto != nxt)
    918 			continue;
    919 
    920 		/* should optimize by looking at address pairs */
    921 
    922 		/* XXX need to pass ep->arg or ep itself to listeners */
    923 		psref_acquire(&elem_psref, &ep->psref,
    924 		    encaptab.elem_class);
    925 		esw = ep->esw;
    926 		if (esw && esw->encapsw6.pr_ctlinput) {
    927 			pserialize_read_exit(s);
    928 			/* pr_ctlinput is sleepable. e.g. rtcache_free */
    929 			(*esw->encapsw6.pr_ctlinput)(cmd, sa, d, ep->arg);
    930 			s = pserialize_read_enter();
    931 		}
    932 		psref_release(&elem_psref, &ep->psref,
    933 		    encaptab.elem_class);
    934 	}
    935 	pserialize_read_exit(s);
    936 
    937 	rip6_ctlinput(cmd, sa, d0);
    938 	return NULL;
    939 }
    940 #endif
    941 
    942 int
    943 encap_detach(const struct encaptab *cookie)
    944 {
    945 	const struct encaptab *ep = cookie;
    946 	struct encaptab *p;
    947 	int error;
    948 
    949 	KASSERT(encap_lock_held());
    950 
    951 	PSLIST_WRITER_FOREACH(p, &encap_table, struct encaptab, chain) {
    952 		if (p == ep) {
    953 			error = encap_remove(p);
    954 			if (error)
    955 				return error;
    956 			else
    957 				break;
    958 		}
    959 	}
    960 	if (p == NULL)
    961 		return ENOENT;
    962 
    963 	pserialize_perform(encaptab.psz);
    964 	psref_target_destroy(&p->psref,
    965 	    encaptab.elem_class);
    966 	if (!ep->func) {
    967 		kmem_free(p->addrpack, ep->addrpack->sa_len);
    968 		kmem_free(p->maskpack, ep->maskpack->sa_len);
    969 	}
    970 	kmem_free(p, sizeof(*p));
    971 
    972 	return 0;
    973 }
    974 
    975 #ifdef USE_RADIX
    976 static struct radix_node_head *
    977 encap_rnh(int af)
    978 {
    979 
    980 	switch (af) {
    981 	case AF_INET:
    982 		return encap_head[0];
    983 #ifdef INET6
    984 	case AF_INET6:
    985 		return encap_head[1];
    986 #endif
    987 	default:
    988 		return NULL;
    989 	}
    990 }
    991 
    992 static int
    993 mask_matchlen(const struct sockaddr *sa)
    994 {
    995 	const char *p, *ep;
    996 	int l;
    997 
    998 	p = (const char *)sa;
    999 	ep = p + sa->sa_len;
   1000 	p += 2;	/* sa_len + sa_family */
   1001 
   1002 	l = 0;
   1003 	while (p < ep) {
   1004 		l += (*p ? 8 : 0);	/* estimate */
   1005 		p++;
   1006 	}
   1007 	return l;
   1008 }
   1009 #endif
   1010 
   1011 #ifndef USE_RADIX
   1012 static int
   1013 mask_match(const struct encaptab *ep,
   1014 	   const struct sockaddr *sp,
   1015 	   const struct sockaddr *dp)
   1016 {
   1017 	struct sockaddr_storage s;
   1018 	struct sockaddr_storage d;
   1019 	int i;
   1020 	const u_int8_t *p, *q;
   1021 	u_int8_t *r;
   1022 	int matchlen;
   1023 
   1024 	KASSERTMSG(ep->func == NULL, "wrong encaptab passed to mask_match");
   1025 
   1026 	if (sp->sa_len > sizeof(s) || dp->sa_len > sizeof(d))
   1027 		return 0;
   1028 	if (sp->sa_family != ep->af || dp->sa_family != ep->af)
   1029 		return 0;
   1030 	if (sp->sa_len != ep->src->sa_len || dp->sa_len != ep->dst->sa_len)
   1031 		return 0;
   1032 
   1033 	matchlen = 0;
   1034 
   1035 	p = (const u_int8_t *)sp;
   1036 	q = (const u_int8_t *)ep->srcmask;
   1037 	r = (u_int8_t *)&s;
   1038 	for (i = 0 ; i < sp->sa_len; i++) {
   1039 		r[i] = p[i] & q[i];
   1040 		/* XXX estimate */
   1041 		matchlen += (q[i] ? 8 : 0);
   1042 	}
   1043 
   1044 	p = (const u_int8_t *)dp;
   1045 	q = (const u_int8_t *)ep->dstmask;
   1046 	r = (u_int8_t *)&d;
   1047 	for (i = 0 ; i < dp->sa_len; i++) {
   1048 		r[i] = p[i] & q[i];
   1049 		/* XXX rough estimate */
   1050 		matchlen += (q[i] ? 8 : 0);
   1051 	}
   1052 
   1053 	/* need to overwrite len/family portion as we don't compare them */
   1054 	s.ss_len = sp->sa_len;
   1055 	s.ss_family = sp->sa_family;
   1056 	d.ss_len = dp->sa_len;
   1057 	d.ss_family = dp->sa_family;
   1058 
   1059 	if (memcmp(&s, ep->src, ep->src->sa_len) == 0 &&
   1060 	    memcmp(&d, ep->dst, ep->dst->sa_len) == 0) {
   1061 		return matchlen;
   1062 	} else
   1063 		return 0;
   1064 }
   1065 #endif
   1066 
   1067 static void
   1068 encap_fillarg(struct mbuf *m, const struct encaptab *ep)
   1069 {
   1070 	struct m_tag *mtag;
   1071 
   1072 	mtag = m_tag_get(PACKET_TAG_ENCAP, sizeof(void *), M_NOWAIT);
   1073 	if (mtag) {
   1074 		*(void **)(mtag + 1) = ep->arg;
   1075 		m_tag_prepend(m, mtag);
   1076 	}
   1077 }
   1078 
   1079 void *
   1080 encap_getarg(struct mbuf *m)
   1081 {
   1082 	void *p;
   1083 	struct m_tag *mtag;
   1084 
   1085 	p = NULL;
   1086 	mtag = m_tag_find(m, PACKET_TAG_ENCAP, NULL);
   1087 	if (mtag != NULL) {
   1088 		p = *(void **)(mtag + 1);
   1089 		m_tag_delete(m, mtag);
   1090 	}
   1091 	return p;
   1092 }
   1093 
   1094 int
   1095 encap_lock_enter(void)
   1096 {
   1097 	int error;
   1098 
   1099 	mutex_enter(&encap_whole.lock);
   1100 	while (encap_whole.busy != NULL) {
   1101 		error = cv_wait_sig(&encap_whole.cv, &encap_whole.lock);
   1102 		if (error) {
   1103 			mutex_exit(&encap_whole.lock);
   1104 			return error;
   1105 		}
   1106 	}
   1107 	KASSERT(encap_whole.busy == NULL);
   1108 	encap_whole.busy = curlwp;
   1109 	mutex_exit(&encap_whole.lock);
   1110 
   1111 	return 0;
   1112 }
   1113 
   1114 void
   1115 encap_lock_exit(void)
   1116 {
   1117 
   1118 	mutex_enter(&encap_whole.lock);
   1119 	KASSERT(encap_whole.busy == curlwp);
   1120 	encap_whole.busy = NULL;
   1121 	cv_broadcast(&encap_whole.cv);
   1122 	mutex_exit(&encap_whole.lock);
   1123 }
   1124 
   1125 bool
   1126 encap_lock_held(void)
   1127 {
   1128 
   1129 	return (encap_whole.busy == curlwp);
   1130 }
   1131