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