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