icmp6.c revision 174510
150479Speter/*-
236332Sdes * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
336332Sdes * All rights reserved.
474816Sru *
536332Sdes * Redistribution and use in source and binary forms, with or without
636332Sdes * 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 174510 2007-12-10 16:03:40Z obrien $");
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 __P((struct icmp6errstat *, int, int));
121static int icmp6_rip6_input __P((struct mbuf **, int));
122static int icmp6_ratelimit __P((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 __P((struct mbuf *, int));
126static struct mbuf *ni6_nametodns __P((const char *, int, int));
127static int ni6_dnsmatch __P((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 __P((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			if (maxhlen > hostnamelen)
700				maxhlen = hostnamelen;
701			/*
702			 * Copy IPv6 and ICMPv6 only.
703			 */
704			nip6 = mtod(n, struct ip6_hdr *);
705			bcopy(ip6, nip6, sizeof(struct ip6_hdr));
706			nicmp6 = (struct icmp6_hdr *)(nip6 + 1);
707			bcopy(icmp6, nicmp6, sizeof(struct icmp6_hdr));
708			p = (u_char *)(nicmp6 + 1);
709			bzero(p, 4);
710			bcopy(hostname, p + 4, maxhlen); /* meaningless TTL */
711			noff = sizeof(struct ip6_hdr);
712			n->m_pkthdr.len = n->m_len = sizeof(struct ip6_hdr) +
713				sizeof(struct icmp6_hdr) + 4 + maxhlen;
714			nicmp6->icmp6_type = ICMP6_WRUREPLY;
715			nicmp6->icmp6_code = 0;
716		}
717#undef hostnamelen
718		if (n) {
719			icmp6stat.icp6s_reflect++;
720			icmp6stat.icp6s_outhist[ICMP6_WRUREPLY]++;
721			icmp6_reflect(n, noff);
722		}
723		break;
724	    }
725
726	case ICMP6_WRUREPLY:
727		if (code != 0)
728			goto badcode;
729		break;
730
731	case ND_ROUTER_SOLICIT:
732		icmp6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_routersolicit);
733		if (code != 0)
734			goto badcode;
735		if (icmp6len < sizeof(struct nd_router_solicit))
736			goto badlen;
737		if ((n = m_copym(m, 0, M_COPYALL, M_DONTWAIT)) == NULL) {
738			/* give up local */
739			nd6_rs_input(m, off, icmp6len);
740			m = NULL;
741			goto freeit;
742		}
743		nd6_rs_input(n, off, icmp6len);
744		/* m stays. */
745		break;
746
747	case ND_ROUTER_ADVERT:
748		icmp6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_routeradvert);
749		if (code != 0)
750			goto badcode;
751		if (icmp6len < sizeof(struct nd_router_advert))
752			goto badlen;
753		if ((n = m_copym(m, 0, M_COPYALL, M_DONTWAIT)) == NULL) {
754			/* give up local */
755			nd6_ra_input(m, off, icmp6len);
756			m = NULL;
757			goto freeit;
758		}
759		nd6_ra_input(n, off, icmp6len);
760		/* m stays. */
761		break;
762
763	case ND_NEIGHBOR_SOLICIT:
764		icmp6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_neighborsolicit);
765		if (code != 0)
766			goto badcode;
767		if (icmp6len < sizeof(struct nd_neighbor_solicit))
768			goto badlen;
769		if ((n = m_copym(m, 0, M_COPYALL, M_DONTWAIT)) == NULL) {
770			/* give up local */
771			nd6_ns_input(m, off, icmp6len);
772			m = NULL;
773			goto freeit;
774		}
775		nd6_ns_input(n, off, icmp6len);
776		/* m stays. */
777		break;
778
779	case ND_NEIGHBOR_ADVERT:
780		icmp6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_neighboradvert);
781		if (code != 0)
782			goto badcode;
783		if (icmp6len < sizeof(struct nd_neighbor_advert))
784			goto badlen;
785		if ((n = m_copym(m, 0, M_COPYALL, M_DONTWAIT)) == NULL) {
786			/* give up local */
787			nd6_na_input(m, off, icmp6len);
788			m = NULL;
789			goto freeit;
790		}
791		nd6_na_input(n, off, icmp6len);
792		/* m stays. */
793		break;
794
795	case ND_REDIRECT:
796		icmp6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_redirect);
797		if (code != 0)
798			goto badcode;
799		if (icmp6len < sizeof(struct nd_redirect))
800			goto badlen;
801		if ((n = m_copym(m, 0, M_COPYALL, M_DONTWAIT)) == NULL) {
802			/* give up local */
803			icmp6_redirect_input(m, off);
804			m = NULL;
805			goto freeit;
806		}
807		icmp6_redirect_input(n, off);
808		/* m stays. */
809		break;
810
811	case ICMP6_ROUTER_RENUMBERING:
812		if (code != ICMP6_ROUTER_RENUMBERING_COMMAND &&
813		    code != ICMP6_ROUTER_RENUMBERING_RESULT)
814			goto badcode;
815		if (icmp6len < sizeof(struct icmp6_router_renum))
816			goto badlen;
817		break;
818
819	default:
820		nd6log((LOG_DEBUG,
821		    "icmp6_input: unknown type %d(src=%s, dst=%s, ifid=%d)\n",
822		    icmp6->icmp6_type, ip6_sprintf(ip6bufs, &ip6->ip6_src),
823		    ip6_sprintf(ip6bufd, &ip6->ip6_dst),
824		    m->m_pkthdr.rcvif ? m->m_pkthdr.rcvif->if_index : 0));
825		if (icmp6->icmp6_type < ICMP6_ECHO_REQUEST) {
826			/* ICMPv6 error: MUST deliver it by spec... */
827			code = PRC_NCMDS;
828			/* deliver */
829		} else {
830			/* ICMPv6 informational: MUST not deliver */
831			break;
832		}
833	deliver:
834		if (icmp6_notify_error(&m, off, icmp6len, code)) {
835			/* In this case, m should've been freed. */
836			return (IPPROTO_DONE);
837		}
838		break;
839
840	badcode:
841		icmp6stat.icp6s_badcode++;
842		break;
843
844	badlen:
845		icmp6stat.icp6s_badlen++;
846		break;
847	}
848
849	/* deliver the packet to appropriate sockets */
850	icmp6_rip6_input(&m, *offp);
851
852	return IPPROTO_DONE;
853
854 freeit:
855	m_freem(m);
856	return IPPROTO_DONE;
857}
858
859static int
860icmp6_notify_error(struct mbuf **mp, int off, int icmp6len, int code)
861{
862	struct mbuf *m = *mp;
863	struct icmp6_hdr *icmp6;
864	struct ip6_hdr *eip6;
865	u_int32_t notifymtu;
866	struct sockaddr_in6 icmp6src, icmp6dst;
867
868	if (icmp6len < sizeof(struct icmp6_hdr) + sizeof(struct ip6_hdr)) {
869		icmp6stat.icp6s_tooshort++;
870		goto freeit;
871	}
872#ifndef PULLDOWN_TEST
873	IP6_EXTHDR_CHECK(m, off,
874	    sizeof(struct icmp6_hdr) + sizeof(struct ip6_hdr), -1);
875	icmp6 = (struct icmp6_hdr *)(mtod(m, caddr_t) + off);
876#else
877	IP6_EXTHDR_GET(icmp6, struct icmp6_hdr *, m, off,
878	    sizeof(*icmp6) + sizeof(struct ip6_hdr));
879	if (icmp6 == NULL) {
880		icmp6stat.icp6s_tooshort++;
881		return (-1);
882	}
883#endif
884	eip6 = (struct ip6_hdr *)(icmp6 + 1);
885
886	/* Detect the upper level protocol */
887	{
888		void (*ctlfunc) __P((int, struct sockaddr *, void *));
889		u_int8_t nxt = eip6->ip6_nxt;
890		int eoff = off + sizeof(struct icmp6_hdr) +
891		    sizeof(struct ip6_hdr);
892		struct ip6ctlparam ip6cp;
893		struct in6_addr *finaldst = NULL;
894		int icmp6type = icmp6->icmp6_type;
895		struct ip6_frag *fh;
896		struct ip6_rthdr *rth;
897		struct ip6_rthdr0 *rth0;
898		int rthlen;
899
900		while (1) { /* XXX: should avoid infinite loop explicitly? */
901			struct ip6_ext *eh;
902
903			switch (nxt) {
904			case IPPROTO_HOPOPTS:
905			case IPPROTO_DSTOPTS:
906			case IPPROTO_AH:
907#ifndef PULLDOWN_TEST
908				IP6_EXTHDR_CHECK(m, 0,
909				    eoff + sizeof(struct ip6_ext), -1);
910				eh = (struct ip6_ext *)(mtod(m, caddr_t) + eoff);
911#else
912				IP6_EXTHDR_GET(eh, struct ip6_ext *, m,
913				    eoff, sizeof(*eh));
914				if (eh == NULL) {
915					icmp6stat.icp6s_tooshort++;
916					return (-1);
917				}
918#endif
919
920				if (nxt == IPPROTO_AH)
921					eoff += (eh->ip6e_len + 2) << 2;
922				else
923					eoff += (eh->ip6e_len + 1) << 3;
924				nxt = eh->ip6e_nxt;
925				break;
926			case IPPROTO_ROUTING:
927				/*
928				 * When the erroneous packet contains a
929				 * routing header, we should examine the
930				 * header to determine the final destination.
931				 * Otherwise, we can't properly update
932				 * information that depends on the final
933				 * destination (e.g. path MTU).
934				 */
935#ifndef PULLDOWN_TEST
936				IP6_EXTHDR_CHECK(m, 0, eoff + sizeof(*rth), -1);
937				rth = (struct ip6_rthdr *)
938				    (mtod(m, caddr_t) + eoff);
939#else
940				IP6_EXTHDR_GET(rth, struct ip6_rthdr *, m,
941				    eoff, sizeof(*rth));
942				if (rth == NULL) {
943					icmp6stat.icp6s_tooshort++;
944					return (-1);
945				}
946#endif
947				rthlen = (rth->ip6r_len + 1) << 3;
948				/*
949				 * XXX: currently there is no
950				 * officially defined type other
951				 * than type-0.
952				 * Note that if the segment left field
953				 * is 0, all intermediate hops must
954				 * have been passed.
955				 */
956				if (rth->ip6r_segleft &&
957				    rth->ip6r_type == IPV6_RTHDR_TYPE_0) {
958					int hops;
959
960#ifndef PULLDOWN_TEST
961					IP6_EXTHDR_CHECK(m, 0, eoff + rthlen, -1);
962					rth0 = (struct ip6_rthdr0 *)
963					    (mtod(m, caddr_t) + eoff);
964#else
965					IP6_EXTHDR_GET(rth0,
966					    struct ip6_rthdr0 *, m,
967					    eoff, rthlen);
968					if (rth0 == NULL) {
969						icmp6stat.icp6s_tooshort++;
970						return (-1);
971					}
972#endif
973					/* just ignore a bogus header */
974					if ((rth0->ip6r0_len % 2) == 0 &&
975					    (hops = rth0->ip6r0_len/2))
976						finaldst = (struct in6_addr *)(rth0 + 1) + (hops - 1);
977				}
978				eoff += rthlen;
979				nxt = rth->ip6r_nxt;
980				break;
981			case IPPROTO_FRAGMENT:
982#ifndef PULLDOWN_TEST
983				IP6_EXTHDR_CHECK(m, 0, eoff +
984				    sizeof(struct ip6_frag), -1);
985				fh = (struct ip6_frag *)(mtod(m, caddr_t) +
986				    eoff);
987#else
988				IP6_EXTHDR_GET(fh, struct ip6_frag *, m,
989				    eoff, sizeof(*fh));
990				if (fh == NULL) {
991					icmp6stat.icp6s_tooshort++;
992					return (-1);
993				}
994#endif
995				/*
996				 * Data after a fragment header is meaningless
997				 * unless it is the first fragment, but
998				 * we'll go to the notify label for path MTU
999				 * discovery.
1000				 */
1001				if (fh->ip6f_offlg & IP6F_OFF_MASK)
1002					goto notify;
1003
1004				eoff += sizeof(struct ip6_frag);
1005				nxt = fh->ip6f_nxt;
1006				break;
1007			default:
1008				/*
1009				 * This case includes ESP and the No Next
1010				 * Header.  In such cases going to the notify
1011				 * label does not have any meaning
1012				 * (i.e. ctlfunc will be NULL), but we go
1013				 * anyway since we might have to update
1014				 * path MTU information.
1015				 */
1016				goto notify;
1017			}
1018		}
1019	  notify:
1020#ifndef PULLDOWN_TEST
1021		icmp6 = (struct icmp6_hdr *)(mtod(m, caddr_t) + off);
1022#else
1023		IP6_EXTHDR_GET(icmp6, struct icmp6_hdr *, m, off,
1024		    sizeof(*icmp6) + sizeof(struct ip6_hdr));
1025		if (icmp6 == NULL) {
1026			icmp6stat.icp6s_tooshort++;
1027			return (-1);
1028		}
1029#endif
1030
1031		/*
1032		 * retrieve parameters from the inner IPv6 header, and convert
1033		 * them into sockaddr structures.
1034		 * XXX: there is no guarantee that the source or destination
1035		 * addresses of the inner packet are in the same scope as
1036		 * the addresses of the icmp packet.  But there is no other
1037		 * way to determine the zone.
1038		 */
1039		eip6 = (struct ip6_hdr *)(icmp6 + 1);
1040
1041		bzero(&icmp6dst, sizeof(icmp6dst));
1042		icmp6dst.sin6_len = sizeof(struct sockaddr_in6);
1043		icmp6dst.sin6_family = AF_INET6;
1044		if (finaldst == NULL)
1045			icmp6dst.sin6_addr = eip6->ip6_dst;
1046		else
1047			icmp6dst.sin6_addr = *finaldst;
1048		if (in6_setscope(&icmp6dst.sin6_addr, m->m_pkthdr.rcvif, NULL))
1049			goto freeit;
1050		bzero(&icmp6src, sizeof(icmp6src));
1051		icmp6src.sin6_len = sizeof(struct sockaddr_in6);
1052		icmp6src.sin6_family = AF_INET6;
1053		icmp6src.sin6_addr = eip6->ip6_src;
1054		if (in6_setscope(&icmp6src.sin6_addr, m->m_pkthdr.rcvif, NULL))
1055			goto freeit;
1056		icmp6src.sin6_flowinfo =
1057		    (eip6->ip6_flow & IPV6_FLOWLABEL_MASK);
1058
1059		if (finaldst == NULL)
1060			finaldst = &eip6->ip6_dst;
1061		ip6cp.ip6c_m = m;
1062		ip6cp.ip6c_icmp6 = icmp6;
1063		ip6cp.ip6c_ip6 = (struct ip6_hdr *)(icmp6 + 1);
1064		ip6cp.ip6c_off = eoff;
1065		ip6cp.ip6c_finaldst = finaldst;
1066		ip6cp.ip6c_src = &icmp6src;
1067		ip6cp.ip6c_nxt = nxt;
1068
1069		if (icmp6type == ICMP6_PACKET_TOO_BIG) {
1070			notifymtu = ntohl(icmp6->icmp6_mtu);
1071			ip6cp.ip6c_cmdarg = (void *)&notifymtu;
1072			icmp6_mtudisc_update(&ip6cp, 1);	/*XXX*/
1073		}
1074
1075		ctlfunc = (void (*) __P((int, struct sockaddr *, void *)))
1076		    (inet6sw[ip6_protox[nxt]].pr_ctlinput);
1077		if (ctlfunc) {
1078			(void) (*ctlfunc)(code, (struct sockaddr *)&icmp6dst,
1079			    &ip6cp);
1080		}
1081	}
1082	*mp = m;
1083	return (0);
1084
1085  freeit:
1086	m_freem(m);
1087	return (-1);
1088}
1089
1090void
1091icmp6_mtudisc_update(struct ip6ctlparam *ip6cp, int validated)
1092{
1093	struct in6_addr *dst = ip6cp->ip6c_finaldst;
1094	struct icmp6_hdr *icmp6 = ip6cp->ip6c_icmp6;
1095	struct mbuf *m = ip6cp->ip6c_m;	/* will be necessary for scope issue */
1096	u_int mtu = ntohl(icmp6->icmp6_mtu);
1097	struct in_conninfo inc;
1098
1099#if 0
1100	/*
1101	 * RFC2460 section 5, last paragraph.
1102	 * even though minimum link MTU for IPv6 is IPV6_MMTU,
1103	 * we may see ICMPv6 too big with mtu < IPV6_MMTU
1104	 * due to packet translator in the middle.
1105	 * see ip6_output() and ip6_getpmtu() "alwaysfrag" case for
1106	 * special handling.
1107	 */
1108	if (mtu < IPV6_MMTU)
1109		return;
1110#endif
1111
1112	/*
1113	 * we reject ICMPv6 too big with abnormally small value.
1114	 * XXX what is the good definition of "abnormally small"?
1115	 */
1116	if (mtu < sizeof(struct ip6_hdr) + sizeof(struct ip6_frag) + 8)
1117		return;
1118
1119	if (!validated)
1120		return;
1121
1122	bzero(&inc, sizeof(inc));
1123	inc.inc_flags = 1; /* IPv6 */
1124	inc.inc6_faddr = *dst;
1125	if (in6_setscope(&inc.inc6_faddr, m->m_pkthdr.rcvif, NULL))
1126		return;
1127
1128	if (mtu < tcp_maxmtu6(&inc, NULL)) {
1129		tcp_hc_updatemtu(&inc, mtu);
1130		icmp6stat.icp6s_pmtuchg++;
1131	}
1132}
1133
1134/*
1135 * Process a Node Information Query packet, based on
1136 * draft-ietf-ipngwg-icmp-name-lookups-07.
1137 *
1138 * Spec incompatibilities:
1139 * - IPv6 Subject address handling
1140 * - IPv4 Subject address handling support missing
1141 * - Proxy reply (answer even if it's not for me)
1142 * - joins NI group address at in6_ifattach() time only, does not cope
1143 *   with hostname changes by sethostname(3)
1144 */
1145#define hostnamelen	strlen(hostname)
1146static struct mbuf *
1147ni6_input(struct mbuf *m, int off)
1148{
1149	struct icmp6_nodeinfo *ni6, *nni6;
1150	struct mbuf *n = NULL;
1151	u_int16_t qtype;
1152	int subjlen;
1153	int replylen = sizeof(struct ip6_hdr) + sizeof(struct icmp6_nodeinfo);
1154	struct ni_reply_fqdn *fqdn;
1155	int addrs;		/* for NI_QTYPE_NODEADDR */
1156	struct ifnet *ifp = NULL; /* for NI_QTYPE_NODEADDR */
1157	struct in6_addr in6_subj; /* subject address */
1158	struct ip6_hdr *ip6;
1159	int oldfqdn = 0;	/* if 1, return pascal string (03 draft) */
1160	char *subj = NULL;
1161	struct in6_ifaddr *ia6 = NULL;
1162
1163	ip6 = mtod(m, struct ip6_hdr *);
1164#ifndef PULLDOWN_TEST
1165	ni6 = (struct icmp6_nodeinfo *)(mtod(m, caddr_t) + off);
1166#else
1167	IP6_EXTHDR_GET(ni6, struct icmp6_nodeinfo *, m, off, sizeof(*ni6));
1168	if (ni6 == NULL) {
1169		/* m is already reclaimed */
1170		return (NULL);
1171	}
1172#endif
1173
1174	/*
1175	 * Validate IPv6 source address.
1176	 * The default configuration MUST be to refuse answering queries from
1177	 * global-scope addresses according to RFC4602.
1178	 * Notes:
1179	 *  - it's not very clear what "refuse" means; this implementation
1180	 *    simply drops it.
1181	 *  - it's not very easy to identify global-scope (unicast) addresses
1182	 *    since there are many prefixes for them.  It should be safer
1183	 *    and in practice sufficient to check "all" but loopback and
1184	 *    link-local (note that site-local unicast was deprecated and
1185	 *    ULA is defined as global scope-wise)
1186	 */
1187	if ((icmp6_nodeinfo & ICMP6_NODEINFO_GLOBALOK) == 0 &&
1188	    !IN6_IS_ADDR_LOOPBACK(&ip6->ip6_src) &&
1189	    !IN6_IS_ADDR_LINKLOCAL(&ip6->ip6_src))
1190		goto bad;
1191
1192	/*
1193	 * Validate IPv6 destination address.
1194	 *
1195	 * The Responder must discard the Query without further processing
1196	 * unless it is one of the Responder's unicast or anycast addresses, or
1197	 * a link-local scope multicast address which the Responder has joined.
1198	 * [RFC4602, Section 5.]
1199	 */
1200	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
1201		if (!IN6_IS_ADDR_MC_LINKLOCAL(&ip6->ip6_dst))
1202			goto bad;
1203		/* else it's a link-local multicast, fine */
1204	} else {		/* unicast or anycast */
1205		if ((ia6 = ip6_getdstifaddr(m)) == NULL)
1206			goto bad; /* XXX impossible */
1207
1208		if ((ia6->ia6_flags & IN6_IFF_TEMPORARY) &&
1209		    !(icmp6_nodeinfo & ICMP6_NODEINFO_TMPADDROK)) {
1210			nd6log((LOG_DEBUG, "ni6_input: ignore node info to "
1211				"a temporary address in %s:%d",
1212			       __FILE__, __LINE__));
1213			goto bad;
1214		}
1215	}
1216
1217	/* validate query Subject field. */
1218	qtype = ntohs(ni6->ni_qtype);
1219	subjlen = m->m_pkthdr.len - off - sizeof(struct icmp6_nodeinfo);
1220	switch (qtype) {
1221	case NI_QTYPE_NOOP:
1222	case NI_QTYPE_SUPTYPES:
1223		/* 07 draft */
1224		if (ni6->ni_code == ICMP6_NI_SUBJ_FQDN && subjlen == 0)
1225			break;
1226		/* FALLTHROUGH */
1227	case NI_QTYPE_FQDN:
1228	case NI_QTYPE_NODEADDR:
1229	case NI_QTYPE_IPV4ADDR:
1230		switch (ni6->ni_code) {
1231		case ICMP6_NI_SUBJ_IPV6:
1232#if ICMP6_NI_SUBJ_IPV6 != 0
1233		case 0:
1234#endif
1235			/*
1236			 * backward compatibility - try to accept 03 draft
1237			 * format, where no Subject is present.
1238			 */
1239			if (qtype == NI_QTYPE_FQDN && ni6->ni_code == 0 &&
1240			    subjlen == 0) {
1241				oldfqdn++;
1242				break;
1243			}
1244#if ICMP6_NI_SUBJ_IPV6 != 0
1245			if (ni6->ni_code != ICMP6_NI_SUBJ_IPV6)
1246				goto bad;
1247#endif
1248
1249			if (subjlen != sizeof(struct in6_addr))
1250				goto bad;
1251
1252			/*
1253			 * Validate Subject address.
1254			 *
1255			 * Not sure what exactly "address belongs to the node"
1256			 * means in the spec, is it just unicast, or what?
1257			 *
1258			 * At this moment we consider Subject address as
1259			 * "belong to the node" if the Subject address equals
1260			 * to the IPv6 destination address; validation for
1261			 * IPv6 destination address should have done enough
1262			 * check for us.
1263			 *
1264			 * We do not do proxy at this moment.
1265			 */
1266			/* m_pulldown instead of copy? */
1267			m_copydata(m, off + sizeof(struct icmp6_nodeinfo),
1268			    subjlen, (caddr_t)&in6_subj);
1269			if (in6_setscope(&in6_subj, m->m_pkthdr.rcvif, NULL))
1270				goto bad;
1271
1272			subj = (char *)&in6_subj;
1273			if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &in6_subj))
1274				break;
1275
1276			/*
1277			 * XXX if we are to allow other cases, we should really
1278			 * be careful about scope here.
1279			 * basically, we should disallow queries toward IPv6
1280			 * destination X with subject Y,
1281			 * if scope(X) > scope(Y).
1282			 * if we allow scope(X) > scope(Y), it will result in
1283			 * information leakage across scope boundary.
1284			 */
1285			goto bad;
1286
1287		case ICMP6_NI_SUBJ_FQDN:
1288			/*
1289			 * Validate Subject name with gethostname(3).
1290			 *
1291			 * The behavior may need some debate, since:
1292			 * - we are not sure if the node has FQDN as
1293			 *   hostname (returned by gethostname(3)).
1294			 * - the code does wildcard match for truncated names.
1295			 *   however, we are not sure if we want to perform
1296			 *   wildcard match, if gethostname(3) side has
1297			 *   truncated hostname.
1298			 */
1299			n = ni6_nametodns(hostname, hostnamelen, 0);
1300			if (!n || n->m_next || n->m_len == 0)
1301				goto bad;
1302			IP6_EXTHDR_GET(subj, char *, m,
1303			    off + sizeof(struct icmp6_nodeinfo), subjlen);
1304			if (subj == NULL)
1305				goto bad;
1306			if (!ni6_dnsmatch(subj, subjlen, mtod(n, const char *),
1307			    n->m_len)) {
1308				goto bad;
1309			}
1310			m_freem(n);
1311			n = NULL;
1312			break;
1313
1314		case ICMP6_NI_SUBJ_IPV4:	/* XXX: to be implemented? */
1315		default:
1316			goto bad;
1317		}
1318		break;
1319	}
1320
1321	/* refuse based on configuration.  XXX ICMP6_NI_REFUSED? */
1322	switch (qtype) {
1323	case NI_QTYPE_FQDN:
1324		if ((icmp6_nodeinfo & ICMP6_NODEINFO_FQDNOK) == 0)
1325			goto bad;
1326		break;
1327	case NI_QTYPE_NODEADDR:
1328	case NI_QTYPE_IPV4ADDR:
1329		if ((icmp6_nodeinfo & ICMP6_NODEINFO_NODEADDROK) == 0)
1330			goto bad;
1331		break;
1332	}
1333
1334	/* guess reply length */
1335	switch (qtype) {
1336	case NI_QTYPE_NOOP:
1337		break;		/* no reply data */
1338	case NI_QTYPE_SUPTYPES:
1339		replylen += sizeof(u_int32_t);
1340		break;
1341	case NI_QTYPE_FQDN:
1342		/* XXX will append an mbuf */
1343		replylen += offsetof(struct ni_reply_fqdn, ni_fqdn_namelen);
1344		break;
1345	case NI_QTYPE_NODEADDR:
1346		addrs = ni6_addrs(ni6, m, &ifp, (struct in6_addr *)subj);
1347		if ((replylen += addrs * (sizeof(struct in6_addr) +
1348		    sizeof(u_int32_t))) > MCLBYTES)
1349			replylen = MCLBYTES; /* XXX: will truncate pkt later */
1350		break;
1351	case NI_QTYPE_IPV4ADDR:
1352		/* unsupported - should respond with unknown Qtype? */
1353		break;
1354	default:
1355		/*
1356		 * XXX: We must return a reply with the ICMP6 code
1357		 * `unknown Qtype' in this case.  However we regard the case
1358		 * as an FQDN query for backward compatibility.
1359		 * Older versions set a random value to this field,
1360		 * so it rarely varies in the defined qtypes.
1361		 * But the mechanism is not reliable...
1362		 * maybe we should obsolete older versions.
1363		 */
1364		qtype = NI_QTYPE_FQDN;
1365		/* XXX will append an mbuf */
1366		replylen += offsetof(struct ni_reply_fqdn, ni_fqdn_namelen);
1367		oldfqdn++;
1368		break;
1369	}
1370
1371	/* allocate an mbuf to reply. */
1372	MGETHDR(n, M_DONTWAIT, m->m_type);
1373	if (n == NULL) {
1374		m_freem(m);
1375		return (NULL);
1376	}
1377	M_MOVE_PKTHDR(n, m); /* just for recvif */
1378	if (replylen > MHLEN) {
1379		if (replylen > MCLBYTES) {
1380			/*
1381			 * XXX: should we try to allocate more? But MCLBYTES
1382			 * is probably much larger than IPV6_MMTU...
1383			 */
1384			goto bad;
1385		}
1386		MCLGET(n, M_DONTWAIT);
1387		if ((n->m_flags & M_EXT) == 0) {
1388			goto bad;
1389		}
1390	}
1391	n->m_pkthdr.len = n->m_len = replylen;
1392
1393	/* copy mbuf header and IPv6 + Node Information base headers */
1394	bcopy(mtod(m, caddr_t), mtod(n, caddr_t), sizeof(struct ip6_hdr));
1395	nni6 = (struct icmp6_nodeinfo *)(mtod(n, struct ip6_hdr *) + 1);
1396	bcopy((caddr_t)ni6, (caddr_t)nni6, sizeof(struct icmp6_nodeinfo));
1397
1398	/* qtype dependent procedure */
1399	switch (qtype) {
1400	case NI_QTYPE_NOOP:
1401		nni6->ni_code = ICMP6_NI_SUCCESS;
1402		nni6->ni_flags = 0;
1403		break;
1404	case NI_QTYPE_SUPTYPES:
1405	{
1406		u_int32_t v;
1407		nni6->ni_code = ICMP6_NI_SUCCESS;
1408		nni6->ni_flags = htons(0x0000);	/* raw bitmap */
1409		/* supports NOOP, SUPTYPES, FQDN, and NODEADDR */
1410		v = (u_int32_t)htonl(0x0000000f);
1411		bcopy(&v, nni6 + 1, sizeof(u_int32_t));
1412		break;
1413	}
1414	case NI_QTYPE_FQDN:
1415		nni6->ni_code = ICMP6_NI_SUCCESS;
1416		fqdn = (struct ni_reply_fqdn *)(mtod(n, caddr_t) +
1417		    sizeof(struct ip6_hdr) + sizeof(struct icmp6_nodeinfo));
1418		nni6->ni_flags = 0; /* XXX: meaningless TTL */
1419		fqdn->ni_fqdn_ttl = 0;	/* ditto. */
1420		/*
1421		 * XXX do we really have FQDN in variable "hostname"?
1422		 */
1423		n->m_next = ni6_nametodns(hostname, hostnamelen, oldfqdn);
1424		if (n->m_next == NULL)
1425			goto bad;
1426		/* XXX we assume that n->m_next is not a chain */
1427		if (n->m_next->m_next != NULL)
1428			goto bad;
1429		n->m_pkthdr.len += n->m_next->m_len;
1430		break;
1431	case NI_QTYPE_NODEADDR:
1432	{
1433		int lenlim, copied;
1434
1435		nni6->ni_code = ICMP6_NI_SUCCESS;
1436		n->m_pkthdr.len = n->m_len =
1437		    sizeof(struct ip6_hdr) + sizeof(struct icmp6_nodeinfo);
1438		lenlim = M_TRAILINGSPACE(n);
1439		copied = ni6_store_addrs(ni6, nni6, ifp, lenlim);
1440		/* XXX: reset mbuf length */
1441		n->m_pkthdr.len = n->m_len = sizeof(struct ip6_hdr) +
1442		    sizeof(struct icmp6_nodeinfo) + copied;
1443		break;
1444	}
1445	default:
1446		break;		/* XXX impossible! */
1447	}
1448
1449	nni6->ni_type = ICMP6_NI_REPLY;
1450	m_freem(m);
1451	return (n);
1452
1453  bad:
1454	m_freem(m);
1455	if (n)
1456		m_freem(n);
1457	return (NULL);
1458}
1459#undef hostnamelen
1460
1461/*
1462 * make a mbuf with DNS-encoded string.  no compression support.
1463 *
1464 * XXX names with less than 2 dots (like "foo" or "foo.section") will be
1465 * treated as truncated name (two \0 at the end).  this is a wild guess.
1466 *
1467 * old - return pascal string if non-zero
1468 */
1469static struct mbuf *
1470ni6_nametodns(const char *name, int namelen, int old)
1471{
1472	struct mbuf *m;
1473	char *cp, *ep;
1474	const char *p, *q;
1475	int i, len, nterm;
1476
1477	if (old)
1478		len = namelen + 1;
1479	else
1480		len = MCLBYTES;
1481
1482	/* because MAXHOSTNAMELEN is usually 256, we use cluster mbuf */
1483	MGET(m, M_DONTWAIT, MT_DATA);
1484	if (m && len > MLEN) {
1485		MCLGET(m, M_DONTWAIT);
1486		if ((m->m_flags & M_EXT) == 0)
1487			goto fail;
1488	}
1489	if (!m)
1490		goto fail;
1491	m->m_next = NULL;
1492
1493	if (old) {
1494		m->m_len = len;
1495		*mtod(m, char *) = namelen;
1496		bcopy(name, mtod(m, char *) + 1, namelen);
1497		return m;
1498	} else {
1499		m->m_len = 0;
1500		cp = mtod(m, char *);
1501		ep = mtod(m, char *) + M_TRAILINGSPACE(m);
1502
1503		/* if not certain about my name, return empty buffer */
1504		if (namelen == 0)
1505			return m;
1506
1507		/*
1508		 * guess if it looks like shortened hostname, or FQDN.
1509		 * shortened hostname needs two trailing "\0".
1510		 */
1511		i = 0;
1512		for (p = name; p < name + namelen; p++) {
1513			if (*p && *p == '.')
1514				i++;
1515		}
1516		if (i < 2)
1517			nterm = 2;
1518		else
1519			nterm = 1;
1520
1521		p = name;
1522		while (cp < ep && p < name + namelen) {
1523			i = 0;
1524			for (q = p; q < name + namelen && *q && *q != '.'; q++)
1525				i++;
1526			/* result does not fit into mbuf */
1527			if (cp + i + 1 >= ep)
1528				goto fail;
1529			/*
1530			 * DNS label length restriction, RFC1035 page 8.
1531			 * "i == 0" case is included here to avoid returning
1532			 * 0-length label on "foo..bar".
1533			 */
1534			if (i <= 0 || i >= 64)
1535				goto fail;
1536			*cp++ = i;
1537			bcopy(p, cp, i);
1538			cp += i;
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 && bcmp(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 (bcmp(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, struct ifnet **ifpp,
1628    struct in6_addr *subj)
1629{
1630	struct ifnet *ifp;
1631	struct in6_ifaddr *ifa6;
1632	struct ifaddr *ifa;
1633	int addrs = 0, addrsofif, iffound = 0;
1634	int niflags = ni6->ni_flags;
1635
1636	if ((niflags & NI_NODEADDR_FLAG_ALL) == 0) {
1637		switch (ni6->ni_code) {
1638		case ICMP6_NI_SUBJ_IPV6:
1639			if (subj == NULL) /* must be impossible... */
1640				return (0);
1641			break;
1642		default:
1643			/*
1644			 * XXX: we only support IPv6 subject address for
1645			 * this Qtype.
1646			 */
1647			return (0);
1648		}
1649	}
1650
1651	IFNET_RLOCK();
1652	for (ifp = TAILQ_FIRST(&ifnet); ifp; ifp = TAILQ_NEXT(ifp, if_list)) {
1653		addrsofif = 0;
1654		TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
1655			if (ifa->ifa_addr->sa_family != AF_INET6)
1656				continue;
1657			ifa6 = (struct in6_ifaddr *)ifa;
1658
1659			if ((niflags & NI_NODEADDR_FLAG_ALL) == 0 &&
1660			    IN6_ARE_ADDR_EQUAL(subj, &ifa6->ia_addr.sin6_addr))
1661				iffound = 1;
1662
1663			/*
1664			 * IPv4-mapped addresses can only be returned by a
1665			 * Node Information proxy, since they represent
1666			 * addresses of IPv4-only nodes, which perforce do
1667			 * not implement this protocol.
1668			 * [icmp-name-lookups-07, Section 5.4]
1669			 * So we don't support NI_NODEADDR_FLAG_COMPAT in
1670			 * this function at this moment.
1671			 */
1672
1673			/* What do we have to do about ::1? */
1674			switch (in6_addrscope(&ifa6->ia_addr.sin6_addr)) {
1675			case IPV6_ADDR_SCOPE_LINKLOCAL:
1676				if ((niflags & NI_NODEADDR_FLAG_LINKLOCAL) == 0)
1677					continue;
1678				break;
1679			case IPV6_ADDR_SCOPE_SITELOCAL:
1680				if ((niflags & NI_NODEADDR_FLAG_SITELOCAL) == 0)
1681					continue;
1682				break;
1683			case IPV6_ADDR_SCOPE_GLOBAL:
1684				if ((niflags & NI_NODEADDR_FLAG_GLOBAL) == 0)
1685					continue;
1686				break;
1687			default:
1688				continue;
1689			}
1690
1691			/*
1692			 * check if anycast is okay.
1693			 * XXX: just experimental.  not in the spec.
1694			 */
1695			if ((ifa6->ia6_flags & IN6_IFF_ANYCAST) != 0 &&
1696			    (niflags & NI_NODEADDR_FLAG_ANYCAST) == 0)
1697				continue; /* we need only unicast addresses */
1698			if ((ifa6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
1699			    (icmp6_nodeinfo & ICMP6_NODEINFO_TMPADDROK) == 0) {
1700				continue;
1701			}
1702			addrsofif++; /* count the address */
1703		}
1704		if (iffound) {
1705			*ifpp = ifp;
1706			IFNET_RUNLOCK();
1707			return (addrsofif);
1708		}
1709
1710		addrs += addrsofif;
1711	}
1712	IFNET_RUNLOCK();
1713
1714	return (addrs);
1715}
1716
1717static int
1718ni6_store_addrs(struct icmp6_nodeinfo *ni6, struct icmp6_nodeinfo *nni6,
1719    struct ifnet *ifp0, int resid)
1720{
1721	struct ifnet *ifp = ifp0 ? ifp0 : TAILQ_FIRST(&ifnet);
1722	struct in6_ifaddr *ifa6;
1723	struct ifaddr *ifa;
1724	struct ifnet *ifp_dep = NULL;
1725	int copied = 0, allow_deprecated = 0;
1726	u_char *cp = (u_char *)(nni6 + 1);
1727	int niflags = ni6->ni_flags;
1728	u_int32_t ltime;
1729
1730	if (ifp0 == NULL && !(niflags & NI_NODEADDR_FLAG_ALL))
1731		return (0);	/* needless to copy */
1732
1733	IFNET_RLOCK();
1734  again:
1735
1736	for (; ifp; ifp = TAILQ_NEXT(ifp, if_list)) {
1737		for (ifa = ifp->if_addrlist.tqh_first; ifa;
1738		     ifa = ifa->ifa_list.tqe_next) {
1739			if (ifa->ifa_addr->sa_family != AF_INET6)
1740				continue;
1741			ifa6 = (struct in6_ifaddr *)ifa;
1742
1743			if ((ifa6->ia6_flags & IN6_IFF_DEPRECATED) != 0 &&
1744			    allow_deprecated == 0) {
1745				/*
1746				 * prefererred address should be put before
1747				 * deprecated addresses.
1748				 */
1749
1750				/* record the interface for later search */
1751				if (ifp_dep == NULL)
1752					ifp_dep = ifp;
1753
1754				continue;
1755			} else if ((ifa6->ia6_flags & IN6_IFF_DEPRECATED) == 0 &&
1756			    allow_deprecated != 0)
1757				continue; /* we now collect deprecated addrs */
1758
1759			/* What do we have to do about ::1? */
1760			switch (in6_addrscope(&ifa6->ia_addr.sin6_addr)) {
1761			case IPV6_ADDR_SCOPE_LINKLOCAL:
1762				if ((niflags & NI_NODEADDR_FLAG_LINKLOCAL) == 0)
1763					continue;
1764				break;
1765			case IPV6_ADDR_SCOPE_SITELOCAL:
1766				if ((niflags & NI_NODEADDR_FLAG_SITELOCAL) == 0)
1767					continue;
1768				break;
1769			case IPV6_ADDR_SCOPE_GLOBAL:
1770				if ((niflags & NI_NODEADDR_FLAG_GLOBAL) == 0)
1771					continue;
1772				break;
1773			default:
1774				continue;
1775			}
1776
1777			/*
1778			 * check if anycast is okay.
1779			 * XXX: just experimental.  not in the spec.
1780			 */
1781			if ((ifa6->ia6_flags & IN6_IFF_ANYCAST) != 0 &&
1782			    (niflags & NI_NODEADDR_FLAG_ANYCAST) == 0)
1783				continue;
1784			if ((ifa6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
1785			    (icmp6_nodeinfo & ICMP6_NODEINFO_TMPADDROK) == 0) {
1786				continue;
1787			}
1788
1789			/* now we can copy the address */
1790			if (resid < sizeof(struct in6_addr) +
1791			    sizeof(u_int32_t)) {
1792				/*
1793				 * We give up much more copy.
1794				 * Set the truncate flag and return.
1795				 */
1796				nni6->ni_flags |= NI_NODEADDR_FLAG_TRUNCATE;
1797				IFNET_RUNLOCK();
1798				return (copied);
1799			}
1800
1801			/*
1802			 * Set the TTL of the address.
1803			 * The TTL value should be one of the following
1804			 * according to the specification:
1805			 *
1806			 * 1. The remaining lifetime of a DHCP lease on the
1807			 *    address, or
1808			 * 2. The remaining Valid Lifetime of a prefix from
1809			 *    which the address was derived through Stateless
1810			 *    Autoconfiguration.
1811			 *
1812			 * Note that we currently do not support stateful
1813			 * address configuration by DHCPv6, so the former
1814			 * case can't happen.
1815			 */
1816			if (ifa6->ia6_lifetime.ia6t_expire == 0)
1817				ltime = ND6_INFINITE_LIFETIME;
1818			else {
1819				if (ifa6->ia6_lifetime.ia6t_expire >
1820				    time_second)
1821					ltime = htonl(ifa6->ia6_lifetime.ia6t_expire - time_second);
1822				else
1823					ltime = 0;
1824			}
1825
1826			bcopy(&ltime, cp, sizeof(u_int32_t));
1827			cp += sizeof(u_int32_t);
1828
1829			/* copy the address itself */
1830			bcopy(&ifa6->ia_addr.sin6_addr, cp,
1831			    sizeof(struct in6_addr));
1832			in6_clearscope((struct in6_addr *)cp); /* XXX */
1833			cp += sizeof(struct in6_addr);
1834
1835			resid -= (sizeof(struct in6_addr) + sizeof(u_int32_t));
1836			copied += (sizeof(struct in6_addr) + sizeof(u_int32_t));
1837		}
1838		if (ifp0)	/* we need search only on the specified IF */
1839			break;
1840	}
1841
1842	if (allow_deprecated == 0 && ifp_dep != NULL) {
1843		ifp = ifp_dep;
1844		allow_deprecated = 1;
1845
1846		goto again;
1847	}
1848
1849	IFNET_RUNLOCK();
1850
1851	return (copied);
1852}
1853
1854/*
1855 * XXX almost dup'ed code with rip6_input.
1856 */
1857static int
1858icmp6_rip6_input(struct mbuf **mp, int off)
1859{
1860	struct mbuf *m = *mp;
1861	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
1862	struct in6pcb *in6p;
1863	struct in6pcb *last = NULL;
1864	struct sockaddr_in6 fromsa;
1865	struct icmp6_hdr *icmp6;
1866	struct mbuf *opts = NULL;
1867
1868#ifndef PULLDOWN_TEST
1869	/* this is assumed to be safe. */
1870	icmp6 = (struct icmp6_hdr *)((caddr_t)ip6 + off);
1871#else
1872	IP6_EXTHDR_GET(icmp6, struct icmp6_hdr *, m, off, sizeof(*icmp6));
1873	if (icmp6 == NULL) {
1874		/* m is already reclaimed */
1875		return (IPPROTO_DONE);
1876	}
1877#endif
1878
1879	/*
1880	 * XXX: the address may have embedded scope zone ID, which should be
1881	 * hidden from applications.
1882	 */
1883	bzero(&fromsa, sizeof(fromsa));
1884	fromsa.sin6_family = AF_INET6;
1885	fromsa.sin6_len = sizeof(struct sockaddr_in6);
1886	fromsa.sin6_addr = ip6->ip6_src;
1887	if (sa6_recoverscope(&fromsa)) {
1888		m_freem(m);
1889		return (IPPROTO_DONE);
1890	}
1891
1892	INP_INFO_RLOCK(&ripcbinfo);
1893	LIST_FOREACH(in6p, &ripcb, inp_list) {
1894		INP_LOCK(in6p);
1895		if ((in6p->inp_vflag & INP_IPV6) == 0) {
1896	docontinue:
1897			INP_UNLOCK(in6p);
1898			continue;
1899		}
1900		if (in6p->in6p_ip6_nxt != IPPROTO_ICMPV6)
1901			goto docontinue;
1902		if (!IN6_IS_ADDR_UNSPECIFIED(&in6p->in6p_laddr) &&
1903		   !IN6_ARE_ADDR_EQUAL(&in6p->in6p_laddr, &ip6->ip6_dst))
1904			goto docontinue;
1905		if (!IN6_IS_ADDR_UNSPECIFIED(&in6p->in6p_faddr) &&
1906		   !IN6_ARE_ADDR_EQUAL(&in6p->in6p_faddr, &ip6->ip6_src))
1907			goto docontinue;
1908		if (in6p->in6p_icmp6filt
1909		    && ICMP6_FILTER_WILLBLOCK(icmp6->icmp6_type,
1910				 in6p->in6p_icmp6filt))
1911			goto docontinue;
1912		if (last) {
1913			struct	mbuf *n = NULL;
1914
1915			/*
1916			 * Recent network drivers tend to allocate a single
1917			 * mbuf cluster, rather than to make a couple of
1918			 * mbufs without clusters.  Also, since the IPv6 code
1919			 * path tries to avoid m_pullup(), it is highly
1920			 * probable that we still have an mbuf cluster here
1921			 * even though the necessary length can be stored in an
1922			 * mbuf's internal buffer.
1923			 * Meanwhile, the default size of the receive socket
1924			 * buffer for raw sockets is not so large.  This means
1925			 * the possibility of packet loss is relatively higher
1926			 * than before.  To avoid this scenario, we copy the
1927			 * received data to a separate mbuf that does not use
1928			 * a cluster, if possible.
1929			 * XXX: it is better to copy the data after stripping
1930			 * intermediate headers.
1931			 */
1932			if ((m->m_flags & M_EXT) && m->m_next == NULL &&
1933			    m->m_len <= MHLEN) {
1934				MGET(n, M_DONTWAIT, m->m_type);
1935				if (n != NULL) {
1936					if (m_dup_pkthdr(n, m, M_NOWAIT)) {
1937						bcopy(m->m_data, n->m_data,
1938						      m->m_len);
1939						n->m_len = m->m_len;
1940					} else {
1941						m_free(n);
1942						n = NULL;
1943					}
1944				}
1945			}
1946			if (n != NULL ||
1947			    (n = m_copy(m, 0, (int)M_COPYALL)) != NULL) {
1948				if (last->in6p_flags & IN6P_CONTROLOPTS)
1949					ip6_savecontrol(last, n, &opts);
1950				/* strip intermediate headers */
1951				m_adj(n, off);
1952				SOCKBUF_LOCK(&last->in6p_socket->so_rcv);
1953				if (sbappendaddr_locked(
1954				    &last->in6p_socket->so_rcv,
1955				    (struct sockaddr *)&fromsa, n, opts)
1956				    == 0) {
1957					/* should notify about lost packet */
1958					m_freem(n);
1959					if (opts) {
1960						m_freem(opts);
1961					}
1962					SOCKBUF_UNLOCK(
1963					    &last->in6p_socket->so_rcv);
1964				} else
1965					sorwakeup_locked(last->in6p_socket);
1966				opts = NULL;
1967			}
1968			INP_UNLOCK(last);
1969		}
1970		last = in6p;
1971	}
1972	if (last) {
1973		if (last->in6p_flags & IN6P_CONTROLOPTS)
1974			ip6_savecontrol(last, m, &opts);
1975		/* strip intermediate headers */
1976		m_adj(m, off);
1977
1978		/* avoid using mbuf clusters if possible (see above) */
1979		if ((m->m_flags & M_EXT) && m->m_next == NULL &&
1980		    m->m_len <= MHLEN) {
1981			struct mbuf *n;
1982
1983			MGET(n, M_DONTWAIT, m->m_type);
1984			if (n != NULL) {
1985				if (m_dup_pkthdr(n, m, M_NOWAIT)) {
1986					bcopy(m->m_data, n->m_data, m->m_len);
1987					n->m_len = m->m_len;
1988
1989					m_freem(m);
1990					m = n;
1991				} else {
1992					m_freem(n);
1993					n = NULL;
1994				}
1995			}
1996		}
1997		SOCKBUF_LOCK(&last->in6p_socket->so_rcv);
1998		if (sbappendaddr_locked(&last->in6p_socket->so_rcv,
1999		    (struct sockaddr *)&fromsa, m, opts) == 0) {
2000			m_freem(m);
2001			if (opts)
2002				m_freem(opts);
2003			SOCKBUF_UNLOCK(&last->in6p_socket->so_rcv);
2004		} else
2005			sorwakeup_locked(last->in6p_socket);
2006		INP_UNLOCK(last);
2007	} else {
2008		m_freem(m);
2009		ip6stat.ip6s_delivered--;
2010	}
2011	INP_INFO_RUNLOCK(&ripcbinfo);
2012	return IPPROTO_DONE;
2013}
2014
2015/*
2016 * Reflect the ip6 packet back to the source.
2017 * OFF points to the icmp6 header, counted from the top of the mbuf.
2018 */
2019void
2020icmp6_reflect(struct mbuf *m, size_t off)
2021{
2022	struct ip6_hdr *ip6;
2023	struct icmp6_hdr *icmp6;
2024	struct in6_ifaddr *ia;
2025	int plen;
2026	int type, code;
2027	struct ifnet *outif = NULL;
2028	struct in6_addr origdst, *src = NULL;
2029
2030	/* too short to reflect */
2031	if (off < sizeof(struct ip6_hdr)) {
2032		nd6log((LOG_DEBUG,
2033		    "sanity fail: off=%lx, sizeof(ip6)=%lx in %s:%d\n",
2034		    (u_long)off, (u_long)sizeof(struct ip6_hdr),
2035		    __FILE__, __LINE__));
2036		goto bad;
2037	}
2038
2039	/*
2040	 * If there are extra headers between IPv6 and ICMPv6, strip
2041	 * off that header first.
2042	 */
2043#ifdef DIAGNOSTIC
2044	if (sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr) > MHLEN)
2045		panic("assumption failed in icmp6_reflect");
2046#endif
2047	if (off > sizeof(struct ip6_hdr)) {
2048		size_t l;
2049		struct ip6_hdr nip6;
2050
2051		l = off - sizeof(struct ip6_hdr);
2052		m_copydata(m, 0, sizeof(nip6), (caddr_t)&nip6);
2053		m_adj(m, l);
2054		l = sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr);
2055		if (m->m_len < l) {
2056			if ((m = m_pullup(m, l)) == NULL)
2057				return;
2058		}
2059		bcopy((caddr_t)&nip6, mtod(m, caddr_t), sizeof(nip6));
2060	} else /* off == sizeof(struct ip6_hdr) */ {
2061		size_t l;
2062		l = sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr);
2063		if (m->m_len < l) {
2064			if ((m = m_pullup(m, l)) == NULL)
2065				return;
2066		}
2067	}
2068	plen = m->m_pkthdr.len - sizeof(struct ip6_hdr);
2069	ip6 = mtod(m, struct ip6_hdr *);
2070	ip6->ip6_nxt = IPPROTO_ICMPV6;
2071	icmp6 = (struct icmp6_hdr *)(ip6 + 1);
2072	type = icmp6->icmp6_type; /* keep type for statistics */
2073	code = icmp6->icmp6_code; /* ditto. */
2074
2075	origdst = ip6->ip6_dst;
2076	/*
2077	 * ip6_input() drops a packet if its src is multicast.
2078	 * So, the src is never multicast.
2079	 */
2080	ip6->ip6_dst = ip6->ip6_src;
2081
2082	/*
2083	 * If the incoming packet was addressed directly to us (i.e. unicast),
2084	 * use dst as the src for the reply.
2085	 * The IN6_IFF_NOTREADY case should be VERY rare, but is possible
2086	 * (for example) when we encounter an error while forwarding procedure
2087	 * destined to a duplicated address of ours.
2088	 * Note that ip6_getdstifaddr() may fail if we are in an error handling
2089	 * procedure of an outgoing packet of our own, in which case we need
2090	 * to search in the ifaddr list.
2091	 */
2092	if (!IN6_IS_ADDR_MULTICAST(&origdst)) {
2093		if ((ia = ip6_getdstifaddr(m))) {
2094			if (!(ia->ia6_flags &
2095			    (IN6_IFF_ANYCAST|IN6_IFF_NOTREADY)))
2096				src = &ia->ia_addr.sin6_addr;
2097		} else {
2098			struct sockaddr_in6 d;
2099
2100			bzero(&d, sizeof(d));
2101			d.sin6_family = AF_INET6;
2102			d.sin6_len = sizeof(d);
2103			d.sin6_addr = origdst;
2104			ia = (struct in6_ifaddr *)
2105			    ifa_ifwithaddr((struct sockaddr *)&d);
2106			if (ia &&
2107			    !(ia->ia6_flags &
2108			    (IN6_IFF_ANYCAST|IN6_IFF_NOTREADY))) {
2109				src = &ia->ia_addr.sin6_addr;
2110			}
2111		}
2112	}
2113
2114	if (src == NULL) {
2115		int e;
2116		struct sockaddr_in6 sin6;
2117		struct route_in6 ro;
2118
2119		/*
2120		 * This case matches to multicasts, our anycast, or unicasts
2121		 * that we do not own.  Select a source address based on the
2122		 * source address of the erroneous packet.
2123		 */
2124		bzero(&sin6, sizeof(sin6));
2125		sin6.sin6_family = AF_INET6;
2126		sin6.sin6_len = sizeof(sin6);
2127		sin6.sin6_addr = ip6->ip6_dst; /* zone ID should be embedded */
2128
2129		bzero(&ro, sizeof(ro));
2130		src = in6_selectsrc(&sin6, NULL, NULL, &ro, NULL, &outif, &e);
2131		if (ro.ro_rt)
2132			RTFREE(ro.ro_rt); /* XXX: we could use this */
2133		if (src == NULL) {
2134			char ip6buf[INET6_ADDRSTRLEN];
2135			nd6log((LOG_DEBUG,
2136			    "icmp6_reflect: source can't be determined: "
2137			    "dst=%s, error=%d\n",
2138			    ip6_sprintf(ip6buf, &sin6.sin6_addr), e));
2139			goto bad;
2140		}
2141	}
2142
2143	ip6->ip6_src = *src;
2144	ip6->ip6_flow = 0;
2145	ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
2146	ip6->ip6_vfc |= IPV6_VERSION;
2147	ip6->ip6_nxt = IPPROTO_ICMPV6;
2148	if (outif)
2149		ip6->ip6_hlim = ND_IFINFO(outif)->chlim;
2150	else if (m->m_pkthdr.rcvif) {
2151		/* XXX: This may not be the outgoing interface */
2152		ip6->ip6_hlim = ND_IFINFO(m->m_pkthdr.rcvif)->chlim;
2153	} else
2154		ip6->ip6_hlim = ip6_defhlim;
2155
2156	icmp6->icmp6_cksum = 0;
2157	icmp6->icmp6_cksum = in6_cksum(m, IPPROTO_ICMPV6,
2158	    sizeof(struct ip6_hdr), plen);
2159
2160	/*
2161	 * XXX option handling
2162	 */
2163
2164	m->m_flags &= ~(M_BCAST|M_MCAST);
2165
2166	ip6_output(m, NULL, NULL, 0, NULL, &outif, NULL);
2167	if (outif)
2168		icmp6_ifoutstat_inc(outif, type, code);
2169
2170	return;
2171
2172 bad:
2173	m_freem(m);
2174	return;
2175}
2176
2177void
2178icmp6_fasttimo(void)
2179{
2180
2181	return;
2182}
2183
2184static const char *
2185icmp6_redirect_diag(struct in6_addr *src6, struct in6_addr *dst6,
2186    struct in6_addr *tgt6)
2187{
2188	static char buf[1024];
2189	char ip6bufs[INET6_ADDRSTRLEN];
2190	char ip6bufd[INET6_ADDRSTRLEN];
2191	char ip6buft[INET6_ADDRSTRLEN];
2192	snprintf(buf, sizeof(buf), "(src=%s dst=%s tgt=%s)",
2193	    ip6_sprintf(ip6bufs, src6), ip6_sprintf(ip6bufd, dst6),
2194	    ip6_sprintf(ip6buft, tgt6));
2195	return buf;
2196}
2197
2198void
2199icmp6_redirect_input(struct mbuf *m, int off)
2200{
2201	struct ifnet *ifp;
2202	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
2203	struct nd_redirect *nd_rd;
2204	int icmp6len = ntohs(ip6->ip6_plen);
2205	char *lladdr = NULL;
2206	int lladdrlen = 0;
2207	u_char *redirhdr = NULL;
2208	int redirhdrlen = 0;
2209	struct rtentry *rt = NULL;
2210	int is_router;
2211	int is_onlink;
2212	struct in6_addr src6 = ip6->ip6_src;
2213	struct in6_addr redtgt6;
2214	struct in6_addr reddst6;
2215	union nd_opts ndopts;
2216	char ip6buf[INET6_ADDRSTRLEN];
2217
2218	if (!m)
2219		return;
2220
2221	ifp = m->m_pkthdr.rcvif;
2222
2223	if (!ifp)
2224		return;
2225
2226	/* XXX if we are router, we don't update route by icmp6 redirect */
2227	if (ip6_forwarding)
2228		goto freeit;
2229	if (!icmp6_rediraccept)
2230		goto freeit;
2231
2232#ifndef PULLDOWN_TEST
2233	IP6_EXTHDR_CHECK(m, off, icmp6len,);
2234	nd_rd = (struct nd_redirect *)((caddr_t)ip6 + off);
2235#else
2236	IP6_EXTHDR_GET(nd_rd, struct nd_redirect *, m, off, icmp6len);
2237	if (nd_rd == NULL) {
2238		icmp6stat.icp6s_tooshort++;
2239		return;
2240	}
2241#endif
2242	redtgt6 = nd_rd->nd_rd_target;
2243	reddst6 = nd_rd->nd_rd_dst;
2244
2245	if (in6_setscope(&redtgt6, m->m_pkthdr.rcvif, NULL) ||
2246	    in6_setscope(&reddst6, m->m_pkthdr.rcvif, NULL)) {
2247		goto freeit;
2248	}
2249
2250	/* validation */
2251	if (!IN6_IS_ADDR_LINKLOCAL(&src6)) {
2252		nd6log((LOG_ERR,
2253		    "ICMP6 redirect sent from %s rejected; "
2254		    "must be from linklocal\n",
2255		    ip6_sprintf(ip6buf, &src6)));
2256		goto bad;
2257	}
2258	if (ip6->ip6_hlim != 255) {
2259		nd6log((LOG_ERR,
2260		    "ICMP6 redirect sent from %s rejected; "
2261		    "hlim=%d (must be 255)\n",
2262		    ip6_sprintf(ip6buf, &src6), ip6->ip6_hlim));
2263		goto bad;
2264	}
2265    {
2266	/* ip6->ip6_src must be equal to gw for icmp6->icmp6_reddst */
2267	struct sockaddr_in6 sin6;
2268	struct in6_addr *gw6;
2269
2270	bzero(&sin6, sizeof(sin6));
2271	sin6.sin6_family = AF_INET6;
2272	sin6.sin6_len = sizeof(struct sockaddr_in6);
2273	bcopy(&reddst6, &sin6.sin6_addr, sizeof(reddst6));
2274	rt = rtalloc1((struct sockaddr *)&sin6, 0, 0UL);
2275	if (rt) {
2276		if (rt->rt_gateway == NULL ||
2277		    rt->rt_gateway->sa_family != AF_INET6) {
2278			nd6log((LOG_ERR,
2279			    "ICMP6 redirect rejected; no route "
2280			    "with inet6 gateway found for redirect dst: %s\n",
2281			    icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2282			RTFREE_LOCKED(rt);
2283			goto bad;
2284		}
2285
2286		gw6 = &(((struct sockaddr_in6 *)rt->rt_gateway)->sin6_addr);
2287		if (bcmp(&src6, gw6, sizeof(struct in6_addr)) != 0) {
2288			nd6log((LOG_ERR,
2289			    "ICMP6 redirect rejected; "
2290			    "not equal to gw-for-src=%s (must be same): "
2291			    "%s\n",
2292			    ip6_sprintf(ip6buf, gw6),
2293			    icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2294			RTFREE_LOCKED(rt);
2295			goto bad;
2296		}
2297	} else {
2298		nd6log((LOG_ERR,
2299		    "ICMP6 redirect rejected; "
2300		    "no route found for redirect dst: %s\n",
2301		    icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2302		goto bad;
2303	}
2304	RTFREE_LOCKED(rt);
2305	rt = NULL;
2306    }
2307	if (IN6_IS_ADDR_MULTICAST(&reddst6)) {
2308		nd6log((LOG_ERR,
2309		    "ICMP6 redirect rejected; "
2310		    "redirect dst must be unicast: %s\n",
2311		    icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2312		goto bad;
2313	}
2314
2315	is_router = is_onlink = 0;
2316	if (IN6_IS_ADDR_LINKLOCAL(&redtgt6))
2317		is_router = 1;	/* router case */
2318	if (bcmp(&redtgt6, &reddst6, sizeof(redtgt6)) == 0)
2319		is_onlink = 1;	/* on-link destination case */
2320	if (!is_router && !is_onlink) {
2321		nd6log((LOG_ERR,
2322		    "ICMP6 redirect rejected; "
2323		    "neither router case nor onlink case: %s\n",
2324		    icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2325		goto bad;
2326	}
2327	/* validation passed */
2328
2329	icmp6len -= sizeof(*nd_rd);
2330	nd6_option_init(nd_rd + 1, icmp6len, &ndopts);
2331	if (nd6_options(&ndopts) < 0) {
2332		nd6log((LOG_INFO, "icmp6_redirect_input: "
2333		    "invalid ND option, rejected: %s\n",
2334		    icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2335		/* nd6_options have incremented stats */
2336		goto freeit;
2337	}
2338
2339	if (ndopts.nd_opts_tgt_lladdr) {
2340		lladdr = (char *)(ndopts.nd_opts_tgt_lladdr + 1);
2341		lladdrlen = ndopts.nd_opts_tgt_lladdr->nd_opt_len << 3;
2342	}
2343
2344	if (ndopts.nd_opts_rh) {
2345		redirhdrlen = ndopts.nd_opts_rh->nd_opt_rh_len;
2346		redirhdr = (u_char *)(ndopts.nd_opts_rh + 1); /* xxx */
2347	}
2348
2349	if (lladdr && ((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
2350		nd6log((LOG_INFO,
2351		    "icmp6_redirect_input: lladdrlen mismatch for %s "
2352		    "(if %d, icmp6 packet %d): %s\n",
2353		    ip6_sprintf(ip6buf, &redtgt6),
2354		    ifp->if_addrlen, lladdrlen - 2,
2355		    icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2356		goto bad;
2357	}
2358
2359	/* RFC 2461 8.3 */
2360	nd6_cache_lladdr(ifp, &redtgt6, lladdr, lladdrlen, ND_REDIRECT,
2361	    is_onlink ? ND_REDIRECT_ONLINK : ND_REDIRECT_ROUTER);
2362
2363	if (!is_onlink) {	/* better router case.  perform rtredirect. */
2364		/* perform rtredirect */
2365		struct sockaddr_in6 sdst;
2366		struct sockaddr_in6 sgw;
2367		struct sockaddr_in6 ssrc;
2368
2369		bzero(&sdst, sizeof(sdst));
2370		bzero(&sgw, sizeof(sgw));
2371		bzero(&ssrc, sizeof(ssrc));
2372		sdst.sin6_family = sgw.sin6_family = ssrc.sin6_family = AF_INET6;
2373		sdst.sin6_len = sgw.sin6_len = ssrc.sin6_len =
2374			sizeof(struct sockaddr_in6);
2375		bcopy(&redtgt6, &sgw.sin6_addr, sizeof(struct in6_addr));
2376		bcopy(&reddst6, &sdst.sin6_addr, sizeof(struct in6_addr));
2377		bcopy(&src6, &ssrc.sin6_addr, sizeof(struct in6_addr));
2378		rtredirect((struct sockaddr *)&sdst, (struct sockaddr *)&sgw,
2379		    (struct sockaddr *)NULL, RTF_GATEWAY | RTF_HOST,
2380		    (struct sockaddr *)&ssrc);
2381	}
2382	/* finally update cached route in each socket via pfctlinput */
2383    {
2384	struct sockaddr_in6 sdst;
2385
2386	bzero(&sdst, sizeof(sdst));
2387	sdst.sin6_family = AF_INET6;
2388	sdst.sin6_len = sizeof(struct sockaddr_in6);
2389	bcopy(&reddst6, &sdst.sin6_addr, sizeof(struct in6_addr));
2390	pfctlinput(PRC_REDIRECT_HOST, (struct sockaddr *)&sdst);
2391#ifdef IPSEC
2392	key_sa_routechange((struct sockaddr *)&sdst);
2393#endif /* IPSEC */
2394    }
2395
2396 freeit:
2397	m_freem(m);
2398	return;
2399
2400 bad:
2401	icmp6stat.icp6s_badredirect++;
2402	m_freem(m);
2403}
2404
2405void
2406icmp6_redirect_output(struct mbuf *m0, struct rtentry *rt)
2407{
2408	struct ifnet *ifp;	/* my outgoing interface */
2409	struct in6_addr *ifp_ll6;
2410	struct in6_addr *router_ll6;
2411	struct ip6_hdr *sip6;	/* m0 as struct ip6_hdr */
2412	struct mbuf *m = NULL;	/* newly allocated one */
2413	struct ip6_hdr *ip6;	/* m as struct ip6_hdr */
2414	struct nd_redirect *nd_rd;
2415	size_t maxlen;
2416	u_char *p;
2417	struct ifnet *outif = NULL;
2418	struct sockaddr_in6 src_sa;
2419
2420	icmp6_errcount(&icmp6stat.icp6s_outerrhist, ND_REDIRECT, 0);
2421
2422	/* if we are not router, we don't send icmp6 redirect */
2423	if (!ip6_forwarding)
2424		goto fail;
2425
2426	/* sanity check */
2427	if (!m0 || !rt || !(rt->rt_flags & RTF_UP) || !(ifp = rt->rt_ifp))
2428		goto fail;
2429
2430	/*
2431	 * Address check:
2432	 *  the source address must identify a neighbor, and
2433	 *  the destination address must not be a multicast address
2434	 *  [RFC 2461, sec 8.2]
2435	 */
2436	sip6 = mtod(m0, struct ip6_hdr *);
2437	bzero(&src_sa, sizeof(src_sa));
2438	src_sa.sin6_family = AF_INET6;
2439	src_sa.sin6_len = sizeof(src_sa);
2440	src_sa.sin6_addr = sip6->ip6_src;
2441	if (nd6_is_addr_neighbor(&src_sa, ifp) == 0)
2442		goto fail;
2443	if (IN6_IS_ADDR_MULTICAST(&sip6->ip6_dst))
2444		goto fail;	/* what should we do here? */
2445
2446	/* rate limit */
2447	if (icmp6_ratelimit(&sip6->ip6_src, ND_REDIRECT, 0))
2448		goto fail;
2449
2450	/*
2451	 * Since we are going to append up to 1280 bytes (= IPV6_MMTU),
2452	 * we almost always ask for an mbuf cluster for simplicity.
2453	 * (MHLEN < IPV6_MMTU is almost always true)
2454	 */
2455#if IPV6_MMTU >= MCLBYTES
2456# error assumption failed about IPV6_MMTU and MCLBYTES
2457#endif
2458	MGETHDR(m, M_DONTWAIT, MT_HEADER);
2459	if (m && IPV6_MMTU >= MHLEN)
2460		MCLGET(m, M_DONTWAIT);
2461	if (!m)
2462		goto fail;
2463	m->m_pkthdr.rcvif = NULL;
2464	m->m_len = 0;
2465	maxlen = M_TRAILINGSPACE(m);
2466	maxlen = min(IPV6_MMTU, maxlen);
2467	/* just for safety */
2468	if (maxlen < sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr) +
2469	    ((sizeof(struct nd_opt_hdr) + ifp->if_addrlen + 7) & ~7)) {
2470		goto fail;
2471	}
2472
2473	{
2474		/* get ip6 linklocal address for ifp(my outgoing interface). */
2475		struct in6_ifaddr *ia;
2476		if ((ia = in6ifa_ifpforlinklocal(ifp,
2477						 IN6_IFF_NOTREADY|
2478						 IN6_IFF_ANYCAST)) == NULL)
2479			goto fail;
2480		ifp_ll6 = &ia->ia_addr.sin6_addr;
2481	}
2482
2483	/* get ip6 linklocal address for the router. */
2484	if (rt->rt_gateway && (rt->rt_flags & RTF_GATEWAY)) {
2485		struct sockaddr_in6 *sin6;
2486		sin6 = (struct sockaddr_in6 *)rt->rt_gateway;
2487		router_ll6 = &sin6->sin6_addr;
2488		if (!IN6_IS_ADDR_LINKLOCAL(router_ll6))
2489			router_ll6 = (struct in6_addr *)NULL;
2490	} else
2491		router_ll6 = (struct in6_addr *)NULL;
2492
2493	/* ip6 */
2494	ip6 = mtod(m, struct ip6_hdr *);
2495	ip6->ip6_flow = 0;
2496	ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
2497	ip6->ip6_vfc |= IPV6_VERSION;
2498	/* ip6->ip6_plen will be set later */
2499	ip6->ip6_nxt = IPPROTO_ICMPV6;
2500	ip6->ip6_hlim = 255;
2501	/* ip6->ip6_src must be linklocal addr for my outgoing if. */
2502	bcopy(ifp_ll6, &ip6->ip6_src, sizeof(struct in6_addr));
2503	bcopy(&sip6->ip6_src, &ip6->ip6_dst, sizeof(struct in6_addr));
2504
2505	/* ND Redirect */
2506	nd_rd = (struct nd_redirect *)(ip6 + 1);
2507	nd_rd->nd_rd_type = ND_REDIRECT;
2508	nd_rd->nd_rd_code = 0;
2509	nd_rd->nd_rd_reserved = 0;
2510	if (rt->rt_flags & RTF_GATEWAY) {
2511		/*
2512		 * nd_rd->nd_rd_target must be a link-local address in
2513		 * better router cases.
2514		 */
2515		if (!router_ll6)
2516			goto fail;
2517		bcopy(router_ll6, &nd_rd->nd_rd_target,
2518		    sizeof(nd_rd->nd_rd_target));
2519		bcopy(&sip6->ip6_dst, &nd_rd->nd_rd_dst,
2520		    sizeof(nd_rd->nd_rd_dst));
2521	} else {
2522		/* make sure redtgt == reddst */
2523		bcopy(&sip6->ip6_dst, &nd_rd->nd_rd_target,
2524		    sizeof(nd_rd->nd_rd_target));
2525		bcopy(&sip6->ip6_dst, &nd_rd->nd_rd_dst,
2526		    sizeof(nd_rd->nd_rd_dst));
2527	}
2528
2529	p = (u_char *)(nd_rd + 1);
2530
2531	if (!router_ll6)
2532		goto nolladdropt;
2533
2534	{
2535		/* target lladdr option */
2536		struct rtentry *rt_router = NULL;
2537		int len;
2538		struct sockaddr_dl *sdl;
2539		struct nd_opt_hdr *nd_opt;
2540		char *lladdr;
2541
2542		rt_router = nd6_lookup(router_ll6, 0, ifp);
2543		if (!rt_router)
2544			goto nolladdropt;
2545		len = sizeof(*nd_opt) + ifp->if_addrlen;
2546		len = (len + 7) & ~7;	/* round by 8 */
2547		/* safety check */
2548		if (len + (p - (u_char *)ip6) > maxlen)
2549			goto nolladdropt;
2550		if (!(rt_router->rt_flags & RTF_GATEWAY) &&
2551		    (rt_router->rt_flags & RTF_LLINFO) &&
2552		    (rt_router->rt_gateway->sa_family == AF_LINK) &&
2553		    (sdl = (struct sockaddr_dl *)rt_router->rt_gateway) &&
2554		    sdl->sdl_alen) {
2555			nd_opt = (struct nd_opt_hdr *)p;
2556			nd_opt->nd_opt_type = ND_OPT_TARGET_LINKADDR;
2557			nd_opt->nd_opt_len = len >> 3;
2558			lladdr = (char *)(nd_opt + 1);
2559			bcopy(LLADDR(sdl), lladdr, ifp->if_addrlen);
2560			p += len;
2561		}
2562	}
2563nolladdropt:;
2564
2565	m->m_pkthdr.len = m->m_len = p - (u_char *)ip6;
2566
2567	/* just to be safe */
2568#ifdef M_DECRYPTED	/*not openbsd*/
2569	if (m0->m_flags & M_DECRYPTED)
2570		goto noredhdropt;
2571#endif
2572	if (p - (u_char *)ip6 > maxlen)
2573		goto noredhdropt;
2574
2575	{
2576		/* redirected header option */
2577		int len;
2578		struct nd_opt_rd_hdr *nd_opt_rh;
2579
2580		/*
2581		 * compute the maximum size for icmp6 redirect header option.
2582		 * XXX room for auth header?
2583		 */
2584		len = maxlen - (p - (u_char *)ip6);
2585		len &= ~7;
2586
2587		/* This is just for simplicity. */
2588		if (m0->m_pkthdr.len != m0->m_len) {
2589			if (m0->m_next) {
2590				m_freem(m0->m_next);
2591				m0->m_next = NULL;
2592			}
2593			m0->m_pkthdr.len = m0->m_len;
2594		}
2595
2596		/*
2597		 * Redirected header option spec (RFC2461 4.6.3) talks nothing
2598		 * about padding/truncate rule for the original IP packet.
2599		 * From the discussion on IPv6imp in Feb 1999,
2600		 * the consensus was:
2601		 * - "attach as much as possible" is the goal
2602		 * - pad if not aligned (original size can be guessed by
2603		 *   original ip6 header)
2604		 * Following code adds the padding if it is simple enough,
2605		 * and truncates if not.
2606		 */
2607		if (m0->m_next || m0->m_pkthdr.len != m0->m_len)
2608			panic("assumption failed in %s:%d", __FILE__,
2609			    __LINE__);
2610
2611		if (len - sizeof(*nd_opt_rh) < m0->m_pkthdr.len) {
2612			/* not enough room, truncate */
2613			m0->m_pkthdr.len = m0->m_len = len -
2614			    sizeof(*nd_opt_rh);
2615		} else {
2616			/* enough room, pad or truncate */
2617			size_t extra;
2618
2619			extra = m0->m_pkthdr.len % 8;
2620			if (extra) {
2621				/* pad if easy enough, truncate if not */
2622				if (8 - extra <= M_TRAILINGSPACE(m0)) {
2623					/* pad */
2624					m0->m_len += (8 - extra);
2625					m0->m_pkthdr.len += (8 - extra);
2626				} else {
2627					/* truncate */
2628					m0->m_pkthdr.len -= extra;
2629					m0->m_len -= extra;
2630				}
2631			}
2632			len = m0->m_pkthdr.len + sizeof(*nd_opt_rh);
2633			m0->m_pkthdr.len = m0->m_len = len -
2634			    sizeof(*nd_opt_rh);
2635		}
2636
2637		nd_opt_rh = (struct nd_opt_rd_hdr *)p;
2638		bzero(nd_opt_rh, sizeof(*nd_opt_rh));
2639		nd_opt_rh->nd_opt_rh_type = ND_OPT_REDIRECTED_HEADER;
2640		nd_opt_rh->nd_opt_rh_len = len >> 3;
2641		p += sizeof(*nd_opt_rh);
2642		m->m_pkthdr.len = m->m_len = p - (u_char *)ip6;
2643
2644		/* connect m0 to m */
2645		m_tag_delete_chain(m0, NULL);
2646		m0->m_flags &= ~M_PKTHDR;
2647		m->m_next = m0;
2648		m->m_pkthdr.len = m->m_len + m0->m_len;
2649		m0 = NULL;
2650	}
2651noredhdropt:;
2652	if (m0) {
2653		m_freem(m0);
2654		m0 = NULL;
2655	}
2656
2657	/* XXX: clear embedded link IDs in the inner header */
2658	in6_clearscope(&sip6->ip6_src);
2659	in6_clearscope(&sip6->ip6_dst);
2660	in6_clearscope(&nd_rd->nd_rd_target);
2661	in6_clearscope(&nd_rd->nd_rd_dst);
2662
2663	ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(struct ip6_hdr));
2664
2665	nd_rd->nd_rd_cksum = 0;
2666	nd_rd->nd_rd_cksum = in6_cksum(m, IPPROTO_ICMPV6,
2667	    sizeof(*ip6), ntohs(ip6->ip6_plen));
2668
2669	/* send the packet to outside... */
2670	ip6_output(m, NULL, NULL, 0, NULL, &outif, NULL);
2671	if (outif) {
2672		icmp6_ifstat_inc(outif, ifs6_out_msg);
2673		icmp6_ifstat_inc(outif, ifs6_out_redirect);
2674	}
2675	icmp6stat.icp6s_outhist[ND_REDIRECT]++;
2676
2677	return;
2678
2679fail:
2680	if (m)
2681		m_freem(m);
2682	if (m0)
2683		m_freem(m0);
2684}
2685
2686/*
2687 * ICMPv6 socket option processing.
2688 */
2689int
2690icmp6_ctloutput(struct socket *so, struct sockopt *sopt)
2691{
2692	int error = 0;
2693	int optlen;
2694	struct inpcb *inp = sotoinpcb(so);
2695	int level, op, optname;
2696
2697	if (sopt) {
2698		level = sopt->sopt_level;
2699		op = sopt->sopt_dir;
2700		optname = sopt->sopt_name;
2701		optlen = sopt->sopt_valsize;
2702	} else
2703		level = op = optname = optlen = 0;
2704
2705	if (level != IPPROTO_ICMPV6) {
2706		return EINVAL;
2707	}
2708
2709	switch (op) {
2710	case PRCO_SETOPT:
2711		switch (optname) {
2712		case ICMP6_FILTER:
2713		    {
2714			struct icmp6_filter *p;
2715
2716			if (optlen != sizeof(*p)) {
2717				error = EMSGSIZE;
2718				break;
2719			}
2720			if (inp->in6p_icmp6filt == NULL) {
2721				error = EINVAL;
2722				break;
2723			}
2724			error = sooptcopyin(sopt, inp->in6p_icmp6filt, optlen,
2725				optlen);
2726			break;
2727		    }
2728
2729		default:
2730			error = ENOPROTOOPT;
2731			break;
2732		}
2733		break;
2734
2735	case PRCO_GETOPT:
2736		switch (optname) {
2737		case ICMP6_FILTER:
2738		    {
2739			if (inp->in6p_icmp6filt == NULL) {
2740				error = EINVAL;
2741				break;
2742			}
2743			error = sooptcopyout(sopt, inp->in6p_icmp6filt,
2744				sizeof(struct icmp6_filter));
2745			break;
2746		    }
2747
2748		default:
2749			error = ENOPROTOOPT;
2750			break;
2751		}
2752		break;
2753	}
2754
2755	return (error);
2756}
2757
2758/*
2759 * Perform rate limit check.
2760 * Returns 0 if it is okay to send the icmp6 packet.
2761 * Returns 1 if the router SHOULD NOT send this icmp6 packet due to rate
2762 * limitation.
2763 *
2764 * XXX per-destination/type check necessary?
2765 *
2766 * dst - not used at this moment
2767 * type - not used at this moment
2768 * code - not used at this moment
2769 */
2770static int
2771icmp6_ratelimit(const struct in6_addr *dst, const int type,
2772    const int code)
2773{
2774	int ret;
2775
2776	ret = 0;	/* okay to send */
2777
2778	/* PPS limit */
2779	if (!ppsratecheck(&icmp6errppslim_last, &icmp6errpps_count,
2780	    icmp6errppslim)) {
2781		/* The packet is subject to rate limit */
2782		ret++;
2783	}
2784
2785	return ret;
2786}
2787