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