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