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