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