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