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