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