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