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