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