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