Home | History | Annotate | Line # | Download | only in netinet6
icmp6.c revision 1.257
      1 /*	$NetBSD: icmp6.c,v 1.257 2024/06/29 13:00:44 riastradh Exp $	*/
      2 /*	$KAME: icmp6.c,v 1.217 2001/06/20 15:03:29 jinmei 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 /*
     34  * Copyright (c) 1982, 1986, 1988, 1993
     35  *	The Regents of the University of California.  All rights reserved.
     36  *
     37  * Redistribution and use in source and binary forms, with or without
     38  * modification, are permitted provided that the following conditions
     39  * are met:
     40  * 1. Redistributions of source code must retain the above copyright
     41  *    notice, this list of conditions and the following disclaimer.
     42  * 2. Redistributions in binary form must reproduce the above copyright
     43  *    notice, this list of conditions and the following disclaimer in the
     44  *    documentation and/or other materials provided with the distribution.
     45  * 3. Neither the name of the University nor the names of its contributors
     46  *    may be used to endorse or promote products derived from this software
     47  *    without specific prior written permission.
     48  *
     49  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     50  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     51  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     52  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     53  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     54  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     55  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     56  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     57  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     58  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     59  * SUCH DAMAGE.
     60  *
     61  *	@(#)ip_icmp.c	8.2 (Berkeley) 1/4/94
     62  */
     63 
     64 #include <sys/cdefs.h>
     65 __KERNEL_RCSID(0, "$NetBSD: icmp6.c,v 1.257 2024/06/29 13:00:44 riastradh Exp $");
     66 
     67 #ifdef _KERNEL_OPT
     68 #include "opt_compat_netbsd.h"
     69 #include "opt_inet.h"
     70 #include "opt_ipsec.h"
     71 #endif
     72 
     73 #include <sys/param.h>
     74 #include <sys/systm.h>
     75 #include <sys/kmem.h>
     76 #include <sys/mbuf.h>
     77 #include <sys/protosw.h>
     78 #include <sys/socket.h>
     79 #include <sys/socketvar.h>
     80 #include <sys/time.h>
     81 #include <sys/kernel.h>
     82 #include <sys/syslog.h>
     83 #include <sys/domain.h>
     84 #include <sys/sysctl.h>
     85 
     86 #include <net/if.h>
     87 #include <net/route.h>
     88 #include <net/if_dl.h>
     89 #include <net/if_types.h>
     90 #include <net/nd.h>
     91 
     92 #include <netinet/in.h>
     93 #include <netinet/in_pcb.h>
     94 #include <netinet/in_var.h>
     95 #include <netinet/ip6.h>
     96 #include <netinet/wqinput.h>
     97 #include <netinet6/ip6_var.h>
     98 #include <netinet6/ip6_private.h>
     99 #include <netinet/icmp6.h>
    100 #include <netinet6/icmp6_private.h>
    101 #include <netinet6/mld6_var.h>
    102 #include <netinet6/in6_pcb.h>
    103 #include <netinet6/in6_ifattach.h>
    104 #include <netinet6/ip6protosw.h>
    105 #include <netinet6/nd6.h>
    106 #include <netinet6/scope6_var.h>
    107 
    108 #ifdef IPSEC
    109 #include <netipsec/ipsec.h>
    110 #include <netipsec/ipsec6.h>
    111 #include <netipsec/key.h>
    112 #endif
    113 
    114 #include "faith.h"
    115 #if defined(NFAITH) && 0 < NFAITH
    116 #include <net/if_faith.h>
    117 #endif
    118 
    119 /* Ensure that non packed structures are the desired size. */
    120 __CTASSERT(sizeof(struct icmp6_hdr) == 8);
    121 __CTASSERT(sizeof(struct icmp6_nodeinfo) == 16);
    122 __CTASSERT(sizeof(struct icmp6_namelookup) == 20);
    123 __CTASSERT(sizeof(struct icmp6_router_renum) == 16);
    124 
    125 __CTASSERT(sizeof(struct nd_router_solicit) == 8);
    126 __CTASSERT(sizeof(struct nd_router_advert) == 16);
    127 __CTASSERT(sizeof(struct nd_neighbor_solicit) == 24);
    128 __CTASSERT(sizeof(struct nd_neighbor_advert) == 24);
    129 __CTASSERT(sizeof(struct nd_redirect) == 40);
    130 __CTASSERT(sizeof(struct nd_opt_hdr) == 2);
    131 __CTASSERT(sizeof(struct nd_opt_route_info) == 8);
    132 __CTASSERT(sizeof(struct nd_opt_prefix_info) == 32);
    133 __CTASSERT(sizeof(struct nd_opt_rd_hdr) == 8);
    134 __CTASSERT(sizeof(struct nd_opt_mtu) == 8);
    135 __CTASSERT(sizeof(struct nd_opt_nonce) == 2 + ND_OPT_NONCE_LEN);
    136 __CTASSERT(sizeof(struct nd_opt_rdnss) == 8);
    137 __CTASSERT(sizeof(struct nd_opt_dnssl) == 8);
    138 
    139 __CTASSERT(sizeof(struct mld_hdr) == 24);
    140 __CTASSERT(sizeof(struct ni_reply_fqdn) == 8);
    141 __CTASSERT(sizeof(struct rr_pco_match) == 24);
    142 __CTASSERT(sizeof(struct rr_pco_use) == 32);
    143 __CTASSERT(sizeof(struct rr_result) == 24);
    144 
    145 extern struct domain inet6domain;
    146 
    147 percpu_t *icmp6stat_percpu;
    148 
    149 extern struct inpcbtable raw6cbtable;
    150 extern int icmp6errppslim;
    151 static int icmp6errpps_count = 0;
    152 static struct timeval icmp6errppslim_last;
    153 extern int icmp6_nodeinfo;
    154 
    155 bool icmp6_dynamic_rt_msg = false;
    156 
    157 /*
    158  * List of callbacks to notify when Path MTU changes are made.
    159  */
    160 struct icmp6_mtudisc_callback {
    161 	LIST_ENTRY(icmp6_mtudisc_callback) mc_list;
    162 	void (*mc_func)(struct in6_addr *);
    163 };
    164 
    165 LIST_HEAD(, icmp6_mtudisc_callback) icmp6_mtudisc_callbacks =
    166     LIST_HEAD_INITIALIZER(&icmp6_mtudisc_callbacks);
    167 
    168 static struct rttimer_queue *icmp6_mtudisc_timeout_q = NULL;
    169 extern int pmtu_expire;
    170 
    171 /* XXX do these values make any sense? */
    172 static int icmp6_mtudisc_hiwat = 1280;
    173 static int icmp6_mtudisc_lowat = 256;
    174 
    175 /*
    176  * keep track of # of redirect routes.
    177  */
    178 static struct rttimer_queue *icmp6_redirect_timeout_q = NULL;
    179 
    180 /* XXX experimental, turned off */
    181 static int icmp6_redirect_hiwat = -1;
    182 static int icmp6_redirect_lowat = -1;
    183 
    184 /* Protect mtudisc and redirect stuffs */
    185 static kmutex_t icmp6_mtx __cacheline_aligned;
    186 
    187 static bool icmp6_reflect_pmtu = false;
    188 
    189 static void icmp6_errcount(u_int, int, int);
    190 static int icmp6_rip6_input(struct mbuf **, int);
    191 static void icmp6_reflect(struct mbuf *, size_t);
    192 static int icmp6_ratelimit(const struct in6_addr *, const int, const int);
    193 static const char *icmp6_redirect_diag(char *, size_t, struct in6_addr *,
    194     struct in6_addr *, struct in6_addr *);
    195 static void icmp6_redirect_input(struct mbuf *, int);
    196 static struct mbuf *ni6_input(struct mbuf *, int);
    197 static struct mbuf *ni6_nametodns(const char *, int, int);
    198 static int ni6_dnsmatch(const char *, int, const char *, int);
    199 static int ni6_addrs(struct icmp6_nodeinfo *, struct ifnet **, char *,
    200     struct psref *);
    201 static int ni6_store_addrs(struct icmp6_nodeinfo *, struct icmp6_nodeinfo *,
    202     struct ifnet *, int);
    203 static int icmp6_notify_error(struct mbuf *, int, int, int);
    204 static struct rtentry *icmp6_mtudisc_clone(struct sockaddr *);
    205 static void icmp6_mtudisc_timeout(struct rtentry *, struct rttimer *);
    206 static void icmp6_redirect_timeout(struct rtentry *, struct rttimer *);
    207 static void sysctl_net_inet6_icmp6_setup(struct sysctllog **);
    208 
    209 /* workqueue-based pr_input */
    210 static struct wqinput *icmp6_wqinput;
    211 static void _icmp6_input(struct mbuf *m, int off, int proto);
    212 
    213 void
    214 icmp6_init(void)
    215 {
    216 
    217 	sysctl_net_inet6_icmp6_setup(NULL);
    218 	mld_init();
    219 
    220 	mutex_init(&icmp6_mtx, MUTEX_DEFAULT, IPL_NONE);
    221 	mutex_enter(&icmp6_mtx);
    222 	icmp6_mtudisc_timeout_q = rt_timer_queue_create(pmtu_expire);
    223 	icmp6_redirect_timeout_q = rt_timer_queue_create(icmp6_redirtimeout);
    224 	mutex_exit(&icmp6_mtx);
    225 
    226 	icmp6stat_percpu = percpu_alloc(sizeof(uint64_t) * ICMP6_NSTATS);
    227 
    228 	icmp6_wqinput = wqinput_create("icmp6", _icmp6_input);
    229 }
    230 
    231 static void
    232 icmp6_errcount(u_int base, int type, int code)
    233 {
    234 	switch (type) {
    235 	case ICMP6_DST_UNREACH:
    236 		switch (code) {
    237 		case ICMP6_DST_UNREACH_NOROUTE:
    238 			ICMP6_STATINC(base + ICMP6_ERRSTAT_DST_UNREACH_NOROUTE);
    239 			return;
    240 		case ICMP6_DST_UNREACH_ADMIN:
    241 			ICMP6_STATINC(base + ICMP6_ERRSTAT_DST_UNREACH_ADMIN);
    242 			return;
    243 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
    244 			ICMP6_STATINC(base +
    245 				      ICMP6_ERRSTAT_DST_UNREACH_BEYONDSCOPE);
    246 			return;
    247 		case ICMP6_DST_UNREACH_ADDR:
    248 			ICMP6_STATINC(base + ICMP6_ERRSTAT_DST_UNREACH_ADDR);
    249 			return;
    250 		case ICMP6_DST_UNREACH_NOPORT:
    251 			ICMP6_STATINC(base + ICMP6_ERRSTAT_DST_UNREACH_NOPORT);
    252 			return;
    253 		}
    254 		break;
    255 	case ICMP6_PACKET_TOO_BIG:
    256 		ICMP6_STATINC(base + ICMP6_ERRSTAT_PACKET_TOO_BIG);
    257 		return;
    258 	case ICMP6_TIME_EXCEEDED:
    259 		switch (code) {
    260 		case ICMP6_TIME_EXCEED_TRANSIT:
    261 			ICMP6_STATINC(base + ICMP6_ERRSTAT_TIME_EXCEED_TRANSIT);
    262 			return;
    263 		case ICMP6_TIME_EXCEED_REASSEMBLY:
    264 			ICMP6_STATINC(base +
    265 				      ICMP6_ERRSTAT_TIME_EXCEED_REASSEMBLY);
    266 			return;
    267 		}
    268 		break;
    269 	case ICMP6_PARAM_PROB:
    270 		switch (code) {
    271 		case ICMP6_PARAMPROB_HEADER:
    272 			ICMP6_STATINC(base + ICMP6_ERRSTAT_PARAMPROB_HEADER);
    273 			return;
    274 		case ICMP6_PARAMPROB_NEXTHEADER:
    275 			ICMP6_STATINC(base +
    276 				      ICMP6_ERRSTAT_PARAMPROB_NEXTHEADER);
    277 			return;
    278 		case ICMP6_PARAMPROB_OPTION:
    279 			ICMP6_STATINC(base + ICMP6_ERRSTAT_PARAMPROB_OPTION);
    280 			return;
    281 		}
    282 		break;
    283 	case ND_REDIRECT:
    284 		ICMP6_STATINC(base + ICMP6_ERRSTAT_REDIRECT);
    285 		return;
    286 	}
    287 	ICMP6_STATINC(base + ICMP6_ERRSTAT_UNKNOWN);
    288 }
    289 
    290 /*
    291  * Register a Path MTU Discovery callback.
    292  */
    293 void
    294 icmp6_mtudisc_callback_register(void (*func)(struct in6_addr *))
    295 {
    296 	struct icmp6_mtudisc_callback *mc, *new;
    297 
    298 	new = kmem_alloc(sizeof(*mc), KM_SLEEP);
    299 
    300 	mutex_enter(&icmp6_mtx);
    301 	for (mc = LIST_FIRST(&icmp6_mtudisc_callbacks); mc != NULL;
    302 	     mc = LIST_NEXT(mc, mc_list)) {
    303 		if (mc->mc_func == func) {
    304 			mutex_exit(&icmp6_mtx);
    305 			kmem_free(new, sizeof(*mc));
    306 			return;
    307 		}
    308 	}
    309 
    310 	new->mc_func = func;
    311 	LIST_INSERT_HEAD(&icmp6_mtudisc_callbacks, new, mc_list);
    312 	mutex_exit(&icmp6_mtx);
    313 }
    314 
    315 /*
    316  * A wrapper function for icmp6_error() necessary when the erroneous packet
    317  * may not contain enough scope zone information.
    318  */
    319 void
    320 icmp6_error2(struct mbuf *m, int type, int code, int param,
    321 	struct ifnet *ifp, struct in6_addr *src)
    322 {
    323 	struct ip6_hdr *ip6;
    324 
    325 	KASSERT(ifp != NULL);
    326 
    327 	if (m->m_len < sizeof(struct ip6_hdr)) {
    328 		m = m_pullup(m, sizeof(struct ip6_hdr));
    329 		if (m == NULL)
    330 			return;
    331 	}
    332 
    333 	ip6 = mtod(m, struct ip6_hdr *);
    334 
    335 	if (in6_setscope(&ip6->ip6_src, ifp, NULL) != 0)
    336 		goto out;
    337 	if (in6_setscope(&ip6->ip6_dst, ifp, NULL) != 0)
    338 		goto out;
    339 
    340 	*src = ip6->ip6_src;
    341 	icmp6_error(m, type, code, param);
    342 	return;
    343 
    344 out:
    345 	m_freem(m);
    346 }
    347 
    348 /*
    349  * Generate an error packet of type error in response to bad IP6 packet.
    350  */
    351 void
    352 icmp6_error(struct mbuf *m, int type, int code, int param)
    353 {
    354 	struct ip6_hdr *oip6, *nip6;
    355 	struct icmp6_hdr *icmp6;
    356 	u_int preplen;
    357 	int off;
    358 	int nxt;
    359 
    360 	ICMP6_STATINC(ICMP6_STAT_ERROR);
    361 
    362 	/* count per-type-code statistics */
    363 	icmp6_errcount(ICMP6_STAT_OUTERRHIST, type, code);
    364 
    365 	if (m->m_flags & M_DECRYPTED) {
    366 		ICMP6_STATINC(ICMP6_STAT_CANTERROR);
    367 		goto freeit;
    368 	}
    369 
    370 	if (M_UNWRITABLE(m, sizeof(struct ip6_hdr)) &&
    371 	    (m = m_pullup(m, sizeof(struct ip6_hdr))) == NULL)
    372 		return;
    373 	oip6 = mtod(m, struct ip6_hdr *);
    374 
    375 	/*
    376 	 * If the destination address of the erroneous packet is a multicast
    377 	 * address, or the packet was sent using link-layer multicast,
    378 	 * we should basically suppress sending an error (RFC 2463, Section
    379 	 * 2.4).
    380 	 * We have two exceptions (the item e.2 in that section):
    381 	 * - the Packet Too Big message can be sent for path MTU discovery.
    382 	 * - the Parameter Problem Message that can be allowed an icmp6 error
    383 	 *   in the option type field.  This check has been done in
    384 	 *   ip6_unknown_opt(), so we can just check the type and code.
    385 	 */
    386 	if ((m->m_flags & (M_BCAST|M_MCAST) ||
    387 	     IN6_IS_ADDR_MULTICAST(&oip6->ip6_dst)) &&
    388 	    (type != ICMP6_PACKET_TOO_BIG &&
    389 	     (type != ICMP6_PARAM_PROB ||
    390 	      code != ICMP6_PARAMPROB_OPTION)))
    391 		goto freeit;
    392 
    393 	/*
    394 	 * RFC 2463, 2.4 (e.5): source address check.
    395 	 * XXX: the case of anycast source?
    396 	 */
    397 	if (IN6_IS_ADDR_UNSPECIFIED(&oip6->ip6_src) ||
    398 	    IN6_IS_ADDR_MULTICAST(&oip6->ip6_src))
    399 		goto freeit;
    400 
    401 	/*
    402 	 * If we are about to send ICMPv6 against ICMPv6 error/redirect,
    403 	 * don't do it.
    404 	 */
    405 	nxt = -1;
    406 	off = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxt);
    407 	if (off >= 0 && nxt == IPPROTO_ICMPV6) {
    408 		struct icmp6_hdr *icp;
    409 
    410 		IP6_EXTHDR_GET(icp, struct icmp6_hdr *, m, off,
    411 			sizeof(*icp));
    412 		if (icp == NULL) {
    413 			ICMP6_STATINC(ICMP6_STAT_TOOSHORT);
    414 			return;
    415 		}
    416 		if (icp->icmp6_type < ICMP6_ECHO_REQUEST ||
    417 		    icp->icmp6_type == ND_REDIRECT) {
    418 			/*
    419 			 * ICMPv6 error
    420 			 * Special case: for redirect (which is
    421 			 * informational) we must not send icmp6 error.
    422 			 */
    423 			ICMP6_STATINC(ICMP6_STAT_CANTERROR);
    424 			goto freeit;
    425 		} else {
    426 			/* ICMPv6 informational - send the error */
    427 		}
    428 	} else {
    429 		/* non-ICMPv6 - send the error */
    430 	}
    431 
    432 	oip6 = mtod(m, struct ip6_hdr *); /* adjust pointer */
    433 
    434 	/* Finally, do rate limitation check. */
    435 	if (icmp6_ratelimit(&oip6->ip6_src, type, code)) {
    436 		ICMP6_STATINC(ICMP6_STAT_TOOFREQ);
    437 		goto freeit;
    438 	}
    439 
    440 	/*
    441 	 * OK, ICMP6 can be generated.
    442 	 */
    443 
    444 	if (m->m_pkthdr.len >= ICMPV6_PLD_MAXLEN)
    445 		m_adj(m, ICMPV6_PLD_MAXLEN - m->m_pkthdr.len);
    446 
    447 	preplen = sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr);
    448 	M_PREPEND(m, preplen, M_DONTWAIT);
    449 	if (m && M_UNWRITABLE(m, preplen))
    450 		m = m_pullup(m, preplen);
    451 	if (m == NULL) {
    452 		nd6log(LOG_DEBUG, "ENOBUFS in icmp6_error %d\n", __LINE__);
    453 		return;
    454 	}
    455 
    456 	nip6 = mtod(m, struct ip6_hdr *);
    457 	nip6->ip6_src  = oip6->ip6_src;
    458 	nip6->ip6_dst  = oip6->ip6_dst;
    459 
    460 	in6_clearscope(&oip6->ip6_src);
    461 	in6_clearscope(&oip6->ip6_dst);
    462 
    463 	icmp6 = (struct icmp6_hdr *)(nip6 + 1);
    464 	icmp6->icmp6_type = type;
    465 	icmp6->icmp6_code = code;
    466 	icmp6->icmp6_pptr = htonl((u_int32_t)param);
    467 
    468 	/*
    469 	 * icmp6_reflect() is designed to be in the input path.
    470 	 * icmp6_error() can be called from both input and output path,
    471 	 * and if we are in output path rcvif could contain bogus value.
    472 	 * clear m->m_pkthdr.rcvif for safety, we should have enough scope
    473 	 * information in ip header (nip6).
    474 	 */
    475 	m_reset_rcvif(m);
    476 
    477 	ICMP6_STATINC(ICMP6_STAT_OUTHIST + type);
    478 
    479 	/* header order: IPv6 - ICMPv6 */
    480 	icmp6_reflect(m, sizeof(struct ip6_hdr));
    481 
    482 	return;
    483 
    484 freeit:
    485 	/*
    486 	 * If we can't tell whether or not we can generate ICMP6, free it.
    487 	 */
    488 	m_freem(m);
    489 }
    490 
    491 /*
    492  * Process a received ICMP6 message.
    493  */
    494 static void
    495 _icmp6_input(struct mbuf *m, int off, int proto)
    496 {
    497 	struct mbuf *n;
    498 	struct ip6_hdr *ip6, *nip6;
    499 	struct icmp6_hdr *icmp6, *nicmp6;
    500 	int icmp6len = m->m_pkthdr.len - off;
    501 	int code, sum;
    502 	struct ifnet *rcvif;
    503 	struct psref psref;
    504 	char ip6buf[INET6_ADDRSTRLEN], ip6buf2[INET6_ADDRSTRLEN];
    505 
    506 	rcvif = m_get_rcvif_psref(m, &psref);
    507 	if (__predict_false(rcvif == NULL))
    508 		goto freeit;
    509 
    510 #define ICMP6_MAXLEN (sizeof(*nip6) + sizeof(*nicmp6) + 4)
    511 	KASSERT(ICMP6_MAXLEN < MCLBYTES);
    512 	icmp6_ifstat_inc(rcvif, ifs6_in_msg);
    513 
    514 	/*
    515 	 * Locate icmp6 structure in mbuf, and check
    516 	 * that not corrupted and of at least minimum length
    517 	 */
    518 
    519 	if (icmp6len < sizeof(struct icmp6_hdr)) {
    520 		ICMP6_STATINC(ICMP6_STAT_TOOSHORT);
    521 		icmp6_ifstat_inc(rcvif, ifs6_in_error);
    522 		goto freeit;
    523 	}
    524 
    525 	if (m->m_len < sizeof(struct ip6_hdr)) {
    526 		m = m_pullup(m, sizeof(struct ip6_hdr));
    527 		if (m == NULL) {
    528 			ICMP6_STATINC(ICMP6_STAT_TOOSHORT);
    529 			icmp6_ifstat_inc(rcvif, ifs6_in_error);
    530 			goto freeit;
    531 		}
    532 	}
    533 
    534 	ip6 = mtod(m, struct ip6_hdr *);
    535 	IP6_EXTHDR_GET(icmp6, struct icmp6_hdr *, m, off, sizeof(*icmp6));
    536 	if (icmp6 == NULL) {
    537 		ICMP6_STATINC(ICMP6_STAT_TOOSHORT);
    538 		icmp6_ifstat_inc(rcvif, ifs6_in_error);
    539 		goto freeit;
    540 	}
    541 
    542 	/*
    543 	 * Enforce alignment requirements that are violated in
    544 	 * some cases, see kern/50766 for details.
    545 	 */
    546 	if (ACCESSIBLE_POINTER(icmp6, struct ip6_hdr) == 0) {
    547 		m = m_copyup(m, off + sizeof(struct icmp6_hdr), 0);
    548 		if (m == NULL) {
    549 			ICMP6_STATINC(ICMP6_STAT_TOOSHORT);
    550 			icmp6_ifstat_inc(rcvif, ifs6_in_error);
    551 			goto freeit;
    552 		}
    553 		ip6 = mtod(m, struct ip6_hdr *);
    554 		icmp6 = (struct icmp6_hdr *)(mtod(m, char *) + off);
    555 	}
    556 	KASSERT(ACCESSIBLE_POINTER(icmp6, struct ip6_hdr));
    557 
    558 	/*
    559 	 * calculate the checksum
    560 	 */
    561 	if ((sum = in6_cksum(m, IPPROTO_ICMPV6, off, icmp6len)) != 0) {
    562 		nd6log(LOG_ERR, "ICMP6 checksum error(%d|%x) %s\n",
    563 		    icmp6->icmp6_type, sum, IN6_PRINT(ip6buf, &ip6->ip6_src));
    564 		ICMP6_STATINC(ICMP6_STAT_CHECKSUM);
    565 		icmp6_ifstat_inc(rcvif, ifs6_in_error);
    566 		goto freeit;
    567 	}
    568 
    569 #if defined(NFAITH) && 0 < NFAITH
    570 	if (faithprefix(&ip6->ip6_dst)) {
    571 		/*
    572 		 * Deliver very specific ICMP6 type only.
    573 		 * This is important to deliver TOOBIG.  Otherwise PMTUD
    574 		 * will not work.
    575 		 */
    576 		switch (icmp6->icmp6_type) {
    577 		case ICMP6_DST_UNREACH:
    578 		case ICMP6_PACKET_TOO_BIG:
    579 		case ICMP6_TIME_EXCEEDED:
    580 			break;
    581 		default:
    582 			goto freeit;
    583 		}
    584 	}
    585 #endif
    586 
    587 	code = icmp6->icmp6_code;
    588 	ICMP6_STATINC(ICMP6_STAT_INHIST + icmp6->icmp6_type);
    589 
    590 	switch (icmp6->icmp6_type) {
    591 	case ICMP6_DST_UNREACH:
    592 		icmp6_ifstat_inc(rcvif, ifs6_in_dstunreach);
    593 		switch (code) {
    594 		case ICMP6_DST_UNREACH_NOROUTE:
    595 			code = PRC_UNREACH_NET;
    596 			break;
    597 		case ICMP6_DST_UNREACH_ADMIN:
    598 			icmp6_ifstat_inc(rcvif, ifs6_in_adminprohib);
    599 			code = PRC_UNREACH_PROTOCOL; /* is this a good code? */
    600 			break;
    601 		case ICMP6_DST_UNREACH_ADDR:
    602 			code = PRC_HOSTDEAD;
    603 			break;
    604 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
    605 			/* I mean "source address was incorrect." */
    606 			code = PRC_UNREACH_NET;
    607 			break;
    608 		case ICMP6_DST_UNREACH_NOPORT:
    609 			code = PRC_UNREACH_PORT;
    610 			break;
    611 		default:
    612 			goto badcode;
    613 		}
    614 		goto deliver;
    615 
    616 	case ICMP6_PACKET_TOO_BIG:
    617 		icmp6_ifstat_inc(rcvif, ifs6_in_pkttoobig);
    618 
    619 		/*
    620 		 * MTU is checked in icmp6_mtudisc.
    621 		 */
    622 		code = PRC_MSGSIZE;
    623 
    624 		/*
    625 		 * Updating the path MTU will be done after examining
    626 		 * intermediate extension headers.
    627 		 */
    628 		goto deliver;
    629 
    630 	case ICMP6_TIME_EXCEEDED:
    631 		icmp6_ifstat_inc(rcvif, ifs6_in_timeexceed);
    632 		switch (code) {
    633 		case ICMP6_TIME_EXCEED_TRANSIT:
    634 			code = PRC_TIMXCEED_INTRANS;
    635 			break;
    636 		case ICMP6_TIME_EXCEED_REASSEMBLY:
    637 			code = PRC_TIMXCEED_REASS;
    638 			break;
    639 		default:
    640 			goto badcode;
    641 		}
    642 		goto deliver;
    643 
    644 	case ICMP6_PARAM_PROB:
    645 		icmp6_ifstat_inc(rcvif, ifs6_in_paramprob);
    646 		switch (code) {
    647 		case ICMP6_PARAMPROB_NEXTHEADER:
    648 			code = PRC_UNREACH_PROTOCOL;
    649 			break;
    650 		case ICMP6_PARAMPROB_HEADER:
    651 		case ICMP6_PARAMPROB_OPTION:
    652 			code = PRC_PARAMPROB;
    653 			break;
    654 		default:
    655 			goto badcode;
    656 		}
    657 		goto deliver;
    658 
    659 	case ICMP6_ECHO_REQUEST:
    660 		icmp6_ifstat_inc(rcvif, ifs6_in_echo);
    661 		if (code != 0)
    662 			goto badcode;
    663 		/*
    664 		 * Copy mbuf to send to two data paths: userland socket(s),
    665 		 * and to the querier (echo reply).
    666 		 * m: a copy for socket, n: a copy for querier
    667 		 *
    668 		 * If the first mbuf is shared, or the first mbuf is too short,
    669 		 * copy the first part of the data into a fresh mbuf.
    670 		 * Otherwise, we will wrongly overwrite both copies.
    671 		 */
    672 		if ((n = m_copypacket(m, M_DONTWAIT)) == NULL) {
    673 			/* Give up local */
    674 			n = m;
    675 			m = NULL;
    676 		} else if (M_UNWRITABLE(n, off + sizeof(struct icmp6_hdr))) {
    677 			struct mbuf *n0 = n;
    678 
    679 			/*
    680 			 * Prepare an internal mbuf.  m_pullup() doesn't
    681 			 * always copy the length we specified.
    682 			 */
    683 			if ((n = m_dup(n0, 0, M_COPYALL, M_DONTWAIT)) == NULL) {
    684 				/* Give up local */
    685 				n = m;
    686 				m = NULL;
    687 			}
    688 			m_freem(n0);
    689 		}
    690 		IP6_EXTHDR_GET(nicmp6, struct icmp6_hdr *, n, off,
    691 		    sizeof(*nicmp6));
    692 		if (nicmp6 == NULL)
    693 			goto freeit;
    694 		nicmp6->icmp6_type = ICMP6_ECHO_REPLY;
    695 		nicmp6->icmp6_code = 0;
    696 		if (n) {
    697 			net_stat_ref_t icmp6s = ICMP6_STAT_GETREF();
    698 			_NET_STATINC_REF(icmp6s, ICMP6_STAT_REFLECT);
    699 			_NET_STATINC_REF(icmp6s,
    700 			    ICMP6_STAT_OUTHIST + ICMP6_ECHO_REPLY);
    701 			ICMP6_STAT_PUTREF();
    702 			icmp6_reflect(n, off);
    703 		}
    704 		if (!m)
    705 			goto freeit;
    706 		break;
    707 
    708 	case ICMP6_ECHO_REPLY:
    709 		icmp6_ifstat_inc(rcvif, ifs6_in_echoreply);
    710 		if (code != 0)
    711 			goto badcode;
    712 		break;
    713 
    714 	case MLD_LISTENER_QUERY:
    715 	case MLD_LISTENER_REPORT:
    716 		if (icmp6len < sizeof(struct mld_hdr))
    717 			goto badlen;
    718 		if (icmp6->icmp6_type == MLD_LISTENER_QUERY) /* XXX: ugly... */
    719 			icmp6_ifstat_inc(rcvif, ifs6_in_mldquery);
    720 		else
    721 			icmp6_ifstat_inc(rcvif, ifs6_in_mldreport);
    722 		if ((n = m_copypacket(m, M_DONTWAIT)) == NULL) {
    723 			/* give up local */
    724 			mld_input(m, off);
    725 			m = NULL;
    726 			goto freeit;
    727 		}
    728 		mld_input(n, off);
    729 		/* m stays. */
    730 		break;
    731 
    732 	case MLD_LISTENER_DONE:
    733 		icmp6_ifstat_inc(rcvif, ifs6_in_mlddone);
    734 		if (icmp6len < sizeof(struct mld_hdr))	/* necessary? */
    735 			goto badlen;
    736 		break;		/* nothing to be done in kernel */
    737 
    738 	case MLD_MTRACE_RESP:
    739 	case MLD_MTRACE:
    740 		/* XXX: these two are experimental.  not officially defined. */
    741 		/* XXX: per-interface statistics? */
    742 		break;		/* just pass it to applications */
    743 
    744 	case ICMP6_WRUREQUEST:	/* ICMP6_FQDN_QUERY */
    745 	    {
    746 		enum { WRU, FQDN } mode;
    747 
    748 		if (!icmp6_nodeinfo)
    749 			break;
    750 
    751 		if (icmp6len == sizeof(struct icmp6_hdr) + 4)
    752 			mode = WRU;
    753 		else if (icmp6len >= sizeof(struct icmp6_nodeinfo))
    754 			mode = FQDN;
    755 		else
    756 			goto badlen;
    757 
    758 		if (mode == FQDN) {
    759 			n = m_copypacket(m, M_DONTWAIT);
    760 			if (n)
    761 				n = ni6_input(n, off);
    762 		} else {
    763 			u_char *p;
    764 			int maxhlen;
    765 
    766 			if ((icmp6_nodeinfo & 5) != 5)
    767 				break;
    768 
    769 			if (code != 0)
    770 				goto badcode;
    771 			MGETHDR(n, M_DONTWAIT, m->m_type);
    772 			if (n && ICMP6_MAXLEN > MHLEN) {
    773 				MCLGET(n, M_DONTWAIT);
    774 				if ((n->m_flags & M_EXT) == 0) {
    775 					m_free(n);
    776 					n = NULL;
    777 				}
    778 			}
    779 			if (n == NULL) {
    780 				/* Give up remote */
    781 				break;
    782 			}
    783 			m_reset_rcvif(n);
    784 			n->m_len = 0;
    785 			maxhlen = M_TRAILINGSPACE(n) - ICMP6_MAXLEN;
    786 			if (maxhlen < 0) {
    787 				m_free(n);
    788 				break;
    789 			}
    790 			if (maxhlen > hostnamelen)
    791 				maxhlen = hostnamelen;
    792 			/*
    793 			 * Copy IPv6 and ICMPv6 only.
    794 			 */
    795 			nip6 = mtod(n, struct ip6_hdr *);
    796 			memcpy(nip6, ip6, sizeof(struct ip6_hdr));
    797 			nicmp6 = (struct icmp6_hdr *)(nip6 + 1);
    798 			memcpy(nicmp6, icmp6, sizeof(struct icmp6_hdr));
    799 
    800 			p = (u_char *)(nicmp6 + 1);
    801 			memset(p, 0, 4);
    802 			memcpy(p + 4, hostname, maxhlen); /* meaningless TTL */
    803 
    804 			m_copy_pkthdr(n, m);
    805 			n->m_pkthdr.len = n->m_len = sizeof(struct ip6_hdr) +
    806 				sizeof(struct icmp6_hdr) + 4 + maxhlen;
    807 			nicmp6->icmp6_type = ICMP6_WRUREPLY;
    808 			nicmp6->icmp6_code = 0;
    809 		}
    810 		if (n) {
    811 			net_stat_ref_t icmp6s = ICMP6_STAT_GETREF();
    812 			_NET_STATINC_REF(icmp6s, ICMP6_STAT_REFLECT);
    813 			_NET_STATINC_REF(icmp6s,
    814 			    ICMP6_STAT_OUTHIST + ICMP6_WRUREPLY);
    815 			ICMP6_STAT_PUTREF();
    816 			icmp6_reflect(n, sizeof(struct ip6_hdr));
    817 		}
    818 		break;
    819 	    }
    820 
    821 	case ICMP6_WRUREPLY:
    822 		if (code != 0)
    823 			goto badcode;
    824 		break;
    825 
    826 	case ND_ROUTER_SOLICIT:
    827 		icmp6_ifstat_inc(rcvif, ifs6_in_routersolicit);
    828 		/* FALLTHROUGH */
    829 	case ND_ROUTER_ADVERT:
    830 		if (icmp6->icmp6_type == ND_ROUTER_ADVERT)
    831 			icmp6_ifstat_inc(rcvif, ifs6_in_routeradvert);
    832 		if (code != 0)
    833 			goto badcode;
    834 		if ((icmp6->icmp6_type == ND_ROUTER_SOLICIT &&
    835 		    icmp6len < sizeof(struct nd_router_solicit)) ||
    836 		    (icmp6->icmp6_type == ND_ROUTER_ADVERT &&
    837 		    icmp6len < sizeof(struct nd_router_advert)))
    838 			goto badlen;
    839 		if ((n = m_copypacket(m, M_DONTWAIT)) == NULL) {
    840 			/* give up local */
    841 			nd6_rtr_cache(m, off, icmp6len, icmp6->icmp6_type);
    842 			m = NULL;
    843 			goto freeit;
    844 		}
    845 		nd6_rtr_cache(n, off, icmp6len, icmp6->icmp6_type);
    846 		/* m stays. */
    847 		break;
    848 
    849 	case ND_NEIGHBOR_SOLICIT:
    850 		icmp6_ifstat_inc(rcvif, ifs6_in_neighborsolicit);
    851 		if (code != 0)
    852 			goto badcode;
    853 		if (icmp6len < sizeof(struct nd_neighbor_solicit))
    854 			goto badlen;
    855 		if ((n = m_copypacket(m, M_DONTWAIT)) == NULL) {
    856 			/* give up local */
    857 			nd6_ns_input(m, off, icmp6len);
    858 			m = NULL;
    859 			goto freeit;
    860 		}
    861 		nd6_ns_input(n, off, icmp6len);
    862 		/* m stays. */
    863 		break;
    864 
    865 	case ND_NEIGHBOR_ADVERT:
    866 		icmp6_ifstat_inc(rcvif, ifs6_in_neighboradvert);
    867 		if (code != 0)
    868 			goto badcode;
    869 		if (icmp6len < sizeof(struct nd_neighbor_advert))
    870 			goto badlen;
    871 		if ((n = m_copypacket(m, M_DONTWAIT)) == NULL) {
    872 			/* give up local */
    873 			nd6_na_input(m, off, icmp6len);
    874 			m = NULL;
    875 			goto freeit;
    876 		}
    877 		nd6_na_input(n, off, icmp6len);
    878 		/* m stays. */
    879 		break;
    880 
    881 	case ND_REDIRECT:
    882 		icmp6_ifstat_inc(rcvif, ifs6_in_redirect);
    883 		if (code != 0)
    884 			goto badcode;
    885 		if (icmp6len < sizeof(struct nd_redirect))
    886 			goto badlen;
    887 		if ((n = m_copypacket(m, M_DONTWAIT)) == NULL) {
    888 			/* give up local */
    889 			icmp6_redirect_input(m, off);
    890 			m = NULL;
    891 			goto freeit;
    892 		}
    893 		icmp6_redirect_input(n, off);
    894 		/* m stays. */
    895 		break;
    896 
    897 	case ICMP6_ROUTER_RENUMBERING:
    898 		if (code != ICMP6_ROUTER_RENUMBERING_COMMAND &&
    899 		    code != ICMP6_ROUTER_RENUMBERING_RESULT)
    900 			goto badcode;
    901 		if (icmp6len < sizeof(struct icmp6_router_renum))
    902 			goto badlen;
    903 		break;
    904 
    905 	default:
    906 		nd6log(LOG_DEBUG,
    907 		    "unknown type %d(src=%s, dst=%s, ifid=%d)\n",
    908 		    icmp6->icmp6_type,
    909 		    IN6_PRINT(ip6buf, &ip6->ip6_src),
    910 		    IN6_PRINT(ip6buf2, &ip6->ip6_dst),
    911 		    rcvif ? rcvif->if_index : 0);
    912 		if (icmp6->icmp6_type < ICMP6_ECHO_REQUEST) {
    913 			/* ICMPv6 error: MUST deliver it by spec... */
    914 			code = PRC_NCMDS;
    915 			/* deliver */
    916 		} else {
    917 			/* ICMPv6 informational: MUST not deliver */
    918 			break;
    919 		}
    920 	deliver:
    921 		if (icmp6_notify_error(m, off, icmp6len, code)) {
    922 			/* In this case, m should've been freed. */
    923 			m_put_rcvif_psref(rcvif, &psref);
    924 			return;
    925 		}
    926 		break;
    927 
    928 	badcode:
    929 		ICMP6_STATINC(ICMP6_STAT_BADCODE);
    930 		break;
    931 
    932 	badlen:
    933 		ICMP6_STATINC(ICMP6_STAT_BADLEN);
    934 		break;
    935 	}
    936 	m_put_rcvif_psref(rcvif, &psref);
    937 
    938 	/* deliver the packet to appropriate sockets */
    939 	icmp6_rip6_input(&m, off);
    940 
    941 	return;
    942 
    943 freeit:
    944 	m_put_rcvif_psref(rcvif, &psref);
    945 	m_freem(m);
    946 	return;
    947 }
    948 
    949 int
    950 icmp6_input(struct mbuf **mp, int *offp, int proto)
    951 {
    952 
    953 	wqinput_input(icmp6_wqinput, *mp, *offp, proto);
    954 
    955 	return IPPROTO_DONE;
    956 }
    957 
    958 static int
    959 icmp6_notify_error(struct mbuf *m, int off, int icmp6len, int code)
    960 {
    961 	struct icmp6_hdr *icmp6;
    962 	struct ip6_hdr *eip6;
    963 	u_int32_t notifymtu;
    964 	struct sockaddr_in6 icmp6src, icmp6dst;
    965 
    966 	if (icmp6len < sizeof(struct icmp6_hdr) + sizeof(struct ip6_hdr)) {
    967 		ICMP6_STATINC(ICMP6_STAT_TOOSHORT);
    968 		goto freeit;
    969 	}
    970 	IP6_EXTHDR_GET(icmp6, struct icmp6_hdr *, m, off,
    971 	    sizeof(*icmp6) + sizeof(struct ip6_hdr));
    972 	if (icmp6 == NULL) {
    973 		ICMP6_STATINC(ICMP6_STAT_TOOSHORT);
    974 		return (-1);
    975 	}
    976 	eip6 = (struct ip6_hdr *)(icmp6 + 1);
    977 
    978 	/* Detect the upper level protocol */
    979 	{
    980 		void *(*ctlfunc)(int, const struct sockaddr *, void *);
    981 		u_int8_t nxt = eip6->ip6_nxt;
    982 		int eoff = off + sizeof(struct icmp6_hdr) +
    983 			sizeof(struct ip6_hdr);
    984 		struct ip6ctlparam ip6cp;
    985 		struct in6_addr *finaldst = NULL;
    986 		int icmp6type = icmp6->icmp6_type;
    987 		struct ip6_frag *fh;
    988 		struct ip6_rthdr *rth;
    989 		struct ifnet *rcvif;
    990 		int s;
    991 
    992 		while (1) { /* XXX: should avoid infinite loop explicitly? */
    993 			struct ip6_ext *eh;
    994 
    995 			switch (nxt) {
    996 			case IPPROTO_HOPOPTS:
    997 			case IPPROTO_DSTOPTS:
    998 			case IPPROTO_AH:
    999 				IP6_EXTHDR_GET(eh, struct ip6_ext *, m,
   1000 				    eoff, sizeof(*eh));
   1001 				if (eh == NULL) {
   1002 					ICMP6_STATINC(ICMP6_STAT_TOOSHORT);
   1003 					return (-1);
   1004 				}
   1005 
   1006 				if (nxt == IPPROTO_AH)
   1007 					eoff += (eh->ip6e_len + 2) << 2;
   1008 				else
   1009 					eoff += (eh->ip6e_len + 1) << 3;
   1010 				nxt = eh->ip6e_nxt;
   1011 				break;
   1012 			case IPPROTO_ROUTING:
   1013 				/* Ignore the option. */
   1014 				IP6_EXTHDR_GET(rth, struct ip6_rthdr *, m,
   1015 				    eoff, sizeof(*rth));
   1016 				if (rth == NULL) {
   1017 					ICMP6_STATINC(ICMP6_STAT_TOOSHORT);
   1018 					return (-1);
   1019 				}
   1020 
   1021 				eoff += (rth->ip6r_len + 1) << 3;
   1022 				nxt = rth->ip6r_nxt;
   1023 				break;
   1024 			case IPPROTO_FRAGMENT:
   1025 				IP6_EXTHDR_GET(fh, struct ip6_frag *, m,
   1026 				    eoff, sizeof(*fh));
   1027 				if (fh == NULL) {
   1028 					ICMP6_STATINC(ICMP6_STAT_TOOSHORT);
   1029 					return (-1);
   1030 				}
   1031 				/*
   1032 				 * Data after a fragment header is meaningless
   1033 				 * unless it is the first fragment, but
   1034 				 * we'll go to the notify label for path MTU
   1035 				 * discovery.
   1036 				 */
   1037 				if (fh->ip6f_offlg & IP6F_OFF_MASK)
   1038 					goto notify;
   1039 
   1040 				eoff += sizeof(struct ip6_frag);
   1041 				nxt = fh->ip6f_nxt;
   1042 				break;
   1043 			default:
   1044 				/*
   1045 				 * This case includes ESP and the No Next
   1046 				 * Header.  In such cases going to the notify
   1047 				 * label does not have any meaning
   1048 				 * (i.e. ctlfunc will be NULL), but we go
   1049 				 * anyway since we might have to update
   1050 				 * path MTU information.
   1051 				 */
   1052 				goto notify;
   1053 			}
   1054 		}
   1055 	  notify:
   1056 		IP6_EXTHDR_GET(icmp6, struct icmp6_hdr *, m, off,
   1057 		    sizeof(*icmp6) + sizeof(struct ip6_hdr));
   1058 		if (icmp6 == NULL) {
   1059 			ICMP6_STATINC(ICMP6_STAT_TOOSHORT);
   1060 			return (-1);
   1061 		}
   1062 
   1063 		/*
   1064 		 * retrieve parameters from the inner IPv6 header, and convert
   1065 		 * them into sockaddr structures.
   1066 		 * XXX: there is no guarantee that the source or destination
   1067 		 * addresses of the inner packet are in the same scope zone as
   1068 		 * the addresses of the icmp packet.  But there is no other
   1069 		 * way to determine the zone.
   1070 		 */
   1071 		eip6 = (struct ip6_hdr *)(icmp6 + 1);
   1072 
   1073 		rcvif = m_get_rcvif(m, &s);
   1074 		if (__predict_false(rcvif == NULL))
   1075 			goto freeit;
   1076 		sockaddr_in6_init(&icmp6dst,
   1077 		    (finaldst == NULL) ? &eip6->ip6_dst : finaldst, 0, 0, 0);
   1078 		if (in6_setscope(&icmp6dst.sin6_addr, rcvif, NULL)) {
   1079 			m_put_rcvif(rcvif, &s);
   1080 			goto freeit;
   1081 		}
   1082 		sockaddr_in6_init(&icmp6src, &eip6->ip6_src, 0, 0, 0);
   1083 		if (in6_setscope(&icmp6src.sin6_addr, rcvif, NULL)) {
   1084 			m_put_rcvif(rcvif, &s);
   1085 			goto freeit;
   1086 		}
   1087 		m_put_rcvif(rcvif, &s);
   1088 
   1089 		icmp6src.sin6_flowinfo =
   1090 			(eip6->ip6_flow & IPV6_FLOWLABEL_MASK);
   1091 
   1092 		if (finaldst == NULL)
   1093 			finaldst = &eip6->ip6_dst;
   1094 		ip6cp.ip6c_m = m;
   1095 		ip6cp.ip6c_icmp6 = icmp6;
   1096 		ip6cp.ip6c_ip6 = (struct ip6_hdr *)(icmp6 + 1);
   1097 		ip6cp.ip6c_off = eoff;
   1098 		ip6cp.ip6c_finaldst = finaldst;
   1099 		ip6cp.ip6c_src = &icmp6src;
   1100 		ip6cp.ip6c_nxt = nxt;
   1101 
   1102 		if (icmp6type == ICMP6_PACKET_TOO_BIG) {
   1103 			notifymtu = ntohl(icmp6->icmp6_mtu);
   1104 			ip6cp.ip6c_cmdarg = (void *)&notifymtu;
   1105 		}
   1106 
   1107 		ctlfunc = inet6sw[ip6_protox[nxt]].pr_ctlinput;
   1108 		if (ctlfunc) {
   1109 			(void)(*ctlfunc)(code, sin6tosa(&icmp6dst), &ip6cp);
   1110 		}
   1111 	}
   1112 	return (0);
   1113 
   1114 freeit:
   1115 	m_freem(m);
   1116 	return (-1);
   1117 }
   1118 
   1119 void
   1120 icmp6_mtudisc_update(struct ip6ctlparam *ip6cp, int validated)
   1121 {
   1122 	unsigned long rtcount;
   1123 	struct icmp6_mtudisc_callback *mc;
   1124 	struct in6_addr *dst = ip6cp->ip6c_finaldst;
   1125 	struct icmp6_hdr *icmp6 = ip6cp->ip6c_icmp6;
   1126 	struct mbuf *m = ip6cp->ip6c_m;	/* will be necessary for scope issue */
   1127 	u_int mtu = ntohl(icmp6->icmp6_mtu);
   1128 	struct rtentry *rt = NULL;
   1129 	struct sockaddr_in6 sin6;
   1130 	struct ifnet *rcvif;
   1131 	int s;
   1132 
   1133 	/*
   1134 	 * The MTU should not be less than the minimal IPv6 MTU except for the
   1135 	 * hack in ip6_output/ip6_setpmtu where we always include a frag header.
   1136 	 * In that one case, the MTU might be less than 1280.
   1137 	 */
   1138 	if (__predict_false(mtu < IPV6_MMTU - sizeof(struct ip6_frag))) {
   1139 		/* is the mtu even sane? */
   1140 		if (mtu < sizeof(struct ip6_hdr) + sizeof(struct ip6_frag) + 8)
   1141 			return;
   1142 		if (!validated)
   1143 			return;
   1144 		mtu = IPV6_MMTU - sizeof(struct ip6_frag);
   1145 	}
   1146 
   1147 	/*
   1148 	 * allow non-validated cases if memory is plenty, to make traffic
   1149 	 * from non-connected pcb happy.
   1150 	 */
   1151 	mutex_enter(&icmp6_mtx);
   1152 	rtcount = rt_timer_count(icmp6_mtudisc_timeout_q);
   1153 	if (validated) {
   1154 		if (0 <= icmp6_mtudisc_hiwat && rtcount > icmp6_mtudisc_hiwat) {
   1155 			mutex_exit(&icmp6_mtx);
   1156 			return;
   1157 		} else if (0 <= icmp6_mtudisc_lowat &&
   1158 		    rtcount > icmp6_mtudisc_lowat) {
   1159 			/*
   1160 			 * XXX nuke a victim, install the new one.
   1161 			 */
   1162 		}
   1163 	} else {
   1164 		if (0 <= icmp6_mtudisc_lowat && rtcount > icmp6_mtudisc_lowat) {
   1165 			mutex_exit(&icmp6_mtx);
   1166 			return;
   1167 		}
   1168 	}
   1169 	mutex_exit(&icmp6_mtx);
   1170 
   1171 	memset(&sin6, 0, sizeof(sin6));
   1172 	sin6.sin6_family = PF_INET6;
   1173 	sin6.sin6_len = sizeof(struct sockaddr_in6);
   1174 	sin6.sin6_addr = *dst;
   1175 	rcvif = m_get_rcvif(m, &s);
   1176 	if (__predict_false(rcvif == NULL))
   1177 		return;
   1178 	if (in6_setscope(&sin6.sin6_addr, rcvif, NULL)) {
   1179 		m_put_rcvif(rcvif, &s);
   1180 		return;
   1181 	}
   1182 	m_put_rcvif(rcvif, &s);
   1183 
   1184 	rt = icmp6_mtudisc_clone(sin6tosa(&sin6));
   1185 
   1186 	if (rt && (rt->rt_flags & RTF_HOST) &&
   1187 	    !(rt->rt_rmx.rmx_locks & RTV_MTU) &&
   1188 	    (rt->rt_rmx.rmx_mtu > mtu || rt->rt_rmx.rmx_mtu == 0)) {
   1189 		if (mtu < rt->rt_ifp->if_mtu) {
   1190 			ICMP6_STATINC(ICMP6_STAT_PMTUCHG);
   1191 			rt->rt_rmx.rmx_mtu = mtu;
   1192 		}
   1193 	}
   1194 	if (rt) {
   1195 		rt_unref(rt);
   1196 	}
   1197 
   1198 	/*
   1199 	 * Notify protocols that the MTU for this destination
   1200 	 * has changed.
   1201 	 */
   1202 	mutex_enter(&icmp6_mtx);
   1203 	for (mc = LIST_FIRST(&icmp6_mtudisc_callbacks); mc != NULL;
   1204 	     mc = LIST_NEXT(mc, mc_list))
   1205 		(*mc->mc_func)(&sin6.sin6_addr);
   1206 	mutex_exit(&icmp6_mtx);
   1207 }
   1208 
   1209 /*
   1210  * Process a Node Information Query packet, based on
   1211  * draft-ietf-ipngwg-icmp-name-lookups-07.
   1212  *
   1213  * Spec incompatibilities:
   1214  * - IPv6 Subject address handling
   1215  * - IPv4 Subject address handling support missing
   1216  * - Proxy reply (answer even if it's not for me)
   1217  * - joins NI group address at in6_ifattach() time only, does not cope
   1218  *   with hostname changes by sethostname(3)
   1219  */
   1220 static struct mbuf *
   1221 ni6_input(struct mbuf *m, int off)
   1222 {
   1223 	struct icmp6_nodeinfo *ni6, *nni6;
   1224 	struct mbuf *n = NULL;
   1225 	u_int16_t qtype;
   1226 	int subjlen;
   1227 	int replylen = sizeof(struct ip6_hdr) + sizeof(struct icmp6_nodeinfo);
   1228 	struct ni_reply_fqdn *fqdn;
   1229 	int addrs;		/* for NI_QTYPE_NODEADDR */
   1230 	struct ifnet *ifp = NULL; /* for NI_QTYPE_NODEADDR */
   1231 	struct sockaddr_in6 sin6; /* ip6_dst */
   1232 	struct in6_addr in6_subj; /* subject address */
   1233 	struct ip6_hdr *ip6;
   1234 	int oldfqdn = 0;	/* if 1, return pascal string (03 draft) */
   1235 	char *subj = NULL;
   1236 	struct ifnet *rcvif;
   1237 	int s, ss;
   1238 	struct ifaddr *ifa;
   1239 	struct psref psref;
   1240 
   1241 	ip6 = mtod(m, struct ip6_hdr *);
   1242 	IP6_EXTHDR_GET(ni6, struct icmp6_nodeinfo *, m, off, sizeof(*ni6));
   1243 	if (ni6 == NULL) {
   1244 		/* m is already reclaimed */
   1245 		return NULL;
   1246 	}
   1247 	KASSERT((m->m_flags & M_PKTHDR) != 0);
   1248 
   1249 	/*
   1250 	 * Validate IPv6 destination address.
   1251 	 *
   1252 	 * The Responder must discard the Query without further processing
   1253 	 * unless it is one of the Responder's unicast or anycast addresses, or
   1254 	 * a link-local scope multicast address which the Responder has joined.
   1255 	 * [icmp-name-lookups-07, Section 4.]
   1256 	 */
   1257 	sockaddr_in6_init(&sin6, &ip6->ip6_dst, 0, 0, 0);
   1258 	/* XXX scopeid */
   1259 	ss = pserialize_read_enter();
   1260 	ifa = ifa_ifwithaddr(sin6tosa(&sin6));
   1261 	if (ifa != NULL) {
   1262 		; /* unicast/anycast, fine */
   1263 	} else if (IN6_IS_ADDR_MC_LINKLOCAL(&sin6.sin6_addr)) {
   1264 		; /* link-local multicast, fine */
   1265 	} else {
   1266 		pserialize_read_exit(ss);
   1267 		goto bad;
   1268 	}
   1269 	pserialize_read_exit(ss);
   1270 
   1271 	/* validate query Subject field. */
   1272 	qtype = ntohs(ni6->ni_qtype);
   1273 	subjlen = m->m_pkthdr.len - off - sizeof(struct icmp6_nodeinfo);
   1274 	switch (qtype) {
   1275 	case NI_QTYPE_NOOP:
   1276 	case NI_QTYPE_SUPTYPES:
   1277 		/* 07 draft */
   1278 		if (ni6->ni_code == ICMP6_NI_SUBJ_FQDN && subjlen == 0)
   1279 			break;
   1280 		/* FALLTHROUGH */
   1281 	case NI_QTYPE_FQDN:
   1282 	case NI_QTYPE_NODEADDR:
   1283 	case NI_QTYPE_IPV4ADDR:
   1284 		switch (ni6->ni_code) {
   1285 		case ICMP6_NI_SUBJ_IPV6:
   1286 #if ICMP6_NI_SUBJ_IPV6 != 0
   1287 		case 0:
   1288 #endif
   1289 			/*
   1290 			 * backward compatibility - try to accept 03 draft
   1291 			 * format, where no Subject is present.
   1292 			 */
   1293 			if (qtype == NI_QTYPE_FQDN && ni6->ni_code == 0 &&
   1294 			    subjlen == 0) {
   1295 				oldfqdn++;
   1296 				break;
   1297 			}
   1298 #if ICMP6_NI_SUBJ_IPV6 != 0
   1299 			if (ni6->ni_code != ICMP6_NI_SUBJ_IPV6)
   1300 				goto bad;
   1301 #endif
   1302 
   1303 			if (subjlen != sizeof(sin6.sin6_addr))
   1304 				goto bad;
   1305 
   1306 			/*
   1307 			 * Validate Subject address.
   1308 			 *
   1309 			 * Not sure what exactly "address belongs to the node"
   1310 			 * means in the spec, is it just unicast, or what?
   1311 			 *
   1312 			 * At this moment we consider Subject address as
   1313 			 * "belong to the node" if the Subject address equals
   1314 			 * to the IPv6 destination address; validation for
   1315 			 * IPv6 destination address should have done enough
   1316 			 * check for us.
   1317 			 *
   1318 			 * We do not do proxy at this moment.
   1319 			 */
   1320 			/* m_pulldown instead of copy? */
   1321 			m_copydata(m, off + sizeof(struct icmp6_nodeinfo),
   1322 			    subjlen, (void *)&in6_subj);
   1323 			rcvif = m_get_rcvif(m, &s);
   1324 			if (__predict_false(rcvif == NULL))
   1325 				goto bad;
   1326 			if (in6_setscope(&in6_subj, rcvif, NULL)) {
   1327 				m_put_rcvif(rcvif, &s);
   1328 				goto bad;
   1329 			}
   1330 			m_put_rcvif(rcvif, &s);
   1331 
   1332 			subj = (char *)&in6_subj;
   1333 			if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &in6_subj))
   1334 				break;
   1335 
   1336 			/*
   1337 			 * XXX if we are to allow other cases, we should really
   1338 			 * be careful about scope here.
   1339 			 * basically, we should disallow queries toward IPv6
   1340 			 * destination X with subject Y, if scope(X) > scope(Y).
   1341 			 * if we allow scope(X) > scope(Y), it will result in
   1342 			 * information leakage across scope boundary.
   1343 			 */
   1344 			goto bad;
   1345 
   1346 		case ICMP6_NI_SUBJ_FQDN:
   1347 			/*
   1348 			 * Validate Subject name with gethostname(3).
   1349 			 *
   1350 			 * The behavior may need some debate, since:
   1351 			 * - we are not sure if the node has FQDN as
   1352 			 *   hostname (returned by gethostname(3)).
   1353 			 * - the code does wildcard match for truncated names.
   1354 			 *   however, we are not sure if we want to perform
   1355 			 *   wildcard match, if gethostname(3) side has
   1356 			 *   truncated hostname.
   1357 			 */
   1358 			n = ni6_nametodns(hostname, hostnamelen, 0);
   1359 			if (!n || n->m_next || n->m_len == 0)
   1360 				goto bad;
   1361 			IP6_EXTHDR_GET(subj, char *, m,
   1362 			    off + sizeof(struct icmp6_nodeinfo), subjlen);
   1363 			if (subj == NULL)
   1364 				goto bad;
   1365 			if (!ni6_dnsmatch(subj, subjlen, mtod(n, const char *),
   1366 			    n->m_len)) {
   1367 				goto bad;
   1368 			}
   1369 			m_freem(n);
   1370 			n = NULL;
   1371 			break;
   1372 
   1373 		case ICMP6_NI_SUBJ_IPV4:	/* XXX: to be implemented? */
   1374 		default:
   1375 			goto bad;
   1376 		}
   1377 		break;
   1378 	}
   1379 
   1380 	/* refuse based on configuration.  XXX ICMP6_NI_REFUSED? */
   1381 	switch (qtype) {
   1382 	case NI_QTYPE_FQDN:
   1383 		if ((icmp6_nodeinfo & 1) == 0)
   1384 			goto bad;
   1385 		break;
   1386 	case NI_QTYPE_NODEADDR:
   1387 	case NI_QTYPE_IPV4ADDR:
   1388 		if ((icmp6_nodeinfo & 2) == 0)
   1389 			goto bad;
   1390 		break;
   1391 	}
   1392 
   1393 	/* guess reply length */
   1394 	switch (qtype) {
   1395 	case NI_QTYPE_NOOP:
   1396 		break;		/* no reply data */
   1397 	case NI_QTYPE_SUPTYPES:
   1398 		replylen += sizeof(u_int32_t);
   1399 		break;
   1400 	case NI_QTYPE_FQDN:
   1401 		/* will append an mbuf */
   1402 		replylen += offsetof(struct ni_reply_fqdn, ni_fqdn_namelen);
   1403 		break;
   1404 	case NI_QTYPE_NODEADDR:
   1405 		addrs = ni6_addrs(ni6, &ifp, subj, &psref);
   1406 		replylen += addrs *
   1407 		    (sizeof(struct in6_addr) + sizeof(u_int32_t));
   1408 		if (replylen > MCLBYTES)
   1409 			replylen = MCLBYTES; /* XXX: will truncate pkt later */
   1410 		break;
   1411 	case NI_QTYPE_IPV4ADDR:
   1412 		/* unsupported - should respond with unknown Qtype? */
   1413 		goto bad;
   1414 	default:
   1415 		/*
   1416 		 * XXX: We must return a reply with the ICMP6 code
   1417 		 * `unknown Qtype' in this case.  However we regard the case
   1418 		 * as an FQDN query for backward compatibility.
   1419 		 * Older versions set a random value to this field,
   1420 		 * so it rarely varies in the defined qtypes.
   1421 		 * But the mechanism is not reliable...
   1422 		 * maybe we should obsolete older versions.
   1423 		 */
   1424 		qtype = NI_QTYPE_FQDN;
   1425 		/* will append an mbuf */
   1426 		replylen += offsetof(struct ni_reply_fqdn, ni_fqdn_namelen);
   1427 		oldfqdn++;
   1428 		break;
   1429 	}
   1430 
   1431 	/* allocate an mbuf to reply. */
   1432 	MGETHDR(n, M_DONTWAIT, m->m_type);
   1433 	if (n == NULL) {
   1434 		goto bad;
   1435 	}
   1436 	m_move_pkthdr(n, m);
   1437 	if (replylen > MHLEN) {
   1438 		if (replylen > MCLBYTES) {
   1439 			/*
   1440 			 * XXX: should we try to allocate more? But MCLBYTES
   1441 			 * is probably much larger than IPV6_MMTU...
   1442 			 */
   1443 			goto bad;
   1444 		}
   1445 		MCLGET(n, M_DONTWAIT);
   1446 		if ((n->m_flags & M_EXT) == 0) {
   1447 			goto bad;
   1448 		}
   1449 	}
   1450 	n->m_pkthdr.len = n->m_len = replylen;
   1451 
   1452 	/* copy mbuf header and IPv6 + Node Information base headers */
   1453 	bcopy(mtod(m, void *), mtod(n, void *), sizeof(struct ip6_hdr));
   1454 	nni6 = (struct icmp6_nodeinfo *)(mtod(n, struct ip6_hdr *) + 1);
   1455 	bcopy((void *)ni6, (void *)nni6, sizeof(struct icmp6_nodeinfo));
   1456 
   1457 	/* qtype dependent procedure */
   1458 	switch (qtype) {
   1459 	case NI_QTYPE_NOOP:
   1460 		nni6->ni_code = ICMP6_NI_SUCCESS;
   1461 		nni6->ni_flags = 0;
   1462 		break;
   1463 	case NI_QTYPE_SUPTYPES:
   1464 	{
   1465 		u_int32_t v;
   1466 		nni6->ni_code = ICMP6_NI_SUCCESS;
   1467 		nni6->ni_flags = htons(0x0000);	/* raw bitmap */
   1468 		/* supports NOOP, SUPTYPES, FQDN, and NODEADDR */
   1469 		v = (u_int32_t)htonl(0x0000000f);
   1470 		memcpy(nni6 + 1, &v, sizeof(u_int32_t));
   1471 		break;
   1472 	}
   1473 	case NI_QTYPE_FQDN:
   1474 		nni6->ni_code = ICMP6_NI_SUCCESS;
   1475 		fqdn = (struct ni_reply_fqdn *)(mtod(n, char *) +
   1476 		    sizeof(struct ip6_hdr) + sizeof(struct icmp6_nodeinfo));
   1477 		nni6->ni_flags = 0; /* XXX: meaningless TTL */
   1478 		fqdn->ni_fqdn_ttl = 0;	/* ditto. */
   1479 		/*
   1480 		 * XXX do we really have FQDN in variable "hostname"?
   1481 		 */
   1482 		n->m_next = ni6_nametodns(hostname, hostnamelen, oldfqdn);
   1483 		if (n->m_next == NULL)
   1484 			goto bad;
   1485 		/* XXX we assume that n->m_next is not a chain */
   1486 		if (n->m_next->m_next != NULL)
   1487 			goto bad;
   1488 		n->m_pkthdr.len += n->m_next->m_len;
   1489 		break;
   1490 	case NI_QTYPE_NODEADDR:
   1491 	{
   1492 		int lenlim, copied;
   1493 
   1494 		nni6->ni_code = ICMP6_NI_SUCCESS;
   1495 		n->m_pkthdr.len = n->m_len = sizeof(struct ip6_hdr) +
   1496 		    sizeof(struct icmp6_nodeinfo);
   1497 		lenlim = M_TRAILINGSPACE(n);
   1498 		copied = ni6_store_addrs(ni6, nni6, ifp, lenlim);
   1499 		if_put(ifp, &psref);
   1500 		ifp = NULL;
   1501 		/* update mbuf length */
   1502 		n->m_pkthdr.len = n->m_len = sizeof(struct ip6_hdr) +
   1503 		    sizeof(struct icmp6_nodeinfo) + copied;
   1504 		break;
   1505 	}
   1506 	default:
   1507 		panic("%s: impossible", __func__);
   1508 		break;
   1509 	}
   1510 
   1511 	nni6->ni_type = ICMP6_NI_REPLY;
   1512 	m_freem(m);
   1513 	return n;
   1514 
   1515 bad:
   1516 	if_put(ifp, &psref);
   1517 	m_freem(m);
   1518 	if (n)
   1519 		m_freem(n);
   1520 	return NULL;
   1521 }
   1522 
   1523 #define isupper(x) ('A' <= (x) && (x) <= 'Z')
   1524 #define isalpha(x) (('A' <= (x) && (x) <= 'Z') || ('a' <= (x) && (x) <= 'z'))
   1525 #define isalnum(x) (isalpha(x) || ('0' <= (x) && (x) <= '9'))
   1526 #define tolower(x) (isupper(x) ? (x) + 'a' - 'A' : (x))
   1527 
   1528 /*
   1529  * make a mbuf with DNS-encoded string.  no compression support.
   1530  *
   1531  * XXX names with less than 2 dots (like "foo" or "foo.section") will be
   1532  * treated as truncated name (two \0 at the end).  this is a wild guess.
   1533  *
   1534  * old - return pascal string if non-zero
   1535  */
   1536 static struct mbuf *
   1537 ni6_nametodns(const char *name, int namelen, int old)
   1538 {
   1539 	struct mbuf *m;
   1540 	char *cp, *ep;
   1541 	const char *p, *q;
   1542 	int i, len, nterm;
   1543 
   1544 	if (old)
   1545 		len = namelen + 1;
   1546 	else
   1547 		len = MCLBYTES;
   1548 
   1549 	/* because MAXHOSTNAMELEN is usually 256, we use cluster mbuf */
   1550 	MGET(m, M_DONTWAIT, MT_DATA);
   1551 	if (m && len > MLEN) {
   1552 		MCLGET(m, M_DONTWAIT);
   1553 		if ((m->m_flags & M_EXT) == 0)
   1554 			goto fail;
   1555 	}
   1556 	if (!m)
   1557 		goto fail;
   1558 	m->m_next = NULL;
   1559 
   1560 	if (old) {
   1561 		m->m_len = len;
   1562 		*mtod(m, char *) = namelen;
   1563 		memcpy(mtod(m, char *) + 1, name, namelen);
   1564 		return m;
   1565 	} else {
   1566 		m->m_len = 0;
   1567 		cp = mtod(m, char *);
   1568 		ep = mtod(m, char *) + M_TRAILINGSPACE(m);
   1569 
   1570 		/* if not certain about my name, return empty buffer */
   1571 		if (namelen == 0)
   1572 			return m;
   1573 
   1574 		/*
   1575 		 * guess if it looks like shortened hostname, or FQDN.
   1576 		 * shortened hostname needs two trailing "\0".
   1577 		 */
   1578 		i = 0;
   1579 		for (p = name; p < name + namelen; p++) {
   1580 			if (*p == '.')
   1581 				i++;
   1582 		}
   1583 		if (i < 2)
   1584 			nterm = 2;
   1585 		else
   1586 			nterm = 1;
   1587 
   1588 		p = name;
   1589 		while (cp < ep && p < name + namelen) {
   1590 			i = 0;
   1591 			for (q = p; q < name + namelen && *q && *q != '.'; q++)
   1592 				i++;
   1593 			/* result does not fit into mbuf */
   1594 			if (cp + i + 1 >= ep)
   1595 				goto fail;
   1596 			/*
   1597 			 * DNS label length restriction, RFC1035 page 8.
   1598 			 * "i == 0" case is included here to avoid returning
   1599 			 * 0-length label on "foo..bar".
   1600 			 */
   1601 			if (i <= 0 || i >= 64)
   1602 				goto fail;
   1603 			*cp++ = i;
   1604 			if (!isalpha(p[0]) || !isalnum(p[i - 1]))
   1605 				goto fail;
   1606 			while (i > 0) {
   1607 				if (!isalnum(*p) && *p != '-')
   1608 					goto fail;
   1609 				if (isupper(*p)) {
   1610 					*cp++ = tolower(*p);
   1611 					p++;
   1612 				} else
   1613 					*cp++ = *p++;
   1614 				i--;
   1615 			}
   1616 			p = q;
   1617 			if (p < name + namelen && *p == '.')
   1618 				p++;
   1619 		}
   1620 		/* termination */
   1621 		if (cp + nterm >= ep)
   1622 			goto fail;
   1623 		while (nterm-- > 0)
   1624 			*cp++ = '\0';
   1625 		m->m_len = cp - mtod(m, char *);
   1626 		return m;
   1627 	}
   1628 
   1629 	panic("should not reach here");
   1630 	/* NOTREACHED */
   1631 
   1632 fail:
   1633 	if (m)
   1634 		m_freem(m);
   1635 	return NULL;
   1636 }
   1637 
   1638 /*
   1639  * check if two DNS-encoded string matches.  takes care of truncated
   1640  * form (with \0\0 at the end).  no compression support.
   1641  * XXX upper/lowercase match (see RFC2065)
   1642  */
   1643 static int
   1644 ni6_dnsmatch(const char *a, int alen, const char *b, int blen)
   1645 {
   1646 	const char *a0, *b0;
   1647 	int l;
   1648 
   1649 	/* simplest case - need validation? */
   1650 	if (alen == blen && memcmp(a, b, alen) == 0)
   1651 		return 1;
   1652 
   1653 	a0 = a;
   1654 	b0 = b;
   1655 
   1656 	/* termination is mandatory */
   1657 	if (alen < 2 || blen < 2)
   1658 		return 0;
   1659 	if (a0[alen - 1] != '\0' || b0[blen - 1] != '\0')
   1660 		return 0;
   1661 	alen--;
   1662 	blen--;
   1663 
   1664 	while (a - a0 < alen && b - b0 < blen) {
   1665 		if (a - a0 + 1 > alen || b - b0 + 1 > blen)
   1666 			return 0;
   1667 
   1668 		if ((signed char)a[0] < 0 || (signed char)b[0] < 0)
   1669 			return 0;
   1670 		/* we don't support compression yet */
   1671 		if (a[0] >= 64 || b[0] >= 64)
   1672 			return 0;
   1673 
   1674 		/* truncated case */
   1675 		if (a[0] == 0 && a - a0 == alen - 1)
   1676 			return 1;
   1677 		if (b[0] == 0 && b - b0 == blen - 1)
   1678 			return 1;
   1679 		if (a[0] == 0 || b[0] == 0)
   1680 			return 0;
   1681 
   1682 		if (a[0] != b[0])
   1683 			return 0;
   1684 		l = a[0];
   1685 		if (a - a0 + 1 + l > alen || b - b0 + 1 + l > blen)
   1686 			return 0;
   1687 		if (memcmp(a + 1, b + 1, l) != 0)
   1688 			return 0;
   1689 
   1690 		a += 1 + l;
   1691 		b += 1 + l;
   1692 	}
   1693 
   1694 	if (a - a0 == alen && b - b0 == blen)
   1695 		return 1;
   1696 	else
   1697 		return 0;
   1698 }
   1699 
   1700 /*
   1701  * calculate the number of addresses to be returned in the node info reply.
   1702  */
   1703 static int
   1704 ni6_addrs(struct icmp6_nodeinfo *ni6, struct ifnet **ifpp, char *subj,
   1705     struct psref *psref)
   1706 {
   1707 	struct ifnet *ifp;
   1708 	struct in6_ifaddr *ia6;
   1709 	struct ifaddr *ifa;
   1710 	struct sockaddr_in6 *subj_ip6 = NULL; /* XXX pedant */
   1711 	int addrs = 0, addrsofif, iffound = 0;
   1712 	int niflags = ni6->ni_flags;
   1713 	int s;
   1714 
   1715 	if ((niflags & NI_NODEADDR_FLAG_ALL) == 0) {
   1716 		switch (ni6->ni_code) {
   1717 		case ICMP6_NI_SUBJ_IPV6:
   1718 			if (subj == NULL) /* must be impossible... */
   1719 				return 0;
   1720 			subj_ip6 = (struct sockaddr_in6 *)subj;
   1721 			break;
   1722 		default:
   1723 			/*
   1724 			 * XXX: we only support IPv6 subject address for
   1725 			 * this Qtype.
   1726 			 */
   1727 			return 0;
   1728 		}
   1729 	}
   1730 
   1731 	s = pserialize_read_enter();
   1732 	IFNET_READER_FOREACH(ifp) {
   1733 		addrsofif = 0;
   1734 		IFADDR_READER_FOREACH(ifa, ifp) {
   1735 			if (ifa->ifa_addr->sa_family != AF_INET6)
   1736 				continue;
   1737 			ia6 = (struct in6_ifaddr *)ifa;
   1738 
   1739 			if ((niflags & NI_NODEADDR_FLAG_ALL) == 0 &&
   1740 			    IN6_ARE_ADDR_EQUAL(&subj_ip6->sin6_addr,
   1741 			     &ia6->ia_addr.sin6_addr))
   1742 				iffound = 1;
   1743 
   1744 			/*
   1745 			 * IPv4-mapped addresses can only be returned by a
   1746 			 * Node Information proxy, since they represent
   1747 			 * addresses of IPv4-only nodes, which perforce do
   1748 			 * not implement this protocol.
   1749 			 * [icmp-name-lookups-07, Section 5.4]
   1750 			 * So we don't support NI_NODEADDR_FLAG_COMPAT in
   1751 			 * this function at this moment.
   1752 			 */
   1753 
   1754 			/* What do we have to do about ::1? */
   1755 			switch (in6_addrscope(&ia6->ia_addr.sin6_addr)) {
   1756 			case IPV6_ADDR_SCOPE_LINKLOCAL:
   1757 				if ((niflags & NI_NODEADDR_FLAG_LINKLOCAL) == 0)
   1758 					continue;
   1759 				break;
   1760 			case IPV6_ADDR_SCOPE_SITELOCAL:
   1761 				if ((niflags & NI_NODEADDR_FLAG_SITELOCAL) == 0)
   1762 					continue;
   1763 				break;
   1764 			case IPV6_ADDR_SCOPE_GLOBAL:
   1765 				if ((niflags & NI_NODEADDR_FLAG_GLOBAL) == 0)
   1766 					continue;
   1767 				break;
   1768 			default:
   1769 				continue;
   1770 			}
   1771 
   1772 			/*
   1773 			 * check if anycast is okay.
   1774 			 * XXX: just experimental.  not in the spec.
   1775 			 */
   1776 			if ((ia6->ia6_flags & IN6_IFF_ANYCAST) != 0 &&
   1777 			    (niflags & NI_NODEADDR_FLAG_ANYCAST) == 0)
   1778 				continue; /* we need only unicast addresses */
   1779 
   1780 			addrsofif++; /* count the address */
   1781 		}
   1782 		if (iffound) {
   1783 			if_acquire(ifp, psref);
   1784 			pserialize_read_exit(s);
   1785 			*ifpp = ifp;
   1786 			return addrsofif;
   1787 		}
   1788 
   1789 		addrs += addrsofif;
   1790 	}
   1791 	pserialize_read_exit(s);
   1792 
   1793 	return addrs;
   1794 }
   1795 
   1796 static int
   1797 ni6_store_addrs(struct icmp6_nodeinfo *ni6,
   1798 	struct icmp6_nodeinfo *nni6, struct ifnet *ifp0,
   1799 	int resid)
   1800 {
   1801 	struct ifnet *ifp;
   1802 	struct in6_ifaddr *ia6;
   1803 	struct ifaddr *ifa;
   1804 	struct ifnet *ifp_dep = NULL;
   1805 	int copied = 0, allow_deprecated = 0;
   1806 	u_char *cp = (u_char *)(nni6 + 1);
   1807 	int niflags = ni6->ni_flags;
   1808 	u_int32_t ltime;
   1809 	int s;
   1810 
   1811 	if (ifp0 == NULL && !(niflags & NI_NODEADDR_FLAG_ALL))
   1812 		return 0;	/* needless to copy */
   1813 
   1814 	s = pserialize_read_enter();
   1815 	ifp = ifp0 ? ifp0 : IFNET_READER_FIRST();
   1816 again:
   1817 
   1818 	for (; ifp; ifp = IFNET_READER_NEXT(ifp))
   1819 	{
   1820 		IFADDR_READER_FOREACH(ifa, ifp) {
   1821 			if (ifa->ifa_addr->sa_family != AF_INET6)
   1822 				continue;
   1823 			ia6 = (struct in6_ifaddr *)ifa;
   1824 
   1825 			if ((ia6->ia6_flags & IN6_IFF_DEPRECATED) != 0 &&
   1826 			    allow_deprecated == 0) {
   1827 				/*
   1828 				 * prefererred address should be put before
   1829 				 * deprecated addresses.
   1830 				 */
   1831 
   1832 				/* record the interface for later search */
   1833 				if (ifp_dep == NULL)
   1834 					ifp_dep = ifp;
   1835 
   1836 				continue;
   1837 			}
   1838 			else if ((ia6->ia6_flags & IN6_IFF_DEPRECATED) == 0 &&
   1839 				 allow_deprecated != 0)
   1840 				continue; /* we now collect deprecated addrs */
   1841 
   1842 			/* What do we have to do about ::1? */
   1843 			switch (in6_addrscope(&ia6->ia_addr.sin6_addr)) {
   1844 			case IPV6_ADDR_SCOPE_LINKLOCAL:
   1845 				if ((niflags & NI_NODEADDR_FLAG_LINKLOCAL) == 0)
   1846 					continue;
   1847 				break;
   1848 			case IPV6_ADDR_SCOPE_SITELOCAL:
   1849 				if ((niflags & NI_NODEADDR_FLAG_SITELOCAL) == 0)
   1850 					continue;
   1851 				break;
   1852 			case IPV6_ADDR_SCOPE_GLOBAL:
   1853 				if ((niflags & NI_NODEADDR_FLAG_GLOBAL) == 0)
   1854 					continue;
   1855 				break;
   1856 			default:
   1857 				continue;
   1858 			}
   1859 
   1860 			/*
   1861 			 * check if anycast is okay.
   1862 			 * XXX: just experimental.  not in the spec.
   1863 			 */
   1864 			if ((ia6->ia6_flags & IN6_IFF_ANYCAST) != 0 &&
   1865 			    (niflags & NI_NODEADDR_FLAG_ANYCAST) == 0)
   1866 				continue;
   1867 
   1868 			/* now we can copy the address */
   1869 			if (resid < sizeof(struct in6_addr) +
   1870 			    sizeof(u_int32_t)) {
   1871 				/*
   1872 				 * We give up much more copy.
   1873 				 * Set the truncate flag and return.
   1874 				 */
   1875 				nni6->ni_flags |= NI_NODEADDR_FLAG_TRUNCATE;
   1876 				goto out;
   1877 			}
   1878 
   1879 			/*
   1880 			 * Set the TTL of the address.
   1881 			 * The TTL value should be one of the following
   1882 			 * according to the specification:
   1883 			 *
   1884 			 * 1. The remaining lifetime of a DHCP lease on the
   1885 			 *    address, or
   1886 			 * 2. The remaining Valid Lifetime of a prefix from
   1887 			 *    which the address was derived through Stateless
   1888 			 *    Autoconfiguration.
   1889 			 *
   1890 			 * Note that we currently do not support stateful
   1891 			 * address configuration by DHCPv6, so the former
   1892 			 * case can't happen.
   1893 			 *
   1894 			 * TTL must be 2^31 > TTL >= 0.
   1895 			 */
   1896 			if (ia6->ia6_lifetime.ia6t_expire == 0)
   1897 				ltime = ND6_INFINITE_LIFETIME;
   1898 			else {
   1899 				if (ia6->ia6_lifetime.ia6t_expire >
   1900 				    time_uptime)
   1901 					ltime = ia6->ia6_lifetime.ia6t_expire -
   1902 					    time_uptime;
   1903 				else
   1904 					ltime = 0;
   1905 			}
   1906 			if (ltime > 0x7fffffff)
   1907 				ltime = 0x7fffffff;
   1908 			ltime = htonl(ltime);
   1909 
   1910 			memcpy(cp, &ltime, sizeof(u_int32_t));
   1911 			cp += sizeof(u_int32_t);
   1912 
   1913 			/* copy the address itself */
   1914 			bcopy(&ia6->ia_addr.sin6_addr, cp,
   1915 			      sizeof(struct in6_addr));
   1916 			in6_clearscope((struct in6_addr *)cp); /* XXX */
   1917 			cp += sizeof(struct in6_addr);
   1918 
   1919 			resid -= (sizeof(struct in6_addr) + sizeof(u_int32_t));
   1920 			copied += (sizeof(struct in6_addr) + sizeof(u_int32_t));
   1921 		}
   1922 		if (ifp0)	/* we need search only on the specified IF */
   1923 			break;
   1924 	}
   1925 
   1926 	if (allow_deprecated == 0 && ifp_dep != NULL) {
   1927 		ifp = ifp_dep;
   1928 		allow_deprecated = 1;
   1929 
   1930 		goto again;
   1931 	}
   1932 out:
   1933 	pserialize_read_exit(s);
   1934 	return copied;
   1935 }
   1936 
   1937 /*
   1938  * XXX almost dup'ed code with rip6_input.
   1939  */
   1940 static int
   1941 icmp6_rip6_input(struct mbuf **mp, int off)
   1942 {
   1943 	struct mbuf *m = *mp;
   1944 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
   1945 	struct inpcb *inp;
   1946 	struct inpcb *last = NULL;
   1947 	struct sockaddr_in6 rip6src;
   1948 	struct icmp6_hdr *icmp6;
   1949 	struct mbuf *n, *opts = NULL;
   1950 
   1951 	IP6_EXTHDR_GET(icmp6, struct icmp6_hdr *, m, off, sizeof(*icmp6));
   1952 	if (icmp6 == NULL) {
   1953 		/* m is already reclaimed */
   1954 		return IPPROTO_DONE;
   1955 	}
   1956 
   1957 	/*
   1958 	 * XXX: the address may have embedded scope zone ID, which should be
   1959 	 * hidden from applications.
   1960 	 */
   1961 	sockaddr_in6_init(&rip6src, &ip6->ip6_src, 0, 0, 0);
   1962 	if (sa6_recoverscope(&rip6src)) {
   1963 		m_freem(m);
   1964 		return IPPROTO_DONE;
   1965 	}
   1966 
   1967 	TAILQ_FOREACH(inp, &raw6cbtable.inpt_queue, inp_queue) {
   1968 		if (inp->inp_af != AF_INET6)
   1969 			continue;
   1970 		if (in6p_ip6(inp).ip6_nxt != IPPROTO_ICMPV6)
   1971 			continue;
   1972 		if (!IN6_IS_ADDR_UNSPECIFIED(&in6p_laddr(inp)) &&
   1973 		    !IN6_ARE_ADDR_EQUAL(&in6p_laddr(inp), &ip6->ip6_dst))
   1974 			continue;
   1975 		if (!IN6_IS_ADDR_UNSPECIFIED(&in6p_faddr(inp)) &&
   1976 		    !IN6_ARE_ADDR_EQUAL(&in6p_faddr(inp), &ip6->ip6_src))
   1977 			continue;
   1978 		if (in6p_icmp6filt(inp) &&
   1979 		    ICMP6_FILTER_WILLBLOCK(icmp6->icmp6_type,
   1980 		    in6p_icmp6filt(inp)))
   1981 			continue;
   1982 
   1983 		if (last == NULL) {
   1984 			;
   1985 		}
   1986 #ifdef IPSEC
   1987 		else if (ipsec_used && ipsec_in_reject(m, last)) {
   1988 			/* do not inject data into pcb */
   1989 		}
   1990 #endif
   1991 		else if ((n = m_copypacket(m, M_DONTWAIT)) != NULL) {
   1992 			if (last->inp_flags & IN6P_CONTROLOPTS ||
   1993 			    SOOPT_TIMESTAMP(last->inp_socket->so_options))
   1994 				ip6_savecontrol(last, &opts, ip6, n);
   1995 			/* strip intermediate headers */
   1996 			m_adj(n, off);
   1997 			if (sbappendaddr(&last->inp_socket->so_rcv,
   1998 			    sin6tosa(&rip6src), n, opts) == 0) {
   1999 				soroverflow(last->inp_socket);
   2000 				m_freem(n);
   2001 				if (opts)
   2002 					m_freem(opts);
   2003 			} else {
   2004 				sorwakeup(last->inp_socket);
   2005 			}
   2006 			opts = NULL;
   2007 		}
   2008 
   2009 		last = inp;
   2010 	}
   2011 
   2012 #ifdef IPSEC
   2013 	if (ipsec_used && last && ipsec_in_reject(m, last)) {
   2014 		m_freem(m);
   2015 		IP6_STATDEC(IP6_STAT_DELIVERED);
   2016 		/* do not inject data into pcb */
   2017 	} else
   2018 #endif
   2019 	if (last) {
   2020 		if (last->inp_flags & IN6P_CONTROLOPTS ||
   2021 		    SOOPT_TIMESTAMP(last->inp_socket->so_options))
   2022 			ip6_savecontrol(last, &opts, ip6, m);
   2023 		/* strip intermediate headers */
   2024 		m_adj(m, off);
   2025 		if (sbappendaddr(&last->inp_socket->so_rcv,
   2026 		    sin6tosa(&rip6src), m, opts) == 0) {
   2027 			soroverflow(last->inp_socket);
   2028 			m_freem(m);
   2029 			if (opts)
   2030 				m_freem(opts);
   2031 		} else {
   2032 			sorwakeup(last->inp_socket);
   2033 		}
   2034 	} else {
   2035 		m_freem(m);
   2036 		IP6_STATDEC(IP6_STAT_DELIVERED);
   2037 	}
   2038 	return IPPROTO_DONE;
   2039 }
   2040 
   2041 /*
   2042  * Reflect the ip6 packet back to the source.
   2043  * OFF points to the icmp6 header, counted from the top of the mbuf.
   2044  *
   2045  * Note: RFC 1885 required that an echo reply should be truncated if it
   2046  * did not fit in with (return) path MTU, and KAME code supported the
   2047  * behavior.  However, as a clarification after the RFC, this limitation
   2048  * was removed in a revised version of the spec, RFC 2463.  We had kept the
   2049  * old behavior, with a (non-default) ifdef block, while the new version of
   2050  * the spec was an internet-draft status, and even after the new RFC was
   2051  * published.  But it would rather make sense to clean the obsoleted part
   2052  * up, and to make the code simpler at this stage.
   2053  */
   2054 static void
   2055 icmp6_reflect(struct mbuf *m, size_t off)
   2056 {
   2057 	struct ip6_hdr *ip6;
   2058 	struct icmp6_hdr *icmp6;
   2059 	const struct in6_ifaddr *ia;
   2060 	const struct ip6aux *ip6a;
   2061 	int plen;
   2062 	int type, code;
   2063 	struct ifnet *outif = NULL;
   2064 	struct in6_addr origdst;
   2065 	struct ifnet *rcvif;
   2066 	int s;
   2067 	bool ip6_src_filled = false;
   2068 	int flags;
   2069 
   2070 	/* too short to reflect */
   2071 	if (off < sizeof(struct ip6_hdr)) {
   2072 		nd6log(LOG_DEBUG,
   2073 		    "sanity fail: off=%lx, sizeof(ip6)=%lx in %s:%d\n",
   2074 		    (u_long)off, (u_long)sizeof(struct ip6_hdr),
   2075 		    __FILE__, __LINE__);
   2076 		goto bad;
   2077 	}
   2078 
   2079 	/*
   2080 	 * If there are extra headers between IPv6 and ICMPv6, strip
   2081 	 * off that header first.
   2082 	 */
   2083 	CTASSERT(sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr) <= MHLEN);
   2084 	if (off > sizeof(struct ip6_hdr)) {
   2085 		size_t l;
   2086 		struct ip6_hdr nip6;
   2087 
   2088 		l = off - sizeof(struct ip6_hdr);
   2089 		m_copydata(m, 0, sizeof(nip6), (void *)&nip6);
   2090 		m_adj(m, l);
   2091 		l = sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr);
   2092 		if (m->m_len < l) {
   2093 			if ((m = m_pullup(m, l)) == NULL)
   2094 				return;
   2095 		}
   2096 		memcpy(mtod(m, void *), (void *)&nip6, sizeof(nip6));
   2097 	} else {
   2098 		size_t l = sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr);
   2099 		if (m->m_len < l) {
   2100 			if ((m = m_pullup(m, l)) == NULL)
   2101 				return;
   2102 		}
   2103 	}
   2104 
   2105 	plen = m->m_pkthdr.len - sizeof(struct ip6_hdr);
   2106 	ip6 = mtod(m, struct ip6_hdr *);
   2107 	ip6->ip6_nxt = IPPROTO_ICMPV6;
   2108 	icmp6 = (struct icmp6_hdr *)(ip6 + 1);
   2109 	type = icmp6->icmp6_type; /* keep type for statistics */
   2110 	code = icmp6->icmp6_code; /* ditto. */
   2111 
   2112 	origdst = ip6->ip6_dst;
   2113 	/*
   2114 	 * ip6_input() drops a packet if its src is multicast.
   2115 	 * So, the src is never multicast.
   2116 	 */
   2117 	ip6->ip6_dst = ip6->ip6_src;
   2118 
   2119 	/*
   2120 	 * If the incoming packet was addressed directly to us (i.e. unicast),
   2121 	 * use dst as the src for the reply.
   2122 	 * The IN6_IFF_NOTREADY case should be VERY rare, but is possible
   2123 	 * (for example) when we encounter an error while forwarding procedure
   2124 	 * destined to a duplicated address of ours.
   2125 	 * Note that ip6_getdstifaddr() may fail if we are in an error handling
   2126 	 * procedure of an outgoing packet of our own, in which case we need
   2127 	 * to search in the ifaddr list.
   2128 	 */
   2129 	if (IN6_IS_ADDR_MULTICAST(&origdst)) {
   2130 		;
   2131 	} else if ((ip6a = ip6_getdstifaddr(m)) != NULL) {
   2132 		if ((ip6a->ip6a_flags &
   2133 		     (IN6_IFF_ANYCAST|IN6_IFF_NOTREADY)) == 0) {
   2134 			ip6->ip6_src = ip6a->ip6a_src;
   2135 			ip6_src_filled = true;
   2136 		}
   2137 	} else {
   2138 		union {
   2139 			struct sockaddr_in6 sin6;
   2140 			struct sockaddr sa;
   2141 		} u;
   2142 		int _s;
   2143 		struct ifaddr *ifa;
   2144 
   2145 		sockaddr_in6_init(&u.sin6, &origdst, 0, 0, 0);
   2146 
   2147 		_s = pserialize_read_enter();
   2148 		ifa = ifa_ifwithaddr(&u.sa);
   2149 
   2150 		if (ifa != NULL) {
   2151 			ia = ifatoia6(ifa);
   2152 			if ((ia->ia6_flags &
   2153 				 (IN6_IFF_ANYCAST|IN6_IFF_NOTREADY)) == 0) {
   2154 				ip6->ip6_src = ia->ia_addr.sin6_addr;
   2155 				ip6_src_filled = true;
   2156 			}
   2157 		}
   2158 		pserialize_read_exit(_s);
   2159 	}
   2160 
   2161 	if (!ip6_src_filled) {
   2162 		int e;
   2163 		struct sockaddr_in6 sin6;
   2164 		struct route ro;
   2165 
   2166 		/*
   2167 		 * This case matches to multicasts, our anycast, or unicasts
   2168 		 * that we do not own.  Select a source address based on the
   2169 		 * source address of the erroneous packet.
   2170 		 */
   2171 		/* zone ID should be embedded */
   2172 		sockaddr_in6_init(&sin6, &ip6->ip6_dst, 0, 0, 0);
   2173 
   2174 		memset(&ro, 0, sizeof(ro));
   2175 		e = in6_selectsrc(&sin6, NULL, NULL, &ro, NULL, NULL, NULL,
   2176 		    &ip6->ip6_src);
   2177 		rtcache_free(&ro);
   2178 		if (e != 0) {
   2179 			char ip6buf[INET6_ADDRSTRLEN];
   2180 			nd6log(LOG_DEBUG,
   2181 			    "source can't be determined: "
   2182 			    "dst=%s, error=%d\n",
   2183 			    IN6_PRINT(ip6buf, &sin6.sin6_addr), e);
   2184 			goto bad;
   2185 		}
   2186 	}
   2187 
   2188 	ip6->ip6_flow = 0;
   2189 	ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
   2190 	ip6->ip6_vfc |= IPV6_VERSION;
   2191 	ip6->ip6_nxt = IPPROTO_ICMPV6;
   2192 	rcvif = m_get_rcvif(m, &s);
   2193 	if (rcvif) {
   2194 		/* XXX: This may not be the outgoing interface */
   2195 		ip6->ip6_hlim = ND_IFINFO(rcvif)->chlim;
   2196 	} else {
   2197 		ip6->ip6_hlim = ip6_defhlim;
   2198 	}
   2199 	m_put_rcvif(rcvif, &s);
   2200 
   2201 	m->m_pkthdr.csum_flags = 0;
   2202 	icmp6->icmp6_cksum = 0;
   2203 	icmp6->icmp6_cksum = in6_cksum(m, IPPROTO_ICMPV6,
   2204 	    sizeof(struct ip6_hdr), plen);
   2205 
   2206 	/*
   2207 	 * XXX option handling
   2208 	 */
   2209 
   2210 	m->m_flags &= ~(M_BCAST|M_MCAST);
   2211 
   2212 	/*
   2213 	 * Note for icmp6_reflect_pmtu == false
   2214 	 * To avoid a "too big" situation at an intermediate router
   2215 	 * and the path MTU discovery process, specify the IPV6_MINMTU flag.
   2216 	 * Note that only echo and node information replies are affected,
   2217 	 * since the length of ICMP6 errors is limited to the minimum MTU.
   2218 	 */
   2219 	flags = icmp6_reflect_pmtu ? 0 : IPV6_MINMTU;
   2220 	if (ip6_output(m, NULL, NULL, flags, NULL, NULL, &outif) != 0 &&
   2221 	    outif)
   2222 		icmp6_ifstat_inc(outif, ifs6_out_error);
   2223 	if (outif)
   2224 		icmp6_ifoutstat_inc(outif, type, code);
   2225 
   2226 	return;
   2227 
   2228  bad:
   2229 	m_freem(m);
   2230 	return;
   2231 }
   2232 
   2233 static const char *
   2234 icmp6_redirect_diag(char *buf, size_t buflen, struct in6_addr *src6,
   2235     struct in6_addr *dst6,  struct in6_addr *tgt6)
   2236 {
   2237 	char ip6bufs[INET6_ADDRSTRLEN], ip6bufd[INET6_ADDRSTRLEN];
   2238 	char ip6buft[INET6_ADDRSTRLEN];
   2239 
   2240 	snprintf(buf, buflen, "(src=%s dst=%s tgt=%s)",
   2241 	    IN6_PRINT(ip6bufs, src6), IN6_PRINT(ip6bufd, dst6),
   2242 	    IN6_PRINT(ip6buft, tgt6));
   2243 	return buf;
   2244 }
   2245 
   2246 static void
   2247 icmp6_redirect_input(struct mbuf *m, int off)
   2248 {
   2249 	struct ifnet *ifp;
   2250 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
   2251 	struct nd_redirect *nd_rd;
   2252 	int icmp6len = m->m_pkthdr.len - off;
   2253 	char *lladdr = NULL;
   2254 	int lladdrlen = 0;
   2255 	struct rtentry *rt = NULL;
   2256 	int is_router;
   2257 	int is_onlink;
   2258 	struct in6_addr src6 = ip6->ip6_src;
   2259 	struct in6_addr redtgt6;
   2260 	struct in6_addr reddst6;
   2261 	union nd_opts ndopts;
   2262 	struct psref psref;
   2263 	char ip6buf[INET6_ADDRSTRLEN];
   2264 	char diagbuf[256];
   2265 
   2266 	ifp = m_get_rcvif_psref(m, &psref);
   2267 	if (ifp == NULL)
   2268 		goto freeit;
   2269 
   2270 	/* XXX if we are router, we don't update route by icmp6 redirect */
   2271 	if (ip6_forwarding)
   2272 		goto freeit;
   2273 	if (!icmp6_rediraccept)
   2274 		goto freeit;
   2275 
   2276 	IP6_EXTHDR_GET(nd_rd, struct nd_redirect *, m, off, icmp6len);
   2277 	if (nd_rd == NULL) {
   2278 		ICMP6_STATINC(ICMP6_STAT_TOOSHORT);
   2279 		m_put_rcvif_psref(ifp, &psref);
   2280 		return;
   2281 	}
   2282 	redtgt6 = nd_rd->nd_rd_target;
   2283 	reddst6 = nd_rd->nd_rd_dst;
   2284 
   2285 	if (in6_setscope(&redtgt6, ifp, NULL) ||
   2286 	    in6_setscope(&reddst6, ifp, NULL)) {
   2287 		goto freeit;
   2288 	}
   2289 
   2290 	/* validation */
   2291 	if (!IN6_IS_ADDR_LINKLOCAL(&src6)) {
   2292 		nd6log(LOG_ERR,
   2293 		    "ICMP6 redirect sent from %s rejected; "
   2294 		    "must be from linklocal\n", IN6_PRINT(ip6buf, &src6));
   2295 		goto bad;
   2296 	}
   2297 	if (ip6->ip6_hlim != 255) {
   2298 		nd6log(LOG_ERR,
   2299 		    "ICMP6 redirect sent from %s rejected; "
   2300 		    "hlim=%d (must be 255)\n",
   2301 		    IN6_PRINT(ip6buf, &src6), ip6->ip6_hlim);
   2302 		goto bad;
   2303 	}
   2304 
   2305     {
   2306 	/* ip6->ip6_src must be equal to gw for icmp6->icmp6_reddst */
   2307 	struct sockaddr_in6 sin6;
   2308 	struct in6_addr *gw6;
   2309 
   2310 	sockaddr_in6_init(&sin6, &reddst6, 0, 0, 0);
   2311 	rt = rtalloc1(sin6tosa(&sin6), 0);
   2312 	if (rt) {
   2313 		if (rt->rt_gateway == NULL ||
   2314 		    rt->rt_gateway->sa_family != AF_INET6) {
   2315 			nd6log(LOG_ERR,
   2316 			    "ICMP6 redirect rejected; no route "
   2317 			    "with inet6 gateway found for redirect dst: %s\n",
   2318 			    icmp6_redirect_diag(diagbuf, sizeof(diagbuf),
   2319 			    &src6, &reddst6, &redtgt6));
   2320 			rt_unref(rt);
   2321 			goto bad;
   2322 		}
   2323 
   2324 		gw6 = &(((struct sockaddr_in6 *)rt->rt_gateway)->sin6_addr);
   2325 		if (memcmp(&src6, gw6, sizeof(struct in6_addr)) != 0) {
   2326 			nd6log(LOG_ERR,
   2327 			    "ICMP6 redirect rejected; "
   2328 			    "not equal to gw-for-src=%s (must be same): %s\n",
   2329 			    IN6_PRINT(ip6buf, gw6),
   2330 			    icmp6_redirect_diag(diagbuf, sizeof(diagbuf),
   2331 			    &src6, &reddst6, &redtgt6));
   2332 			rt_unref(rt);
   2333 			goto bad;
   2334 		}
   2335 	} else {
   2336 		nd6log(LOG_ERR, "ICMP6 redirect rejected; "
   2337 		    "no route found for redirect dst: %s\n",
   2338 		    icmp6_redirect_diag(diagbuf, sizeof(diagbuf),
   2339 		    &src6, &reddst6, &redtgt6));
   2340 		goto bad;
   2341 	}
   2342 	rt_unref(rt);
   2343 	rt = NULL;
   2344     }
   2345 
   2346 	if (IN6_IS_ADDR_MULTICAST(&reddst6)) {
   2347 		nd6log(LOG_ERR, "ICMP6 redirect rejected; "
   2348 		    "redirect dst must be unicast: %s\n",
   2349 		    icmp6_redirect_diag(diagbuf, sizeof(diagbuf),
   2350 		    &src6, &reddst6, &redtgt6));
   2351 		goto bad;
   2352 	}
   2353 
   2354 	is_router = is_onlink = 0;
   2355 	if (IN6_IS_ADDR_LINKLOCAL(&redtgt6))
   2356 		is_router = 1;	/* router case */
   2357 	if (memcmp(&redtgt6, &reddst6, sizeof(redtgt6)) == 0)
   2358 		is_onlink = 1;	/* on-link destination case */
   2359 	if (!is_router && !is_onlink) {
   2360 		nd6log(LOG_ERR, "ICMP6 redirect rejected; "
   2361 		    "neither router case nor onlink case: %s\n",
   2362 		    icmp6_redirect_diag(diagbuf, sizeof(diagbuf),
   2363 		    &src6, &reddst6, &redtgt6));
   2364 		goto bad;
   2365 	}
   2366 	/* validation passed */
   2367 
   2368 	icmp6len -= sizeof(*nd_rd);
   2369 	nd6_option_init(nd_rd + 1, icmp6len, &ndopts);
   2370 	if (nd6_options(&ndopts) < 0) {
   2371 		nd6log(LOG_INFO, "invalid ND option, rejected: %s\n",
   2372 		    icmp6_redirect_diag(diagbuf, sizeof(diagbuf),
   2373 		    &src6, &reddst6, &redtgt6));
   2374 		/* nd6_options have incremented stats */
   2375 		goto freeit;
   2376 	}
   2377 
   2378 	if (ndopts.nd_opts_tgt_lladdr) {
   2379 		lladdr = (char *)(ndopts.nd_opts_tgt_lladdr + 1);
   2380 		lladdrlen = ndopts.nd_opts_tgt_lladdr->nd_opt_len << 3;
   2381 	}
   2382 
   2383 	if (lladdr && ((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
   2384 		nd6log(LOG_INFO, "lladdrlen mismatch for %s "
   2385 		    "(if %d, icmp6 packet %d): %s\n",
   2386 		    IN6_PRINT(ip6buf, &redtgt6),
   2387 		    ifp->if_addrlen, lladdrlen - 2,
   2388 		    icmp6_redirect_diag(diagbuf, sizeof(diagbuf),
   2389 		    &src6, &reddst6, &redtgt6));
   2390 		goto bad;
   2391 	}
   2392 
   2393 	/* RFC 2461 8.3 */
   2394 	nd6_cache_lladdr(ifp, &redtgt6, lladdr, lladdrlen, ND_REDIRECT,
   2395 	    is_onlink ? ND_REDIRECT_ONLINK : ND_REDIRECT_ROUTER);
   2396 
   2397 	m_put_rcvif_psref(ifp, &psref);
   2398 	ifp = NULL;
   2399 
   2400 	if (!is_onlink) {	/* better router case.  perform rtredirect. */
   2401 		/* perform rtredirect */
   2402 		struct sockaddr_in6 sdst;
   2403 		struct sockaddr_in6 sgw;
   2404 		struct sockaddr_in6 ssrc;
   2405 		unsigned long rtcount;
   2406 		struct rtentry *newrt = NULL;
   2407 
   2408 		/*
   2409 		 * do not install redirect route, if the number of entries
   2410 		 * is too much (> hiwat).  note that, the node (= host) will
   2411 		 * work just fine even if we do not install redirect route
   2412 		 * (there will be additional hops, though).
   2413 		 */
   2414 		mutex_enter(&icmp6_mtx);
   2415 		rtcount = rt_timer_count(icmp6_redirect_timeout_q);
   2416 		if (0 <= ip6_maxdynroutes && rtcount >= ip6_maxdynroutes) {
   2417 			mutex_exit(&icmp6_mtx);
   2418 			goto freeit;
   2419 		}
   2420 		if (0 <= icmp6_redirect_hiwat && rtcount > icmp6_redirect_hiwat) {
   2421 			mutex_exit(&icmp6_mtx);
   2422 			goto freeit;
   2423 		} else if (0 <= icmp6_redirect_lowat &&
   2424 		    rtcount > icmp6_redirect_lowat) {
   2425 			/*
   2426 			 * XXX nuke a victim, install the new one.
   2427 			 */
   2428 		}
   2429 
   2430 		memset(&sdst, 0, sizeof(sdst));
   2431 		memset(&sgw, 0, sizeof(sgw));
   2432 		memset(&ssrc, 0, sizeof(ssrc));
   2433 		sdst.sin6_family = sgw.sin6_family = ssrc.sin6_family = AF_INET6;
   2434 		sdst.sin6_len = sgw.sin6_len = ssrc.sin6_len =
   2435 		    sizeof(struct sockaddr_in6);
   2436 		bcopy(&redtgt6, &sgw.sin6_addr, sizeof(struct in6_addr));
   2437 		bcopy(&reddst6, &sdst.sin6_addr, sizeof(struct in6_addr));
   2438 		bcopy(&src6, &ssrc.sin6_addr, sizeof(struct in6_addr));
   2439 		rtredirect(sin6tosa(&sdst), sin6tosa(&sgw), NULL,
   2440 		    RTF_GATEWAY | RTF_HOST, sin6tosa(&ssrc), &newrt);
   2441 
   2442 		if (newrt) {
   2443 			(void)rt_timer_add(newrt, icmp6_redirect_timeout,
   2444 			    icmp6_redirect_timeout_q);
   2445 			rt_unref(newrt);
   2446 		}
   2447 		mutex_exit(&icmp6_mtx);
   2448 	}
   2449 	/* finally update cached route in each socket via pfctlinput */
   2450 	{
   2451 		struct sockaddr_in6 sdst;
   2452 
   2453 		sockaddr_in6_init(&sdst, &reddst6, 0, 0, 0);
   2454 		pfctlinput(PRC_REDIRECT_HOST, sin6tosa(&sdst));
   2455 #if defined(IPSEC)
   2456 		if (ipsec_used)
   2457 			key_sa_routechange(sin6tosa(&sdst));
   2458 #endif
   2459 	}
   2460 
   2461 freeit:
   2462 	if (ifp != NULL)
   2463 		m_put_rcvif_psref(ifp, &psref);
   2464 	m_freem(m);
   2465 	return;
   2466 
   2467 bad:
   2468 	m_put_rcvif_psref(ifp, &psref);
   2469 	ICMP6_STATINC(ICMP6_STAT_BADREDIRECT);
   2470 	m_freem(m);
   2471 }
   2472 
   2473 void
   2474 icmp6_redirect_output(struct mbuf *m0, struct rtentry *rt)
   2475 {
   2476 	struct ifnet *ifp;	/* my outgoing interface */
   2477 	struct in6_addr *ifp_ll6;
   2478 	struct in6_addr *nexthop;
   2479 	struct ip6_hdr *sip6;	/* m0 as struct ip6_hdr */
   2480 	struct mbuf *m = NULL;	/* newly allocated one */
   2481 	struct ip6_hdr *ip6;	/* m as struct ip6_hdr */
   2482 	struct nd_redirect *nd_rd;
   2483 	size_t maxlen;
   2484 	u_char *p;
   2485 	struct sockaddr_in6 src_sa;
   2486 
   2487 	icmp6_errcount(ICMP6_STAT_OUTERRHIST, ND_REDIRECT, 0);
   2488 
   2489 	/* if we are not router, we don't send icmp6 redirect */
   2490 	if (!ip6_forwarding)
   2491 		goto fail;
   2492 
   2493 	/* sanity check */
   2494 	KASSERT(m0 != NULL);
   2495 	KASSERT(rt != NULL);
   2496 
   2497 	ifp = rt->rt_ifp;
   2498 
   2499 	/*
   2500 	 * Address check:
   2501 	 *  the source address must identify a neighbor, and
   2502 	 *  the destination address must not be a multicast address
   2503 	 *  [RFC 2461, sec 8.2]
   2504 	 */
   2505 	sip6 = mtod(m0, struct ip6_hdr *);
   2506 	sockaddr_in6_init(&src_sa, &sip6->ip6_src, 0, 0, 0);
   2507 	if (nd6_is_addr_neighbor(&src_sa, ifp) == 0)
   2508 		goto fail;
   2509 	if (IN6_IS_ADDR_MULTICAST(&sip6->ip6_dst))
   2510 		goto fail;	/* what should we do here? */
   2511 
   2512 	/* rate limit */
   2513 	if (icmp6_ratelimit(&sip6->ip6_src, ND_REDIRECT, 0))
   2514 		goto fail;
   2515 
   2516 	/*
   2517 	 * Since we are going to append up to 1280 bytes (= IPV6_MMTU),
   2518 	 * we almost always ask for an mbuf cluster for simplicity.
   2519 	 * (MHLEN < IPV6_MMTU is almost always true)
   2520 	 */
   2521 	MGETHDR(m, M_DONTWAIT, MT_HEADER);
   2522 	if (m && IPV6_MMTU >= MHLEN) {
   2523 #if IPV6_MMTU >= MCLBYTES
   2524 		MEXTMALLOC(m, IPV6_MMTU, M_NOWAIT);
   2525 #else
   2526 		MCLGET(m, M_DONTWAIT);
   2527 #endif
   2528 	}
   2529 
   2530 	if (!m)
   2531 		goto fail;
   2532 	m_reset_rcvif(m);
   2533 	m->m_len = 0;
   2534 	maxlen = M_TRAILINGSPACE(m);
   2535 	maxlen = uimin(IPV6_MMTU, maxlen);
   2536 
   2537 	/* just for safety */
   2538 	if (maxlen < sizeof(struct ip6_hdr) + sizeof(struct nd_redirect) +
   2539 	    ((sizeof(struct nd_opt_hdr) + ifp->if_addrlen + 7) & ~7)) {
   2540 		goto fail;
   2541 	}
   2542 
   2543 	{
   2544 		/* get ip6 linklocal address for ifp(my outgoing interface). */
   2545 		struct in6_ifaddr *ia;
   2546 		int s = pserialize_read_enter();
   2547 		if ((ia = in6ifa_ifpforlinklocal(ifp,
   2548 						 IN6_IFF_NOTREADY|
   2549 						 IN6_IFF_ANYCAST)) == NULL) {
   2550 			pserialize_read_exit(s);
   2551 			goto fail;
   2552 		}
   2553 		ifp_ll6 = &ia->ia_addr.sin6_addr;
   2554 		pserialize_read_exit(s);
   2555 	}
   2556 
   2557 	/* get ip6 linklocal address for the router. */
   2558 	if (rt->rt_gateway && (rt->rt_flags & RTF_GATEWAY)) {
   2559 		struct sockaddr_in6 *sin6;
   2560 		sin6 = (struct sockaddr_in6 *)rt->rt_gateway;
   2561 		nexthop = &sin6->sin6_addr;
   2562 		if (!IN6_IS_ADDR_LINKLOCAL(nexthop))
   2563 			nexthop = NULL;
   2564 	} else
   2565 		nexthop = NULL;
   2566 
   2567 	/* ip6 */
   2568 	ip6 = mtod(m, struct ip6_hdr *);
   2569 	ip6->ip6_flow = 0;
   2570 	ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
   2571 	ip6->ip6_vfc |= IPV6_VERSION;
   2572 	/* ip6->ip6_plen will be set later */
   2573 	ip6->ip6_nxt = IPPROTO_ICMPV6;
   2574 	ip6->ip6_hlim = 255;
   2575 	/* ip6->ip6_src must be linklocal addr for my outgoing if. */
   2576 	bcopy(ifp_ll6, &ip6->ip6_src, sizeof(struct in6_addr));
   2577 	bcopy(&sip6->ip6_src, &ip6->ip6_dst, sizeof(struct in6_addr));
   2578 
   2579 	/* ND Redirect */
   2580 	nd_rd = (struct nd_redirect *)(ip6 + 1);
   2581 	nd_rd->nd_rd_type = ND_REDIRECT;
   2582 	nd_rd->nd_rd_code = 0;
   2583 	nd_rd->nd_rd_reserved = 0;
   2584 	if (rt->rt_flags & RTF_GATEWAY) {
   2585 		/*
   2586 		 * nd_rd->nd_rd_target must be a link-local address in
   2587 		 * better router cases.
   2588 		 */
   2589 		if (!nexthop)
   2590 			goto fail;
   2591 		bcopy(nexthop, &nd_rd->nd_rd_target,
   2592 		      sizeof(nd_rd->nd_rd_target));
   2593 		bcopy(&sip6->ip6_dst, &nd_rd->nd_rd_dst,
   2594 		      sizeof(nd_rd->nd_rd_dst));
   2595 	} else {
   2596 		/* make sure redtgt == reddst */
   2597 		nexthop = &sip6->ip6_dst;
   2598 		bcopy(&sip6->ip6_dst, &nd_rd->nd_rd_target,
   2599 		      sizeof(nd_rd->nd_rd_target));
   2600 		bcopy(&sip6->ip6_dst, &nd_rd->nd_rd_dst,
   2601 		      sizeof(nd_rd->nd_rd_dst));
   2602 	}
   2603 
   2604 	p = (u_char *)(nd_rd + 1);
   2605 
   2606 	{
   2607 		/* target lladdr option */
   2608 		struct llentry *ln = NULL;
   2609 		int len, pad;
   2610 		struct nd_opt_hdr *nd_opt;
   2611 		char *lladdr;
   2612 
   2613 		ln = nd6_lookup(nexthop, ifp, false);
   2614 		if (ln == NULL)
   2615 			goto nolladdropt;
   2616 		len = sizeof(*nd_opt) + ifp->if_addrlen;
   2617 		len = (len + 7) & ~7;	/* round by 8 */
   2618 		pad = len - (sizeof(*nd_opt) + ifp->if_addrlen);
   2619 
   2620 		/* safety check */
   2621 		if (len + (p - (u_char *)ip6) > maxlen) {
   2622 			LLE_RUNLOCK(ln);
   2623 			goto nolladdropt;
   2624 		}
   2625 
   2626 		if (ln->la_flags & LLE_VALID) {
   2627 			nd_opt = (struct nd_opt_hdr *)p;
   2628 			nd_opt->nd_opt_type = ND_OPT_TARGET_LINKADDR;
   2629 			nd_opt->nd_opt_len = len >> 3;
   2630 			lladdr = (char *)(nd_opt + 1);
   2631 			memcpy(lladdr, &ln->ll_addr, ifp->if_addrlen);
   2632 			memset(lladdr + ifp->if_addrlen, 0, pad);
   2633 			p += len;
   2634 		}
   2635 		LLE_RUNLOCK(ln);
   2636 	}
   2637 nolladdropt:
   2638 
   2639 	m->m_pkthdr.len = m->m_len = p - (u_char *)ip6;
   2640 
   2641 	/* just to be safe */
   2642 	if (m0->m_flags & M_DECRYPTED)
   2643 		goto noredhdropt;
   2644 	if (p - (u_char *)ip6 > maxlen)
   2645 		goto noredhdropt;
   2646 
   2647 	{
   2648 		/* redirected header option */
   2649 		int len;
   2650 		struct nd_opt_rd_hdr *nd_opt_rh;
   2651 
   2652 		/*
   2653 		 * compute the maximum size for icmp6 redirect header option.
   2654 		 * XXX room for auth header?
   2655 		 */
   2656 		len = maxlen - (p - (u_char *)ip6);
   2657 		len &= ~7;
   2658 
   2659 		if (len < sizeof(*nd_opt_rh)) {
   2660 			goto noredhdropt;
   2661 		}
   2662 
   2663 		/*
   2664 		 * Redirected header option spec (RFC2461 4.6.3) talks nothing
   2665 		 * about padding/truncate rule for the original IP packet.
   2666 		 * From the discussion on IPv6imp in Feb 1999,
   2667 		 * the consensus was:
   2668 		 * - "attach as much as possible" is the goal
   2669 		 * - pad if not aligned (original size can be guessed by
   2670 		 *   original ip6 header)
   2671 		 * Following code adds the padding if it is simple enough,
   2672 		 * and truncates if not.
   2673 		 */
   2674 		if (len - sizeof(*nd_opt_rh) < m0->m_pkthdr.len) {
   2675 			/* not enough room, truncate */
   2676 			m_adj(m0, (len - sizeof(*nd_opt_rh)) -
   2677 			    m0->m_pkthdr.len);
   2678 		} else {
   2679 			/*
   2680 			 * enough room, truncate if not aligned.
   2681 			 * we don't pad here for simplicity.
   2682 			 */
   2683 			int extra;
   2684 
   2685 			extra = m0->m_pkthdr.len % 8;
   2686 			if (extra) {
   2687 				/* truncate */
   2688 				m_adj(m0, -extra);
   2689 			}
   2690 			len = m0->m_pkthdr.len + sizeof(*nd_opt_rh);
   2691 		}
   2692 
   2693 		nd_opt_rh = (struct nd_opt_rd_hdr *)p;
   2694 		memset(nd_opt_rh, 0, sizeof(*nd_opt_rh));
   2695 		nd_opt_rh->nd_opt_rh_type = ND_OPT_REDIRECTED_HEADER;
   2696 		nd_opt_rh->nd_opt_rh_len = len >> 3;
   2697 		p += sizeof(*nd_opt_rh);
   2698 		m->m_pkthdr.len = m->m_len = p - (u_char *)ip6;
   2699 
   2700 		/* connect m0 to m */
   2701 		m->m_pkthdr.len += m0->m_pkthdr.len;
   2702 		m_cat(m, m0);
   2703 		m0 = NULL;
   2704 	}
   2705 noredhdropt:
   2706 	if (m0) {
   2707 		m_freem(m0);
   2708 		m0 = NULL;
   2709 	}
   2710 
   2711 	/* XXX: clear embedded link IDs in the inner header */
   2712 	in6_clearscope(&sip6->ip6_src);
   2713 	in6_clearscope(&sip6->ip6_dst);
   2714 	in6_clearscope(&nd_rd->nd_rd_target);
   2715 	in6_clearscope(&nd_rd->nd_rd_dst);
   2716 
   2717 	ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(struct ip6_hdr));
   2718 
   2719 	nd_rd->nd_rd_cksum = 0;
   2720 	nd_rd->nd_rd_cksum =
   2721 	    in6_cksum(m, IPPROTO_ICMPV6, sizeof(*ip6), ntohs(ip6->ip6_plen));
   2722 
   2723 	/* send the packet to outside... */
   2724 	if (ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL) != 0)
   2725 		icmp6_ifstat_inc(ifp, ifs6_out_error);
   2726 
   2727 	icmp6_ifstat_inc(ifp, ifs6_out_msg);
   2728 	icmp6_ifstat_inc(ifp, ifs6_out_redirect);
   2729 	ICMP6_STATINC(ICMP6_STAT_OUTHIST + ND_REDIRECT);
   2730 
   2731 	return;
   2732 
   2733 fail:
   2734 	if (m)
   2735 		m_freem(m);
   2736 	if (m0)
   2737 		m_freem(m0);
   2738 }
   2739 
   2740 /*
   2741  * ICMPv6 socket option processing.
   2742  */
   2743 int
   2744 icmp6_ctloutput(int op, struct socket *so, struct sockopt *sopt)
   2745 {
   2746 	int error = 0;
   2747 	struct inpcb *inp = sotoinpcb(so);
   2748 
   2749 	if (sopt->sopt_level != IPPROTO_ICMPV6)
   2750 		return rip6_ctloutput(op, so, sopt);
   2751 
   2752 	switch (op) {
   2753 	case PRCO_SETOPT:
   2754 		switch (sopt->sopt_name) {
   2755 		case ICMP6_FILTER:
   2756 		    {
   2757 			struct icmp6_filter fil;
   2758 
   2759 			error = sockopt_get(sopt, &fil, sizeof(fil));
   2760 			if (error)
   2761 				break;
   2762 			memcpy(in6p_icmp6filt(inp), &fil,
   2763 			    sizeof(struct icmp6_filter));
   2764 			error = 0;
   2765 			break;
   2766 		    }
   2767 
   2768 		default:
   2769 			error = ENOPROTOOPT;
   2770 			break;
   2771 		}
   2772 		break;
   2773 
   2774 	case PRCO_GETOPT:
   2775 		switch (sopt->sopt_name) {
   2776 		case ICMP6_FILTER:
   2777 		    {
   2778 			if (in6p_icmp6filt(inp) == NULL) {
   2779 				error = EINVAL;
   2780 				break;
   2781 			}
   2782 			error = sockopt_set(sopt, in6p_icmp6filt(inp),
   2783 			    sizeof(struct icmp6_filter));
   2784 			break;
   2785 		    }
   2786 
   2787 		default:
   2788 			error = ENOPROTOOPT;
   2789 			break;
   2790 		}
   2791 		break;
   2792 	}
   2793 
   2794 	return error;
   2795 }
   2796 
   2797 /*
   2798  * Perform rate limit check.
   2799  * Returns 0 if it is okay to send the icmp6 packet.
   2800  * Returns 1 if the router SHOULD NOT send this icmp6 packet due to rate
   2801  * limitation.
   2802  *
   2803  * XXX per-destination/type check necessary?
   2804  */
   2805 static int
   2806 icmp6_ratelimit(
   2807 	const struct in6_addr *dst,	/* not used at this moment */
   2808 	const int type,		/* not used at this moment */
   2809 	const int code)		/* not used at this moment */
   2810 {
   2811 	int ret;
   2812 
   2813 	ret = 0;	/* okay to send */
   2814 
   2815 	/* PPS limit */
   2816 	if (!ppsratecheck(&icmp6errppslim_last, &icmp6errpps_count,
   2817 	    icmp6errppslim)) {
   2818 		/* The packet is subject to rate limit */
   2819 		ret++;
   2820 	}
   2821 
   2822 	return ret;
   2823 }
   2824 
   2825 static struct rtentry *
   2826 icmp6_mtudisc_clone(struct sockaddr *dst)
   2827 {
   2828 	struct rtentry *rt;
   2829 	int    error;
   2830 
   2831 	rt = rtalloc1(dst, 1);
   2832 	if (rt == NULL)
   2833 		return NULL;
   2834 
   2835 	/* If we didn't get a host route, allocate one */
   2836 	if ((rt->rt_flags & RTF_HOST) == 0) {
   2837 		struct rtentry *nrt;
   2838 
   2839 		error = rtrequest(RTM_ADD, dst, rt->rt_gateway, NULL,
   2840 		    RTF_GATEWAY | RTF_HOST | RTF_DYNAMIC, &nrt);
   2841 		if (error) {
   2842 			rt_unref(rt);
   2843 			return NULL;
   2844 		}
   2845 		nrt->rt_rmx = rt->rt_rmx;
   2846 		rt_newmsg_dynamic(RTM_ADD, nrt);
   2847 		rt_unref(rt);
   2848 		rt = nrt;
   2849 	}
   2850 
   2851 	mutex_enter(&icmp6_mtx);
   2852 	error = rt_timer_add(rt, icmp6_mtudisc_timeout,
   2853 			icmp6_mtudisc_timeout_q);
   2854 	mutex_exit(&icmp6_mtx);
   2855 
   2856 	if (error) {
   2857 		rt_unref(rt);
   2858 		return NULL;
   2859 	}
   2860 
   2861 	return rt;	/* caller need to call rtfree() */
   2862 }
   2863 
   2864 static void
   2865 icmp6_mtudisc_timeout(struct rtentry *rt, struct rttimer *r)
   2866 {
   2867 	struct rtentry *retrt;
   2868 
   2869 	KASSERT(rt != NULL);
   2870 	rt_assert_referenced(rt);
   2871 
   2872 	if ((rt->rt_flags & (RTF_DYNAMIC | RTF_HOST)) ==
   2873 	    (RTF_DYNAMIC | RTF_HOST)) {
   2874 		rtrequest(RTM_DELETE, rt_getkey(rt),
   2875 		    rt->rt_gateway, rt_mask(rt), rt->rt_flags, &retrt);
   2876 		rt_newmsg_dynamic(RTM_DELETE, retrt);
   2877 		rt_unref(rt);
   2878 		rt_free(retrt);
   2879 	} else {
   2880 		if (!(rt->rt_rmx.rmx_locks & RTV_MTU))
   2881 			rt->rt_rmx.rmx_mtu = 0;
   2882 	}
   2883 }
   2884 
   2885 static void
   2886 icmp6_redirect_timeout(struct rtentry *rt, struct rttimer *r)
   2887 {
   2888 	struct rtentry *retrt;
   2889 
   2890 	KASSERT(rt != NULL);
   2891 	rt_assert_referenced(rt);
   2892 
   2893 	if ((rt->rt_flags & (RTF_GATEWAY | RTF_DYNAMIC | RTF_HOST)) ==
   2894 	    (RTF_GATEWAY | RTF_DYNAMIC | RTF_HOST)) {
   2895 		rtrequest(RTM_DELETE, rt_getkey(rt),
   2896 		    rt->rt_gateway, rt_mask(rt), rt->rt_flags, &retrt);
   2897 		rt_newmsg_dynamic(RTM_DELETE, retrt);
   2898 		rt_unref(rt);
   2899 		rt_free(retrt);
   2900 	}
   2901 }
   2902 
   2903 static int
   2904 sysctl_net_inet6_icmp6_stats(SYSCTLFN_ARGS)
   2905 {
   2906 
   2907 	return (NETSTAT_SYSCTL(icmp6stat_percpu, ICMP6_NSTATS));
   2908 }
   2909 
   2910 static int
   2911 sysctl_net_inet6_icmp6_redirtimeout(SYSCTLFN_ARGS)
   2912 {
   2913 	int error, tmp;
   2914 	struct sysctlnode node;
   2915 
   2916 	mutex_enter(&icmp6_mtx);
   2917 
   2918 	node = *rnode;
   2919 	node.sysctl_data = &tmp;
   2920 	tmp = icmp6_redirtimeout;
   2921 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
   2922 	if (error || newp == NULL)
   2923 		goto out;
   2924 	if (tmp < 0) {
   2925 		error = EINVAL;
   2926 		goto out;
   2927 	}
   2928 	icmp6_redirtimeout = tmp;
   2929 
   2930 	if (icmp6_redirect_timeout_q != NULL) {
   2931 		if (icmp6_redirtimeout == 0) {
   2932 			rt_timer_queue_destroy(icmp6_redirect_timeout_q);
   2933 		} else {
   2934 			rt_timer_queue_change(icmp6_redirect_timeout_q,
   2935 			    icmp6_redirtimeout);
   2936 		}
   2937 	} else if (icmp6_redirtimeout > 0) {
   2938 		icmp6_redirect_timeout_q =
   2939 		    rt_timer_queue_create(icmp6_redirtimeout);
   2940 	}
   2941 	error = 0;
   2942 out:
   2943 	mutex_exit(&icmp6_mtx);
   2944 	return error;
   2945 }
   2946 
   2947 static void
   2948 sysctl_net_inet6_icmp6_setup(struct sysctllog **clog)
   2949 {
   2950 
   2951 	sysctl_createv(clog, 0, NULL, NULL,
   2952 		       CTLFLAG_PERMANENT,
   2953 		       CTLTYPE_NODE, "inet6", NULL,
   2954 		       NULL, 0, NULL, 0,
   2955 		       CTL_NET, PF_INET6, CTL_EOL);
   2956 	sysctl_createv(clog, 0, NULL, NULL,
   2957 		       CTLFLAG_PERMANENT,
   2958 		       CTLTYPE_NODE, "icmp6",
   2959 		       SYSCTL_DESCR("ICMPv6 related settings"),
   2960 		       NULL, 0, NULL, 0,
   2961 		       CTL_NET, PF_INET6, IPPROTO_ICMPV6, CTL_EOL);
   2962 
   2963 	sysctl_createv(clog, 0, NULL, NULL,
   2964 		       CTLFLAG_PERMANENT,
   2965 		       CTLTYPE_STRUCT, "stats",
   2966 		       SYSCTL_DESCR("ICMPv6 transmission statistics"),
   2967 		       sysctl_net_inet6_icmp6_stats, 0, NULL, 0,
   2968 		       CTL_NET, PF_INET6, IPPROTO_ICMPV6,
   2969 		       ICMPV6CTL_STATS, CTL_EOL);
   2970 	sysctl_createv(clog, 0, NULL, NULL,
   2971 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2972 		       CTLTYPE_INT, "rediraccept",
   2973 		       SYSCTL_DESCR("Accept and process redirect messages"),
   2974 		       NULL, 0, &icmp6_rediraccept, 0,
   2975 		       CTL_NET, PF_INET6, IPPROTO_ICMPV6,
   2976 		       ICMPV6CTL_REDIRACCEPT, CTL_EOL);
   2977 	sysctl_createv(clog, 0, NULL, NULL,
   2978 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2979 		       CTLTYPE_INT, "redirtimeout",
   2980 		       SYSCTL_DESCR("Redirect generated route lifetime"),
   2981 		       sysctl_net_inet6_icmp6_redirtimeout, 0,
   2982 		       &icmp6_redirtimeout, 0,
   2983 		       CTL_NET, PF_INET6, IPPROTO_ICMPV6,
   2984 		       ICMPV6CTL_REDIRTIMEOUT, CTL_EOL);
   2985 #if 0 /* obsoleted */
   2986 	sysctl_createv(clog, 0, NULL, NULL,
   2987 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2988 		       CTLTYPE_INT, "errratelimit", NULL,
   2989 		       NULL, 0, &icmp6_errratelimit, 0,
   2990 		       CTL_NET, PF_INET6, IPPROTO_ICMPV6,
   2991 		       ICMPV6CTL_ERRRATELIMIT, CTL_EOL);
   2992 #endif
   2993 	sysctl_createv(clog, 0, NULL, NULL,
   2994 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2995 		       CTLTYPE_INT, "nd6_prune",
   2996 		       SYSCTL_DESCR("Neighbor discovery prune interval"),
   2997 		       NULL, 0, &nd6_prune, 0,
   2998 		       CTL_NET, PF_INET6, IPPROTO_ICMPV6,
   2999 		       ICMPV6CTL_ND6_PRUNE, CTL_EOL);
   3000 	sysctl_createv(clog, 0, NULL, NULL,
   3001 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   3002 		       CTLTYPE_INT, "nd6_delay",
   3003 		       SYSCTL_DESCR("First probe delay time"),
   3004 		       NULL, 0, &nd6_nd_domain.nd_delay, 0,
   3005 		       CTL_NET, PF_INET6, IPPROTO_ICMPV6,
   3006 		       ICMPV6CTL_ND6_DELAY, CTL_EOL);
   3007 	sysctl_createv(clog, 0, NULL, NULL,
   3008 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   3009 		       CTLTYPE_INT, "nd6_mmaxtries",
   3010 		       SYSCTL_DESCR("Number of multicast discovery attempts"),
   3011 		       NULL, 0, &nd6_nd_domain.nd_mmaxtries, 0,
   3012 		       CTL_NET, PF_INET6, IPPROTO_ICMPV6,
   3013 		       ICMPV6CTL_ND6_MMAXTRIES, CTL_EOL);
   3014 	sysctl_createv(clog, 0, NULL, NULL,
   3015 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   3016 		       CTLTYPE_INT, "nd6_umaxtries",
   3017 		       SYSCTL_DESCR("Number of unicast discovery attempts"),
   3018 		       NULL, 0, &nd6_nd_domain.nd_umaxtries, 0,
   3019 		       CTL_NET, PF_INET6, IPPROTO_ICMPV6,
   3020 		       ICMPV6CTL_ND6_UMAXTRIES, CTL_EOL);
   3021 	sysctl_createv(clog, 0, NULL, NULL,
   3022 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   3023 		       CTLTYPE_INT, "nd6_maxnudhint",
   3024 		       SYSCTL_DESCR("Maximum neighbor unreachable hint count"),
   3025 		       NULL, 0, &nd6_nd_domain.nd_maxnudhint, 0,
   3026 		       CTL_NET, PF_INET6, IPPROTO_ICMPV6,
   3027 		       ICMPV6CTL_ND6_MAXNUDHINT, CTL_EOL);
   3028 	sysctl_createv(clog, 0, NULL, NULL,
   3029 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   3030 		       CTLTYPE_INT, "maxqueuelen",
   3031 		       SYSCTL_DESCR("max packet queue len for a unresolved ND"),
   3032 		       NULL, 1, &nd6_nd_domain.nd_maxqueuelen, 0,
   3033 		       CTL_NET, PF_INET6, IPPROTO_ICMPV6,
   3034 		       ICMPV6CTL_ND6_MAXQLEN, CTL_EOL);
   3035 	sysctl_createv(clog, 0, NULL, NULL,
   3036 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   3037 		       CTLTYPE_INT, "nd6_useloopback",
   3038 		       SYSCTL_DESCR("Use loopback interface for local traffic"),
   3039 		       NULL, 0, &nd6_useloopback, 0,
   3040 		       CTL_NET, PF_INET6, IPPROTO_ICMPV6,
   3041 		       ICMPV6CTL_ND6_USELOOPBACK, CTL_EOL);
   3042 #if 0 /* obsoleted */
   3043 	sysctl_createv(clog, 0, NULL, NULL,
   3044 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   3045 		       CTLTYPE_INT, "nd6_proxyall", NULL,
   3046 		       NULL, 0, &nd6_proxyall, 0,
   3047 		       CTL_NET, PF_INET6, IPPROTO_ICMPV6,
   3048 		       ICMPV6CTL_ND6_PROXYALL, CTL_EOL);
   3049 #endif
   3050 	sysctl_createv(clog, 0, NULL, NULL,
   3051 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   3052 		       CTLTYPE_INT, "nodeinfo",
   3053 		       SYSCTL_DESCR("Respond to node information requests"),
   3054 		       NULL, 0, &icmp6_nodeinfo, 0,
   3055 		       CTL_NET, PF_INET6, IPPROTO_ICMPV6,
   3056 		       ICMPV6CTL_NODEINFO, CTL_EOL);
   3057 	sysctl_createv(clog, 0, NULL, NULL,
   3058 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   3059 		       CTLTYPE_INT, "errppslimit",
   3060 		       SYSCTL_DESCR("Maximum ICMP errors sent per second"),
   3061 		       NULL, 0, &icmp6errppslim, 0,
   3062 		       CTL_NET, PF_INET6, IPPROTO_ICMPV6,
   3063 		       ICMPV6CTL_ERRPPSLIMIT, CTL_EOL);
   3064 	sysctl_createv(clog, 0, NULL, NULL,
   3065 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   3066 		       CTLTYPE_INT, "mtudisc_hiwat",
   3067 		       SYSCTL_DESCR("Low mark on MTU Discovery route timers"),
   3068 		       NULL, 0, &icmp6_mtudisc_hiwat, 0,
   3069 		       CTL_NET, PF_INET6, IPPROTO_ICMPV6,
   3070 		       ICMPV6CTL_MTUDISC_HIWAT, CTL_EOL);
   3071 	sysctl_createv(clog, 0, NULL, NULL,
   3072 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   3073 		       CTLTYPE_INT, "mtudisc_lowat",
   3074 		       SYSCTL_DESCR("Low mark on MTU Discovery route timers"),
   3075 		       NULL, 0, &icmp6_mtudisc_lowat, 0,
   3076 		       CTL_NET, PF_INET6, IPPROTO_ICMPV6,
   3077 		       ICMPV6CTL_MTUDISC_LOWAT, CTL_EOL);
   3078 	sysctl_createv(clog, 0, NULL, NULL,
   3079 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   3080 		       CTLTYPE_INT, "nd6_debug",
   3081 		       SYSCTL_DESCR("Enable neighbor discovery debug output"),
   3082 		       NULL, 0, &nd6_debug, 0,
   3083 		       CTL_NET, PF_INET6, IPPROTO_ICMPV6,
   3084 		       ICMPV6CTL_ND6_DEBUG, CTL_EOL);
   3085 	sysctl_createv(clog, 0, NULL, NULL,
   3086 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   3087 		       CTLTYPE_BOOL, "reflect_pmtu",
   3088 		       SYSCTL_DESCR("Use path MTU Discovery for icmpv6 reflect"),
   3089 		       NULL, 0, &icmp6_reflect_pmtu, 0,
   3090 		       CTL_NET, PF_INET6, IPPROTO_ICMPV6,
   3091 		       ICMPV6CTL_REFLECT_PMTU, CTL_EOL);
   3092 	sysctl_createv(clog, 0, NULL, NULL,
   3093 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   3094 		       CTLTYPE_BOOL, "dynamic_rt_msg",
   3095 		       SYSCTL_DESCR("Send routing message for RTF_DYNAMIC"),
   3096 		       NULL, 0, &icmp6_dynamic_rt_msg, 0,
   3097 		       CTL_NET, PF_INET6, IPPROTO_ICMPV6,
   3098 		       ICMPV6CTL_DYNAMIC_RT_MSG, CTL_EOL);
   3099 }
   3100 
   3101 void
   3102 icmp6_statinc(u_int stat)
   3103 {
   3104 
   3105 	KASSERT(stat < ICMP6_NSTATS);
   3106 	ICMP6_STATINC(stat);
   3107 }
   3108