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