xref: /freebsd/sys/netinet6/icmp6.c (revision 190cef3d)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the project nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *	$KAME: icmp6.c,v 1.211 2001/04/04 05:56:20 itojun Exp $
32  */
33 
34 /*-
35  * Copyright (c) 1982, 1986, 1988, 1993
36  *	The Regents of the University of California.  All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 3. Neither the name of the University nor the names of its contributors
47  *    may be used to endorse or promote products derived from this software
48  *    without specific prior written permission.
49  *
50  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60  * SUCH DAMAGE.
61  *
62  *	@(#)ip_icmp.c	8.2 (Berkeley) 1/4/94
63  */
64 
65 #include <sys/cdefs.h>
66 __FBSDID("$FreeBSD$");
67 
68 #define	MBUF_PRIVATE	/* XXXRW: Optimisation tries to avoid M_EXT mbufs */
69 
70 #include "opt_inet.h"
71 #include "opt_inet6.h"
72 
73 #include <sys/param.h>
74 #include <sys/domain.h>
75 #include <sys/jail.h>
76 #include <sys/kernel.h>
77 #include <sys/lock.h>
78 #include <sys/malloc.h>
79 #include <sys/mbuf.h>
80 #include <sys/proc.h>
81 #include <sys/protosw.h>
82 #include <sys/signalvar.h>
83 #include <sys/socket.h>
84 #include <sys/socketvar.h>
85 #include <sys/sx.h>
86 #include <sys/syslog.h>
87 #include <sys/systm.h>
88 #include <sys/time.h>
89 
90 #include <net/if.h>
91 #include <net/if_var.h>
92 #include <net/if_dl.h>
93 #include <net/if_llatbl.h>
94 #include <net/if_types.h>
95 #include <net/route.h>
96 #include <net/vnet.h>
97 
98 #include <netinet/in.h>
99 #include <netinet/in_pcb.h>
100 #include <netinet/in_var.h>
101 #include <netinet/ip6.h>
102 #include <netinet/icmp6.h>
103 #include <netinet/tcp_var.h>
104 
105 #include <netinet6/in6_fib.h>
106 #include <netinet6/in6_ifattach.h>
107 #include <netinet6/in6_pcb.h>
108 #include <netinet6/ip6protosw.h>
109 #include <netinet6/ip6_var.h>
110 #include <netinet6/scope6_var.h>
111 #include <netinet6/mld6_var.h>
112 #include <netinet6/nd6.h>
113 #include <netinet6/send.h>
114 
115 extern struct domain inet6domain;
116 
117 VNET_PCPUSTAT_DEFINE(struct icmp6stat, icmp6stat);
118 VNET_PCPUSTAT_SYSINIT(icmp6stat);
119 
120 #ifdef VIMAGE
121 VNET_PCPUSTAT_SYSUNINIT(icmp6stat);
122 #endif /* VIMAGE */
123 
124 VNET_DECLARE(struct inpcbinfo, ripcbinfo);
125 VNET_DECLARE(struct inpcbhead, ripcb);
126 VNET_DECLARE(int, icmp6errppslim);
127 VNET_DEFINE_STATIC(int, icmp6errpps_count) = 0;
128 VNET_DEFINE_STATIC(struct timeval, icmp6errppslim_last);
129 VNET_DECLARE(int, icmp6_nodeinfo);
130 
131 #define	V_ripcbinfo			VNET(ripcbinfo)
132 #define	V_ripcb				VNET(ripcb)
133 #define	V_icmp6errppslim		VNET(icmp6errppslim)
134 #define	V_icmp6errpps_count		VNET(icmp6errpps_count)
135 #define	V_icmp6errppslim_last		VNET(icmp6errppslim_last)
136 #define	V_icmp6_nodeinfo		VNET(icmp6_nodeinfo)
137 
138 static void icmp6_errcount(int, int);
139 static int icmp6_rip6_input(struct mbuf **, int);
140 static int icmp6_ratelimit(const struct in6_addr *, const int, const int);
141 static const char *icmp6_redirect_diag(struct in6_addr *,
142 	struct in6_addr *, struct in6_addr *);
143 static struct mbuf *ni6_input(struct mbuf *, int);
144 static struct mbuf *ni6_nametodns(const char *, int, int);
145 static int ni6_dnsmatch(const char *, int, const char *, int);
146 static int ni6_addrs(struct icmp6_nodeinfo *, struct mbuf *,
147 			  struct ifnet **, struct in6_addr *);
148 static int ni6_store_addrs(struct icmp6_nodeinfo *, struct icmp6_nodeinfo *,
149 				struct ifnet *, int);
150 static int icmp6_notify_error(struct mbuf **, int, int, int);
151 
152 /*
153  * Kernel module interface for updating icmp6stat.  The argument is an index
154  * into icmp6stat treated as an array of u_quad_t.  While this encodes the
155  * general layout of icmp6stat into the caller, it doesn't encode its
156  * location, so that future changes to add, for example, per-CPU stats
157  * support won't cause binary compatibility problems for kernel modules.
158  */
159 void
160 kmod_icmp6stat_inc(int statnum)
161 {
162 
163 	counter_u64_add(VNET(icmp6stat)[statnum], 1);
164 }
165 
166 static void
167 icmp6_errcount(int type, int code)
168 {
169 	switch (type) {
170 	case ICMP6_DST_UNREACH:
171 		switch (code) {
172 		case ICMP6_DST_UNREACH_NOROUTE:
173 			ICMP6STAT_INC(icp6s_odst_unreach_noroute);
174 			return;
175 		case ICMP6_DST_UNREACH_ADMIN:
176 			ICMP6STAT_INC(icp6s_odst_unreach_admin);
177 			return;
178 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
179 			ICMP6STAT_INC(icp6s_odst_unreach_beyondscope);
180 			return;
181 		case ICMP6_DST_UNREACH_ADDR:
182 			ICMP6STAT_INC(icp6s_odst_unreach_addr);
183 			return;
184 		case ICMP6_DST_UNREACH_NOPORT:
185 			ICMP6STAT_INC(icp6s_odst_unreach_noport);
186 			return;
187 		}
188 		break;
189 	case ICMP6_PACKET_TOO_BIG:
190 		ICMP6STAT_INC(icp6s_opacket_too_big);
191 		return;
192 	case ICMP6_TIME_EXCEEDED:
193 		switch (code) {
194 		case ICMP6_TIME_EXCEED_TRANSIT:
195 			ICMP6STAT_INC(icp6s_otime_exceed_transit);
196 			return;
197 		case ICMP6_TIME_EXCEED_REASSEMBLY:
198 			ICMP6STAT_INC(icp6s_otime_exceed_reassembly);
199 			return;
200 		}
201 		break;
202 	case ICMP6_PARAM_PROB:
203 		switch (code) {
204 		case ICMP6_PARAMPROB_HEADER:
205 			ICMP6STAT_INC(icp6s_oparamprob_header);
206 			return;
207 		case ICMP6_PARAMPROB_NEXTHEADER:
208 			ICMP6STAT_INC(icp6s_oparamprob_nextheader);
209 			return;
210 		case ICMP6_PARAMPROB_OPTION:
211 			ICMP6STAT_INC(icp6s_oparamprob_option);
212 			return;
213 		}
214 		break;
215 	case ND_REDIRECT:
216 		ICMP6STAT_INC(icp6s_oredirect);
217 		return;
218 	}
219 	ICMP6STAT_INC(icp6s_ounknown);
220 }
221 
222 /*
223  * A wrapper function for icmp6_error() necessary when the erroneous packet
224  * may not contain enough scope zone information.
225  */
226 void
227 icmp6_error2(struct mbuf *m, int type, int code, int param,
228     struct ifnet *ifp)
229 {
230 	struct ip6_hdr *ip6;
231 
232 	if (ifp == NULL)
233 		return;
234 
235 #ifndef PULLDOWN_TEST
236 	IP6_EXTHDR_CHECK(m, 0, sizeof(struct ip6_hdr), );
237 #else
238 	if (m->m_len < sizeof(struct ip6_hdr)) {
239 		m = m_pullup(m, sizeof(struct ip6_hdr));
240 		if (m == NULL)
241 			return;
242 	}
243 #endif
244 
245 	ip6 = mtod(m, struct ip6_hdr *);
246 
247 	if (in6_setscope(&ip6->ip6_src, ifp, NULL) != 0)
248 		return;
249 	if (in6_setscope(&ip6->ip6_dst, ifp, NULL) != 0)
250 		return;
251 
252 	icmp6_error(m, type, code, param);
253 }
254 
255 /*
256  * Generate an error packet of type error in response to bad IP6 packet.
257  */
258 void
259 icmp6_error(struct mbuf *m, int type, int code, int param)
260 {
261 	struct ip6_hdr *oip6, *nip6;
262 	struct icmp6_hdr *icmp6;
263 	u_int preplen;
264 	int off;
265 	int nxt;
266 
267 	ICMP6STAT_INC(icp6s_error);
268 
269 	/* count per-type-code statistics */
270 	icmp6_errcount(type, code);
271 
272 #ifdef M_DECRYPTED	/*not openbsd*/
273 	if (m->m_flags & M_DECRYPTED) {
274 		ICMP6STAT_INC(icp6s_canterror);
275 		goto freeit;
276 	}
277 #endif
278 
279 #ifndef PULLDOWN_TEST
280 	IP6_EXTHDR_CHECK(m, 0, sizeof(struct ip6_hdr), );
281 #else
282 	if (m->m_len < sizeof(struct ip6_hdr)) {
283 		m = m_pullup(m, sizeof(struct ip6_hdr));
284 		if (m == NULL)
285 			return;
286 	}
287 #endif
288 	oip6 = mtod(m, struct ip6_hdr *);
289 
290 	/*
291 	 * If the destination address of the erroneous packet is a multicast
292 	 * address, or the packet was sent using link-layer multicast,
293 	 * we should basically suppress sending an error (RFC 2463, Section
294 	 * 2.4).
295 	 * We have two exceptions (the item e.2 in that section):
296 	 * - the Packet Too Big message can be sent for path MTU discovery.
297 	 * - the Parameter Problem Message that can be allowed an icmp6 error
298 	 *   in the option type field.  This check has been done in
299 	 *   ip6_unknown_opt(), so we can just check the type and code.
300 	 */
301 	if ((m->m_flags & (M_BCAST|M_MCAST) ||
302 	     IN6_IS_ADDR_MULTICAST(&oip6->ip6_dst)) &&
303 	    (type != ICMP6_PACKET_TOO_BIG &&
304 	     (type != ICMP6_PARAM_PROB ||
305 	      code != ICMP6_PARAMPROB_OPTION)))
306 		goto freeit;
307 
308 	/*
309 	 * RFC 2463, 2.4 (e.5): source address check.
310 	 * XXX: the case of anycast source?
311 	 */
312 	if (IN6_IS_ADDR_UNSPECIFIED(&oip6->ip6_src) ||
313 	    IN6_IS_ADDR_MULTICAST(&oip6->ip6_src))
314 		goto freeit;
315 
316 	/*
317 	 * If we are about to send ICMPv6 against ICMPv6 error/redirect,
318 	 * don't do it.
319 	 */
320 	nxt = -1;
321 	off = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxt);
322 	if (off >= 0 && nxt == IPPROTO_ICMPV6) {
323 		struct icmp6_hdr *icp;
324 
325 #ifndef PULLDOWN_TEST
326 		IP6_EXTHDR_CHECK(m, 0, off + sizeof(struct icmp6_hdr), );
327 		icp = (struct icmp6_hdr *)(mtod(m, caddr_t) + off);
328 #else
329 		IP6_EXTHDR_GET(icp, struct icmp6_hdr *, m, off,
330 			sizeof(*icp));
331 		if (icp == NULL) {
332 			ICMP6STAT_INC(icp6s_tooshort);
333 			return;
334 		}
335 #endif
336 		if (icp->icmp6_type < ICMP6_ECHO_REQUEST ||
337 		    icp->icmp6_type == ND_REDIRECT) {
338 			/*
339 			 * ICMPv6 error
340 			 * Special case: for redirect (which is
341 			 * informational) we must not send icmp6 error.
342 			 */
343 			ICMP6STAT_INC(icp6s_canterror);
344 			goto freeit;
345 		} else {
346 			/* ICMPv6 informational - send the error */
347 		}
348 	} else {
349 		/* non-ICMPv6 - send the error */
350 	}
351 
352 	oip6 = mtod(m, struct ip6_hdr *); /* adjust pointer */
353 
354 	/* Finally, do rate limitation check. */
355 	if (icmp6_ratelimit(&oip6->ip6_src, type, code)) {
356 		ICMP6STAT_INC(icp6s_toofreq);
357 		goto freeit;
358 	}
359 
360 	/*
361 	 * OK, ICMP6 can be generated.
362 	 */
363 
364 	if (m->m_pkthdr.len >= ICMPV6_PLD_MAXLEN)
365 		m_adj(m, ICMPV6_PLD_MAXLEN - m->m_pkthdr.len);
366 
367 	preplen = sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr);
368 	M_PREPEND(m, preplen, M_NOWAIT);	/* FIB is also copied over. */
369 	if (m == NULL) {
370 		nd6log((LOG_DEBUG, "ENOBUFS in icmp6_error %d\n", __LINE__));
371 		return;
372 	}
373 
374 	nip6 = mtod(m, struct ip6_hdr *);
375 	nip6->ip6_src  = oip6->ip6_src;
376 	nip6->ip6_dst  = oip6->ip6_dst;
377 
378 	in6_clearscope(&oip6->ip6_src);
379 	in6_clearscope(&oip6->ip6_dst);
380 
381 	icmp6 = (struct icmp6_hdr *)(nip6 + 1);
382 	icmp6->icmp6_type = type;
383 	icmp6->icmp6_code = code;
384 	icmp6->icmp6_pptr = htonl((u_int32_t)param);
385 
386 	ICMP6STAT_INC(icp6s_outhist[type]);
387 	icmp6_reflect(m, sizeof(struct ip6_hdr)); /* header order: IPv6 - ICMPv6 */
388 
389 	return;
390 
391   freeit:
392 	/*
393 	 * If we can't tell whether or not we can generate ICMP6, free it.
394 	 */
395 	m_freem(m);
396 }
397 
398 /*
399  * Process a received ICMP6 message.
400  */
401 int
402 icmp6_input(struct mbuf **mp, int *offp, int proto)
403 {
404 	struct mbuf *m = *mp, *n;
405 	struct ifnet *ifp;
406 	struct ip6_hdr *ip6, *nip6;
407 	struct icmp6_hdr *icmp6, *nicmp6;
408 	int off = *offp;
409 	int icmp6len = m->m_pkthdr.len - *offp;
410 	int code, sum, noff;
411 	char ip6bufs[INET6_ADDRSTRLEN], ip6bufd[INET6_ADDRSTRLEN];
412 	int ip6len, error;
413 
414 	ifp = m->m_pkthdr.rcvif;
415 
416 #ifndef PULLDOWN_TEST
417 	IP6_EXTHDR_CHECK(m, off, sizeof(struct icmp6_hdr), IPPROTO_DONE);
418 	/* m might change if M_LOOP.  So, call mtod after this */
419 #endif
420 
421 	/*
422 	 * Locate icmp6 structure in mbuf, and check
423 	 * that not corrupted and of at least minimum length
424 	 */
425 
426 	ip6 = mtod(m, struct ip6_hdr *);
427 	ip6len = sizeof(struct ip6_hdr) + ntohs(ip6->ip6_plen);
428 	if (icmp6len < sizeof(struct icmp6_hdr)) {
429 		ICMP6STAT_INC(icp6s_tooshort);
430 		goto freeit;
431 	}
432 
433 	/*
434 	 * Check multicast group membership.
435 	 * Note: SSM filters are not applied for ICMPv6 traffic.
436 	 */
437 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
438 		struct in6_multi	*inm;
439 
440 		inm = in6m_lookup(ifp, &ip6->ip6_dst);
441 		if (inm == NULL) {
442 			IP6STAT_INC(ip6s_notmember);
443 			in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_discard);
444 			goto freeit;
445 		}
446 	}
447 
448 	/*
449 	 * calculate the checksum
450 	 */
451 #ifndef PULLDOWN_TEST
452 	icmp6 = (struct icmp6_hdr *)((caddr_t)ip6 + off);
453 #else
454 	IP6_EXTHDR_GET(icmp6, struct icmp6_hdr *, m, off, sizeof(*icmp6));
455 	if (icmp6 == NULL) {
456 		ICMP6STAT_INC(icp6s_tooshort);
457 		return IPPROTO_DONE;
458 	}
459 #endif
460 	code = icmp6->icmp6_code;
461 
462 	if ((sum = in6_cksum(m, IPPROTO_ICMPV6, off, icmp6len)) != 0) {
463 		nd6log((LOG_ERR,
464 		    "ICMP6 checksum error(%d|%x) %s\n",
465 		    icmp6->icmp6_type, sum,
466 		    ip6_sprintf(ip6bufs, &ip6->ip6_src)));
467 		ICMP6STAT_INC(icp6s_checksum);
468 		goto freeit;
469 	}
470 
471 	ICMP6STAT_INC(icp6s_inhist[icmp6->icmp6_type]);
472 	icmp6_ifstat_inc(ifp, ifs6_in_msg);
473 	if (icmp6->icmp6_type < ICMP6_INFOMSG_MASK)
474 		icmp6_ifstat_inc(ifp, ifs6_in_error);
475 
476 	switch (icmp6->icmp6_type) {
477 	case ICMP6_DST_UNREACH:
478 		icmp6_ifstat_inc(ifp, ifs6_in_dstunreach);
479 		switch (code) {
480 		case ICMP6_DST_UNREACH_NOROUTE:
481 		case ICMP6_DST_UNREACH_ADDR:	/* PRC_HOSTDEAD is a DOS */
482 			code = PRC_UNREACH_NET;
483 			break;
484 		case ICMP6_DST_UNREACH_ADMIN:
485 			icmp6_ifstat_inc(ifp, ifs6_in_adminprohib);
486 			code = PRC_UNREACH_ADMIN_PROHIB;
487 			break;
488 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
489 			/* I mean "source address was incorrect." */
490 			code = PRC_PARAMPROB;
491 			break;
492 		case ICMP6_DST_UNREACH_NOPORT:
493 			code = PRC_UNREACH_PORT;
494 			break;
495 		default:
496 			goto badcode;
497 		}
498 		goto deliver;
499 		break;
500 
501 	case ICMP6_PACKET_TOO_BIG:
502 		icmp6_ifstat_inc(ifp, ifs6_in_pkttoobig);
503 
504 		/* validation is made in icmp6_mtudisc_update */
505 
506 		code = PRC_MSGSIZE;
507 
508 		/*
509 		 * Updating the path MTU will be done after examining
510 		 * intermediate extension headers.
511 		 */
512 		goto deliver;
513 		break;
514 
515 	case ICMP6_TIME_EXCEEDED:
516 		icmp6_ifstat_inc(ifp, ifs6_in_timeexceed);
517 		switch (code) {
518 		case ICMP6_TIME_EXCEED_TRANSIT:
519 			code = PRC_TIMXCEED_INTRANS;
520 			break;
521 		case ICMP6_TIME_EXCEED_REASSEMBLY:
522 			code = PRC_TIMXCEED_REASS;
523 			break;
524 		default:
525 			goto badcode;
526 		}
527 		goto deliver;
528 		break;
529 
530 	case ICMP6_PARAM_PROB:
531 		icmp6_ifstat_inc(ifp, ifs6_in_paramprob);
532 		switch (code) {
533 		case ICMP6_PARAMPROB_NEXTHEADER:
534 			code = PRC_UNREACH_PROTOCOL;
535 			break;
536 		case ICMP6_PARAMPROB_HEADER:
537 		case ICMP6_PARAMPROB_OPTION:
538 			code = PRC_PARAMPROB;
539 			break;
540 		default:
541 			goto badcode;
542 		}
543 		goto deliver;
544 		break;
545 
546 	case ICMP6_ECHO_REQUEST:
547 		icmp6_ifstat_inc(ifp, ifs6_in_echo);
548 		if (code != 0)
549 			goto badcode;
550 		if ((n = m_copym(m, 0, M_COPYALL, M_NOWAIT)) == NULL) {
551 			/* Give up remote */
552 			break;
553 		}
554 		if (!M_WRITABLE(n)
555 		 || n->m_len < off + sizeof(struct icmp6_hdr)) {
556 			struct mbuf *n0 = n;
557 			int n0len;
558 
559 			CTASSERT(sizeof(*nip6) + sizeof(*nicmp6) <= MHLEN);
560 			n = m_gethdr(M_NOWAIT, n0->m_type);
561 			if (n == NULL) {
562 				/* Give up remote */
563 				m_freem(n0);
564 				break;
565 			}
566 
567 			m_move_pkthdr(n, n0);	/* FIB copied. */
568 			n0len = n0->m_pkthdr.len;	/* save for use below */
569 			/*
570 			 * Copy IPv6 and ICMPv6 only.
571 			 */
572 			nip6 = mtod(n, struct ip6_hdr *);
573 			bcopy(ip6, nip6, sizeof(struct ip6_hdr));
574 			nicmp6 = (struct icmp6_hdr *)(nip6 + 1);
575 			bcopy(icmp6, nicmp6, sizeof(struct icmp6_hdr));
576 			noff = sizeof(struct ip6_hdr);
577 			/* new mbuf contains only ipv6+icmpv6 headers */
578 			n->m_len = noff + sizeof(struct icmp6_hdr);
579 			/*
580 			 * Adjust mbuf.  ip6_plen will be adjusted in
581 			 * ip6_output().
582 			 */
583 			m_adj(n0, off + sizeof(struct icmp6_hdr));
584 			/* recalculate complete packet size */
585 			n->m_pkthdr.len = n0len + (noff - off);
586 			n->m_next = n0;
587 		} else {
588 			IP6_EXTHDR_GET(nicmp6, struct icmp6_hdr *, n, off,
589 			    sizeof(*nicmp6));
590 			noff = off;
591 		}
592 		if (n) {
593 			nicmp6->icmp6_type = ICMP6_ECHO_REPLY;
594 			nicmp6->icmp6_code = 0;
595 			ICMP6STAT_INC(icp6s_reflect);
596 			ICMP6STAT_INC(icp6s_outhist[ICMP6_ECHO_REPLY]);
597 			icmp6_reflect(n, noff);
598 		}
599 		break;
600 
601 	case ICMP6_ECHO_REPLY:
602 		icmp6_ifstat_inc(ifp, ifs6_in_echoreply);
603 		if (code != 0)
604 			goto badcode;
605 		break;
606 
607 	case MLD_LISTENER_QUERY:
608 	case MLD_LISTENER_REPORT:
609 	case MLD_LISTENER_DONE:
610 	case MLDV2_LISTENER_REPORT:
611 		/*
612 		 * Drop MLD traffic which is not link-local, has a hop limit
613 		 * of greater than 1 hop, or which does not have the
614 		 * IPv6 HBH Router Alert option.
615 		 * As IPv6 HBH options are stripped in ip6_input() we must
616 		 * check an mbuf header flag.
617 		 * XXX Should we also sanity check that these messages
618 		 * were directed to a link-local multicast prefix?
619 		 */
620 		if ((ip6->ip6_hlim != 1) || (m->m_flags & M_RTALERT_MLD) == 0)
621 			goto freeit;
622 		if (mld_input(m, off, icmp6len) != 0)
623 			return (IPPROTO_DONE);
624 		/* m stays. */
625 		break;
626 
627 	case ICMP6_WRUREQUEST:	/* ICMP6_FQDN_QUERY */
628 	    {
629 		enum { WRU, FQDN } mode;
630 
631 		if (!V_icmp6_nodeinfo)
632 			break;
633 
634 		if (icmp6len == sizeof(struct icmp6_hdr) + 4)
635 			mode = WRU;
636 		else if (icmp6len >= sizeof(struct icmp6_nodeinfo))
637 			mode = FQDN;
638 		else
639 			goto badlen;
640 
641 		if (mode == FQDN) {
642 #ifndef PULLDOWN_TEST
643 			IP6_EXTHDR_CHECK(m, off, sizeof(struct icmp6_nodeinfo),
644 			    IPPROTO_DONE);
645 #endif
646 			n = m_copym(m, 0, M_COPYALL, M_NOWAIT);
647 			if (n)
648 				n = ni6_input(n, off);
649 			/* XXX meaningless if n == NULL */
650 			noff = sizeof(struct ip6_hdr);
651 		} else {
652 			struct prison *pr;
653 			u_char *p;
654 			int maxhlen, hlen;
655 
656 			/*
657 			 * XXX: this combination of flags is pointless,
658 			 * but should we keep this for compatibility?
659 			 */
660 			if ((V_icmp6_nodeinfo & (ICMP6_NODEINFO_FQDNOK |
661 			    ICMP6_NODEINFO_TMPADDROK)) !=
662 			    (ICMP6_NODEINFO_FQDNOK | ICMP6_NODEINFO_TMPADDROK))
663 				break;
664 
665 			if (code != 0)
666 				goto badcode;
667 
668 			CTASSERT(sizeof(*nip6) + sizeof(*nicmp6) + 4 <= MHLEN);
669 			n = m_gethdr(M_NOWAIT, m->m_type);
670 			if (n == NULL) {
671 				/* Give up remote */
672 				break;
673 			}
674 			if (!m_dup_pkthdr(n, m, M_NOWAIT)) {
675 				/*
676 				 * Previous code did a blind M_COPY_PKTHDR
677 				 * and said "just for rcvif".  If true, then
678 				 * we could tolerate the dup failing (due to
679 				 * the deep copy of the tag chain).  For now
680 				 * be conservative and just fail.
681 				 */
682 				m_free(n);
683 				n = NULL;
684 				break;
685 			}
686 			maxhlen = M_TRAILINGSPACE(n) -
687 			    (sizeof(*nip6) + sizeof(*nicmp6) + 4);
688 			pr = curthread->td_ucred->cr_prison;
689 			mtx_lock(&pr->pr_mtx);
690 			hlen = strlen(pr->pr_hostname);
691 			if (maxhlen > hlen)
692 				maxhlen = hlen;
693 			/*
694 			 * Copy IPv6 and ICMPv6 only.
695 			 */
696 			nip6 = mtod(n, struct ip6_hdr *);
697 			bcopy(ip6, nip6, sizeof(struct ip6_hdr));
698 			nicmp6 = (struct icmp6_hdr *)(nip6 + 1);
699 			bcopy(icmp6, nicmp6, sizeof(struct icmp6_hdr));
700 			p = (u_char *)(nicmp6 + 1);
701 			bzero(p, 4);
702 			/* meaningless TTL */
703 			bcopy(pr->pr_hostname, p + 4, maxhlen);
704 			mtx_unlock(&pr->pr_mtx);
705 			noff = sizeof(struct ip6_hdr);
706 			n->m_pkthdr.len = n->m_len = sizeof(struct ip6_hdr) +
707 				sizeof(struct icmp6_hdr) + 4 + maxhlen;
708 			nicmp6->icmp6_type = ICMP6_WRUREPLY;
709 			nicmp6->icmp6_code = 0;
710 		}
711 		if (n) {
712 			ICMP6STAT_INC(icp6s_reflect);
713 			ICMP6STAT_INC(icp6s_outhist[ICMP6_WRUREPLY]);
714 			icmp6_reflect(n, noff);
715 		}
716 		break;
717 	    }
718 
719 	case ICMP6_WRUREPLY:
720 		if (code != 0)
721 			goto badcode;
722 		break;
723 
724 	case ND_ROUTER_SOLICIT:
725 		icmp6_ifstat_inc(ifp, ifs6_in_routersolicit);
726 		if (code != 0)
727 			goto badcode;
728 		if (icmp6len < sizeof(struct nd_router_solicit))
729 			goto badlen;
730 		if (send_sendso_input_hook != NULL) {
731 			IP6_EXTHDR_CHECK(m, off, icmp6len, IPPROTO_DONE);
732 			error = send_sendso_input_hook(m, ifp, SND_IN, ip6len);
733 			if (error == 0) {
734 				m = NULL;
735 				goto freeit;
736 			}
737 		}
738 		n = m_copym(m, 0, M_COPYALL, M_NOWAIT);
739 		nd6_rs_input(m, off, icmp6len);
740 		m = n;
741 		if (m == NULL)
742 			goto freeit;
743 		break;
744 
745 	case ND_ROUTER_ADVERT:
746 		icmp6_ifstat_inc(ifp, ifs6_in_routeradvert);
747 		if (code != 0)
748 			goto badcode;
749 		if (icmp6len < sizeof(struct nd_router_advert))
750 			goto badlen;
751 		if (send_sendso_input_hook != NULL) {
752 			error = send_sendso_input_hook(m, ifp, SND_IN, ip6len);
753 			if (error == 0) {
754 				m = NULL;
755 				goto freeit;
756 			}
757 		}
758 		n = m_copym(m, 0, M_COPYALL, M_NOWAIT);
759 		nd6_ra_input(m, off, icmp6len);
760 		m = n;
761 		if (m == NULL)
762 			goto freeit;
763 		break;
764 
765 	case ND_NEIGHBOR_SOLICIT:
766 		icmp6_ifstat_inc(ifp, ifs6_in_neighborsolicit);
767 		if (code != 0)
768 			goto badcode;
769 		if (icmp6len < sizeof(struct nd_neighbor_solicit))
770 			goto badlen;
771 		if (send_sendso_input_hook != NULL) {
772 			error = send_sendso_input_hook(m, ifp, SND_IN, ip6len);
773 			if (error == 0) {
774 				m = NULL;
775 				goto freeit;
776 			}
777 		}
778 		n = m_copym(m, 0, M_COPYALL, M_NOWAIT);
779 		nd6_ns_input(m, off, icmp6len);
780 		m = n;
781 		if (m == NULL)
782 			goto freeit;
783 		break;
784 
785 	case ND_NEIGHBOR_ADVERT:
786 		icmp6_ifstat_inc(ifp, ifs6_in_neighboradvert);
787 		if (code != 0)
788 			goto badcode;
789 		if (icmp6len < sizeof(struct nd_neighbor_advert))
790 			goto badlen;
791 		if (send_sendso_input_hook != NULL) {
792 			error = send_sendso_input_hook(m, ifp, SND_IN, ip6len);
793 			if (error == 0) {
794 				m = NULL;
795 				goto freeit;
796 			}
797 		}
798 		n = m_copym(m, 0, M_COPYALL, M_NOWAIT);
799 		nd6_na_input(m, off, icmp6len);
800 		m = n;
801 		if (m == NULL)
802 			goto freeit;
803 		break;
804 
805 	case ND_REDIRECT:
806 		icmp6_ifstat_inc(ifp, ifs6_in_redirect);
807 		if (code != 0)
808 			goto badcode;
809 		if (icmp6len < sizeof(struct nd_redirect))
810 			goto badlen;
811 		if (send_sendso_input_hook != NULL) {
812 			error = send_sendso_input_hook(m, ifp, SND_IN, ip6len);
813 			if (error == 0) {
814 				m = NULL;
815 				goto freeit;
816 			}
817 		}
818 		n = m_copym(m, 0, M_COPYALL, M_NOWAIT);
819 		icmp6_redirect_input(m, off);
820 		m = n;
821 		if (m == NULL)
822 			goto freeit;
823 		break;
824 
825 	case ICMP6_ROUTER_RENUMBERING:
826 		if (code != ICMP6_ROUTER_RENUMBERING_COMMAND &&
827 		    code != ICMP6_ROUTER_RENUMBERING_RESULT)
828 			goto badcode;
829 		if (icmp6len < sizeof(struct icmp6_router_renum))
830 			goto badlen;
831 		break;
832 
833 	default:
834 		nd6log((LOG_DEBUG,
835 		    "icmp6_input: unknown type %d(src=%s, dst=%s, ifid=%d)\n",
836 		    icmp6->icmp6_type, ip6_sprintf(ip6bufs, &ip6->ip6_src),
837 		    ip6_sprintf(ip6bufd, &ip6->ip6_dst),
838 		    ifp ? ifp->if_index : 0));
839 		if (icmp6->icmp6_type < ICMP6_ECHO_REQUEST) {
840 			/* ICMPv6 error: MUST deliver it by spec... */
841 			code = PRC_NCMDS;
842 			/* deliver */
843 		} else {
844 			/* ICMPv6 informational: MUST not deliver */
845 			break;
846 		}
847 	deliver:
848 		if (icmp6_notify_error(&m, off, icmp6len, code) != 0) {
849 			/* In this case, m should've been freed. */
850 			return (IPPROTO_DONE);
851 		}
852 		break;
853 
854 	badcode:
855 		ICMP6STAT_INC(icp6s_badcode);
856 		break;
857 
858 	badlen:
859 		ICMP6STAT_INC(icp6s_badlen);
860 		break;
861 	}
862 
863 	/* deliver the packet to appropriate sockets */
864 	icmp6_rip6_input(&m, *offp);
865 
866 	return IPPROTO_DONE;
867 
868  freeit:
869 	m_freem(m);
870 	return IPPROTO_DONE;
871 }
872 
873 static int
874 icmp6_notify_error(struct mbuf **mp, int off, int icmp6len, int code)
875 {
876 	struct mbuf *m = *mp;
877 	struct icmp6_hdr *icmp6;
878 	struct ip6_hdr *eip6;
879 	u_int32_t notifymtu;
880 	struct sockaddr_in6 icmp6src, icmp6dst;
881 
882 	if (icmp6len < sizeof(struct icmp6_hdr) + sizeof(struct ip6_hdr)) {
883 		ICMP6STAT_INC(icp6s_tooshort);
884 		goto freeit;
885 	}
886 #ifndef PULLDOWN_TEST
887 	IP6_EXTHDR_CHECK(m, off,
888 	    sizeof(struct icmp6_hdr) + sizeof(struct ip6_hdr), -1);
889 	icmp6 = (struct icmp6_hdr *)(mtod(m, caddr_t) + off);
890 #else
891 	IP6_EXTHDR_GET(icmp6, struct icmp6_hdr *, m, off,
892 	    sizeof(*icmp6) + sizeof(struct ip6_hdr));
893 	if (icmp6 == NULL) {
894 		ICMP6STAT_INC(icp6s_tooshort);
895 		return (-1);
896 	}
897 #endif
898 	eip6 = (struct ip6_hdr *)(icmp6 + 1);
899 
900 	/* Detect the upper level protocol */
901 	{
902 		void (*ctlfunc)(int, struct sockaddr *, void *);
903 		u_int8_t nxt = eip6->ip6_nxt;
904 		int eoff = off + sizeof(struct icmp6_hdr) +
905 		    sizeof(struct ip6_hdr);
906 		struct ip6ctlparam ip6cp;
907 		struct in6_addr *finaldst = NULL;
908 		int icmp6type = icmp6->icmp6_type;
909 		struct ip6_frag *fh;
910 		struct ip6_rthdr *rth;
911 		struct ip6_rthdr0 *rth0;
912 		int rthlen;
913 
914 		while (1) { /* XXX: should avoid infinite loop explicitly? */
915 			struct ip6_ext *eh;
916 
917 			switch (nxt) {
918 			case IPPROTO_HOPOPTS:
919 			case IPPROTO_DSTOPTS:
920 			case IPPROTO_AH:
921 #ifndef PULLDOWN_TEST
922 				IP6_EXTHDR_CHECK(m, 0,
923 				    eoff + sizeof(struct ip6_ext), -1);
924 				eh = (struct ip6_ext *)(mtod(m, caddr_t) + eoff);
925 #else
926 				IP6_EXTHDR_GET(eh, struct ip6_ext *, m,
927 				    eoff, sizeof(*eh));
928 				if (eh == NULL) {
929 					ICMP6STAT_INC(icp6s_tooshort);
930 					return (-1);
931 				}
932 #endif
933 
934 				if (nxt == IPPROTO_AH)
935 					eoff += (eh->ip6e_len + 2) << 2;
936 				else
937 					eoff += (eh->ip6e_len + 1) << 3;
938 				nxt = eh->ip6e_nxt;
939 				break;
940 			case IPPROTO_ROUTING:
941 				/*
942 				 * When the erroneous packet contains a
943 				 * routing header, we should examine the
944 				 * header to determine the final destination.
945 				 * Otherwise, we can't properly update
946 				 * information that depends on the final
947 				 * destination (e.g. path MTU).
948 				 */
949 #ifndef PULLDOWN_TEST
950 				IP6_EXTHDR_CHECK(m, 0, eoff + sizeof(*rth), -1);
951 				rth = (struct ip6_rthdr *)
952 				    (mtod(m, caddr_t) + eoff);
953 #else
954 				IP6_EXTHDR_GET(rth, struct ip6_rthdr *, m,
955 				    eoff, sizeof(*rth));
956 				if (rth == NULL) {
957 					ICMP6STAT_INC(icp6s_tooshort);
958 					return (-1);
959 				}
960 #endif
961 				rthlen = (rth->ip6r_len + 1) << 3;
962 				/*
963 				 * XXX: currently there is no
964 				 * officially defined type other
965 				 * than type-0.
966 				 * Note that if the segment left field
967 				 * is 0, all intermediate hops must
968 				 * have been passed.
969 				 */
970 				if (rth->ip6r_segleft &&
971 				    rth->ip6r_type == IPV6_RTHDR_TYPE_0) {
972 					int hops;
973 
974 #ifndef PULLDOWN_TEST
975 					IP6_EXTHDR_CHECK(m, 0, eoff + rthlen, -1);
976 					rth0 = (struct ip6_rthdr0 *)
977 					    (mtod(m, caddr_t) + eoff);
978 #else
979 					IP6_EXTHDR_GET(rth0,
980 					    struct ip6_rthdr0 *, m,
981 					    eoff, rthlen);
982 					if (rth0 == NULL) {
983 						ICMP6STAT_INC(icp6s_tooshort);
984 						return (-1);
985 					}
986 #endif
987 					/* just ignore a bogus header */
988 					if ((rth0->ip6r0_len % 2) == 0 &&
989 					    (hops = rth0->ip6r0_len/2))
990 						finaldst = (struct in6_addr *)(rth0 + 1) + (hops - 1);
991 				}
992 				eoff += rthlen;
993 				nxt = rth->ip6r_nxt;
994 				break;
995 			case IPPROTO_FRAGMENT:
996 #ifndef PULLDOWN_TEST
997 				IP6_EXTHDR_CHECK(m, 0, eoff +
998 				    sizeof(struct ip6_frag), -1);
999 				fh = (struct ip6_frag *)(mtod(m, caddr_t) +
1000 				    eoff);
1001 #else
1002 				IP6_EXTHDR_GET(fh, struct ip6_frag *, m,
1003 				    eoff, sizeof(*fh));
1004 				if (fh == NULL) {
1005 					ICMP6STAT_INC(icp6s_tooshort);
1006 					return (-1);
1007 				}
1008 #endif
1009 				/*
1010 				 * Data after a fragment header is meaningless
1011 				 * unless it is the first fragment, but
1012 				 * we'll go to the notify label for path MTU
1013 				 * discovery.
1014 				 */
1015 				if (fh->ip6f_offlg & IP6F_OFF_MASK)
1016 					goto notify;
1017 
1018 				eoff += sizeof(struct ip6_frag);
1019 				nxt = fh->ip6f_nxt;
1020 				break;
1021 			default:
1022 				/*
1023 				 * This case includes ESP and the No Next
1024 				 * Header.  In such cases going to the notify
1025 				 * label does not have any meaning
1026 				 * (i.e. ctlfunc will be NULL), but we go
1027 				 * anyway since we might have to update
1028 				 * path MTU information.
1029 				 */
1030 				goto notify;
1031 			}
1032 		}
1033 	  notify:
1034 #ifndef PULLDOWN_TEST
1035 		icmp6 = (struct icmp6_hdr *)(mtod(m, caddr_t) + off);
1036 #else
1037 		IP6_EXTHDR_GET(icmp6, struct icmp6_hdr *, m, off,
1038 		    sizeof(*icmp6) + sizeof(struct ip6_hdr));
1039 		if (icmp6 == NULL) {
1040 			ICMP6STAT_INC(icp6s_tooshort);
1041 			return (-1);
1042 		}
1043 #endif
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 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 		bzero(&icmp6dst, sizeof(icmp6dst));
1056 		icmp6dst.sin6_len = sizeof(struct sockaddr_in6);
1057 		icmp6dst.sin6_family = AF_INET6;
1058 		if (finaldst == NULL)
1059 			icmp6dst.sin6_addr = eip6->ip6_dst;
1060 		else
1061 			icmp6dst.sin6_addr = *finaldst;
1062 		if (in6_setscope(&icmp6dst.sin6_addr, m->m_pkthdr.rcvif, NULL))
1063 			goto freeit;
1064 		bzero(&icmp6src, sizeof(icmp6src));
1065 		icmp6src.sin6_len = sizeof(struct sockaddr_in6);
1066 		icmp6src.sin6_family = AF_INET6;
1067 		icmp6src.sin6_addr = eip6->ip6_src;
1068 		if (in6_setscope(&icmp6src.sin6_addr, m->m_pkthdr.rcvif, NULL))
1069 			goto freeit;
1070 		icmp6src.sin6_flowinfo =
1071 		    (eip6->ip6_flow & IPV6_FLOWLABEL_MASK);
1072 
1073 		if (finaldst == NULL)
1074 			finaldst = &eip6->ip6_dst;
1075 		ip6cp.ip6c_m = m;
1076 		ip6cp.ip6c_icmp6 = icmp6;
1077 		ip6cp.ip6c_ip6 = (struct ip6_hdr *)(icmp6 + 1);
1078 		ip6cp.ip6c_off = eoff;
1079 		ip6cp.ip6c_finaldst = finaldst;
1080 		ip6cp.ip6c_src = &icmp6src;
1081 		ip6cp.ip6c_nxt = nxt;
1082 
1083 		if (icmp6type == ICMP6_PACKET_TOO_BIG) {
1084 			notifymtu = ntohl(icmp6->icmp6_mtu);
1085 			ip6cp.ip6c_cmdarg = (void *)&notifymtu;
1086 			icmp6_mtudisc_update(&ip6cp, 1);	/*XXX*/
1087 		}
1088 
1089 		ctlfunc = (void (*)(int, struct sockaddr *, void *))
1090 		    (inet6sw[ip6_protox[nxt]].pr_ctlinput);
1091 		if (ctlfunc) {
1092 			(void) (*ctlfunc)(code, (struct sockaddr *)&icmp6dst,
1093 			    &ip6cp);
1094 		}
1095 	}
1096 	*mp = m;
1097 	return (0);
1098 
1099   freeit:
1100 	m_freem(m);
1101 	return (-1);
1102 }
1103 
1104 void
1105 icmp6_mtudisc_update(struct ip6ctlparam *ip6cp, int validated)
1106 {
1107 	struct in6_addr *dst = ip6cp->ip6c_finaldst;
1108 	struct icmp6_hdr *icmp6 = ip6cp->ip6c_icmp6;
1109 	struct mbuf *m = ip6cp->ip6c_m;	/* will be necessary for scope issue */
1110 	u_int mtu = ntohl(icmp6->icmp6_mtu);
1111 	struct in_conninfo inc;
1112 
1113 #if 0
1114 	/*
1115 	 * RFC2460 section 5, last paragraph.
1116 	 * even though minimum link MTU for IPv6 is IPV6_MMTU,
1117 	 * we may see ICMPv6 too big with mtu < IPV6_MMTU
1118 	 * due to packet translator in the middle.
1119 	 * see ip6_output() and ip6_getpmtu() "alwaysfrag" case for
1120 	 * special handling.
1121 	 */
1122 	if (mtu < IPV6_MMTU)
1123 		return;
1124 #endif
1125 
1126 	/*
1127 	 * we reject ICMPv6 too big with abnormally small value.
1128 	 * XXX what is the good definition of "abnormally small"?
1129 	 */
1130 	if (mtu < sizeof(struct ip6_hdr) + sizeof(struct ip6_frag) + 8)
1131 		return;
1132 
1133 	if (!validated)
1134 		return;
1135 
1136 	/*
1137 	 * In case the suggested mtu is less than IPV6_MMTU, we
1138 	 * only need to remember that it was for above mentioned
1139 	 * "alwaysfrag" case.
1140 	 * Try to be as close to the spec as possible.
1141 	 */
1142 	if (mtu < IPV6_MMTU)
1143 		mtu = IPV6_MMTU - 8;
1144 
1145 	bzero(&inc, sizeof(inc));
1146 	inc.inc_fibnum = M_GETFIB(m);
1147 	inc.inc_flags |= INC_ISIPV6;
1148 	inc.inc6_faddr = *dst;
1149 	if (in6_setscope(&inc.inc6_faddr, m->m_pkthdr.rcvif, NULL))
1150 		return;
1151 
1152 	if (mtu < tcp_maxmtu6(&inc, NULL)) {
1153 		tcp_hc_updatemtu(&inc, mtu);
1154 		ICMP6STAT_INC(icp6s_pmtuchg);
1155 	}
1156 }
1157 
1158 /*
1159  * Process a Node Information Query packet, based on
1160  * draft-ietf-ipngwg-icmp-name-lookups-07.
1161  *
1162  * Spec incompatibilities:
1163  * - IPv6 Subject address handling
1164  * - IPv4 Subject address handling support missing
1165  * - Proxy reply (answer even if it's not for me)
1166  * - joins NI group address at in6_ifattach() time only, does not cope
1167  *   with hostname changes by sethostname(3)
1168  */
1169 static struct mbuf *
1170 ni6_input(struct mbuf *m, int off)
1171 {
1172 	struct icmp6_nodeinfo *ni6, *nni6;
1173 	struct mbuf *n = NULL;
1174 	struct prison *pr;
1175 	u_int16_t qtype;
1176 	int subjlen;
1177 	int replylen = sizeof(struct ip6_hdr) + sizeof(struct icmp6_nodeinfo);
1178 	struct ni_reply_fqdn *fqdn;
1179 	int addrs;		/* for NI_QTYPE_NODEADDR */
1180 	struct ifnet *ifp = NULL; /* for NI_QTYPE_NODEADDR */
1181 	struct in6_addr in6_subj; /* subject address */
1182 	struct ip6_hdr *ip6;
1183 	int oldfqdn = 0;	/* if 1, return pascal string (03 draft) */
1184 	char *subj = NULL;
1185 	struct in6_ifaddr *ia6 = NULL;
1186 
1187 	ip6 = mtod(m, struct ip6_hdr *);
1188 #ifndef PULLDOWN_TEST
1189 	ni6 = (struct icmp6_nodeinfo *)(mtod(m, caddr_t) + off);
1190 #else
1191 	IP6_EXTHDR_GET(ni6, struct icmp6_nodeinfo *, m, off, sizeof(*ni6));
1192 	if (ni6 == NULL) {
1193 		/* m is already reclaimed */
1194 		return (NULL);
1195 	}
1196 #endif
1197 
1198 	/*
1199 	 * Validate IPv6 source address.
1200 	 * The default configuration MUST be to refuse answering queries from
1201 	 * global-scope addresses according to RFC4602.
1202 	 * Notes:
1203 	 *  - it's not very clear what "refuse" means; this implementation
1204 	 *    simply drops it.
1205 	 *  - it's not very easy to identify global-scope (unicast) addresses
1206 	 *    since there are many prefixes for them.  It should be safer
1207 	 *    and in practice sufficient to check "all" but loopback and
1208 	 *    link-local (note that site-local unicast was deprecated and
1209 	 *    ULA is defined as global scope-wise)
1210 	 */
1211 	if ((V_icmp6_nodeinfo & ICMP6_NODEINFO_GLOBALOK) == 0 &&
1212 	    !IN6_IS_ADDR_LOOPBACK(&ip6->ip6_src) &&
1213 	    !IN6_IS_ADDR_LINKLOCAL(&ip6->ip6_src))
1214 		goto bad;
1215 
1216 	/*
1217 	 * Validate IPv6 destination address.
1218 	 *
1219 	 * The Responder must discard the Query without further processing
1220 	 * unless it is one of the Responder's unicast or anycast addresses, or
1221 	 * a link-local scope multicast address which the Responder has joined.
1222 	 * [RFC4602, Section 5.]
1223 	 */
1224 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
1225 		if (!IN6_IS_ADDR_MC_LINKLOCAL(&ip6->ip6_dst))
1226 			goto bad;
1227 		/* else it's a link-local multicast, fine */
1228 	} else {		/* unicast or anycast */
1229 		ia6 = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */);
1230 		if (ia6 == NULL)
1231 			goto bad; /* XXX impossible */
1232 
1233 		if ((ia6->ia6_flags & IN6_IFF_TEMPORARY) &&
1234 		    !(V_icmp6_nodeinfo & ICMP6_NODEINFO_TMPADDROK)) {
1235 			ifa_free(&ia6->ia_ifa);
1236 			nd6log((LOG_DEBUG, "ni6_input: ignore node info to "
1237 				"a temporary address in %s:%d",
1238 			       __FILE__, __LINE__));
1239 			goto bad;
1240 		}
1241 		ifa_free(&ia6->ia_ifa);
1242 	}
1243 
1244 	/* validate query Subject field. */
1245 	qtype = ntohs(ni6->ni_qtype);
1246 	subjlen = m->m_pkthdr.len - off - sizeof(struct icmp6_nodeinfo);
1247 	switch (qtype) {
1248 	case NI_QTYPE_NOOP:
1249 	case NI_QTYPE_SUPTYPES:
1250 		/* 07 draft */
1251 		if (ni6->ni_code == ICMP6_NI_SUBJ_FQDN && subjlen == 0)
1252 			break;
1253 		/* FALLTHROUGH */
1254 	case NI_QTYPE_FQDN:
1255 	case NI_QTYPE_NODEADDR:
1256 	case NI_QTYPE_IPV4ADDR:
1257 		switch (ni6->ni_code) {
1258 		case ICMP6_NI_SUBJ_IPV6:
1259 #if ICMP6_NI_SUBJ_IPV6 != 0
1260 		case 0:
1261 #endif
1262 			/*
1263 			 * backward compatibility - try to accept 03 draft
1264 			 * format, where no Subject is present.
1265 			 */
1266 			if (qtype == NI_QTYPE_FQDN && ni6->ni_code == 0 &&
1267 			    subjlen == 0) {
1268 				oldfqdn++;
1269 				break;
1270 			}
1271 #if ICMP6_NI_SUBJ_IPV6 != 0
1272 			if (ni6->ni_code != ICMP6_NI_SUBJ_IPV6)
1273 				goto bad;
1274 #endif
1275 
1276 			if (subjlen != sizeof(struct in6_addr))
1277 				goto bad;
1278 
1279 			/*
1280 			 * Validate Subject address.
1281 			 *
1282 			 * Not sure what exactly "address belongs to the node"
1283 			 * means in the spec, is it just unicast, or what?
1284 			 *
1285 			 * At this moment we consider Subject address as
1286 			 * "belong to the node" if the Subject address equals
1287 			 * to the IPv6 destination address; validation for
1288 			 * IPv6 destination address should have done enough
1289 			 * check for us.
1290 			 *
1291 			 * We do not do proxy at this moment.
1292 			 */
1293 			/* m_pulldown instead of copy? */
1294 			m_copydata(m, off + sizeof(struct icmp6_nodeinfo),
1295 			    subjlen, (caddr_t)&in6_subj);
1296 			if (in6_setscope(&in6_subj, m->m_pkthdr.rcvif, NULL))
1297 				goto bad;
1298 
1299 			subj = (char *)&in6_subj;
1300 			if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &in6_subj))
1301 				break;
1302 
1303 			/*
1304 			 * XXX if we are to allow other cases, we should really
1305 			 * be careful about scope here.
1306 			 * basically, we should disallow queries toward IPv6
1307 			 * destination X with subject Y,
1308 			 * if scope(X) > scope(Y).
1309 			 * if we allow scope(X) > scope(Y), it will result in
1310 			 * information leakage across scope boundary.
1311 			 */
1312 			goto bad;
1313 
1314 		case ICMP6_NI_SUBJ_FQDN:
1315 			/*
1316 			 * Validate Subject name with gethostname(3).
1317 			 *
1318 			 * The behavior may need some debate, since:
1319 			 * - we are not sure if the node has FQDN as
1320 			 *   hostname (returned by gethostname(3)).
1321 			 * - the code does wildcard match for truncated names.
1322 			 *   however, we are not sure if we want to perform
1323 			 *   wildcard match, if gethostname(3) side has
1324 			 *   truncated hostname.
1325 			 */
1326 			pr = curthread->td_ucred->cr_prison;
1327 			mtx_lock(&pr->pr_mtx);
1328 			n = ni6_nametodns(pr->pr_hostname,
1329 			    strlen(pr->pr_hostname), 0);
1330 			mtx_unlock(&pr->pr_mtx);
1331 			if (!n || n->m_next || n->m_len == 0)
1332 				goto bad;
1333 			IP6_EXTHDR_GET(subj, char *, m,
1334 			    off + sizeof(struct icmp6_nodeinfo), subjlen);
1335 			if (subj == NULL)
1336 				goto bad;
1337 			if (!ni6_dnsmatch(subj, subjlen, mtod(n, const char *),
1338 			    n->m_len)) {
1339 				goto bad;
1340 			}
1341 			m_freem(n);
1342 			n = NULL;
1343 			break;
1344 
1345 		case ICMP6_NI_SUBJ_IPV4:	/* XXX: to be implemented? */
1346 		default:
1347 			goto bad;
1348 		}
1349 		break;
1350 	}
1351 
1352 	/* refuse based on configuration.  XXX ICMP6_NI_REFUSED? */
1353 	switch (qtype) {
1354 	case NI_QTYPE_FQDN:
1355 		if ((V_icmp6_nodeinfo & ICMP6_NODEINFO_FQDNOK) == 0)
1356 			goto bad;
1357 		break;
1358 	case NI_QTYPE_NODEADDR:
1359 	case NI_QTYPE_IPV4ADDR:
1360 		if ((V_icmp6_nodeinfo & ICMP6_NODEINFO_NODEADDROK) == 0)
1361 			goto bad;
1362 		break;
1363 	}
1364 
1365 	/* guess reply length */
1366 	switch (qtype) {
1367 	case NI_QTYPE_NOOP:
1368 		break;		/* no reply data */
1369 	case NI_QTYPE_SUPTYPES:
1370 		replylen += sizeof(u_int32_t);
1371 		break;
1372 	case NI_QTYPE_FQDN:
1373 		/* XXX will append an mbuf */
1374 		replylen += offsetof(struct ni_reply_fqdn, ni_fqdn_namelen);
1375 		break;
1376 	case NI_QTYPE_NODEADDR:
1377 		addrs = ni6_addrs(ni6, m, &ifp, (struct in6_addr *)subj);
1378 		if ((replylen += addrs * (sizeof(struct in6_addr) +
1379 		    sizeof(u_int32_t))) > MCLBYTES)
1380 			replylen = MCLBYTES; /* XXX: will truncate pkt later */
1381 		break;
1382 	case NI_QTYPE_IPV4ADDR:
1383 		/* unsupported - should respond with unknown Qtype? */
1384 		break;
1385 	default:
1386 		/*
1387 		 * XXX: We must return a reply with the ICMP6 code
1388 		 * `unknown Qtype' in this case.  However we regard the case
1389 		 * as an FQDN query for backward compatibility.
1390 		 * Older versions set a random value to this field,
1391 		 * so it rarely varies in the defined qtypes.
1392 		 * But the mechanism is not reliable...
1393 		 * maybe we should obsolete older versions.
1394 		 */
1395 		qtype = NI_QTYPE_FQDN;
1396 		/* XXX will append an mbuf */
1397 		replylen += offsetof(struct ni_reply_fqdn, ni_fqdn_namelen);
1398 		oldfqdn++;
1399 		break;
1400 	}
1401 
1402 	/* Allocate an mbuf to reply. */
1403 	if (replylen > MCLBYTES) {
1404 		/*
1405 		 * XXX: should we try to allocate more? But MCLBYTES
1406 		 * is probably much larger than IPV6_MMTU...
1407 		 */
1408 		goto bad;
1409 	}
1410 	if (replylen > MHLEN)
1411 		n = m_getcl(M_NOWAIT, m->m_type, M_PKTHDR);
1412 	else
1413 		n = m_gethdr(M_NOWAIT, m->m_type);
1414 	if (n == NULL) {
1415 		m_freem(m);
1416 		return (NULL);
1417 	}
1418 	m_move_pkthdr(n, m); /* just for recvif and FIB */
1419 	n->m_pkthdr.len = n->m_len = replylen;
1420 
1421 	/* copy mbuf header and IPv6 + Node Information base headers */
1422 	bcopy(mtod(m, caddr_t), mtod(n, caddr_t), sizeof(struct ip6_hdr));
1423 	nni6 = (struct icmp6_nodeinfo *)(mtod(n, struct ip6_hdr *) + 1);
1424 	bcopy((caddr_t)ni6, (caddr_t)nni6, sizeof(struct icmp6_nodeinfo));
1425 
1426 	/* qtype dependent procedure */
1427 	switch (qtype) {
1428 	case NI_QTYPE_NOOP:
1429 		nni6->ni_code = ICMP6_NI_SUCCESS;
1430 		nni6->ni_flags = 0;
1431 		break;
1432 	case NI_QTYPE_SUPTYPES:
1433 	{
1434 		u_int32_t v;
1435 		nni6->ni_code = ICMP6_NI_SUCCESS;
1436 		nni6->ni_flags = htons(0x0000);	/* raw bitmap */
1437 		/* supports NOOP, SUPTYPES, FQDN, and NODEADDR */
1438 		v = (u_int32_t)htonl(0x0000000f);
1439 		bcopy(&v, nni6 + 1, sizeof(u_int32_t));
1440 		break;
1441 	}
1442 	case NI_QTYPE_FQDN:
1443 		nni6->ni_code = ICMP6_NI_SUCCESS;
1444 		fqdn = (struct ni_reply_fqdn *)(mtod(n, caddr_t) +
1445 		    sizeof(struct ip6_hdr) + sizeof(struct icmp6_nodeinfo));
1446 		nni6->ni_flags = 0; /* XXX: meaningless TTL */
1447 		fqdn->ni_fqdn_ttl = 0;	/* ditto. */
1448 		/*
1449 		 * XXX do we really have FQDN in hostname?
1450 		 */
1451 		pr = curthread->td_ucred->cr_prison;
1452 		mtx_lock(&pr->pr_mtx);
1453 		n->m_next = ni6_nametodns(pr->pr_hostname,
1454 		    strlen(pr->pr_hostname), oldfqdn);
1455 		mtx_unlock(&pr->pr_mtx);
1456 		if (n->m_next == NULL)
1457 			goto bad;
1458 		/* XXX we assume that n->m_next is not a chain */
1459 		if (n->m_next->m_next != NULL)
1460 			goto bad;
1461 		n->m_pkthdr.len += n->m_next->m_len;
1462 		break;
1463 	case NI_QTYPE_NODEADDR:
1464 	{
1465 		int lenlim, copied;
1466 
1467 		nni6->ni_code = ICMP6_NI_SUCCESS;
1468 		n->m_pkthdr.len = n->m_len =
1469 		    sizeof(struct ip6_hdr) + sizeof(struct icmp6_nodeinfo);
1470 		lenlim = M_TRAILINGSPACE(n);
1471 		copied = ni6_store_addrs(ni6, nni6, ifp, lenlim);
1472 		/* XXX: reset mbuf length */
1473 		n->m_pkthdr.len = n->m_len = sizeof(struct ip6_hdr) +
1474 		    sizeof(struct icmp6_nodeinfo) + copied;
1475 		break;
1476 	}
1477 	default:
1478 		break;		/* XXX impossible! */
1479 	}
1480 
1481 	nni6->ni_type = ICMP6_NI_REPLY;
1482 	m_freem(m);
1483 	return (n);
1484 
1485   bad:
1486 	m_freem(m);
1487 	if (n)
1488 		m_freem(n);
1489 	return (NULL);
1490 }
1491 
1492 /*
1493  * make a mbuf with DNS-encoded string.  no compression support.
1494  *
1495  * XXX names with less than 2 dots (like "foo" or "foo.section") will be
1496  * treated as truncated name (two \0 at the end).  this is a wild guess.
1497  *
1498  * old - return pascal string if non-zero
1499  */
1500 static struct mbuf *
1501 ni6_nametodns(const char *name, int namelen, int old)
1502 {
1503 	struct mbuf *m;
1504 	char *cp, *ep;
1505 	const char *p, *q;
1506 	int i, len, nterm;
1507 
1508 	if (old)
1509 		len = namelen + 1;
1510 	else
1511 		len = MCLBYTES;
1512 
1513 	/* Because MAXHOSTNAMELEN is usually 256, we use cluster mbuf. */
1514 	if (len > MLEN)
1515 		m = m_getcl(M_NOWAIT, MT_DATA, 0);
1516 	else
1517 		m = m_get(M_NOWAIT, MT_DATA);
1518 	if (m == NULL)
1519 		goto fail;
1520 
1521 	if (old) {
1522 		m->m_len = len;
1523 		*mtod(m, char *) = namelen;
1524 		bcopy(name, mtod(m, char *) + 1, namelen);
1525 		return m;
1526 	} else {
1527 		m->m_len = 0;
1528 		cp = mtod(m, char *);
1529 		ep = mtod(m, char *) + M_TRAILINGSPACE(m);
1530 
1531 		/* if not certain about my name, return empty buffer */
1532 		if (namelen == 0)
1533 			return m;
1534 
1535 		/*
1536 		 * guess if it looks like shortened hostname, or FQDN.
1537 		 * shortened hostname needs two trailing "\0".
1538 		 */
1539 		i = 0;
1540 		for (p = name; p < name + namelen; p++) {
1541 			if (*p && *p == '.')
1542 				i++;
1543 		}
1544 		if (i < 2)
1545 			nterm = 2;
1546 		else
1547 			nterm = 1;
1548 
1549 		p = name;
1550 		while (cp < ep && p < name + namelen) {
1551 			i = 0;
1552 			for (q = p; q < name + namelen && *q && *q != '.'; q++)
1553 				i++;
1554 			/* result does not fit into mbuf */
1555 			if (cp + i + 1 >= ep)
1556 				goto fail;
1557 			/*
1558 			 * DNS label length restriction, RFC1035 page 8.
1559 			 * "i == 0" case is included here to avoid returning
1560 			 * 0-length label on "foo..bar".
1561 			 */
1562 			if (i <= 0 || i >= 64)
1563 				goto fail;
1564 			*cp++ = i;
1565 			bcopy(p, cp, i);
1566 			cp += i;
1567 			p = q;
1568 			if (p < name + namelen && *p == '.')
1569 				p++;
1570 		}
1571 		/* termination */
1572 		if (cp + nterm >= ep)
1573 			goto fail;
1574 		while (nterm-- > 0)
1575 			*cp++ = '\0';
1576 		m->m_len = cp - mtod(m, char *);
1577 		return m;
1578 	}
1579 
1580 	panic("should not reach here");
1581 	/* NOTREACHED */
1582 
1583  fail:
1584 	if (m)
1585 		m_freem(m);
1586 	return NULL;
1587 }
1588 
1589 /*
1590  * check if two DNS-encoded string matches.  takes care of truncated
1591  * form (with \0\0 at the end).  no compression support.
1592  * XXX upper/lowercase match (see RFC2065)
1593  */
1594 static int
1595 ni6_dnsmatch(const char *a, int alen, const char *b, int blen)
1596 {
1597 	const char *a0, *b0;
1598 	int l;
1599 
1600 	/* simplest case - need validation? */
1601 	if (alen == blen && bcmp(a, b, alen) == 0)
1602 		return 1;
1603 
1604 	a0 = a;
1605 	b0 = b;
1606 
1607 	/* termination is mandatory */
1608 	if (alen < 2 || blen < 2)
1609 		return 0;
1610 	if (a0[alen - 1] != '\0' || b0[blen - 1] != '\0')
1611 		return 0;
1612 	alen--;
1613 	blen--;
1614 
1615 	while (a - a0 < alen && b - b0 < blen) {
1616 		if (a - a0 + 1 > alen || b - b0 + 1 > blen)
1617 			return 0;
1618 
1619 		if ((signed char)a[0] < 0 || (signed char)b[0] < 0)
1620 			return 0;
1621 		/* we don't support compression yet */
1622 		if (a[0] >= 64 || b[0] >= 64)
1623 			return 0;
1624 
1625 		/* truncated case */
1626 		if (a[0] == 0 && a - a0 == alen - 1)
1627 			return 1;
1628 		if (b[0] == 0 && b - b0 == blen - 1)
1629 			return 1;
1630 		if (a[0] == 0 || b[0] == 0)
1631 			return 0;
1632 
1633 		if (a[0] != b[0])
1634 			return 0;
1635 		l = a[0];
1636 		if (a - a0 + 1 + l > alen || b - b0 + 1 + l > blen)
1637 			return 0;
1638 		if (bcmp(a + 1, b + 1, l) != 0)
1639 			return 0;
1640 
1641 		a += 1 + l;
1642 		b += 1 + l;
1643 	}
1644 
1645 	if (a - a0 == alen && b - b0 == blen)
1646 		return 1;
1647 	else
1648 		return 0;
1649 }
1650 
1651 /*
1652  * calculate the number of addresses to be returned in the node info reply.
1653  */
1654 static int
1655 ni6_addrs(struct icmp6_nodeinfo *ni6, struct mbuf *m, struct ifnet **ifpp,
1656     struct in6_addr *subj)
1657 {
1658 	struct ifnet *ifp;
1659 	struct in6_ifaddr *ifa6;
1660 	struct ifaddr *ifa;
1661 	int addrs = 0, addrsofif, iffound = 0;
1662 	int niflags = ni6->ni_flags;
1663 
1664 	if ((niflags & NI_NODEADDR_FLAG_ALL) == 0) {
1665 		switch (ni6->ni_code) {
1666 		case ICMP6_NI_SUBJ_IPV6:
1667 			if (subj == NULL) /* must be impossible... */
1668 				return (0);
1669 			break;
1670 		default:
1671 			/*
1672 			 * XXX: we only support IPv6 subject address for
1673 			 * this Qtype.
1674 			 */
1675 			return (0);
1676 		}
1677 	}
1678 
1679 	IFNET_RLOCK_NOSLEEP();
1680 	CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link) {
1681 		addrsofif = 0;
1682 		IF_ADDR_RLOCK(ifp);
1683 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1684 			if (ifa->ifa_addr->sa_family != AF_INET6)
1685 				continue;
1686 			ifa6 = (struct in6_ifaddr *)ifa;
1687 
1688 			if ((niflags & NI_NODEADDR_FLAG_ALL) == 0 &&
1689 			    IN6_ARE_ADDR_EQUAL(subj, &ifa6->ia_addr.sin6_addr))
1690 				iffound = 1;
1691 
1692 			/*
1693 			 * IPv4-mapped addresses can only be returned by a
1694 			 * Node Information proxy, since they represent
1695 			 * addresses of IPv4-only nodes, which perforce do
1696 			 * not implement this protocol.
1697 			 * [icmp-name-lookups-07, Section 5.4]
1698 			 * So we don't support NI_NODEADDR_FLAG_COMPAT in
1699 			 * this function at this moment.
1700 			 */
1701 
1702 			/* What do we have to do about ::1? */
1703 			switch (in6_addrscope(&ifa6->ia_addr.sin6_addr)) {
1704 			case IPV6_ADDR_SCOPE_LINKLOCAL:
1705 				if ((niflags & NI_NODEADDR_FLAG_LINKLOCAL) == 0)
1706 					continue;
1707 				break;
1708 			case IPV6_ADDR_SCOPE_SITELOCAL:
1709 				if ((niflags & NI_NODEADDR_FLAG_SITELOCAL) == 0)
1710 					continue;
1711 				break;
1712 			case IPV6_ADDR_SCOPE_GLOBAL:
1713 				if ((niflags & NI_NODEADDR_FLAG_GLOBAL) == 0)
1714 					continue;
1715 				break;
1716 			default:
1717 				continue;
1718 			}
1719 
1720 			/*
1721 			 * check if anycast is okay.
1722 			 * XXX: just experimental.  not in the spec.
1723 			 */
1724 			if ((ifa6->ia6_flags & IN6_IFF_ANYCAST) != 0 &&
1725 			    (niflags & NI_NODEADDR_FLAG_ANYCAST) == 0)
1726 				continue; /* we need only unicast addresses */
1727 			if ((ifa6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
1728 			    (V_icmp6_nodeinfo & ICMP6_NODEINFO_TMPADDROK) == 0) {
1729 				continue;
1730 			}
1731 			addrsofif++; /* count the address */
1732 		}
1733 		IF_ADDR_RUNLOCK(ifp);
1734 		if (iffound) {
1735 			*ifpp = ifp;
1736 			IFNET_RUNLOCK_NOSLEEP();
1737 			return (addrsofif);
1738 		}
1739 
1740 		addrs += addrsofif;
1741 	}
1742 	IFNET_RUNLOCK_NOSLEEP();
1743 
1744 	return (addrs);
1745 }
1746 
1747 static int
1748 ni6_store_addrs(struct icmp6_nodeinfo *ni6, struct icmp6_nodeinfo *nni6,
1749     struct ifnet *ifp0, int resid)
1750 {
1751 	struct ifnet *ifp;
1752 	struct in6_ifaddr *ifa6;
1753 	struct ifaddr *ifa;
1754 	struct ifnet *ifp_dep = NULL;
1755 	int copied = 0, allow_deprecated = 0;
1756 	u_char *cp = (u_char *)(nni6 + 1);
1757 	int niflags = ni6->ni_flags;
1758 	u_int32_t ltime;
1759 
1760 	if (ifp0 == NULL && !(niflags & NI_NODEADDR_FLAG_ALL))
1761 		return (0);	/* needless to copy */
1762 
1763 	IFNET_RLOCK_NOSLEEP();
1764 	ifp = ifp0 ? ifp0 : CK_STAILQ_FIRST(&V_ifnet);
1765   again:
1766 
1767 	for (; ifp; ifp = CK_STAILQ_NEXT(ifp, if_link)) {
1768 		IF_ADDR_RLOCK(ifp);
1769 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1770 			if (ifa->ifa_addr->sa_family != AF_INET6)
1771 				continue;
1772 			ifa6 = (struct in6_ifaddr *)ifa;
1773 
1774 			if ((ifa6->ia6_flags & IN6_IFF_DEPRECATED) != 0 &&
1775 			    allow_deprecated == 0) {
1776 				/*
1777 				 * prefererred address should be put before
1778 				 * deprecated addresses.
1779 				 */
1780 
1781 				/* record the interface for later search */
1782 				if (ifp_dep == NULL)
1783 					ifp_dep = ifp;
1784 
1785 				continue;
1786 			} else if ((ifa6->ia6_flags & IN6_IFF_DEPRECATED) == 0 &&
1787 			    allow_deprecated != 0)
1788 				continue; /* we now collect deprecated addrs */
1789 
1790 			/* What do we have to do about ::1? */
1791 			switch (in6_addrscope(&ifa6->ia_addr.sin6_addr)) {
1792 			case IPV6_ADDR_SCOPE_LINKLOCAL:
1793 				if ((niflags & NI_NODEADDR_FLAG_LINKLOCAL) == 0)
1794 					continue;
1795 				break;
1796 			case IPV6_ADDR_SCOPE_SITELOCAL:
1797 				if ((niflags & NI_NODEADDR_FLAG_SITELOCAL) == 0)
1798 					continue;
1799 				break;
1800 			case IPV6_ADDR_SCOPE_GLOBAL:
1801 				if ((niflags & NI_NODEADDR_FLAG_GLOBAL) == 0)
1802 					continue;
1803 				break;
1804 			default:
1805 				continue;
1806 			}
1807 
1808 			/*
1809 			 * check if anycast is okay.
1810 			 * XXX: just experimental.  not in the spec.
1811 			 */
1812 			if ((ifa6->ia6_flags & IN6_IFF_ANYCAST) != 0 &&
1813 			    (niflags & NI_NODEADDR_FLAG_ANYCAST) == 0)
1814 				continue;
1815 			if ((ifa6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
1816 			    (V_icmp6_nodeinfo & ICMP6_NODEINFO_TMPADDROK) == 0) {
1817 				continue;
1818 			}
1819 
1820 			/* now we can copy the address */
1821 			if (resid < sizeof(struct in6_addr) +
1822 			    sizeof(u_int32_t)) {
1823 				IF_ADDR_RUNLOCK(ifp);
1824 				/*
1825 				 * We give up much more copy.
1826 				 * Set the truncate flag and return.
1827 				 */
1828 				nni6->ni_flags |= NI_NODEADDR_FLAG_TRUNCATE;
1829 				IFNET_RUNLOCK_NOSLEEP();
1830 				return (copied);
1831 			}
1832 
1833 			/*
1834 			 * Set the TTL of the address.
1835 			 * The TTL value should be one of the following
1836 			 * according to the specification:
1837 			 *
1838 			 * 1. The remaining lifetime of a DHCP lease on the
1839 			 *    address, or
1840 			 * 2. The remaining Valid Lifetime of a prefix from
1841 			 *    which the address was derived through Stateless
1842 			 *    Autoconfiguration.
1843 			 *
1844 			 * Note that we currently do not support stateful
1845 			 * address configuration by DHCPv6, so the former
1846 			 * case can't happen.
1847 			 */
1848 			if (ifa6->ia6_lifetime.ia6t_expire == 0)
1849 				ltime = ND6_INFINITE_LIFETIME;
1850 			else {
1851 				if (ifa6->ia6_lifetime.ia6t_expire >
1852 				    time_uptime)
1853 					ltime = htonl(ifa6->ia6_lifetime.ia6t_expire - time_uptime);
1854 				else
1855 					ltime = 0;
1856 			}
1857 
1858 			bcopy(&ltime, cp, sizeof(u_int32_t));
1859 			cp += sizeof(u_int32_t);
1860 
1861 			/* copy the address itself */
1862 			bcopy(&ifa6->ia_addr.sin6_addr, cp,
1863 			    sizeof(struct in6_addr));
1864 			in6_clearscope((struct in6_addr *)cp); /* XXX */
1865 			cp += sizeof(struct in6_addr);
1866 
1867 			resid -= (sizeof(struct in6_addr) + sizeof(u_int32_t));
1868 			copied += (sizeof(struct in6_addr) + sizeof(u_int32_t));
1869 		}
1870 		IF_ADDR_RUNLOCK(ifp);
1871 		if (ifp0)	/* we need search only on the specified IF */
1872 			break;
1873 	}
1874 
1875 	if (allow_deprecated == 0 && ifp_dep != NULL) {
1876 		ifp = ifp_dep;
1877 		allow_deprecated = 1;
1878 
1879 		goto again;
1880 	}
1881 
1882 	IFNET_RUNLOCK_NOSLEEP();
1883 
1884 	return (copied);
1885 }
1886 
1887 /*
1888  * XXX almost dup'ed code with rip6_input.
1889  */
1890 static int
1891 icmp6_rip6_input(struct mbuf **mp, int off)
1892 {
1893 	struct mbuf *m = *mp;
1894 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
1895 	struct inpcb *in6p;
1896 	struct inpcb *last = NULL;
1897 	struct sockaddr_in6 fromsa;
1898 	struct icmp6_hdr *icmp6;
1899 	struct epoch_tracker et;
1900 	struct mbuf *opts = NULL;
1901 
1902 #ifndef PULLDOWN_TEST
1903 	/* this is assumed to be safe. */
1904 	icmp6 = (struct icmp6_hdr *)((caddr_t)ip6 + off);
1905 #else
1906 	IP6_EXTHDR_GET(icmp6, struct icmp6_hdr *, m, off, sizeof(*icmp6));
1907 	if (icmp6 == NULL) {
1908 		/* m is already reclaimed */
1909 		return (IPPROTO_DONE);
1910 	}
1911 #endif
1912 
1913 	/*
1914 	 * XXX: the address may have embedded scope zone ID, which should be
1915 	 * hidden from applications.
1916 	 */
1917 	bzero(&fromsa, sizeof(fromsa));
1918 	fromsa.sin6_family = AF_INET6;
1919 	fromsa.sin6_len = sizeof(struct sockaddr_in6);
1920 	fromsa.sin6_addr = ip6->ip6_src;
1921 	if (sa6_recoverscope(&fromsa)) {
1922 		m_freem(m);
1923 		return (IPPROTO_DONE);
1924 	}
1925 
1926 	INP_INFO_RLOCK_ET(&V_ripcbinfo, et);
1927 	CK_LIST_FOREACH(in6p, &V_ripcb, inp_list) {
1928 		if ((in6p->inp_vflag & INP_IPV6) == 0)
1929 			continue;
1930 		if (in6p->inp_ip_p != IPPROTO_ICMPV6)
1931 			continue;
1932 		if (!IN6_IS_ADDR_UNSPECIFIED(&in6p->in6p_laddr) &&
1933 		   !IN6_ARE_ADDR_EQUAL(&in6p->in6p_laddr, &ip6->ip6_dst))
1934 			continue;
1935 		if (!IN6_IS_ADDR_UNSPECIFIED(&in6p->in6p_faddr) &&
1936 		   !IN6_ARE_ADDR_EQUAL(&in6p->in6p_faddr, &ip6->ip6_src))
1937 			continue;
1938 		INP_RLOCK(in6p);
1939 		if (ICMP6_FILTER_WILLBLOCK(icmp6->icmp6_type,
1940 		    in6p->in6p_icmp6filt)) {
1941 			INP_RUNLOCK(in6p);
1942 			continue;
1943 		}
1944 		if (last != NULL) {
1945 			struct	mbuf *n = NULL;
1946 
1947 			/*
1948 			 * Recent network drivers tend to allocate a single
1949 			 * mbuf cluster, rather than to make a couple of
1950 			 * mbufs without clusters.  Also, since the IPv6 code
1951 			 * path tries to avoid m_pullup(), it is highly
1952 			 * probable that we still have an mbuf cluster here
1953 			 * even though the necessary length can be stored in an
1954 			 * mbuf's internal buffer.
1955 			 * Meanwhile, the default size of the receive socket
1956 			 * buffer for raw sockets is not so large.  This means
1957 			 * the possibility of packet loss is relatively higher
1958 			 * than before.  To avoid this scenario, we copy the
1959 			 * received data to a separate mbuf that does not use
1960 			 * a cluster, if possible.
1961 			 * XXX: it is better to copy the data after stripping
1962 			 * intermediate headers.
1963 			 */
1964 			if ((m->m_flags & M_EXT) && m->m_next == NULL &&
1965 			    m->m_len <= MHLEN) {
1966 				n = m_get(M_NOWAIT, m->m_type);
1967 				if (n != NULL) {
1968 					if (m_dup_pkthdr(n, m, M_NOWAIT)) {
1969 						bcopy(m->m_data, n->m_data,
1970 						      m->m_len);
1971 						n->m_len = m->m_len;
1972 					} else {
1973 						m_free(n);
1974 						n = NULL;
1975 					}
1976 				}
1977 			}
1978 			if (n != NULL ||
1979 			    (n = m_copym(m, 0, M_COPYALL, M_NOWAIT)) != NULL) {
1980 				if (last->inp_flags & INP_CONTROLOPTS)
1981 					ip6_savecontrol(last, n, &opts);
1982 				/* strip intermediate headers */
1983 				m_adj(n, off);
1984 				SOCKBUF_LOCK(&last->inp_socket->so_rcv);
1985 				if (sbappendaddr_locked(
1986 				    &last->inp_socket->so_rcv,
1987 				    (struct sockaddr *)&fromsa, n, opts)
1988 				    == 0) {
1989 					/* should notify about lost packet */
1990 					m_freem(n);
1991 					if (opts) {
1992 						m_freem(opts);
1993 					}
1994 					SOCKBUF_UNLOCK(
1995 					    &last->inp_socket->so_rcv);
1996 				} else
1997 					sorwakeup_locked(last->inp_socket);
1998 				opts = NULL;
1999 			}
2000 			INP_RUNLOCK(last);
2001 		}
2002 		last = in6p;
2003 	}
2004 	INP_INFO_RUNLOCK_ET(&V_ripcbinfo, et);
2005 	if (last != NULL) {
2006 		if (last->inp_flags & INP_CONTROLOPTS)
2007 			ip6_savecontrol(last, m, &opts);
2008 		/* strip intermediate headers */
2009 		m_adj(m, off);
2010 
2011 		/* avoid using mbuf clusters if possible (see above) */
2012 		if ((m->m_flags & M_EXT) && m->m_next == NULL &&
2013 		    m->m_len <= MHLEN) {
2014 			struct mbuf *n;
2015 
2016 			n = m_get(M_NOWAIT, m->m_type);
2017 			if (n != NULL) {
2018 				if (m_dup_pkthdr(n, m, M_NOWAIT)) {
2019 					bcopy(m->m_data, n->m_data, m->m_len);
2020 					n->m_len = m->m_len;
2021 
2022 					m_freem(m);
2023 					m = n;
2024 				} else {
2025 					m_freem(n);
2026 					n = NULL;
2027 				}
2028 			}
2029 		}
2030 		SOCKBUF_LOCK(&last->inp_socket->so_rcv);
2031 		if (sbappendaddr_locked(&last->inp_socket->so_rcv,
2032 		    (struct sockaddr *)&fromsa, m, opts) == 0) {
2033 			m_freem(m);
2034 			if (opts)
2035 				m_freem(opts);
2036 			SOCKBUF_UNLOCK(&last->inp_socket->so_rcv);
2037 		} else
2038 			sorwakeup_locked(last->inp_socket);
2039 		INP_RUNLOCK(last);
2040 	} else {
2041 		m_freem(m);
2042 		IP6STAT_DEC(ip6s_delivered);
2043 	}
2044 	return IPPROTO_DONE;
2045 }
2046 
2047 /*
2048  * Reflect the ip6 packet back to the source.
2049  * OFF points to the icmp6 header, counted from the top of the mbuf.
2050  */
2051 void
2052 icmp6_reflect(struct mbuf *m, size_t off)
2053 {
2054 	struct in6_addr src6, *srcp;
2055 	struct ip6_hdr *ip6;
2056 	struct icmp6_hdr *icmp6;
2057 	struct in6_ifaddr *ia = NULL;
2058 	struct ifnet *outif = NULL;
2059 	int plen;
2060 	int type, code, hlim;
2061 
2062 	/* too short to reflect */
2063 	if (off < sizeof(struct ip6_hdr)) {
2064 		nd6log((LOG_DEBUG,
2065 		    "sanity fail: off=%lx, sizeof(ip6)=%lx in %s:%d\n",
2066 		    (u_long)off, (u_long)sizeof(struct ip6_hdr),
2067 		    __FILE__, __LINE__));
2068 		goto bad;
2069 	}
2070 
2071 	/*
2072 	 * If there are extra headers between IPv6 and ICMPv6, strip
2073 	 * off that header first.
2074 	 */
2075 #ifdef DIAGNOSTIC
2076 	if (sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr) > MHLEN)
2077 		panic("assumption failed in icmp6_reflect");
2078 #endif
2079 	if (off > sizeof(struct ip6_hdr)) {
2080 		size_t l;
2081 		struct ip6_hdr nip6;
2082 
2083 		l = off - sizeof(struct ip6_hdr);
2084 		m_copydata(m, 0, sizeof(nip6), (caddr_t)&nip6);
2085 		m_adj(m, l);
2086 		l = sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr);
2087 		if (m->m_len < l) {
2088 			if ((m = m_pullup(m, l)) == NULL)
2089 				return;
2090 		}
2091 		bcopy((caddr_t)&nip6, mtod(m, caddr_t), sizeof(nip6));
2092 	} else /* off == sizeof(struct ip6_hdr) */ {
2093 		size_t l;
2094 		l = sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr);
2095 		if (m->m_len < l) {
2096 			if ((m = m_pullup(m, l)) == NULL)
2097 				return;
2098 		}
2099 	}
2100 	plen = m->m_pkthdr.len - sizeof(struct ip6_hdr);
2101 	ip6 = mtod(m, struct ip6_hdr *);
2102 	ip6->ip6_nxt = IPPROTO_ICMPV6;
2103 	icmp6 = (struct icmp6_hdr *)(ip6 + 1);
2104 	type = icmp6->icmp6_type; /* keep type for statistics */
2105 	code = icmp6->icmp6_code; /* ditto. */
2106 	hlim = 0;
2107 	srcp = NULL;
2108 
2109 	/*
2110 	 * If the incoming packet was addressed directly to us (i.e. unicast),
2111 	 * use dst as the src for the reply.
2112 	 * The IN6_IFF_NOTREADY case should be VERY rare, but is possible
2113 	 * (for example) when we encounter an error while forwarding procedure
2114 	 * destined to a duplicated address of ours.
2115 	 */
2116 	if (!IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
2117 		ia = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */);
2118 		if (ia != NULL && !(ia->ia6_flags &
2119 		    (IN6_IFF_ANYCAST|IN6_IFF_NOTREADY))) {
2120 			src6 = ia->ia_addr.sin6_addr;
2121 			srcp = &src6;
2122 
2123 			if (m->m_pkthdr.rcvif != NULL) {
2124 				/* XXX: This may not be the outgoing interface */
2125 				hlim = ND_IFINFO(m->m_pkthdr.rcvif)->chlim;
2126 			} else
2127 				hlim = V_ip6_defhlim;
2128 		}
2129 		if (ia != NULL)
2130 			ifa_free(&ia->ia_ifa);
2131 	}
2132 
2133 	if (srcp == NULL) {
2134 		int error;
2135 		struct in6_addr dst6;
2136 		uint32_t scopeid;
2137 
2138 		/*
2139 		 * This case matches to multicasts, our anycast, or unicasts
2140 		 * that we do not own.  Select a source address based on the
2141 		 * source address of the erroneous packet.
2142 		 */
2143 		in6_splitscope(&ip6->ip6_src, &dst6, &scopeid);
2144 		error = in6_selectsrc_addr(M_GETFIB(m), &dst6,
2145 		    scopeid, NULL, &src6, &hlim);
2146 
2147 		if (error) {
2148 			char ip6buf[INET6_ADDRSTRLEN];
2149 			nd6log((LOG_DEBUG,
2150 			    "icmp6_reflect: source can't be determined: "
2151 			    "dst=%s, error=%d\n",
2152 			    ip6_sprintf(ip6buf, &ip6->ip6_dst), error));
2153 			goto bad;
2154 		}
2155 		srcp = &src6;
2156 	}
2157 	/*
2158 	 * ip6_input() drops a packet if its src is multicast.
2159 	 * So, the src is never multicast.
2160 	 */
2161 	ip6->ip6_dst = ip6->ip6_src;
2162 	ip6->ip6_src = *srcp;
2163 	ip6->ip6_flow = 0;
2164 	ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
2165 	ip6->ip6_vfc |= IPV6_VERSION;
2166 	ip6->ip6_nxt = IPPROTO_ICMPV6;
2167 	ip6->ip6_hlim = hlim;
2168 
2169 	icmp6->icmp6_cksum = 0;
2170 	icmp6->icmp6_cksum = in6_cksum(m, IPPROTO_ICMPV6,
2171 	    sizeof(struct ip6_hdr), plen);
2172 
2173 	/*
2174 	 * XXX option handling
2175 	 */
2176 
2177 	m->m_flags &= ~(M_BCAST|M_MCAST);
2178 	m->m_pkthdr.rcvif = NULL;
2179 	ip6_output(m, NULL, NULL, 0, NULL, &outif, NULL);
2180 	if (outif)
2181 		icmp6_ifoutstat_inc(outif, type, code);
2182 
2183 	return;
2184 
2185  bad:
2186 	m_freem(m);
2187 	return;
2188 }
2189 
2190 void
2191 icmp6_fasttimo(void)
2192 {
2193 
2194 	mld_fasttimo();
2195 }
2196 
2197 void
2198 icmp6_slowtimo(void)
2199 {
2200 
2201 	mld_slowtimo();
2202 }
2203 
2204 static const char *
2205 icmp6_redirect_diag(struct in6_addr *src6, struct in6_addr *dst6,
2206     struct in6_addr *tgt6)
2207 {
2208 	static char buf[1024];
2209 	char ip6bufs[INET6_ADDRSTRLEN];
2210 	char ip6bufd[INET6_ADDRSTRLEN];
2211 	char ip6buft[INET6_ADDRSTRLEN];
2212 	snprintf(buf, sizeof(buf), "(src=%s dst=%s tgt=%s)",
2213 	    ip6_sprintf(ip6bufs, src6), ip6_sprintf(ip6bufd, dst6),
2214 	    ip6_sprintf(ip6buft, tgt6));
2215 	return buf;
2216 }
2217 
2218 void
2219 icmp6_redirect_input(struct mbuf *m, int off)
2220 {
2221 	struct ifnet *ifp;
2222 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
2223 	struct nd_redirect *nd_rd;
2224 	int icmp6len = ntohs(ip6->ip6_plen);
2225 	char *lladdr = NULL;
2226 	int lladdrlen = 0;
2227 	int is_router;
2228 	int is_onlink;
2229 	struct in6_addr src6 = ip6->ip6_src;
2230 	struct in6_addr redtgt6;
2231 	struct in6_addr reddst6;
2232 	union nd_opts ndopts;
2233 	char ip6buf[INET6_ADDRSTRLEN];
2234 
2235 	M_ASSERTPKTHDR(m);
2236 	KASSERT(m->m_pkthdr.rcvif != NULL, ("%s: no rcvif", __func__));
2237 
2238 	ifp = m->m_pkthdr.rcvif;
2239 
2240 	/* XXX if we are router, we don't update route by icmp6 redirect */
2241 	if (V_ip6_forwarding)
2242 		goto freeit;
2243 	if (!V_icmp6_rediraccept)
2244 		goto freeit;
2245 
2246 	/* RFC 6980: Nodes MUST silently ignore fragments */
2247 	if(m->m_flags & M_FRAGMENTED)
2248 		goto freeit;
2249 
2250 #ifndef PULLDOWN_TEST
2251 	IP6_EXTHDR_CHECK(m, off, icmp6len,);
2252 	nd_rd = (struct nd_redirect *)((caddr_t)ip6 + off);
2253 #else
2254 	IP6_EXTHDR_GET(nd_rd, struct nd_redirect *, m, off, icmp6len);
2255 	if (nd_rd == NULL) {
2256 		ICMP6STAT_INC(icp6s_tooshort);
2257 		return;
2258 	}
2259 #endif
2260 	redtgt6 = nd_rd->nd_rd_target;
2261 	reddst6 = nd_rd->nd_rd_dst;
2262 
2263 	if (in6_setscope(&redtgt6, m->m_pkthdr.rcvif, NULL) ||
2264 	    in6_setscope(&reddst6, m->m_pkthdr.rcvif, NULL)) {
2265 		goto freeit;
2266 	}
2267 
2268 	/* validation */
2269 	if (!IN6_IS_ADDR_LINKLOCAL(&src6)) {
2270 		nd6log((LOG_ERR,
2271 		    "ICMP6 redirect sent from %s rejected; "
2272 		    "must be from linklocal\n",
2273 		    ip6_sprintf(ip6buf, &src6)));
2274 		goto bad;
2275 	}
2276 	if (ip6->ip6_hlim != 255) {
2277 		nd6log((LOG_ERR,
2278 		    "ICMP6 redirect sent from %s rejected; "
2279 		    "hlim=%d (must be 255)\n",
2280 		    ip6_sprintf(ip6buf, &src6), ip6->ip6_hlim));
2281 		goto bad;
2282 	}
2283     {
2284 	/* ip6->ip6_src must be equal to gw for icmp6->icmp6_reddst */
2285 	struct nhop6_basic nh6;
2286 	struct in6_addr kdst;
2287 	uint32_t scopeid;
2288 
2289 	in6_splitscope(&reddst6, &kdst, &scopeid);
2290 	if (fib6_lookup_nh_basic(ifp->if_fib, &kdst, scopeid, 0, 0,&nh6)==0){
2291 		if ((nh6.nh_flags & NHF_GATEWAY) == 0) {
2292 			nd6log((LOG_ERR,
2293 			    "ICMP6 redirect rejected; no route "
2294 			    "with inet6 gateway found for redirect dst: %s\n",
2295 			    icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2296 			goto bad;
2297 		}
2298 
2299 		/*
2300 		 * Embed scope zone id into next hop address, since
2301 		 * fib6_lookup_nh_basic() returns address without embedded
2302 		 * scope zone id.
2303 		 */
2304 		if (in6_setscope(&nh6.nh_addr, m->m_pkthdr.rcvif, NULL))
2305 			goto freeit;
2306 
2307 		if (IN6_ARE_ADDR_EQUAL(&src6, &nh6.nh_addr) == 0) {
2308 			nd6log((LOG_ERR,
2309 			    "ICMP6 redirect rejected; "
2310 			    "not equal to gw-for-src=%s (must be same): "
2311 			    "%s\n",
2312 			    ip6_sprintf(ip6buf, &nh6.nh_addr),
2313 			    icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2314 			goto bad;
2315 		}
2316 	} else {
2317 		nd6log((LOG_ERR,
2318 		    "ICMP6 redirect rejected; "
2319 		    "no route found for redirect dst: %s\n",
2320 		    icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2321 		goto bad;
2322 	}
2323     }
2324 	if (IN6_IS_ADDR_MULTICAST(&reddst6)) {
2325 		nd6log((LOG_ERR,
2326 		    "ICMP6 redirect rejected; "
2327 		    "redirect dst must be unicast: %s\n",
2328 		    icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2329 		goto bad;
2330 	}
2331 
2332 	is_router = is_onlink = 0;
2333 	if (IN6_IS_ADDR_LINKLOCAL(&redtgt6))
2334 		is_router = 1;	/* router case */
2335 	if (bcmp(&redtgt6, &reddst6, sizeof(redtgt6)) == 0)
2336 		is_onlink = 1;	/* on-link destination case */
2337 	if (!is_router && !is_onlink) {
2338 		nd6log((LOG_ERR,
2339 		    "ICMP6 redirect rejected; "
2340 		    "neither router case nor onlink case: %s\n",
2341 		    icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2342 		goto bad;
2343 	}
2344 
2345 	icmp6len -= sizeof(*nd_rd);
2346 	nd6_option_init(nd_rd + 1, icmp6len, &ndopts);
2347 	if (nd6_options(&ndopts) < 0) {
2348 		nd6log((LOG_INFO, "%s: invalid ND option, rejected: %s\n",
2349 		    __func__, icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2350 		/* nd6_options have incremented stats */
2351 		goto freeit;
2352 	}
2353 
2354 	if (ndopts.nd_opts_tgt_lladdr) {
2355 		lladdr = (char *)(ndopts.nd_opts_tgt_lladdr + 1);
2356 		lladdrlen = ndopts.nd_opts_tgt_lladdr->nd_opt_len << 3;
2357 	}
2358 
2359 	if (lladdr && ((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
2360 		nd6log((LOG_INFO, "%s: lladdrlen mismatch for %s "
2361 		    "(if %d, icmp6 packet %d): %s\n",
2362 		    __func__, ip6_sprintf(ip6buf, &redtgt6),
2363 		    ifp->if_addrlen, lladdrlen - 2,
2364 		    icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2365 		goto bad;
2366 	}
2367 
2368 	/* Validation passed. */
2369 
2370 	/* RFC 2461 8.3 */
2371 	nd6_cache_lladdr(ifp, &redtgt6, lladdr, lladdrlen, ND_REDIRECT,
2372 	    is_onlink ? ND_REDIRECT_ONLINK : ND_REDIRECT_ROUTER);
2373 
2374 	/*
2375 	 * Install a gateway route in the better-router case or an interface
2376 	 * route in the on-link-destination case.
2377 	 */
2378 	{
2379 		struct sockaddr_in6 sdst;
2380 		struct sockaddr_in6 sgw;
2381 		struct sockaddr_in6 ssrc;
2382 		struct sockaddr *gw;
2383 		int rt_flags;
2384 		u_int fibnum;
2385 
2386 		bzero(&sdst, sizeof(sdst));
2387 		bzero(&ssrc, sizeof(ssrc));
2388 		sdst.sin6_family = ssrc.sin6_family = AF_INET6;
2389 		sdst.sin6_len = ssrc.sin6_len = sizeof(struct sockaddr_in6);
2390 		bcopy(&reddst6, &sdst.sin6_addr, sizeof(struct in6_addr));
2391 		bcopy(&src6, &ssrc.sin6_addr, sizeof(struct in6_addr));
2392 		rt_flags = RTF_HOST;
2393 		if (is_router) {
2394 			bzero(&sgw, sizeof(sgw));
2395 			sgw.sin6_family = AF_INET6;
2396 			sgw.sin6_len = sizeof(struct sockaddr_in6);
2397 			bcopy(&redtgt6, &sgw.sin6_addr,
2398 				sizeof(struct in6_addr));
2399 			gw = (struct sockaddr *)&sgw;
2400 			rt_flags |= RTF_GATEWAY;
2401 		} else
2402 			gw = ifp->if_addr->ifa_addr;
2403 		for (fibnum = 0; fibnum < rt_numfibs; fibnum++)
2404 			in6_rtredirect((struct sockaddr *)&sdst, gw,
2405 			    (struct sockaddr *)NULL, rt_flags,
2406 			    (struct sockaddr *)&ssrc, fibnum);
2407 	}
2408 	/* finally update cached route in each socket via pfctlinput */
2409     {
2410 	struct sockaddr_in6 sdst;
2411 
2412 	bzero(&sdst, sizeof(sdst));
2413 	sdst.sin6_family = AF_INET6;
2414 	sdst.sin6_len = sizeof(struct sockaddr_in6);
2415 	bcopy(&reddst6, &sdst.sin6_addr, sizeof(struct in6_addr));
2416 	pfctlinput(PRC_REDIRECT_HOST, (struct sockaddr *)&sdst);
2417     }
2418 
2419  freeit:
2420 	m_freem(m);
2421 	return;
2422 
2423  bad:
2424 	ICMP6STAT_INC(icp6s_badredirect);
2425 	m_freem(m);
2426 }
2427 
2428 void
2429 icmp6_redirect_output(struct mbuf *m0, struct rtentry *rt)
2430 {
2431 	struct ifnet *ifp;	/* my outgoing interface */
2432 	struct in6_addr *ifp_ll6;
2433 	struct in6_addr *router_ll6;
2434 	struct ip6_hdr *sip6;	/* m0 as struct ip6_hdr */
2435 	struct mbuf *m = NULL;	/* newly allocated one */
2436 	struct m_tag *mtag;
2437 	struct ip6_hdr *ip6;	/* m as struct ip6_hdr */
2438 	struct nd_redirect *nd_rd;
2439 	struct llentry *ln = NULL;
2440 	size_t maxlen;
2441 	u_char *p;
2442 	struct ifnet *outif = NULL;
2443 	struct sockaddr_in6 src_sa;
2444 
2445 	icmp6_errcount(ND_REDIRECT, 0);
2446 
2447 	/* if we are not router, we don't send icmp6 redirect */
2448 	if (!V_ip6_forwarding)
2449 		goto fail;
2450 
2451 	/* sanity check */
2452 	if (!m0 || !rt || !(rt->rt_flags & RTF_UP) || !(ifp = rt->rt_ifp))
2453 		goto fail;
2454 
2455 	/*
2456 	 * Address check:
2457 	 *  the source address must identify a neighbor, and
2458 	 *  the destination address must not be a multicast address
2459 	 *  [RFC 2461, sec 8.2]
2460 	 */
2461 	sip6 = mtod(m0, struct ip6_hdr *);
2462 	bzero(&src_sa, sizeof(src_sa));
2463 	src_sa.sin6_family = AF_INET6;
2464 	src_sa.sin6_len = sizeof(src_sa);
2465 	src_sa.sin6_addr = sip6->ip6_src;
2466 	if (nd6_is_addr_neighbor(&src_sa, ifp) == 0)
2467 		goto fail;
2468 	if (IN6_IS_ADDR_MULTICAST(&sip6->ip6_dst))
2469 		goto fail;	/* what should we do here? */
2470 
2471 	/* rate limit */
2472 	if (icmp6_ratelimit(&sip6->ip6_src, ND_REDIRECT, 0))
2473 		goto fail;
2474 
2475 	/*
2476 	 * Since we are going to append up to 1280 bytes (= IPV6_MMTU),
2477 	 * we almost always ask for an mbuf cluster for simplicity.
2478 	 * (MHLEN < IPV6_MMTU is almost always true)
2479 	 */
2480 #if IPV6_MMTU >= MCLBYTES
2481 # error assumption failed about IPV6_MMTU and MCLBYTES
2482 #endif
2483 	m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
2484 	if (m == NULL)
2485 		goto fail;
2486 	M_SETFIB(m, rt->rt_fibnum);
2487 	maxlen = M_TRAILINGSPACE(m);
2488 	maxlen = min(IPV6_MMTU, maxlen);
2489 	/* just for safety */
2490 	if (maxlen < sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr) +
2491 	    ((sizeof(struct nd_opt_hdr) + ifp->if_addrlen + 7) & ~7)) {
2492 		goto fail;
2493 	}
2494 
2495 	{
2496 		/* get ip6 linklocal address for ifp(my outgoing interface). */
2497 		struct in6_ifaddr *ia;
2498 		if ((ia = in6ifa_ifpforlinklocal(ifp,
2499 						 IN6_IFF_NOTREADY|
2500 						 IN6_IFF_ANYCAST)) == NULL)
2501 			goto fail;
2502 		ifp_ll6 = &ia->ia_addr.sin6_addr;
2503 		/* XXXRW: reference released prematurely. */
2504 		ifa_free(&ia->ia_ifa);
2505 	}
2506 
2507 	/* get ip6 linklocal address for the router. */
2508 	if (rt->rt_gateway && (rt->rt_flags & RTF_GATEWAY)) {
2509 		struct sockaddr_in6 *sin6;
2510 		sin6 = (struct sockaddr_in6 *)rt->rt_gateway;
2511 		router_ll6 = &sin6->sin6_addr;
2512 		if (!IN6_IS_ADDR_LINKLOCAL(router_ll6))
2513 			router_ll6 = (struct in6_addr *)NULL;
2514 	} else
2515 		router_ll6 = (struct in6_addr *)NULL;
2516 
2517 	/* ip6 */
2518 	ip6 = mtod(m, struct ip6_hdr *);
2519 	ip6->ip6_flow = 0;
2520 	ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
2521 	ip6->ip6_vfc |= IPV6_VERSION;
2522 	/* ip6->ip6_plen will be set later */
2523 	ip6->ip6_nxt = IPPROTO_ICMPV6;
2524 	ip6->ip6_hlim = 255;
2525 	/* ip6->ip6_src must be linklocal addr for my outgoing if. */
2526 	bcopy(ifp_ll6, &ip6->ip6_src, sizeof(struct in6_addr));
2527 	bcopy(&sip6->ip6_src, &ip6->ip6_dst, sizeof(struct in6_addr));
2528 
2529 	/* ND Redirect */
2530 	nd_rd = (struct nd_redirect *)(ip6 + 1);
2531 	nd_rd->nd_rd_type = ND_REDIRECT;
2532 	nd_rd->nd_rd_code = 0;
2533 	nd_rd->nd_rd_reserved = 0;
2534 	if (rt->rt_flags & RTF_GATEWAY) {
2535 		/*
2536 		 * nd_rd->nd_rd_target must be a link-local address in
2537 		 * better router cases.
2538 		 */
2539 		if (!router_ll6)
2540 			goto fail;
2541 		bcopy(router_ll6, &nd_rd->nd_rd_target,
2542 		    sizeof(nd_rd->nd_rd_target));
2543 		bcopy(&sip6->ip6_dst, &nd_rd->nd_rd_dst,
2544 		    sizeof(nd_rd->nd_rd_dst));
2545 	} else {
2546 		/* make sure redtgt == reddst */
2547 		bcopy(&sip6->ip6_dst, &nd_rd->nd_rd_target,
2548 		    sizeof(nd_rd->nd_rd_target));
2549 		bcopy(&sip6->ip6_dst, &nd_rd->nd_rd_dst,
2550 		    sizeof(nd_rd->nd_rd_dst));
2551 	}
2552 
2553 	p = (u_char *)(nd_rd + 1);
2554 
2555 	if (!router_ll6)
2556 		goto nolladdropt;
2557 
2558 	{
2559 		/* target lladdr option */
2560 		int len;
2561 		struct nd_opt_hdr *nd_opt;
2562 		char *lladdr;
2563 
2564 		IF_AFDATA_RLOCK(ifp);
2565 		ln = nd6_lookup(router_ll6, 0, ifp);
2566 		IF_AFDATA_RUNLOCK(ifp);
2567 		if (ln == NULL)
2568 			goto nolladdropt;
2569 
2570 		len = sizeof(*nd_opt) + ifp->if_addrlen;
2571 		len = (len + 7) & ~7;	/* round by 8 */
2572 		/* safety check */
2573 		if (len + (p - (u_char *)ip6) > maxlen)
2574 			goto nolladdropt;
2575 
2576 		if (ln->la_flags & LLE_VALID) {
2577 			nd_opt = (struct nd_opt_hdr *)p;
2578 			nd_opt->nd_opt_type = ND_OPT_TARGET_LINKADDR;
2579 			nd_opt->nd_opt_len = len >> 3;
2580 			lladdr = (char *)(nd_opt + 1);
2581 			bcopy(ln->ll_addr, lladdr, ifp->if_addrlen);
2582 			p += len;
2583 		}
2584 	}
2585 nolladdropt:
2586 	if (ln != NULL)
2587 		LLE_RUNLOCK(ln);
2588 
2589 	m->m_pkthdr.len = m->m_len = p - (u_char *)ip6;
2590 
2591 	/* just to be safe */
2592 #ifdef M_DECRYPTED	/*not openbsd*/
2593 	if (m0->m_flags & M_DECRYPTED)
2594 		goto noredhdropt;
2595 #endif
2596 	if (p - (u_char *)ip6 > maxlen)
2597 		goto noredhdropt;
2598 
2599 	{
2600 		/* redirected header option */
2601 		int len;
2602 		struct nd_opt_rd_hdr *nd_opt_rh;
2603 
2604 		/*
2605 		 * compute the maximum size for icmp6 redirect header option.
2606 		 * XXX room for auth header?
2607 		 */
2608 		len = maxlen - (p - (u_char *)ip6);
2609 		len &= ~7;
2610 
2611 		/* This is just for simplicity. */
2612 		if (m0->m_pkthdr.len != m0->m_len) {
2613 			if (m0->m_next) {
2614 				m_freem(m0->m_next);
2615 				m0->m_next = NULL;
2616 			}
2617 			m0->m_pkthdr.len = m0->m_len;
2618 		}
2619 
2620 		/*
2621 		 * Redirected header option spec (RFC2461 4.6.3) talks nothing
2622 		 * about padding/truncate rule for the original IP packet.
2623 		 * From the discussion on IPv6imp in Feb 1999,
2624 		 * the consensus was:
2625 		 * - "attach as much as possible" is the goal
2626 		 * - pad if not aligned (original size can be guessed by
2627 		 *   original ip6 header)
2628 		 * Following code adds the padding if it is simple enough,
2629 		 * and truncates if not.
2630 		 */
2631 		if (m0->m_next || m0->m_pkthdr.len != m0->m_len)
2632 			panic("assumption failed in %s:%d", __FILE__,
2633 			    __LINE__);
2634 
2635 		if (len - sizeof(*nd_opt_rh) < m0->m_pkthdr.len) {
2636 			/* not enough room, truncate */
2637 			m0->m_pkthdr.len = m0->m_len = len -
2638 			    sizeof(*nd_opt_rh);
2639 		} else {
2640 			/* enough room, pad or truncate */
2641 			size_t extra;
2642 
2643 			extra = m0->m_pkthdr.len % 8;
2644 			if (extra) {
2645 				/* pad if easy enough, truncate if not */
2646 				if (8 - extra <= M_TRAILINGSPACE(m0)) {
2647 					/* pad */
2648 					m0->m_len += (8 - extra);
2649 					m0->m_pkthdr.len += (8 - extra);
2650 				} else {
2651 					/* truncate */
2652 					m0->m_pkthdr.len -= extra;
2653 					m0->m_len -= extra;
2654 				}
2655 			}
2656 			len = m0->m_pkthdr.len + sizeof(*nd_opt_rh);
2657 			m0->m_pkthdr.len = m0->m_len = len -
2658 			    sizeof(*nd_opt_rh);
2659 		}
2660 
2661 		nd_opt_rh = (struct nd_opt_rd_hdr *)p;
2662 		bzero(nd_opt_rh, sizeof(*nd_opt_rh));
2663 		nd_opt_rh->nd_opt_rh_type = ND_OPT_REDIRECTED_HEADER;
2664 		nd_opt_rh->nd_opt_rh_len = len >> 3;
2665 		p += sizeof(*nd_opt_rh);
2666 		m->m_pkthdr.len = m->m_len = p - (u_char *)ip6;
2667 
2668 		/* connect m0 to m */
2669 		m_tag_delete_chain(m0, NULL);
2670 		m0->m_flags &= ~M_PKTHDR;
2671 		m->m_next = m0;
2672 		m->m_pkthdr.len = m->m_len + m0->m_len;
2673 		m0 = NULL;
2674 	}
2675 noredhdropt:;
2676 	if (m0) {
2677 		m_freem(m0);
2678 		m0 = NULL;
2679 	}
2680 
2681 	/* XXX: clear embedded link IDs in the inner header */
2682 	in6_clearscope(&sip6->ip6_src);
2683 	in6_clearscope(&sip6->ip6_dst);
2684 	in6_clearscope(&nd_rd->nd_rd_target);
2685 	in6_clearscope(&nd_rd->nd_rd_dst);
2686 
2687 	ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(struct ip6_hdr));
2688 
2689 	nd_rd->nd_rd_cksum = 0;
2690 	nd_rd->nd_rd_cksum = in6_cksum(m, IPPROTO_ICMPV6,
2691 	    sizeof(*ip6), ntohs(ip6->ip6_plen));
2692 
2693         if (send_sendso_input_hook != NULL) {
2694 		mtag = m_tag_get(PACKET_TAG_ND_OUTGOING, sizeof(unsigned short),
2695 			M_NOWAIT);
2696 		if (mtag == NULL)
2697 			goto fail;
2698 		*(unsigned short *)(mtag + 1) = nd_rd->nd_rd_type;
2699 		m_tag_prepend(m, mtag);
2700 	}
2701 
2702 	/* send the packet to outside... */
2703 	ip6_output(m, NULL, NULL, 0, NULL, &outif, NULL);
2704 	if (outif) {
2705 		icmp6_ifstat_inc(outif, ifs6_out_msg);
2706 		icmp6_ifstat_inc(outif, ifs6_out_redirect);
2707 	}
2708 	ICMP6STAT_INC(icp6s_outhist[ND_REDIRECT]);
2709 
2710 	return;
2711 
2712 fail:
2713 	if (m)
2714 		m_freem(m);
2715 	if (m0)
2716 		m_freem(m0);
2717 }
2718 
2719 /*
2720  * ICMPv6 socket option processing.
2721  */
2722 int
2723 icmp6_ctloutput(struct socket *so, struct sockopt *sopt)
2724 {
2725 	int error = 0;
2726 	int optlen;
2727 	struct inpcb *inp = sotoinpcb(so);
2728 	int level, op, optname;
2729 
2730 	if (sopt) {
2731 		level = sopt->sopt_level;
2732 		op = sopt->sopt_dir;
2733 		optname = sopt->sopt_name;
2734 		optlen = sopt->sopt_valsize;
2735 	} else
2736 		level = op = optname = optlen = 0;
2737 
2738 	if (level != IPPROTO_ICMPV6) {
2739 		return EINVAL;
2740 	}
2741 
2742 	switch (op) {
2743 	case PRCO_SETOPT:
2744 		switch (optname) {
2745 		case ICMP6_FILTER:
2746 		    {
2747 			struct icmp6_filter ic6f;
2748 
2749 			if (optlen != sizeof(ic6f)) {
2750 				error = EMSGSIZE;
2751 				break;
2752 			}
2753 			error = sooptcopyin(sopt, &ic6f, optlen, optlen);
2754 			if (error == 0) {
2755 				INP_WLOCK(inp);
2756 				*inp->in6p_icmp6filt = ic6f;
2757 				INP_WUNLOCK(inp);
2758 			}
2759 			break;
2760 		    }
2761 
2762 		default:
2763 			error = ENOPROTOOPT;
2764 			break;
2765 		}
2766 		break;
2767 
2768 	case PRCO_GETOPT:
2769 		switch (optname) {
2770 		case ICMP6_FILTER:
2771 		    {
2772 			struct icmp6_filter ic6f;
2773 
2774 			INP_RLOCK(inp);
2775 			ic6f = *inp->in6p_icmp6filt;
2776 			INP_RUNLOCK(inp);
2777 			error = sooptcopyout(sopt, &ic6f, sizeof(ic6f));
2778 			break;
2779 		    }
2780 
2781 		default:
2782 			error = ENOPROTOOPT;
2783 			break;
2784 		}
2785 		break;
2786 	}
2787 
2788 	return (error);
2789 }
2790 
2791 /*
2792  * Perform rate limit check.
2793  * Returns 0 if it is okay to send the icmp6 packet.
2794  * Returns 1 if the router SHOULD NOT send this icmp6 packet due to rate
2795  * limitation.
2796  *
2797  * XXX per-destination/type check necessary?
2798  *
2799  * dst - not used at this moment
2800  * type - not used at this moment
2801  * code - not used at this moment
2802  */
2803 static int
2804 icmp6_ratelimit(const struct in6_addr *dst, const int type,
2805     const int code)
2806 {
2807 	int ret;
2808 
2809 	ret = 0;	/* okay to send */
2810 
2811 	/* PPS limit */
2812 	if (!ppsratecheck(&V_icmp6errppslim_last, &V_icmp6errpps_count,
2813 	    V_icmp6errppslim)) {
2814 		/* The packet is subject to rate limit */
2815 		ret++;
2816 	}
2817 
2818 	return ret;
2819 }
2820