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