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