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