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