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