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