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