Home | History | Annotate | Line # | Download | only in netinet
ip_encap.c revision 1.61.2.2
      1 /*	$NetBSD: ip_encap.c,v 1.61.2.2 2017/04/26 02:53:29 pgoyette 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.61.2.2 2017/04/26 02:53:29 pgoyette 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 	if (encaptab.elem_class == NULL)
    178 		panic("encaptab.elem_class cannot be allocated.\n");
    179 
    180 	mutex_init(&encap_whole.lock, MUTEX_DEFAULT, IPL_NONE);
    181 	cv_init(&encap_whole.cv, "ip_encap cv");
    182 	encap_whole.busy = NULL;
    183 
    184 	encap_initialized = true;
    185 }
    186 
    187 void
    188 encap_init(void)
    189 {
    190 	static int initialized = 0;
    191 
    192 	if (initialized)
    193 		return;
    194 	initialized++;
    195 #if 0
    196 	/*
    197 	 * we cannot use LIST_INIT() here, since drivers may want to call
    198 	 * encap_attach(), on driver attach.  encap_init() will be called
    199 	 * on AF_INET{,6} initialization, which happens after driver
    200 	 * initialization - using LIST_INIT() here can nuke encap_attach()
    201 	 * from drivers.
    202 	 */
    203 	PSLIST_INIT(&encap_table);
    204 #endif
    205 
    206 #ifdef USE_RADIX
    207 	/*
    208 	 * initialize radix lookup table when the radix subsystem is inited.
    209 	 */
    210 	rn_delayedinit((void *)&encap_head[0],
    211 	    sizeof(struct sockaddr_pack) << 3);
    212 #ifdef INET6
    213 	rn_delayedinit((void *)&encap_head[1],
    214 	    sizeof(struct sockaddr_pack) << 3);
    215 #endif
    216 #endif
    217 }
    218 
    219 #ifdef INET
    220 static struct encaptab *
    221 encap4_lookup(struct mbuf *m, int off, int proto, enum direction dir,
    222     struct psref *match_psref)
    223 {
    224 	struct ip *ip;
    225 	struct ip_pack4 pack;
    226 	struct encaptab *ep, *match;
    227 	int prio, matchprio;
    228 	int s;
    229 #ifdef USE_RADIX
    230 	struct radix_node_head *rnh = encap_rnh(AF_INET);
    231 	struct radix_node *rn;
    232 #endif
    233 
    234 	KASSERT(m->m_len >= sizeof(*ip));
    235 
    236 	ip = mtod(m, struct ip *);
    237 
    238 	memset(&pack, 0, sizeof(pack));
    239 	pack.p.sp_len = sizeof(pack);
    240 	pack.mine.sin_family = pack.yours.sin_family = AF_INET;
    241 	pack.mine.sin_len = pack.yours.sin_len = sizeof(struct sockaddr_in);
    242 	if (dir == INBOUND) {
    243 		pack.mine.sin_addr = ip->ip_dst;
    244 		pack.yours.sin_addr = ip->ip_src;
    245 	} else {
    246 		pack.mine.sin_addr = ip->ip_src;
    247 		pack.yours.sin_addr = ip->ip_dst;
    248 	}
    249 
    250 	match = NULL;
    251 	matchprio = 0;
    252 
    253 	s = pserialize_read_enter();
    254 #ifdef USE_RADIX
    255 	if (encap_head_updating) {
    256 		/*
    257 		 * Update in progress. Do nothing.
    258 		 */
    259 		pserialize_read_exit(s);
    260 		return NULL;
    261 	}
    262 
    263 	rn = rnh->rnh_matchaddr((void *)&pack, rnh);
    264 	if (rn && (rn->rn_flags & RNF_ROOT) == 0) {
    265 		struct encaptab *encapp = (struct encaptab *)rn;
    266 
    267 		psref_acquire(match_psref, &encapp->psref,
    268 		    encaptab.elem_class);
    269 		match = encapp;
    270 		matchprio = mask_matchlen(match->srcmask) +
    271 		    mask_matchlen(match->dstmask);
    272 	}
    273 #endif
    274 	PSLIST_READER_FOREACH(ep, &encap_table, struct encaptab, chain) {
    275 		struct psref elem_psref;
    276 
    277 		if (ep->af != AF_INET)
    278 			continue;
    279 		if (ep->proto >= 0 && ep->proto != proto)
    280 			continue;
    281 
    282 		psref_acquire(&elem_psref, &ep->psref,
    283 		    encaptab.elem_class);
    284 		if (ep->func) {
    285 			pserialize_read_exit(s);
    286 			/* ep->func is sleepable. e.g. rtalloc1 */
    287 			prio = (*ep->func)(m, off, proto, ep->arg);
    288 			s = pserialize_read_enter();
    289 		} else {
    290 #ifdef USE_RADIX
    291 			psref_release(&elem_psref, &ep->psref,
    292 			    encaptab.elem_class);
    293 			continue;
    294 #else
    295 			prio = mask_match(ep, (struct sockaddr *)&pack.mine,
    296 			    (struct sockaddr *)&pack.yours);
    297 #endif
    298 		}
    299 
    300 		/*
    301 		 * We prioritize the matches by using bit length of the
    302 		 * matches.  mask_match() and user-supplied matching function
    303 		 * should return the bit length of the matches (for example,
    304 		 * if both src/dst are matched for IPv4, 64 should be returned).
    305 		 * 0 or negative return value means "it did not match".
    306 		 *
    307 		 * The question is, since we have two "mask" portion, we
    308 		 * cannot really define total order between entries.
    309 		 * For example, which of these should be preferred?
    310 		 * mask_match() returns 48 (32 + 16) for both of them.
    311 		 *	src=3ffe::/16, dst=3ffe:501::/32
    312 		 *	src=3ffe:501::/32, dst=3ffe::/16
    313 		 *
    314 		 * We need to loop through all the possible candidates
    315 		 * to get the best match - the search takes O(n) for
    316 		 * n attachments (i.e. interfaces).
    317 		 *
    318 		 * For radix-based lookup, I guess source takes precedence.
    319 		 * See rn_{refines,lexobetter} for the correct answer.
    320 		 */
    321 		if (prio <= 0) {
    322 			psref_release(&elem_psref, &ep->psref,
    323 			    encaptab.elem_class);
    324 			continue;
    325 		}
    326 		if (prio > matchprio) {
    327 			/* release last matched ep */
    328 			if (match != NULL)
    329 				psref_release(match_psref, &match->psref,
    330 				    encaptab.elem_class);
    331 
    332 			psref_copy(match_psref, &elem_psref,
    333 			    encaptab.elem_class);
    334 			matchprio = prio;
    335 			match = ep;
    336 		}
    337 		KASSERTMSG((match == NULL) || psref_held(&match->psref,
    338 			encaptab.elem_class),
    339 		    "current match = %p, but not hold its psref", match);
    340 
    341 		psref_release(&elem_psref, &ep->psref,
    342 		    encaptab.elem_class);
    343 	}
    344 	pserialize_read_exit(s);
    345 
    346 	return match;
    347 }
    348 
    349 void
    350 encap4_input(struct mbuf *m, ...)
    351 {
    352 	int off, proto;
    353 	va_list ap;
    354 	const struct encapsw *esw;
    355 	struct encaptab *match;
    356 	struct psref match_psref;
    357 
    358 	va_start(ap, m);
    359 	off = va_arg(ap, int);
    360 	proto = va_arg(ap, int);
    361 	va_end(ap);
    362 
    363 	match = encap4_lookup(m, off, proto, INBOUND, &match_psref);
    364 	if (match) {
    365 		/* found a match, "match" has the best one */
    366 		esw = match->esw;
    367 		if (esw && esw->encapsw4.pr_input) {
    368 			encap_fillarg(m, match);
    369 			(*esw->encapsw4.pr_input)(m, off, proto);
    370 			psref_release(&match_psref, &match->psref,
    371 			    encaptab.elem_class);
    372 		} else {
    373 			psref_release(&match_psref, &match->psref,
    374 			    encaptab.elem_class);
    375 			m_freem(m);
    376 		}
    377 		return;
    378 	}
    379 
    380 	/* last resort: inject to raw socket */
    381 	rip_input(m, off, proto);
    382 }
    383 #endif
    384 
    385 #ifdef INET6
    386 static struct encaptab *
    387 encap6_lookup(struct mbuf *m, int off, int proto, enum direction dir,
    388     struct psref *match_psref)
    389 {
    390 	struct ip6_hdr *ip6;
    391 	struct ip_pack6 pack;
    392 	int prio, matchprio;
    393 	int s;
    394 	struct encaptab *ep, *match;
    395 #ifdef USE_RADIX
    396 	struct radix_node_head *rnh = encap_rnh(AF_INET6);
    397 	struct radix_node *rn;
    398 #endif
    399 
    400 	KASSERT(m->m_len >= sizeof(*ip6));
    401 
    402 	ip6 = mtod(m, struct ip6_hdr *);
    403 
    404 	memset(&pack, 0, sizeof(pack));
    405 	pack.p.sp_len = sizeof(pack);
    406 	pack.mine.sin6_family = pack.yours.sin6_family = AF_INET6;
    407 	pack.mine.sin6_len = pack.yours.sin6_len = sizeof(struct sockaddr_in6);
    408 	if (dir == INBOUND) {
    409 		pack.mine.sin6_addr = ip6->ip6_dst;
    410 		pack.yours.sin6_addr = ip6->ip6_src;
    411 	} else {
    412 		pack.mine.sin6_addr = ip6->ip6_src;
    413 		pack.yours.sin6_addr = ip6->ip6_dst;
    414 	}
    415 
    416 	match = NULL;
    417 	matchprio = 0;
    418 
    419 	s = pserialize_read_enter();
    420 #ifdef USE_RADIX
    421 	if (encap_head_updating) {
    422 		/*
    423 		 * Update in progress. Do nothing.
    424 		 */
    425 		pserialize_read_exit(s);
    426 		return NULL;
    427 	}
    428 
    429 	rn = rnh->rnh_matchaddr((void *)&pack, rnh);
    430 	if (rn && (rn->rn_flags & RNF_ROOT) == 0) {
    431 		struct encaptab *encapp = (struct encaptab *)rn;
    432 
    433 		psref_acquire(match_psref, &encapp->psref,
    434 		    encaptab.elem_class);
    435 		match = encapp;
    436 		matchprio = mask_matchlen(match->srcmask) +
    437 		    mask_matchlen(match->dstmask);
    438 	}
    439 #endif
    440 	PSLIST_READER_FOREACH(ep, &encap_table, struct encaptab, chain) {
    441 		struct psref elem_psref;
    442 
    443 		if (ep->af != AF_INET6)
    444 			continue;
    445 		if (ep->proto >= 0 && ep->proto != proto)
    446 			continue;
    447 
    448 		psref_acquire(&elem_psref, &ep->psref,
    449 		    encaptab.elem_class);
    450 
    451 		if (ep->func) {
    452 			pserialize_read_exit(s);
    453 			/* ep->func is sleepable. e.g. rtalloc1 */
    454 			prio = (*ep->func)(m, off, proto, ep->arg);
    455 			s = pserialize_read_enter();
    456 		} else {
    457 #ifdef USE_RADIX
    458 			psref_release(&elem_psref, &ep->psref,
    459 			    encaptab.elem_class);
    460 			continue;
    461 #else
    462 			prio = mask_match(ep, (struct sockaddr *)&pack.mine,
    463 			    (struct sockaddr *)&pack.yours);
    464 #endif
    465 		}
    466 
    467 		/* see encap4_lookup() for issues here */
    468 		if (prio <= 0) {
    469 			psref_release(&elem_psref, &ep->psref,
    470 			    encaptab.elem_class);
    471 			continue;
    472 		}
    473 		if (prio > matchprio) {
    474 			/* release last matched ep */
    475 			if (match != NULL)
    476 				psref_release(match_psref, &match->psref,
    477 				    encaptab.elem_class);
    478 
    479 			psref_copy(match_psref, &elem_psref,
    480 			    encaptab.elem_class);
    481 			matchprio = prio;
    482 			match = ep;
    483 		}
    484 		KASSERTMSG((match == NULL) || psref_held(&match->psref,
    485 			encaptab.elem_class),
    486 		    "current match = %p, but not hold its psref", match);
    487 
    488 		psref_release(&elem_psref, &ep->psref,
    489 		    encaptab.elem_class);
    490 	}
    491 	pserialize_read_exit(s);
    492 
    493 	return match;
    494 }
    495 
    496 int
    497 encap6_input(struct mbuf **mp, int *offp, int proto)
    498 {
    499 	struct mbuf *m = *mp;
    500 	const struct encapsw *esw;
    501 	struct encaptab *match;
    502 	struct psref match_psref;
    503 
    504 	match = encap6_lookup(m, *offp, proto, INBOUND, &match_psref);
    505 
    506 	if (match) {
    507 		/* found a match */
    508 		esw = match->esw;
    509 		if (esw && esw->encapsw6.pr_input) {
    510 			int ret;
    511 			encap_fillarg(m, match);
    512 			ret = (*esw->encapsw6.pr_input)(mp, offp, proto);
    513 			psref_release(&match_psref, &match->psref,
    514 			    encaptab.elem_class);
    515 			return ret;
    516 		} else {
    517 			psref_release(&match_psref, &match->psref,
    518 			    encaptab.elem_class);
    519 			m_freem(m);
    520 			return IPPROTO_DONE;
    521 		}
    522 	}
    523 
    524 	/* last resort: inject to raw socket */
    525 	return rip6_input(mp, offp, proto);
    526 }
    527 #endif
    528 
    529 /*
    530  * XXX
    531  * The encaptab list and the rnh radix tree must be manipulated atomically.
    532  */
    533 static int
    534 encap_add(struct encaptab *ep)
    535 {
    536 #ifdef USE_RADIX
    537 	struct radix_node_head *rnh = encap_rnh(ep->af);
    538 #endif
    539 
    540 	KASSERT(encap_lock_held());
    541 
    542 #ifdef USE_RADIX
    543 	if (!ep->func && rnh) {
    544 		/* Disable access to the radix tree for reader. */
    545 		encap_head_updating = true;
    546 		/* Wait for all readers to drain. */
    547 		pserialize_perform(encaptab.psz);
    548 
    549 		if (!rnh->rnh_addaddr((void *)ep->addrpack,
    550 		    (void *)ep->maskpack, rnh, ep->nodes)) {
    551 			encap_head_updating = false;
    552 			return EEXIST;
    553 		}
    554 
    555 		/*
    556 		 * The ep added to the radix tree must be skipped while
    557 		 * encap[46]_lookup walks encaptab list. In other words,
    558 		 * encap_add() does not need to care whether the ep has
    559 		 * been added encaptab list or not yet.
    560 		 * So, we can re-enable access to the radix tree for now.
    561 		 */
    562 		encap_head_updating = false;
    563 	}
    564 #endif
    565 	PSLIST_WRITER_INSERT_HEAD(&encap_table, ep, chain);
    566 
    567 	return 0;
    568 }
    569 
    570 /*
    571  * XXX
    572  * The encaptab list and the rnh radix tree must be manipulated atomically.
    573  */
    574 static int
    575 encap_remove(struct encaptab *ep)
    576 {
    577 #ifdef USE_RADIX
    578 	struct radix_node_head *rnh = encap_rnh(ep->af);
    579 #endif
    580 	int error = 0;
    581 
    582 	KASSERT(encap_lock_held());
    583 
    584 #ifdef USE_RADIX
    585 	if (!ep->func && rnh) {
    586 		/* Disable access to the radix tree for reader. */
    587 		encap_head_updating = true;
    588 		/* Wait for all readers to drain. */
    589 		pserialize_perform(encaptab.psz);
    590 
    591 		if (!rnh->rnh_deladdr((void *)ep->addrpack,
    592 		    (void *)ep->maskpack, rnh))
    593 			error = ESRCH;
    594 
    595 		/*
    596 		 * The ep added to the radix tree must be skipped while
    597 		 * encap[46]_lookup walks encaptab list. In other words,
    598 		 * encap_add() does not need to care whether the ep has
    599 		 * been added encaptab list or not yet.
    600 		 * So, we can re-enable access to the radix tree for now.
    601 		 */
    602 		encap_head_updating = false;
    603 	}
    604 #endif
    605 	PSLIST_WRITER_REMOVE(ep, chain);
    606 
    607 	return error;
    608 }
    609 
    610 static int
    611 encap_afcheck(int af, const struct sockaddr *sp, const struct sockaddr *dp)
    612 {
    613 	if (sp && dp) {
    614 		if (sp->sa_len != dp->sa_len)
    615 			return EINVAL;
    616 		if (af != sp->sa_family || af != dp->sa_family)
    617 			return EINVAL;
    618 	} else if (!sp && !dp)
    619 		;
    620 	else
    621 		return EINVAL;
    622 
    623 	switch (af) {
    624 	case AF_INET:
    625 		if (sp && sp->sa_len != sizeof(struct sockaddr_in))
    626 			return EINVAL;
    627 		if (dp && dp->sa_len != sizeof(struct sockaddr_in))
    628 			return EINVAL;
    629 		break;
    630 #ifdef INET6
    631 	case AF_INET6:
    632 		if (sp && sp->sa_len != sizeof(struct sockaddr_in6))
    633 			return EINVAL;
    634 		if (dp && dp->sa_len != sizeof(struct sockaddr_in6))
    635 			return EINVAL;
    636 		break;
    637 #endif
    638 	default:
    639 		return EAFNOSUPPORT;
    640 	}
    641 
    642 	return 0;
    643 }
    644 
    645 /*
    646  * sp (src ptr) is always my side, and dp (dst ptr) is always remote side.
    647  * length of mask (sm and dm) is assumed to be same as sp/dp.
    648  * Return value will be necessary as input (cookie) for encap_detach().
    649  */
    650 const struct encaptab *
    651 encap_attach(int af, int proto,
    652     const struct sockaddr *sp, const struct sockaddr *sm,
    653     const struct sockaddr *dp, const struct sockaddr *dm,
    654     const struct encapsw *esw, void *arg)
    655 {
    656 	struct encaptab *ep;
    657 	int error;
    658 	int pss;
    659 	size_t l;
    660 	struct ip_pack4 *pack4;
    661 #ifdef INET6
    662 	struct ip_pack6 *pack6;
    663 #endif
    664 #ifndef ENCAP_MPSAFE
    665 	int s;
    666 
    667 	s = splsoftnet();
    668 #endif
    669 	/* sanity check on args */
    670 	error = encap_afcheck(af, sp, dp);
    671 	if (error)
    672 		goto fail;
    673 
    674 	/* check if anyone have already attached with exactly same config */
    675 	pss = pserialize_read_enter();
    676 	PSLIST_READER_FOREACH(ep, &encap_table, struct encaptab, chain) {
    677 		if (ep->af != af)
    678 			continue;
    679 		if (ep->proto != proto)
    680 			continue;
    681 		if (ep->func)
    682 			continue;
    683 
    684 		KASSERT(ep->src != NULL);
    685 		KASSERT(ep->dst != NULL);
    686 		KASSERT(ep->srcmask != NULL);
    687 		KASSERT(ep->dstmask != NULL);
    688 
    689 		if (ep->src->sa_len != sp->sa_len ||
    690 		    memcmp(ep->src, sp, sp->sa_len) != 0 ||
    691 		    memcmp(ep->srcmask, sm, sp->sa_len) != 0)
    692 			continue;
    693 		if (ep->dst->sa_len != dp->sa_len ||
    694 		    memcmp(ep->dst, dp, dp->sa_len) != 0 ||
    695 		    memcmp(ep->dstmask, dm, dp->sa_len) != 0)
    696 			continue;
    697 
    698 		error = EEXIST;
    699 		pserialize_read_exit(pss);
    700 		goto fail;
    701 	}
    702 	pserialize_read_exit(pss);
    703 
    704 	switch (af) {
    705 	case AF_INET:
    706 		l = sizeof(*pack4);
    707 		break;
    708 #ifdef INET6
    709 	case AF_INET6:
    710 		l = sizeof(*pack6);
    711 		break;
    712 #endif
    713 	default:
    714 		goto fail;
    715 	}
    716 
    717 	/* M_NETADDR ok? */
    718 	ep = kmem_zalloc(sizeof(*ep), KM_NOSLEEP);
    719 	if (ep == NULL) {
    720 		error = ENOBUFS;
    721 		goto fail;
    722 	}
    723 	ep->addrpack = kmem_zalloc(l, KM_NOSLEEP);
    724 	if (ep->addrpack == NULL) {
    725 		error = ENOBUFS;
    726 		goto gc;
    727 	}
    728 	ep->maskpack = kmem_zalloc(l, KM_NOSLEEP);
    729 	if (ep->maskpack == NULL) {
    730 		error = ENOBUFS;
    731 		goto gc;
    732 	}
    733 
    734 	ep->af = af;
    735 	ep->proto = proto;
    736 	ep->addrpack->sa_len = l & 0xff;
    737 	ep->maskpack->sa_len = l & 0xff;
    738 	switch (af) {
    739 	case AF_INET:
    740 		pack4 = (struct ip_pack4 *)ep->addrpack;
    741 		ep->src = (struct sockaddr *)&pack4->mine;
    742 		ep->dst = (struct sockaddr *)&pack4->yours;
    743 		pack4 = (struct ip_pack4 *)ep->maskpack;
    744 		ep->srcmask = (struct sockaddr *)&pack4->mine;
    745 		ep->dstmask = (struct sockaddr *)&pack4->yours;
    746 		break;
    747 #ifdef INET6
    748 	case AF_INET6:
    749 		pack6 = (struct ip_pack6 *)ep->addrpack;
    750 		ep->src = (struct sockaddr *)&pack6->mine;
    751 		ep->dst = (struct sockaddr *)&pack6->yours;
    752 		pack6 = (struct ip_pack6 *)ep->maskpack;
    753 		ep->srcmask = (struct sockaddr *)&pack6->mine;
    754 		ep->dstmask = (struct sockaddr *)&pack6->yours;
    755 		break;
    756 #endif
    757 	}
    758 
    759 	memcpy(ep->src, sp, sp->sa_len);
    760 	memcpy(ep->srcmask, sm, sp->sa_len);
    761 	memcpy(ep->dst, dp, dp->sa_len);
    762 	memcpy(ep->dstmask, dm, dp->sa_len);
    763 	ep->esw = esw;
    764 	ep->arg = arg;
    765 	psref_target_init(&ep->psref, encaptab.elem_class);
    766 
    767 	error = encap_add(ep);
    768 	if (error)
    769 		goto gc;
    770 
    771 	error = 0;
    772 #ifndef ENCAP_MPSAFE
    773 	splx(s);
    774 #endif
    775 	return ep;
    776 
    777 gc:
    778 	if (ep->addrpack)
    779 		kmem_free(ep->addrpack, l);
    780 	if (ep->maskpack)
    781 		kmem_free(ep->maskpack, l);
    782 	if (ep)
    783 		kmem_free(ep, sizeof(*ep));
    784 fail:
    785 #ifndef ENCAP_MPSAFE
    786 	splx(s);
    787 #endif
    788 	return NULL;
    789 }
    790 
    791 const struct encaptab *
    792 encap_attach_func(int af, int proto,
    793     int (*func)(struct mbuf *, int, int, void *),
    794     const struct encapsw *esw, void *arg)
    795 {
    796 	struct encaptab *ep;
    797 	int error;
    798 #ifndef ENCAP_MPSAFE
    799 	int s;
    800 
    801 	s = splsoftnet();
    802 #endif
    803 	/* sanity check on args */
    804 	if (!func) {
    805 		error = EINVAL;
    806 		goto fail;
    807 	}
    808 
    809 	error = encap_afcheck(af, NULL, NULL);
    810 	if (error)
    811 		goto fail;
    812 
    813 	ep = kmem_alloc(sizeof(*ep), KM_NOSLEEP);	/*XXX*/
    814 	if (ep == NULL) {
    815 		error = ENOBUFS;
    816 		goto fail;
    817 	}
    818 	memset(ep, 0, sizeof(*ep));
    819 
    820 	ep->af = af;
    821 	ep->proto = proto;
    822 	ep->func = func;
    823 	ep->esw = esw;
    824 	ep->arg = arg;
    825 	psref_target_init(&ep->psref, encaptab.elem_class);
    826 
    827 	error = encap_add(ep);
    828 	if (error)
    829 		goto fail;
    830 
    831 	error = 0;
    832 #ifndef ENCAP_MPSAFE
    833 	splx(s);
    834 #endif
    835 	return ep;
    836 
    837 fail:
    838 #ifndef ENCAP_MPSAFE
    839 	splx(s);
    840 #endif
    841 	return NULL;
    842 }
    843 
    844 /* XXX encap4_ctlinput() is necessary if we set DF=1 on outer IPv4 header */
    845 
    846 #ifdef INET6
    847 void *
    848 encap6_ctlinput(int cmd, const struct sockaddr *sa, void *d0)
    849 {
    850 	void *d = d0;
    851 	struct ip6_hdr *ip6;
    852 	struct mbuf *m;
    853 	int off;
    854 	struct ip6ctlparam *ip6cp = NULL;
    855 	int nxt;
    856 	int s;
    857 	struct encaptab *ep;
    858 	const struct encapsw *esw;
    859 
    860 	if (sa->sa_family != AF_INET6 ||
    861 	    sa->sa_len != sizeof(struct sockaddr_in6))
    862 		return NULL;
    863 
    864 	if ((unsigned)cmd >= PRC_NCMDS)
    865 		return NULL;
    866 	if (cmd == PRC_HOSTDEAD)
    867 		d = NULL;
    868 	else if (cmd == PRC_MSGSIZE)
    869 		; /* special code is present, see below */
    870 	else if (inet6ctlerrmap[cmd] == 0)
    871 		return NULL;
    872 
    873 	/* if the parameter is from icmp6, decode it. */
    874 	if (d != NULL) {
    875 		ip6cp = (struct ip6ctlparam *)d;
    876 		m = ip6cp->ip6c_m;
    877 		ip6 = ip6cp->ip6c_ip6;
    878 		off = ip6cp->ip6c_off;
    879 		nxt = ip6cp->ip6c_nxt;
    880 
    881 		if (ip6 && cmd == PRC_MSGSIZE) {
    882 			int valid = 0;
    883 			struct encaptab *match;
    884 			struct psref elem_psref;
    885 
    886 			/*
    887 		 	* Check to see if we have a valid encap configuration.
    888 		 	*/
    889 			match = encap6_lookup(m, off, nxt, OUTBOUND,
    890 			    &elem_psref);
    891 			if (match)
    892 				valid++;
    893 			psref_release(&elem_psref, &match->psref,
    894 			    encaptab.elem_class);
    895 
    896 			/*
    897 		 	* Depending on the value of "valid" and routing table
    898 		 	* size (mtudisc_{hi,lo}wat), we will:
    899 		 	* - recalcurate the new MTU and create the
    900 		 	*   corresponding routing entry, or
    901 		 	* - ignore the MTU change notification.
    902 		 	*/
    903 			icmp6_mtudisc_update((struct ip6ctlparam *)d, valid);
    904 		}
    905 	} else {
    906 		m = NULL;
    907 		ip6 = NULL;
    908 		nxt = -1;
    909 	}
    910 
    911 	/* inform all listeners */
    912 
    913 	s = pserialize_read_enter();
    914 	PSLIST_READER_FOREACH(ep, &encap_table, struct encaptab, chain) {
    915 		struct psref elem_psref;
    916 
    917 		if (ep->af != AF_INET6)
    918 			continue;
    919 		if (ep->proto >= 0 && ep->proto != nxt)
    920 			continue;
    921 
    922 		/* should optimize by looking at address pairs */
    923 
    924 		/* XXX need to pass ep->arg or ep itself to listeners */
    925 		psref_acquire(&elem_psref, &ep->psref,
    926 		    encaptab.elem_class);
    927 		esw = ep->esw;
    928 		if (esw && esw->encapsw6.pr_ctlinput) {
    929 			pserialize_read_exit(s);
    930 			/* pr_ctlinput is sleepable. e.g. rtcache_free */
    931 			(*esw->encapsw6.pr_ctlinput)(cmd, sa, d, ep->arg);
    932 			s = pserialize_read_enter();
    933 		}
    934 		psref_release(&elem_psref, &ep->psref,
    935 		    encaptab.elem_class);
    936 	}
    937 	pserialize_read_exit(s);
    938 
    939 	rip6_ctlinput(cmd, sa, d0);
    940 	return NULL;
    941 }
    942 #endif
    943 
    944 int
    945 encap_detach(const struct encaptab *cookie)
    946 {
    947 	const struct encaptab *ep = cookie;
    948 	struct encaptab *p;
    949 	int error;
    950 
    951 	KASSERT(encap_lock_held());
    952 
    953 	PSLIST_WRITER_FOREACH(p, &encap_table, struct encaptab, chain) {
    954 		if (p == ep) {
    955 			error = encap_remove(p);
    956 			if (error)
    957 				return error;
    958 			else
    959 				break;
    960 		}
    961 	}
    962 	if (p == NULL)
    963 		return ENOENT;
    964 
    965 	pserialize_perform(encaptab.psz);
    966 	psref_target_destroy(&p->psref,
    967 	    encaptab.elem_class);
    968 	if (!ep->func) {
    969 		kmem_free(p->addrpack, ep->addrpack->sa_len);
    970 		kmem_free(p->maskpack, ep->maskpack->sa_len);
    971 	}
    972 	kmem_free(p, sizeof(*p));
    973 
    974 	return 0;
    975 }
    976 
    977 #ifdef USE_RADIX
    978 static struct radix_node_head *
    979 encap_rnh(int af)
    980 {
    981 
    982 	switch (af) {
    983 	case AF_INET:
    984 		return encap_head[0];
    985 #ifdef INET6
    986 	case AF_INET6:
    987 		return encap_head[1];
    988 #endif
    989 	default:
    990 		return NULL;
    991 	}
    992 }
    993 
    994 static int
    995 mask_matchlen(const struct sockaddr *sa)
    996 {
    997 	const char *p, *ep;
    998 	int l;
    999 
   1000 	p = (const char *)sa;
   1001 	ep = p + sa->sa_len;
   1002 	p += 2;	/* sa_len + sa_family */
   1003 
   1004 	l = 0;
   1005 	while (p < ep) {
   1006 		l += (*p ? 8 : 0);	/* estimate */
   1007 		p++;
   1008 	}
   1009 	return l;
   1010 }
   1011 #endif
   1012 
   1013 #ifndef USE_RADIX
   1014 static int
   1015 mask_match(const struct encaptab *ep,
   1016 	   const struct sockaddr *sp,
   1017 	   const struct sockaddr *dp)
   1018 {
   1019 	struct sockaddr_storage s;
   1020 	struct sockaddr_storage d;
   1021 	int i;
   1022 	const u_int8_t *p, *q;
   1023 	u_int8_t *r;
   1024 	int matchlen;
   1025 
   1026 	KASSERTMSG(ep->func == NULL, "wrong encaptab passed to mask_match");
   1027 
   1028 	if (sp->sa_len > sizeof(s) || dp->sa_len > sizeof(d))
   1029 		return 0;
   1030 	if (sp->sa_family != ep->af || dp->sa_family != ep->af)
   1031 		return 0;
   1032 	if (sp->sa_len != ep->src->sa_len || dp->sa_len != ep->dst->sa_len)
   1033 		return 0;
   1034 
   1035 	matchlen = 0;
   1036 
   1037 	p = (const u_int8_t *)sp;
   1038 	q = (const u_int8_t *)ep->srcmask;
   1039 	r = (u_int8_t *)&s;
   1040 	for (i = 0 ; i < sp->sa_len; i++) {
   1041 		r[i] = p[i] & q[i];
   1042 		/* XXX estimate */
   1043 		matchlen += (q[i] ? 8 : 0);
   1044 	}
   1045 
   1046 	p = (const u_int8_t *)dp;
   1047 	q = (const u_int8_t *)ep->dstmask;
   1048 	r = (u_int8_t *)&d;
   1049 	for (i = 0 ; i < dp->sa_len; i++) {
   1050 		r[i] = p[i] & q[i];
   1051 		/* XXX rough estimate */
   1052 		matchlen += (q[i] ? 8 : 0);
   1053 	}
   1054 
   1055 	/* need to overwrite len/family portion as we don't compare them */
   1056 	s.ss_len = sp->sa_len;
   1057 	s.ss_family = sp->sa_family;
   1058 	d.ss_len = dp->sa_len;
   1059 	d.ss_family = dp->sa_family;
   1060 
   1061 	if (memcmp(&s, ep->src, ep->src->sa_len) == 0 &&
   1062 	    memcmp(&d, ep->dst, ep->dst->sa_len) == 0) {
   1063 		return matchlen;
   1064 	} else
   1065 		return 0;
   1066 }
   1067 #endif
   1068 
   1069 static void
   1070 encap_fillarg(struct mbuf *m, const struct encaptab *ep)
   1071 {
   1072 	struct m_tag *mtag;
   1073 
   1074 	mtag = m_tag_get(PACKET_TAG_ENCAP, sizeof(void *), M_NOWAIT);
   1075 	if (mtag) {
   1076 		*(void **)(mtag + 1) = ep->arg;
   1077 		m_tag_prepend(m, mtag);
   1078 	}
   1079 }
   1080 
   1081 void *
   1082 encap_getarg(struct mbuf *m)
   1083 {
   1084 	void *p;
   1085 	struct m_tag *mtag;
   1086 
   1087 	p = NULL;
   1088 	mtag = m_tag_find(m, PACKET_TAG_ENCAP, NULL);
   1089 	if (mtag != NULL) {
   1090 		p = *(void **)(mtag + 1);
   1091 		m_tag_delete(m, mtag);
   1092 	}
   1093 	return p;
   1094 }
   1095 
   1096 int
   1097 encap_lock_enter(void)
   1098 {
   1099 	int error;
   1100 
   1101 	mutex_enter(&encap_whole.lock);
   1102 	while (encap_whole.busy != NULL) {
   1103 		error = cv_wait_sig(&encap_whole.cv, &encap_whole.lock);
   1104 		if (error) {
   1105 			mutex_exit(&encap_whole.lock);
   1106 			return error;
   1107 		}
   1108 	}
   1109 	KASSERT(encap_whole.busy == NULL);
   1110 	encap_whole.busy = curlwp;
   1111 	mutex_exit(&encap_whole.lock);
   1112 
   1113 	return 0;
   1114 }
   1115 
   1116 void
   1117 encap_lock_exit(void)
   1118 {
   1119 
   1120 	mutex_enter(&encap_whole.lock);
   1121 	KASSERT(encap_whole.busy == curlwp);
   1122 	encap_whole.busy = NULL;
   1123 	cv_broadcast(&encap_whole.cv);
   1124 	mutex_exit(&encap_whole.lock);
   1125 }
   1126 
   1127 bool
   1128 encap_lock_held(void)
   1129 {
   1130 
   1131 	return (encap_whole.busy == curlwp);
   1132 }
   1133