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