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