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