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