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