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