icmp6.c revision 194118
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 194118 2009-06-13 15:39:12Z jamie $");
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			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_hostname,
1339			    strlen(pr->pr_hostname), 0);
1340			mtx_unlock(&pr->pr_mtx);
1341			if (!n || n->m_next || n->m_len == 0)
1342				goto bad;
1343			IP6_EXTHDR_GET(subj, char *, m,
1344			    off + sizeof(struct icmp6_nodeinfo), subjlen);
1345			if (subj == NULL)
1346				goto bad;
1347			if (!ni6_dnsmatch(subj, subjlen, mtod(n, const char *),
1348			    n->m_len)) {
1349				goto bad;
1350			}
1351			m_freem(n);
1352			n = NULL;
1353			break;
1354
1355		case ICMP6_NI_SUBJ_IPV4:	/* XXX: to be implemented? */
1356		default:
1357			goto bad;
1358		}
1359		break;
1360	}
1361
1362	/* refuse based on configuration.  XXX ICMP6_NI_REFUSED? */
1363	switch (qtype) {
1364	case NI_QTYPE_FQDN:
1365		if ((V_icmp6_nodeinfo & ICMP6_NODEINFO_FQDNOK) == 0)
1366			goto bad;
1367		break;
1368	case NI_QTYPE_NODEADDR:
1369	case NI_QTYPE_IPV4ADDR:
1370		if ((V_icmp6_nodeinfo & ICMP6_NODEINFO_NODEADDROK) == 0)
1371			goto bad;
1372		break;
1373	}
1374
1375	/* guess reply length */
1376	switch (qtype) {
1377	case NI_QTYPE_NOOP:
1378		break;		/* no reply data */
1379	case NI_QTYPE_SUPTYPES:
1380		replylen += sizeof(u_int32_t);
1381		break;
1382	case NI_QTYPE_FQDN:
1383		/* XXX will append an mbuf */
1384		replylen += offsetof(struct ni_reply_fqdn, ni_fqdn_namelen);
1385		break;
1386	case NI_QTYPE_NODEADDR:
1387		addrs = ni6_addrs(ni6, m, &ifp, (struct in6_addr *)subj);
1388		if ((replylen += addrs * (sizeof(struct in6_addr) +
1389		    sizeof(u_int32_t))) > MCLBYTES)
1390			replylen = MCLBYTES; /* XXX: will truncate pkt later */
1391		break;
1392	case NI_QTYPE_IPV4ADDR:
1393		/* unsupported - should respond with unknown Qtype? */
1394		break;
1395	default:
1396		/*
1397		 * XXX: We must return a reply with the ICMP6 code
1398		 * `unknown Qtype' in this case.  However we regard the case
1399		 * as an FQDN query for backward compatibility.
1400		 * Older versions set a random value to this field,
1401		 * so it rarely varies in the defined qtypes.
1402		 * But the mechanism is not reliable...
1403		 * maybe we should obsolete older versions.
1404		 */
1405		qtype = NI_QTYPE_FQDN;
1406		/* XXX will append an mbuf */
1407		replylen += offsetof(struct ni_reply_fqdn, ni_fqdn_namelen);
1408		oldfqdn++;
1409		break;
1410	}
1411
1412	/* allocate an mbuf to reply. */
1413	MGETHDR(n, M_DONTWAIT, m->m_type);
1414	if (n == NULL) {
1415		m_freem(m);
1416		return (NULL);
1417	}
1418	M_MOVE_PKTHDR(n, m); /* just for recvif */
1419	if (replylen > MHLEN) {
1420		if (replylen > MCLBYTES) {
1421			/*
1422			 * XXX: should we try to allocate more? But MCLBYTES
1423			 * is probably much larger than IPV6_MMTU...
1424			 */
1425			goto bad;
1426		}
1427		MCLGET(n, M_DONTWAIT);
1428		if ((n->m_flags & M_EXT) == 0) {
1429			goto bad;
1430		}
1431	}
1432	n->m_pkthdr.len = n->m_len = replylen;
1433
1434	/* copy mbuf header and IPv6 + Node Information base headers */
1435	bcopy(mtod(m, caddr_t), mtod(n, caddr_t), sizeof(struct ip6_hdr));
1436	nni6 = (struct icmp6_nodeinfo *)(mtod(n, struct ip6_hdr *) + 1);
1437	bcopy((caddr_t)ni6, (caddr_t)nni6, sizeof(struct icmp6_nodeinfo));
1438
1439	/* qtype dependent procedure */
1440	switch (qtype) {
1441	case NI_QTYPE_NOOP:
1442		nni6->ni_code = ICMP6_NI_SUCCESS;
1443		nni6->ni_flags = 0;
1444		break;
1445	case NI_QTYPE_SUPTYPES:
1446	{
1447		u_int32_t v;
1448		nni6->ni_code = ICMP6_NI_SUCCESS;
1449		nni6->ni_flags = htons(0x0000);	/* raw bitmap */
1450		/* supports NOOP, SUPTYPES, FQDN, and NODEADDR */
1451		v = (u_int32_t)htonl(0x0000000f);
1452		bcopy(&v, nni6 + 1, sizeof(u_int32_t));
1453		break;
1454	}
1455	case NI_QTYPE_FQDN:
1456		nni6->ni_code = ICMP6_NI_SUCCESS;
1457		fqdn = (struct ni_reply_fqdn *)(mtod(n, caddr_t) +
1458		    sizeof(struct ip6_hdr) + sizeof(struct icmp6_nodeinfo));
1459		nni6->ni_flags = 0; /* XXX: meaningless TTL */
1460		fqdn->ni_fqdn_ttl = 0;	/* ditto. */
1461		/*
1462		 * XXX do we really have FQDN in hostname?
1463		 */
1464		pr = curthread->td_ucred->cr_prison;
1465		mtx_lock(&pr->pr_mtx);
1466		n->m_next = ni6_nametodns(pr->pr_hostname,
1467		    strlen(pr->pr_hostname), oldfqdn);
1468		mtx_unlock(&pr->pr_mtx);
1469		if (n->m_next == NULL)
1470			goto bad;
1471		/* XXX we assume that n->m_next is not a chain */
1472		if (n->m_next->m_next != NULL)
1473			goto bad;
1474		n->m_pkthdr.len += n->m_next->m_len;
1475		break;
1476	case NI_QTYPE_NODEADDR:
1477	{
1478		int lenlim, copied;
1479
1480		nni6->ni_code = ICMP6_NI_SUCCESS;
1481		n->m_pkthdr.len = n->m_len =
1482		    sizeof(struct ip6_hdr) + sizeof(struct icmp6_nodeinfo);
1483		lenlim = M_TRAILINGSPACE(n);
1484		copied = ni6_store_addrs(ni6, nni6, ifp, lenlim);
1485		/* XXX: reset mbuf length */
1486		n->m_pkthdr.len = n->m_len = sizeof(struct ip6_hdr) +
1487		    sizeof(struct icmp6_nodeinfo) + copied;
1488		break;
1489	}
1490	default:
1491		break;		/* XXX impossible! */
1492	}
1493
1494	nni6->ni_type = ICMP6_NI_REPLY;
1495	m_freem(m);
1496	return (n);
1497
1498  bad:
1499	m_freem(m);
1500	if (n)
1501		m_freem(n);
1502	return (NULL);
1503}
1504
1505/*
1506 * make a mbuf with DNS-encoded string.  no compression support.
1507 *
1508 * XXX names with less than 2 dots (like "foo" or "foo.section") will be
1509 * treated as truncated name (two \0 at the end).  this is a wild guess.
1510 *
1511 * old - return pascal string if non-zero
1512 */
1513static struct mbuf *
1514ni6_nametodns(const char *name, int namelen, int old)
1515{
1516	struct mbuf *m;
1517	char *cp, *ep;
1518	const char *p, *q;
1519	int i, len, nterm;
1520
1521	if (old)
1522		len = namelen + 1;
1523	else
1524		len = MCLBYTES;
1525
1526	/* because MAXHOSTNAMELEN is usually 256, we use cluster mbuf */
1527	MGET(m, M_DONTWAIT, MT_DATA);
1528	if (m && len > MLEN) {
1529		MCLGET(m, M_DONTWAIT);
1530		if ((m->m_flags & M_EXT) == 0)
1531			goto fail;
1532	}
1533	if (!m)
1534		goto fail;
1535	m->m_next = NULL;
1536
1537	if (old) {
1538		m->m_len = len;
1539		*mtod(m, char *) = namelen;
1540		bcopy(name, mtod(m, char *) + 1, namelen);
1541		return m;
1542	} else {
1543		m->m_len = 0;
1544		cp = mtod(m, char *);
1545		ep = mtod(m, char *) + M_TRAILINGSPACE(m);
1546
1547		/* if not certain about my name, return empty buffer */
1548		if (namelen == 0)
1549			return m;
1550
1551		/*
1552		 * guess if it looks like shortened hostname, or FQDN.
1553		 * shortened hostname needs two trailing "\0".
1554		 */
1555		i = 0;
1556		for (p = name; p < name + namelen; p++) {
1557			if (*p && *p == '.')
1558				i++;
1559		}
1560		if (i < 2)
1561			nterm = 2;
1562		else
1563			nterm = 1;
1564
1565		p = name;
1566		while (cp < ep && p < name + namelen) {
1567			i = 0;
1568			for (q = p; q < name + namelen && *q && *q != '.'; q++)
1569				i++;
1570			/* result does not fit into mbuf */
1571			if (cp + i + 1 >= ep)
1572				goto fail;
1573			/*
1574			 * DNS label length restriction, RFC1035 page 8.
1575			 * "i == 0" case is included here to avoid returning
1576			 * 0-length label on "foo..bar".
1577			 */
1578			if (i <= 0 || i >= 64)
1579				goto fail;
1580			*cp++ = i;
1581			bcopy(p, cp, i);
1582			cp += i;
1583			p = q;
1584			if (p < name + namelen && *p == '.')
1585				p++;
1586		}
1587		/* termination */
1588		if (cp + nterm >= ep)
1589			goto fail;
1590		while (nterm-- > 0)
1591			*cp++ = '\0';
1592		m->m_len = cp - mtod(m, char *);
1593		return m;
1594	}
1595
1596	panic("should not reach here");
1597	/* NOTREACHED */
1598
1599 fail:
1600	if (m)
1601		m_freem(m);
1602	return NULL;
1603}
1604
1605/*
1606 * check if two DNS-encoded string matches.  takes care of truncated
1607 * form (with \0\0 at the end).  no compression support.
1608 * XXX upper/lowercase match (see RFC2065)
1609 */
1610static int
1611ni6_dnsmatch(const char *a, int alen, const char *b, int blen)
1612{
1613	const char *a0, *b0;
1614	int l;
1615
1616	/* simplest case - need validation? */
1617	if (alen == blen && bcmp(a, b, alen) == 0)
1618		return 1;
1619
1620	a0 = a;
1621	b0 = b;
1622
1623	/* termination is mandatory */
1624	if (alen < 2 || blen < 2)
1625		return 0;
1626	if (a0[alen - 1] != '\0' || b0[blen - 1] != '\0')
1627		return 0;
1628	alen--;
1629	blen--;
1630
1631	while (a - a0 < alen && b - b0 < blen) {
1632		if (a - a0 + 1 > alen || b - b0 + 1 > blen)
1633			return 0;
1634
1635		if ((signed char)a[0] < 0 || (signed char)b[0] < 0)
1636			return 0;
1637		/* we don't support compression yet */
1638		if (a[0] >= 64 || b[0] >= 64)
1639			return 0;
1640
1641		/* truncated case */
1642		if (a[0] == 0 && a - a0 == alen - 1)
1643			return 1;
1644		if (b[0] == 0 && b - b0 == blen - 1)
1645			return 1;
1646		if (a[0] == 0 || b[0] == 0)
1647			return 0;
1648
1649		if (a[0] != b[0])
1650			return 0;
1651		l = a[0];
1652		if (a - a0 + 1 + l > alen || b - b0 + 1 + l > blen)
1653			return 0;
1654		if (bcmp(a + 1, b + 1, l) != 0)
1655			return 0;
1656
1657		a += 1 + l;
1658		b += 1 + l;
1659	}
1660
1661	if (a - a0 == alen && b - b0 == blen)
1662		return 1;
1663	else
1664		return 0;
1665}
1666
1667/*
1668 * calculate the number of addresses to be returned in the node info reply.
1669 */
1670static int
1671ni6_addrs(struct icmp6_nodeinfo *ni6, struct mbuf *m, struct ifnet **ifpp,
1672    struct in6_addr *subj)
1673{
1674	INIT_VNET_NET(curvnet);
1675	INIT_VNET_INET6(curvnet);
1676	struct ifnet *ifp;
1677	struct in6_ifaddr *ifa6;
1678	struct ifaddr *ifa;
1679	int addrs = 0, addrsofif, iffound = 0;
1680	int niflags = ni6->ni_flags;
1681
1682	if ((niflags & NI_NODEADDR_FLAG_ALL) == 0) {
1683		switch (ni6->ni_code) {
1684		case ICMP6_NI_SUBJ_IPV6:
1685			if (subj == NULL) /* must be impossible... */
1686				return (0);
1687			break;
1688		default:
1689			/*
1690			 * XXX: we only support IPv6 subject address for
1691			 * this Qtype.
1692			 */
1693			return (0);
1694		}
1695	}
1696
1697	IFNET_RLOCK();
1698	for (ifp = TAILQ_FIRST(&V_ifnet); ifp; ifp = TAILQ_NEXT(ifp, if_list)) {
1699		addrsofif = 0;
1700		IF_ADDR_LOCK(ifp);
1701		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1702			if (ifa->ifa_addr->sa_family != AF_INET6)
1703				continue;
1704			ifa6 = (struct in6_ifaddr *)ifa;
1705
1706			if ((niflags & NI_NODEADDR_FLAG_ALL) == 0 &&
1707			    IN6_ARE_ADDR_EQUAL(subj, &ifa6->ia_addr.sin6_addr))
1708				iffound = 1;
1709
1710			/*
1711			 * IPv4-mapped addresses can only be returned by a
1712			 * Node Information proxy, since they represent
1713			 * addresses of IPv4-only nodes, which perforce do
1714			 * not implement this protocol.
1715			 * [icmp-name-lookups-07, Section 5.4]
1716			 * So we don't support NI_NODEADDR_FLAG_COMPAT in
1717			 * this function at this moment.
1718			 */
1719
1720			/* What do we have to do about ::1? */
1721			switch (in6_addrscope(&ifa6->ia_addr.sin6_addr)) {
1722			case IPV6_ADDR_SCOPE_LINKLOCAL:
1723				if ((niflags & NI_NODEADDR_FLAG_LINKLOCAL) == 0)
1724					continue;
1725				break;
1726			case IPV6_ADDR_SCOPE_SITELOCAL:
1727				if ((niflags & NI_NODEADDR_FLAG_SITELOCAL) == 0)
1728					continue;
1729				break;
1730			case IPV6_ADDR_SCOPE_GLOBAL:
1731				if ((niflags & NI_NODEADDR_FLAG_GLOBAL) == 0)
1732					continue;
1733				break;
1734			default:
1735				continue;
1736			}
1737
1738			/*
1739			 * check if anycast is okay.
1740			 * XXX: just experimental.  not in the spec.
1741			 */
1742			if ((ifa6->ia6_flags & IN6_IFF_ANYCAST) != 0 &&
1743			    (niflags & NI_NODEADDR_FLAG_ANYCAST) == 0)
1744				continue; /* we need only unicast addresses */
1745			if ((ifa6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
1746			    (V_icmp6_nodeinfo & ICMP6_NODEINFO_TMPADDROK) == 0) {
1747				continue;
1748			}
1749			addrsofif++; /* count the address */
1750		}
1751		IF_ADDR_UNLOCK(ifp);
1752		if (iffound) {
1753			*ifpp = ifp;
1754			IFNET_RUNLOCK();
1755			return (addrsofif);
1756		}
1757
1758		addrs += addrsofif;
1759	}
1760	IFNET_RUNLOCK();
1761
1762	return (addrs);
1763}
1764
1765static int
1766ni6_store_addrs(struct icmp6_nodeinfo *ni6, struct icmp6_nodeinfo *nni6,
1767    struct ifnet *ifp0, int resid)
1768{
1769	INIT_VNET_NET(curvnet);
1770	INIT_VNET_INET6(curvnet);
1771	struct ifnet *ifp = ifp0 ? ifp0 : TAILQ_FIRST(&V_ifnet);
1772	struct in6_ifaddr *ifa6;
1773	struct ifaddr *ifa;
1774	struct ifnet *ifp_dep = NULL;
1775	int copied = 0, allow_deprecated = 0;
1776	u_char *cp = (u_char *)(nni6 + 1);
1777	int niflags = ni6->ni_flags;
1778	u_int32_t ltime;
1779
1780	if (ifp0 == NULL && !(niflags & NI_NODEADDR_FLAG_ALL))
1781		return (0);	/* needless to copy */
1782
1783	IFNET_RLOCK();
1784  again:
1785
1786	for (; ifp; ifp = TAILQ_NEXT(ifp, if_list)) {
1787		IF_ADDR_LOCK(ifp);
1788		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1789			if (ifa->ifa_addr->sa_family != AF_INET6)
1790				continue;
1791			ifa6 = (struct in6_ifaddr *)ifa;
1792
1793			if ((ifa6->ia6_flags & IN6_IFF_DEPRECATED) != 0 &&
1794			    allow_deprecated == 0) {
1795				/*
1796				 * prefererred address should be put before
1797				 * deprecated addresses.
1798				 */
1799
1800				/* record the interface for later search */
1801				if (ifp_dep == NULL)
1802					ifp_dep = ifp;
1803
1804				continue;
1805			} else if ((ifa6->ia6_flags & IN6_IFF_DEPRECATED) == 0 &&
1806			    allow_deprecated != 0)
1807				continue; /* we now collect deprecated addrs */
1808
1809			/* What do we have to do about ::1? */
1810			switch (in6_addrscope(&ifa6->ia_addr.sin6_addr)) {
1811			case IPV6_ADDR_SCOPE_LINKLOCAL:
1812				if ((niflags & NI_NODEADDR_FLAG_LINKLOCAL) == 0)
1813					continue;
1814				break;
1815			case IPV6_ADDR_SCOPE_SITELOCAL:
1816				if ((niflags & NI_NODEADDR_FLAG_SITELOCAL) == 0)
1817					continue;
1818				break;
1819			case IPV6_ADDR_SCOPE_GLOBAL:
1820				if ((niflags & NI_NODEADDR_FLAG_GLOBAL) == 0)
1821					continue;
1822				break;
1823			default:
1824				continue;
1825			}
1826
1827			/*
1828			 * check if anycast is okay.
1829			 * XXX: just experimental.  not in the spec.
1830			 */
1831			if ((ifa6->ia6_flags & IN6_IFF_ANYCAST) != 0 &&
1832			    (niflags & NI_NODEADDR_FLAG_ANYCAST) == 0)
1833				continue;
1834			if ((ifa6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
1835			    (V_icmp6_nodeinfo & ICMP6_NODEINFO_TMPADDROK) == 0) {
1836				continue;
1837			}
1838
1839			/* now we can copy the address */
1840			if (resid < sizeof(struct in6_addr) +
1841			    sizeof(u_int32_t)) {
1842				IF_ADDR_UNLOCK(ifp);
1843				/*
1844				 * We give up much more copy.
1845				 * Set the truncate flag and return.
1846				 */
1847				nni6->ni_flags |= NI_NODEADDR_FLAG_TRUNCATE;
1848				IFNET_RUNLOCK();
1849				return (copied);
1850			}
1851
1852			/*
1853			 * Set the TTL of the address.
1854			 * The TTL value should be one of the following
1855			 * according to the specification:
1856			 *
1857			 * 1. The remaining lifetime of a DHCP lease on the
1858			 *    address, or
1859			 * 2. The remaining Valid Lifetime of a prefix from
1860			 *    which the address was derived through Stateless
1861			 *    Autoconfiguration.
1862			 *
1863			 * Note that we currently do not support stateful
1864			 * address configuration by DHCPv6, so the former
1865			 * case can't happen.
1866			 */
1867			if (ifa6->ia6_lifetime.ia6t_expire == 0)
1868				ltime = ND6_INFINITE_LIFETIME;
1869			else {
1870				if (ifa6->ia6_lifetime.ia6t_expire >
1871				    time_second)
1872					ltime = htonl(ifa6->ia6_lifetime.ia6t_expire - time_second);
1873				else
1874					ltime = 0;
1875			}
1876
1877			bcopy(&ltime, cp, sizeof(u_int32_t));
1878			cp += sizeof(u_int32_t);
1879
1880			/* copy the address itself */
1881			bcopy(&ifa6->ia_addr.sin6_addr, cp,
1882			    sizeof(struct in6_addr));
1883			in6_clearscope((struct in6_addr *)cp); /* XXX */
1884			cp += sizeof(struct in6_addr);
1885
1886			resid -= (sizeof(struct in6_addr) + sizeof(u_int32_t));
1887			copied += (sizeof(struct in6_addr) + sizeof(u_int32_t));
1888		}
1889		IF_ADDR_UNLOCK(ifp);
1890		if (ifp0)	/* we need search only on the specified IF */
1891			break;
1892	}
1893
1894	if (allow_deprecated == 0 && ifp_dep != NULL) {
1895		ifp = ifp_dep;
1896		allow_deprecated = 1;
1897
1898		goto again;
1899	}
1900
1901	IFNET_RUNLOCK();
1902
1903	return (copied);
1904}
1905
1906/*
1907 * XXX almost dup'ed code with rip6_input.
1908 */
1909static int
1910icmp6_rip6_input(struct mbuf **mp, int off)
1911{
1912	INIT_VNET_INET(curvnet);
1913	INIT_VNET_INET6(curvnet);
1914	struct mbuf *m = *mp;
1915	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
1916	struct inpcb *in6p;
1917	struct inpcb *last = NULL;
1918	struct sockaddr_in6 fromsa;
1919	struct icmp6_hdr *icmp6;
1920	struct mbuf *opts = NULL;
1921
1922#ifndef PULLDOWN_TEST
1923	/* this is assumed to be safe. */
1924	icmp6 = (struct icmp6_hdr *)((caddr_t)ip6 + off);
1925#else
1926	IP6_EXTHDR_GET(icmp6, struct icmp6_hdr *, m, off, sizeof(*icmp6));
1927	if (icmp6 == NULL) {
1928		/* m is already reclaimed */
1929		return (IPPROTO_DONE);
1930	}
1931#endif
1932
1933	/*
1934	 * XXX: the address may have embedded scope zone ID, which should be
1935	 * hidden from applications.
1936	 */
1937	bzero(&fromsa, sizeof(fromsa));
1938	fromsa.sin6_family = AF_INET6;
1939	fromsa.sin6_len = sizeof(struct sockaddr_in6);
1940	fromsa.sin6_addr = ip6->ip6_src;
1941	if (sa6_recoverscope(&fromsa)) {
1942		m_freem(m);
1943		return (IPPROTO_DONE);
1944	}
1945
1946	INP_INFO_RLOCK(&V_ripcbinfo);
1947	LIST_FOREACH(in6p, &V_ripcb, inp_list) {
1948		if ((in6p->inp_vflag & INP_IPV6) == 0)
1949			continue;
1950		if (in6p->inp_ip_p != IPPROTO_ICMPV6)
1951			continue;
1952		if (!IN6_IS_ADDR_UNSPECIFIED(&in6p->in6p_laddr) &&
1953		   !IN6_ARE_ADDR_EQUAL(&in6p->in6p_laddr, &ip6->ip6_dst))
1954			continue;
1955		if (!IN6_IS_ADDR_UNSPECIFIED(&in6p->in6p_faddr) &&
1956		   !IN6_ARE_ADDR_EQUAL(&in6p->in6p_faddr, &ip6->ip6_src))
1957			continue;
1958		INP_RLOCK(in6p);
1959		if (ICMP6_FILTER_WILLBLOCK(icmp6->icmp6_type,
1960		    in6p->in6p_icmp6filt)) {
1961			INP_RUNLOCK(in6p);
1962			continue;
1963		}
1964		if (last != NULL) {
1965			struct	mbuf *n = NULL;
1966
1967			/*
1968			 * Recent network drivers tend to allocate a single
1969			 * mbuf cluster, rather than to make a couple of
1970			 * mbufs without clusters.  Also, since the IPv6 code
1971			 * path tries to avoid m_pullup(), it is highly
1972			 * probable that we still have an mbuf cluster here
1973			 * even though the necessary length can be stored in an
1974			 * mbuf's internal buffer.
1975			 * Meanwhile, the default size of the receive socket
1976			 * buffer for raw sockets is not so large.  This means
1977			 * the possibility of packet loss is relatively higher
1978			 * than before.  To avoid this scenario, we copy the
1979			 * received data to a separate mbuf that does not use
1980			 * a cluster, if possible.
1981			 * XXX: it is better to copy the data after stripping
1982			 * intermediate headers.
1983			 */
1984			if ((m->m_flags & M_EXT) && m->m_next == NULL &&
1985			    m->m_len <= MHLEN) {
1986				MGET(n, M_DONTWAIT, m->m_type);
1987				if (n != NULL) {
1988					if (m_dup_pkthdr(n, m, M_NOWAIT)) {
1989						bcopy(m->m_data, n->m_data,
1990						      m->m_len);
1991						n->m_len = m->m_len;
1992					} else {
1993						m_free(n);
1994						n = NULL;
1995					}
1996				}
1997			}
1998			if (n != NULL ||
1999			    (n = m_copy(m, 0, (int)M_COPYALL)) != NULL) {
2000				if (last->inp_flags & INP_CONTROLOPTS)
2001					ip6_savecontrol(last, n, &opts);
2002				/* strip intermediate headers */
2003				m_adj(n, off);
2004				SOCKBUF_LOCK(&last->inp_socket->so_rcv);
2005				if (sbappendaddr_locked(
2006				    &last->inp_socket->so_rcv,
2007				    (struct sockaddr *)&fromsa, n, opts)
2008				    == 0) {
2009					/* should notify about lost packet */
2010					m_freem(n);
2011					if (opts) {
2012						m_freem(opts);
2013					}
2014					SOCKBUF_UNLOCK(
2015					    &last->inp_socket->so_rcv);
2016				} else
2017					sorwakeup_locked(last->inp_socket);
2018				opts = NULL;
2019			}
2020			INP_RUNLOCK(last);
2021		}
2022		last = in6p;
2023	}
2024	INP_INFO_RUNLOCK(&V_ripcbinfo);
2025	if (last != NULL) {
2026		if (last->inp_flags & INP_CONTROLOPTS)
2027			ip6_savecontrol(last, m, &opts);
2028		/* strip intermediate headers */
2029		m_adj(m, off);
2030
2031		/* avoid using mbuf clusters if possible (see above) */
2032		if ((m->m_flags & M_EXT) && m->m_next == NULL &&
2033		    m->m_len <= MHLEN) {
2034			struct mbuf *n;
2035
2036			MGET(n, M_DONTWAIT, m->m_type);
2037			if (n != NULL) {
2038				if (m_dup_pkthdr(n, m, M_NOWAIT)) {
2039					bcopy(m->m_data, n->m_data, m->m_len);
2040					n->m_len = m->m_len;
2041
2042					m_freem(m);
2043					m = n;
2044				} else {
2045					m_freem(n);
2046					n = NULL;
2047				}
2048			}
2049		}
2050		SOCKBUF_LOCK(&last->inp_socket->so_rcv);
2051		if (sbappendaddr_locked(&last->inp_socket->so_rcv,
2052		    (struct sockaddr *)&fromsa, m, opts) == 0) {
2053			m_freem(m);
2054			if (opts)
2055				m_freem(opts);
2056			SOCKBUF_UNLOCK(&last->inp_socket->so_rcv);
2057		} else
2058			sorwakeup_locked(last->inp_socket);
2059		INP_RUNLOCK(last);
2060	} else {
2061		m_freem(m);
2062		IP6STAT_DEC(ip6s_delivered);
2063	}
2064	return IPPROTO_DONE;
2065}
2066
2067/*
2068 * Reflect the ip6 packet back to the source.
2069 * OFF points to the icmp6 header, counted from the top of the mbuf.
2070 */
2071void
2072icmp6_reflect(struct mbuf *m, size_t off)
2073{
2074	INIT_VNET_INET6(curvnet);
2075	struct ip6_hdr *ip6;
2076	struct icmp6_hdr *icmp6;
2077	struct in6_ifaddr *ia;
2078	int plen;
2079	int type, code;
2080	struct ifnet *outif = NULL;
2081	struct in6_addr origdst, *src = NULL;
2082
2083	/* too short to reflect */
2084	if (off < sizeof(struct ip6_hdr)) {
2085		nd6log((LOG_DEBUG,
2086		    "sanity fail: off=%lx, sizeof(ip6)=%lx in %s:%d\n",
2087		    (u_long)off, (u_long)sizeof(struct ip6_hdr),
2088		    __FILE__, __LINE__));
2089		goto bad;
2090	}
2091
2092	/*
2093	 * If there are extra headers between IPv6 and ICMPv6, strip
2094	 * off that header first.
2095	 */
2096#ifdef DIAGNOSTIC
2097	if (sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr) > MHLEN)
2098		panic("assumption failed in icmp6_reflect");
2099#endif
2100	if (off > sizeof(struct ip6_hdr)) {
2101		size_t l;
2102		struct ip6_hdr nip6;
2103
2104		l = off - sizeof(struct ip6_hdr);
2105		m_copydata(m, 0, sizeof(nip6), (caddr_t)&nip6);
2106		m_adj(m, l);
2107		l = sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr);
2108		if (m->m_len < l) {
2109			if ((m = m_pullup(m, l)) == NULL)
2110				return;
2111		}
2112		bcopy((caddr_t)&nip6, mtod(m, caddr_t), sizeof(nip6));
2113	} else /* off == sizeof(struct ip6_hdr) */ {
2114		size_t l;
2115		l = sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr);
2116		if (m->m_len < l) {
2117			if ((m = m_pullup(m, l)) == NULL)
2118				return;
2119		}
2120	}
2121	plen = m->m_pkthdr.len - sizeof(struct ip6_hdr);
2122	ip6 = mtod(m, struct ip6_hdr *);
2123	ip6->ip6_nxt = IPPROTO_ICMPV6;
2124	icmp6 = (struct icmp6_hdr *)(ip6 + 1);
2125	type = icmp6->icmp6_type; /* keep type for statistics */
2126	code = icmp6->icmp6_code; /* ditto. */
2127
2128	origdst = ip6->ip6_dst;
2129	/*
2130	 * ip6_input() drops a packet if its src is multicast.
2131	 * So, the src is never multicast.
2132	 */
2133	ip6->ip6_dst = ip6->ip6_src;
2134
2135	/*
2136	 * If the incoming packet was addressed directly to us (i.e. unicast),
2137	 * use dst as the src for the reply.
2138	 * The IN6_IFF_NOTREADY case should be VERY rare, but is possible
2139	 * (for example) when we encounter an error while forwarding procedure
2140	 * destined to a duplicated address of ours.
2141	 * Note that ip6_getdstifaddr() may fail if we are in an error handling
2142	 * procedure of an outgoing packet of our own, in which case we need
2143	 * to search in the ifaddr list.
2144	 */
2145	if (!IN6_IS_ADDR_MULTICAST(&origdst)) {
2146		if ((ia = ip6_getdstifaddr(m))) {
2147			if (!(ia->ia6_flags &
2148			    (IN6_IFF_ANYCAST|IN6_IFF_NOTREADY)))
2149				src = &ia->ia_addr.sin6_addr;
2150		} else {
2151			struct sockaddr_in6 d;
2152
2153			bzero(&d, sizeof(d));
2154			d.sin6_family = AF_INET6;
2155			d.sin6_len = sizeof(d);
2156			d.sin6_addr = origdst;
2157			ia = (struct in6_ifaddr *)
2158			    ifa_ifwithaddr((struct sockaddr *)&d);
2159			if (ia &&
2160			    !(ia->ia6_flags &
2161			    (IN6_IFF_ANYCAST|IN6_IFF_NOTREADY))) {
2162				src = &ia->ia_addr.sin6_addr;
2163			}
2164		}
2165	}
2166
2167	if (src == NULL) {
2168		int e;
2169		struct sockaddr_in6 sin6;
2170		struct route_in6 ro;
2171
2172		/*
2173		 * This case matches to multicasts, our anycast, or unicasts
2174		 * that we do not own.  Select a source address based on the
2175		 * source address of the erroneous packet.
2176		 */
2177		bzero(&sin6, sizeof(sin6));
2178		sin6.sin6_family = AF_INET6;
2179		sin6.sin6_len = sizeof(sin6);
2180		sin6.sin6_addr = ip6->ip6_dst; /* zone ID should be embedded */
2181
2182		bzero(&ro, sizeof(ro));
2183		src = in6_selectsrc(&sin6, NULL, NULL, &ro, NULL, &outif, &e);
2184		if (ro.ro_rt)
2185			RTFREE(ro.ro_rt); /* XXX: we could use this */
2186		if (src == NULL) {
2187			char ip6buf[INET6_ADDRSTRLEN];
2188			nd6log((LOG_DEBUG,
2189			    "icmp6_reflect: source can't be determined: "
2190			    "dst=%s, error=%d\n",
2191			    ip6_sprintf(ip6buf, &sin6.sin6_addr), e));
2192			goto bad;
2193		}
2194	}
2195
2196	ip6->ip6_src = *src;
2197	ip6->ip6_flow = 0;
2198	ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
2199	ip6->ip6_vfc |= IPV6_VERSION;
2200	ip6->ip6_nxt = IPPROTO_ICMPV6;
2201	if (outif)
2202		ip6->ip6_hlim = ND_IFINFO(outif)->chlim;
2203	else if (m->m_pkthdr.rcvif) {
2204		/* XXX: This may not be the outgoing interface */
2205		ip6->ip6_hlim = ND_IFINFO(m->m_pkthdr.rcvif)->chlim;
2206	} else
2207		ip6->ip6_hlim = V_ip6_defhlim;
2208
2209	icmp6->icmp6_cksum = 0;
2210	icmp6->icmp6_cksum = in6_cksum(m, IPPROTO_ICMPV6,
2211	    sizeof(struct ip6_hdr), plen);
2212
2213	/*
2214	 * XXX option handling
2215	 */
2216
2217	m->m_flags &= ~(M_BCAST|M_MCAST);
2218
2219	ip6_output(m, NULL, NULL, 0, NULL, &outif, NULL);
2220	if (outif)
2221		icmp6_ifoutstat_inc(outif, type, code);
2222
2223	return;
2224
2225 bad:
2226	m_freem(m);
2227	return;
2228}
2229
2230void
2231icmp6_fasttimo(void)
2232{
2233
2234	mld_fasttimo();
2235}
2236
2237void
2238icmp6_slowtimo(void)
2239{
2240
2241	mld_slowtimo();
2242}
2243
2244static const char *
2245icmp6_redirect_diag(struct in6_addr *src6, struct in6_addr *dst6,
2246    struct in6_addr *tgt6)
2247{
2248	static char buf[1024];
2249	char ip6bufs[INET6_ADDRSTRLEN];
2250	char ip6bufd[INET6_ADDRSTRLEN];
2251	char ip6buft[INET6_ADDRSTRLEN];
2252	snprintf(buf, sizeof(buf), "(src=%s dst=%s tgt=%s)",
2253	    ip6_sprintf(ip6bufs, src6), ip6_sprintf(ip6bufd, dst6),
2254	    ip6_sprintf(ip6buft, tgt6));
2255	return buf;
2256}
2257
2258void
2259icmp6_redirect_input(struct mbuf *m, int off)
2260{
2261	INIT_VNET_INET6(curvnet);
2262	struct ifnet *ifp;
2263	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
2264	struct nd_redirect *nd_rd;
2265	int icmp6len = ntohs(ip6->ip6_plen);
2266	char *lladdr = NULL;
2267	int lladdrlen = 0;
2268	u_char *redirhdr = NULL;
2269	int redirhdrlen = 0;
2270	struct rtentry *rt = NULL;
2271	int is_router;
2272	int is_onlink;
2273	struct in6_addr src6 = ip6->ip6_src;
2274	struct in6_addr redtgt6;
2275	struct in6_addr reddst6;
2276	union nd_opts ndopts;
2277	char ip6buf[INET6_ADDRSTRLEN];
2278
2279	if (!m)
2280		return;
2281
2282	ifp = m->m_pkthdr.rcvif;
2283
2284	if (!ifp)
2285		return;
2286
2287	/* XXX if we are router, we don't update route by icmp6 redirect */
2288	if (V_ip6_forwarding)
2289		goto freeit;
2290	if (!V_icmp6_rediraccept)
2291		goto freeit;
2292
2293#ifndef PULLDOWN_TEST
2294	IP6_EXTHDR_CHECK(m, off, icmp6len,);
2295	nd_rd = (struct nd_redirect *)((caddr_t)ip6 + off);
2296#else
2297	IP6_EXTHDR_GET(nd_rd, struct nd_redirect *, m, off, icmp6len);
2298	if (nd_rd == NULL) {
2299		ICMP6STAT_INC(icp6s_tooshort);
2300		return;
2301	}
2302#endif
2303	redtgt6 = nd_rd->nd_rd_target;
2304	reddst6 = nd_rd->nd_rd_dst;
2305
2306	if (in6_setscope(&redtgt6, m->m_pkthdr.rcvif, NULL) ||
2307	    in6_setscope(&reddst6, m->m_pkthdr.rcvif, NULL)) {
2308		goto freeit;
2309	}
2310
2311	/* validation */
2312	if (!IN6_IS_ADDR_LINKLOCAL(&src6)) {
2313		nd6log((LOG_ERR,
2314		    "ICMP6 redirect sent from %s rejected; "
2315		    "must be from linklocal\n",
2316		    ip6_sprintf(ip6buf, &src6)));
2317		goto bad;
2318	}
2319	if (ip6->ip6_hlim != 255) {
2320		nd6log((LOG_ERR,
2321		    "ICMP6 redirect sent from %s rejected; "
2322		    "hlim=%d (must be 255)\n",
2323		    ip6_sprintf(ip6buf, &src6), ip6->ip6_hlim));
2324		goto bad;
2325	}
2326    {
2327	/* ip6->ip6_src must be equal to gw for icmp6->icmp6_reddst */
2328	struct sockaddr_in6 sin6;
2329	struct in6_addr *gw6;
2330
2331	bzero(&sin6, sizeof(sin6));
2332	sin6.sin6_family = AF_INET6;
2333	sin6.sin6_len = sizeof(struct sockaddr_in6);
2334	bcopy(&reddst6, &sin6.sin6_addr, sizeof(reddst6));
2335	rt = rtalloc1((struct sockaddr *)&sin6, 0, 0UL);
2336	if (rt) {
2337		if (rt->rt_gateway == NULL ||
2338		    rt->rt_gateway->sa_family != AF_INET6) {
2339			nd6log((LOG_ERR,
2340			    "ICMP6 redirect rejected; no route "
2341			    "with inet6 gateway found for redirect dst: %s\n",
2342			    icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2343			RTFREE_LOCKED(rt);
2344			goto bad;
2345		}
2346
2347		gw6 = &(((struct sockaddr_in6 *)rt->rt_gateway)->sin6_addr);
2348		if (bcmp(&src6, gw6, sizeof(struct in6_addr)) != 0) {
2349			nd6log((LOG_ERR,
2350			    "ICMP6 redirect rejected; "
2351			    "not equal to gw-for-src=%s (must be same): "
2352			    "%s\n",
2353			    ip6_sprintf(ip6buf, gw6),
2354			    icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2355			RTFREE_LOCKED(rt);
2356			goto bad;
2357		}
2358	} else {
2359		nd6log((LOG_ERR,
2360		    "ICMP6 redirect rejected; "
2361		    "no route found for redirect dst: %s\n",
2362		    icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2363		goto bad;
2364	}
2365	RTFREE_LOCKED(rt);
2366	rt = NULL;
2367    }
2368	if (IN6_IS_ADDR_MULTICAST(&reddst6)) {
2369		nd6log((LOG_ERR,
2370		    "ICMP6 redirect rejected; "
2371		    "redirect dst must be unicast: %s\n",
2372		    icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2373		goto bad;
2374	}
2375
2376	is_router = is_onlink = 0;
2377	if (IN6_IS_ADDR_LINKLOCAL(&redtgt6))
2378		is_router = 1;	/* router case */
2379	if (bcmp(&redtgt6, &reddst6, sizeof(redtgt6)) == 0)
2380		is_onlink = 1;	/* on-link destination case */
2381	if (!is_router && !is_onlink) {
2382		nd6log((LOG_ERR,
2383		    "ICMP6 redirect rejected; "
2384		    "neither router case nor onlink case: %s\n",
2385		    icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2386		goto bad;
2387	}
2388	/* validation passed */
2389
2390	icmp6len -= sizeof(*nd_rd);
2391	nd6_option_init(nd_rd + 1, icmp6len, &ndopts);
2392	if (nd6_options(&ndopts) < 0) {
2393		nd6log((LOG_INFO, "icmp6_redirect_input: "
2394		    "invalid ND option, rejected: %s\n",
2395		    icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2396		/* nd6_options have incremented stats */
2397		goto freeit;
2398	}
2399
2400	if (ndopts.nd_opts_tgt_lladdr) {
2401		lladdr = (char *)(ndopts.nd_opts_tgt_lladdr + 1);
2402		lladdrlen = ndopts.nd_opts_tgt_lladdr->nd_opt_len << 3;
2403	}
2404
2405	if (ndopts.nd_opts_rh) {
2406		redirhdrlen = ndopts.nd_opts_rh->nd_opt_rh_len;
2407		redirhdr = (u_char *)(ndopts.nd_opts_rh + 1); /* xxx */
2408	}
2409
2410	if (lladdr && ((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
2411		nd6log((LOG_INFO,
2412		    "icmp6_redirect_input: lladdrlen mismatch for %s "
2413		    "(if %d, icmp6 packet %d): %s\n",
2414		    ip6_sprintf(ip6buf, &redtgt6),
2415		    ifp->if_addrlen, lladdrlen - 2,
2416		    icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2417		goto bad;
2418	}
2419
2420	/* RFC 2461 8.3 */
2421	nd6_cache_lladdr(ifp, &redtgt6, lladdr, lladdrlen, ND_REDIRECT,
2422	    is_onlink ? ND_REDIRECT_ONLINK : ND_REDIRECT_ROUTER);
2423
2424	if (!is_onlink) {	/* better router case.  perform rtredirect. */
2425		/* perform rtredirect */
2426		struct sockaddr_in6 sdst;
2427		struct sockaddr_in6 sgw;
2428		struct sockaddr_in6 ssrc;
2429
2430		bzero(&sdst, sizeof(sdst));
2431		bzero(&sgw, sizeof(sgw));
2432		bzero(&ssrc, sizeof(ssrc));
2433		sdst.sin6_family = sgw.sin6_family = ssrc.sin6_family = AF_INET6;
2434		sdst.sin6_len = sgw.sin6_len = ssrc.sin6_len =
2435			sizeof(struct sockaddr_in6);
2436		bcopy(&redtgt6, &sgw.sin6_addr, sizeof(struct in6_addr));
2437		bcopy(&reddst6, &sdst.sin6_addr, sizeof(struct in6_addr));
2438		bcopy(&src6, &ssrc.sin6_addr, sizeof(struct in6_addr));
2439		rtredirect((struct sockaddr *)&sdst, (struct sockaddr *)&sgw,
2440		    (struct sockaddr *)NULL, RTF_GATEWAY | RTF_HOST,
2441		    (struct sockaddr *)&ssrc);
2442	}
2443	/* finally update cached route in each socket via pfctlinput */
2444    {
2445	struct sockaddr_in6 sdst;
2446
2447	bzero(&sdst, sizeof(sdst));
2448	sdst.sin6_family = AF_INET6;
2449	sdst.sin6_len = sizeof(struct sockaddr_in6);
2450	bcopy(&reddst6, &sdst.sin6_addr, sizeof(struct in6_addr));
2451	pfctlinput(PRC_REDIRECT_HOST, (struct sockaddr *)&sdst);
2452#ifdef IPSEC
2453	key_sa_routechange((struct sockaddr *)&sdst);
2454#endif /* IPSEC */
2455    }
2456
2457 freeit:
2458	m_freem(m);
2459	return;
2460
2461 bad:
2462	ICMP6STAT_INC(icp6s_badredirect);
2463	m_freem(m);
2464}
2465
2466void
2467icmp6_redirect_output(struct mbuf *m0, struct rtentry *rt)
2468{
2469	INIT_VNET_INET6(curvnet);
2470	struct ifnet *ifp;	/* my outgoing interface */
2471	struct in6_addr *ifp_ll6;
2472	struct in6_addr *router_ll6;
2473	struct ip6_hdr *sip6;	/* m0 as struct ip6_hdr */
2474	struct mbuf *m = NULL;	/* newly allocated one */
2475	struct ip6_hdr *ip6;	/* m as struct ip6_hdr */
2476	struct nd_redirect *nd_rd;
2477	struct llentry *ln = NULL;
2478	size_t maxlen;
2479	u_char *p;
2480	struct ifnet *outif = NULL;
2481	struct sockaddr_in6 src_sa;
2482
2483	icmp6_errcount(&V_icmp6stat.icp6s_outerrhist, ND_REDIRECT, 0);
2484
2485	/* if we are not router, we don't send icmp6 redirect */
2486	if (!V_ip6_forwarding)
2487		goto fail;
2488
2489	/* sanity check */
2490	if (!m0 || !rt || !(rt->rt_flags & RTF_UP) || !(ifp = rt->rt_ifp))
2491		goto fail;
2492
2493	/*
2494	 * Address check:
2495	 *  the source address must identify a neighbor, and
2496	 *  the destination address must not be a multicast address
2497	 *  [RFC 2461, sec 8.2]
2498	 */
2499	sip6 = mtod(m0, struct ip6_hdr *);
2500	bzero(&src_sa, sizeof(src_sa));
2501	src_sa.sin6_family = AF_INET6;
2502	src_sa.sin6_len = sizeof(src_sa);
2503	src_sa.sin6_addr = sip6->ip6_src;
2504	if (nd6_is_addr_neighbor(&src_sa, ifp) == 0)
2505		goto fail;
2506	if (IN6_IS_ADDR_MULTICAST(&sip6->ip6_dst))
2507		goto fail;	/* what should we do here? */
2508
2509	/* rate limit */
2510	if (icmp6_ratelimit(&sip6->ip6_src, ND_REDIRECT, 0))
2511		goto fail;
2512
2513	/*
2514	 * Since we are going to append up to 1280 bytes (= IPV6_MMTU),
2515	 * we almost always ask for an mbuf cluster for simplicity.
2516	 * (MHLEN < IPV6_MMTU is almost always true)
2517	 */
2518#if IPV6_MMTU >= MCLBYTES
2519# error assumption failed about IPV6_MMTU and MCLBYTES
2520#endif
2521	MGETHDR(m, M_DONTWAIT, MT_HEADER);
2522	if (m && IPV6_MMTU >= MHLEN)
2523		MCLGET(m, M_DONTWAIT);
2524	if (!m)
2525		goto fail;
2526	m->m_pkthdr.rcvif = NULL;
2527	m->m_len = 0;
2528	maxlen = M_TRAILINGSPACE(m);
2529	maxlen = min(IPV6_MMTU, maxlen);
2530	/* just for safety */
2531	if (maxlen < sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr) +
2532	    ((sizeof(struct nd_opt_hdr) + ifp->if_addrlen + 7) & ~7)) {
2533		goto fail;
2534	}
2535
2536	{
2537		/* get ip6 linklocal address for ifp(my outgoing interface). */
2538		struct in6_ifaddr *ia;
2539		if ((ia = in6ifa_ifpforlinklocal(ifp,
2540						 IN6_IFF_NOTREADY|
2541						 IN6_IFF_ANYCAST)) == NULL)
2542			goto fail;
2543		ifp_ll6 = &ia->ia_addr.sin6_addr;
2544	}
2545
2546	/* get ip6 linklocal address for the router. */
2547	if (rt->rt_gateway && (rt->rt_flags & RTF_GATEWAY)) {
2548		struct sockaddr_in6 *sin6;
2549		sin6 = (struct sockaddr_in6 *)rt->rt_gateway;
2550		router_ll6 = &sin6->sin6_addr;
2551		if (!IN6_IS_ADDR_LINKLOCAL(router_ll6))
2552			router_ll6 = (struct in6_addr *)NULL;
2553	} else
2554		router_ll6 = (struct in6_addr *)NULL;
2555
2556	/* ip6 */
2557	ip6 = mtod(m, struct ip6_hdr *);
2558	ip6->ip6_flow = 0;
2559	ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
2560	ip6->ip6_vfc |= IPV6_VERSION;
2561	/* ip6->ip6_plen will be set later */
2562	ip6->ip6_nxt = IPPROTO_ICMPV6;
2563	ip6->ip6_hlim = 255;
2564	/* ip6->ip6_src must be linklocal addr for my outgoing if. */
2565	bcopy(ifp_ll6, &ip6->ip6_src, sizeof(struct in6_addr));
2566	bcopy(&sip6->ip6_src, &ip6->ip6_dst, sizeof(struct in6_addr));
2567
2568	/* ND Redirect */
2569	nd_rd = (struct nd_redirect *)(ip6 + 1);
2570	nd_rd->nd_rd_type = ND_REDIRECT;
2571	nd_rd->nd_rd_code = 0;
2572	nd_rd->nd_rd_reserved = 0;
2573	if (rt->rt_flags & RTF_GATEWAY) {
2574		/*
2575		 * nd_rd->nd_rd_target must be a link-local address in
2576		 * better router cases.
2577		 */
2578		if (!router_ll6)
2579			goto fail;
2580		bcopy(router_ll6, &nd_rd->nd_rd_target,
2581		    sizeof(nd_rd->nd_rd_target));
2582		bcopy(&sip6->ip6_dst, &nd_rd->nd_rd_dst,
2583		    sizeof(nd_rd->nd_rd_dst));
2584	} else {
2585		/* make sure redtgt == reddst */
2586		bcopy(&sip6->ip6_dst, &nd_rd->nd_rd_target,
2587		    sizeof(nd_rd->nd_rd_target));
2588		bcopy(&sip6->ip6_dst, &nd_rd->nd_rd_dst,
2589		    sizeof(nd_rd->nd_rd_dst));
2590	}
2591
2592	p = (u_char *)(nd_rd + 1);
2593
2594	if (!router_ll6)
2595		goto nolladdropt;
2596
2597	{
2598		/* target lladdr option */
2599		int len;
2600		struct nd_opt_hdr *nd_opt;
2601		char *lladdr;
2602
2603		IF_AFDATA_LOCK(ifp);
2604		ln = nd6_lookup(router_ll6, 0, ifp);
2605		IF_AFDATA_UNLOCK(ifp);
2606		if (ln == NULL)
2607			goto nolladdropt;
2608
2609		len = sizeof(*nd_opt) + ifp->if_addrlen;
2610		len = (len + 7) & ~7;	/* round by 8 */
2611		/* safety check */
2612		if (len + (p - (u_char *)ip6) > maxlen)
2613			goto nolladdropt;
2614
2615		if (ln->la_flags & LLE_VALID) {
2616			nd_opt = (struct nd_opt_hdr *)p;
2617			nd_opt->nd_opt_type = ND_OPT_TARGET_LINKADDR;
2618			nd_opt->nd_opt_len = len >> 3;
2619			lladdr = (char *)(nd_opt + 1);
2620			bcopy(&ln->ll_addr, lladdr, ifp->if_addrlen);
2621			p += len;
2622		}
2623	}
2624nolladdropt:
2625	if (ln != NULL)
2626		LLE_RUNLOCK(ln);
2627
2628	m->m_pkthdr.len = m->m_len = p - (u_char *)ip6;
2629
2630	/* just to be safe */
2631#ifdef M_DECRYPTED	/*not openbsd*/
2632	if (m0->m_flags & M_DECRYPTED)
2633		goto noredhdropt;
2634#endif
2635	if (p - (u_char *)ip6 > maxlen)
2636		goto noredhdropt;
2637
2638	{
2639		/* redirected header option */
2640		int len;
2641		struct nd_opt_rd_hdr *nd_opt_rh;
2642
2643		/*
2644		 * compute the maximum size for icmp6 redirect header option.
2645		 * XXX room for auth header?
2646		 */
2647		len = maxlen - (p - (u_char *)ip6);
2648		len &= ~7;
2649
2650		/* This is just for simplicity. */
2651		if (m0->m_pkthdr.len != m0->m_len) {
2652			if (m0->m_next) {
2653				m_freem(m0->m_next);
2654				m0->m_next = NULL;
2655			}
2656			m0->m_pkthdr.len = m0->m_len;
2657		}
2658
2659		/*
2660		 * Redirected header option spec (RFC2461 4.6.3) talks nothing
2661		 * about padding/truncate rule for the original IP packet.
2662		 * From the discussion on IPv6imp in Feb 1999,
2663		 * the consensus was:
2664		 * - "attach as much as possible" is the goal
2665		 * - pad if not aligned (original size can be guessed by
2666		 *   original ip6 header)
2667		 * Following code adds the padding if it is simple enough,
2668		 * and truncates if not.
2669		 */
2670		if (m0->m_next || m0->m_pkthdr.len != m0->m_len)
2671			panic("assumption failed in %s:%d", __FILE__,
2672			    __LINE__);
2673
2674		if (len - sizeof(*nd_opt_rh) < m0->m_pkthdr.len) {
2675			/* not enough room, truncate */
2676			m0->m_pkthdr.len = m0->m_len = len -
2677			    sizeof(*nd_opt_rh);
2678		} else {
2679			/* enough room, pad or truncate */
2680			size_t extra;
2681
2682			extra = m0->m_pkthdr.len % 8;
2683			if (extra) {
2684				/* pad if easy enough, truncate if not */
2685				if (8 - extra <= M_TRAILINGSPACE(m0)) {
2686					/* pad */
2687					m0->m_len += (8 - extra);
2688					m0->m_pkthdr.len += (8 - extra);
2689				} else {
2690					/* truncate */
2691					m0->m_pkthdr.len -= extra;
2692					m0->m_len -= extra;
2693				}
2694			}
2695			len = m0->m_pkthdr.len + sizeof(*nd_opt_rh);
2696			m0->m_pkthdr.len = m0->m_len = len -
2697			    sizeof(*nd_opt_rh);
2698		}
2699
2700		nd_opt_rh = (struct nd_opt_rd_hdr *)p;
2701		bzero(nd_opt_rh, sizeof(*nd_opt_rh));
2702		nd_opt_rh->nd_opt_rh_type = ND_OPT_REDIRECTED_HEADER;
2703		nd_opt_rh->nd_opt_rh_len = len >> 3;
2704		p += sizeof(*nd_opt_rh);
2705		m->m_pkthdr.len = m->m_len = p - (u_char *)ip6;
2706
2707		/* connect m0 to m */
2708		m_tag_delete_chain(m0, NULL);
2709		m0->m_flags &= ~M_PKTHDR;
2710		m->m_next = m0;
2711		m->m_pkthdr.len = m->m_len + m0->m_len;
2712		m0 = NULL;
2713	}
2714noredhdropt:;
2715	if (m0) {
2716		m_freem(m0);
2717		m0 = NULL;
2718	}
2719
2720	/* XXX: clear embedded link IDs in the inner header */
2721	in6_clearscope(&sip6->ip6_src);
2722	in6_clearscope(&sip6->ip6_dst);
2723	in6_clearscope(&nd_rd->nd_rd_target);
2724	in6_clearscope(&nd_rd->nd_rd_dst);
2725
2726	ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(struct ip6_hdr));
2727
2728	nd_rd->nd_rd_cksum = 0;
2729	nd_rd->nd_rd_cksum = in6_cksum(m, IPPROTO_ICMPV6,
2730	    sizeof(*ip6), ntohs(ip6->ip6_plen));
2731
2732	/* send the packet to outside... */
2733	ip6_output(m, NULL, NULL, 0, NULL, &outif, NULL);
2734	if (outif) {
2735		icmp6_ifstat_inc(outif, ifs6_out_msg);
2736		icmp6_ifstat_inc(outif, ifs6_out_redirect);
2737	}
2738	ICMP6STAT_INC(icp6s_outhist[ND_REDIRECT]);
2739
2740	return;
2741
2742fail:
2743	if (m)
2744		m_freem(m);
2745	if (m0)
2746		m_freem(m0);
2747}
2748
2749/*
2750 * ICMPv6 socket option processing.
2751 */
2752int
2753icmp6_ctloutput(struct socket *so, struct sockopt *sopt)
2754{
2755	int error = 0;
2756	int optlen;
2757	struct inpcb *inp = sotoinpcb(so);
2758	int level, op, optname;
2759
2760	if (sopt) {
2761		level = sopt->sopt_level;
2762		op = sopt->sopt_dir;
2763		optname = sopt->sopt_name;
2764		optlen = sopt->sopt_valsize;
2765	} else
2766		level = op = optname = optlen = 0;
2767
2768	if (level != IPPROTO_ICMPV6) {
2769		return EINVAL;
2770	}
2771
2772	switch (op) {
2773	case PRCO_SETOPT:
2774		switch (optname) {
2775		case ICMP6_FILTER:
2776		    {
2777			struct icmp6_filter ic6f;
2778
2779			if (optlen != sizeof(ic6f)) {
2780				error = EMSGSIZE;
2781				break;
2782			}
2783			error = sooptcopyin(sopt, &ic6f, optlen, optlen);
2784			if (error == 0) {
2785				INP_WLOCK(inp);
2786				*inp->in6p_icmp6filt = ic6f;
2787				INP_WUNLOCK(inp);
2788			}
2789			break;
2790		    }
2791
2792		default:
2793			error = ENOPROTOOPT;
2794			break;
2795		}
2796		break;
2797
2798	case PRCO_GETOPT:
2799		switch (optname) {
2800		case ICMP6_FILTER:
2801		    {
2802			struct icmp6_filter ic6f;
2803
2804			INP_RLOCK(inp);
2805			ic6f = *inp->in6p_icmp6filt;
2806			INP_RUNLOCK(inp);
2807			error = sooptcopyout(sopt, &ic6f, sizeof(ic6f));
2808			break;
2809		    }
2810
2811		default:
2812			error = ENOPROTOOPT;
2813			break;
2814		}
2815		break;
2816	}
2817
2818	return (error);
2819}
2820
2821/*
2822 * Perform rate limit check.
2823 * Returns 0 if it is okay to send the icmp6 packet.
2824 * Returns 1 if the router SHOULD NOT send this icmp6 packet due to rate
2825 * limitation.
2826 *
2827 * XXX per-destination/type check necessary?
2828 *
2829 * dst - not used at this moment
2830 * type - not used at this moment
2831 * code - not used at this moment
2832 */
2833static int
2834icmp6_ratelimit(const struct in6_addr *dst, const int type,
2835    const int code)
2836{
2837	INIT_VNET_INET6(curvnet);
2838	int ret;
2839
2840	ret = 0;	/* okay to send */
2841
2842	/* PPS limit */
2843	if (!ppsratecheck(&V_icmp6errppslim_last, &V_icmp6errpps_count,
2844	    V_icmp6errppslim)) {
2845		/* The packet is subject to rate limit */
2846		ret++;
2847	}
2848
2849	return ret;
2850}
2851