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