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