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