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