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