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