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