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