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