xref: /freebsd/sys/netinet6/ip6_input.c (revision 9162f64b58d01ec01481d60b6cdc06ffd8e8c7fc)
1 /*-
2  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the project nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *	$KAME: ip6_input.c,v 1.259 2002/01/21 04:58:09 jinmei Exp $
30  */
31 
32 /*-
33  * Copyright (c) 1982, 1986, 1988, 1993
34  *	The Regents of the University of California.  All rights reserved.
35  *
36  * Redistribution and use in source and binary forms, with or without
37  * modification, are permitted provided that the following conditions
38  * are met:
39  * 1. Redistributions of source code must retain the above copyright
40  *    notice, this list of conditions and the following disclaimer.
41  * 2. Redistributions in binary form must reproduce the above copyright
42  *    notice, this list of conditions and the following disclaimer in the
43  *    documentation and/or other materials provided with the distribution.
44  * 4. Neither the name of the University nor the names of its contributors
45  *    may be used to endorse or promote products derived from this software
46  *    without specific prior written permission.
47  *
48  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58  * SUCH DAMAGE.
59  *
60  *	@(#)ip_input.c	8.2 (Berkeley) 1/4/94
61  */
62 
63 #include <sys/cdefs.h>
64 __FBSDID("$FreeBSD$");
65 
66 #include "opt_inet.h"
67 #include "opt_inet6.h"
68 #include "opt_ipsec.h"
69 
70 #include <sys/param.h>
71 #include <sys/systm.h>
72 #include <sys/malloc.h>
73 #include <sys/mbuf.h>
74 #include <sys/proc.h>
75 #include <sys/domain.h>
76 #include <sys/protosw.h>
77 #include <sys/socket.h>
78 #include <sys/socketvar.h>
79 #include <sys/errno.h>
80 #include <sys/time.h>
81 #include <sys/kernel.h>
82 #include <sys/syslog.h>
83 #include <sys/vimage.h>
84 
85 #include <net/if.h>
86 #include <net/if_types.h>
87 #include <net/if_dl.h>
88 #include <net/route.h>
89 #include <net/netisr.h>
90 #include <net/pfil.h>
91 #include <net/vnet.h>
92 
93 #include <netinet/in.h>
94 #include <netinet/in_systm.h>
95 #include <net/if_llatbl.h>
96 #ifdef INET
97 #include <netinet/ip.h>
98 #include <netinet/ip_icmp.h>
99 #include <netinet/vinet.h>
100 #endif /* INET */
101 #include <netinet/ip6.h>
102 #include <netinet6/in6_var.h>
103 #include <netinet6/ip6_var.h>
104 #include <netinet/in_pcb.h>
105 #include <netinet/icmp6.h>
106 #include <netinet6/scope6_var.h>
107 #include <netinet6/in6_ifattach.h>
108 #include <netinet6/nd6.h>
109 #include <netinet6/vinet6.h>
110 
111 #ifdef IPSEC
112 #include <netipsec/ipsec.h>
113 #include <netinet6/ip6_ipsec.h>
114 #include <netipsec/ipsec6.h>
115 #endif /* IPSEC */
116 
117 #include <netinet6/ip6protosw.h>
118 
119 extern struct domain inet6domain;
120 
121 u_char ip6_protox[IPPROTO_MAX];
122 static struct ifqueue ip6intrq;
123 
124 #ifndef VIMAGE
125 #ifndef VIMAGE_GLOBALS
126 struct vnet_inet6 vnet_inet6_0;
127 #endif
128 #endif
129 
130 #ifdef VIMAGE_GLOBALS
131 static int ip6qmaxlen;
132 struct in6_ifaddr *in6_ifaddr;
133 struct ip6stat ip6stat;
134 
135 extern struct callout in6_tmpaddrtimer_ch;
136 
137 extern int dad_init;
138 extern int pmtu_expire;
139 extern int pmtu_probe;
140 extern u_long rip6_sendspace;
141 extern u_long rip6_recvspace;
142 extern int icmp6errppslim;
143 extern int icmp6_nodeinfo;
144 extern int udp6_sendspace;
145 extern int udp6_recvspace;
146 
147 extern struct	route_in6 ip6_forward_rt;
148 
149 int ip6_forward_srcrt;			/* XXX */
150 int ip6_sourcecheck;			/* XXX */
151 int ip6_sourcecheck_interval;		/* XXX */
152 int ip6_ours_check_algorithm;
153 #endif
154 
155 struct pfil_head inet6_pfil_hook;
156 
157 static void ip6_init2(void *);
158 static struct ip6aux *ip6_setdstifaddr(struct mbuf *, struct in6_ifaddr *);
159 static int ip6_hopopts_input(u_int32_t *, u_int32_t *, struct mbuf **, int *);
160 #ifdef PULLDOWN_TEST
161 static struct mbuf *ip6_pullexthdr(struct mbuf *, size_t, int);
162 #endif
163 
164 /*
165  * IP6 initialization: fill in IP6 protocol switch table.
166  * All protocols not implemented in kernel go to raw IP6 protocol handler.
167  */
168 void
169 ip6_init(void)
170 {
171 	INIT_VNET_INET6(curvnet);
172 	struct ip6protosw *pr;
173 	int i;
174 
175 	V_ip6qmaxlen = IFQ_MAXLEN;
176 	V_in6_maxmtu = 0;
177 #ifdef IP6_AUTO_LINKLOCAL
178 	V_ip6_auto_linklocal = IP6_AUTO_LINKLOCAL;
179 #else
180 	V_ip6_auto_linklocal = 1;	/* enable by default */
181 #endif
182 	TUNABLE_INT_FETCH("net.inet6.ip6.auto_linklocal",
183 	    &V_ip6_auto_linklocal);
184 
185 #ifndef IPV6FORWARDING
186 #ifdef GATEWAY6
187 #define IPV6FORWARDING	1	/* forward IP6 packets not for us */
188 #else
189 #define IPV6FORWARDING	0	/* don't forward IP6 packets not for us */
190 #endif /* GATEWAY6 */
191 #endif /* !IPV6FORWARDING */
192 
193 #ifndef IPV6_SENDREDIRECTS
194 #define IPV6_SENDREDIRECTS	1
195 #endif
196 
197 	V_ip6_forwarding = IPV6FORWARDING; /* act as router? */
198 	V_ip6_sendredirects = IPV6_SENDREDIRECTS;
199 	V_ip6_defhlim = IPV6_DEFHLIM;
200 	V_ip6_defmcasthlim = IPV6_DEFAULT_MULTICAST_HOPS;
201 	V_ip6_accept_rtadv = 0;	 /* "IPV6FORWARDING ? 0 : 1" is dangerous */
202 	V_ip6_log_interval = 5;
203 	V_ip6_hdrnestlimit = 15; /* How many header options will we process? */
204 	V_ip6_dad_count = 1;	 /* DupAddrDetectionTransmits */
205 	V_ip6_auto_flowlabel = 1;
206 	V_ip6_use_deprecated = 1;/* allow deprecated addr (RFC2462 5.5.4) */
207 	V_ip6_rr_prune = 5;	 /* router renumbering prefix
208                                   * walk list every 5 sec. */
209 	V_ip6_mcast_pmtu = 0;	 /* enable pMTU discovery for multicast? */
210 	V_ip6_v6only = 1;
211 	V_ip6_keepfaith = 0;
212 	V_ip6_log_time = (time_t)0L;
213 #ifdef IPSTEALTH
214 	V_ip6stealth = 0;
215 #endif
216 	V_nd6_onlink_ns_rfc4861 = 0; /* allow 'on-link' nd6 NS (RFC 4861) */
217 
218 	V_pmtu_expire = 60*10;
219 	V_pmtu_probe = 60*2;
220 
221 	/* raw IP6 parameters */
222 	/*
223 	 * Nominal space allocated to a raw ip socket.
224 	 */
225 #define RIPV6SNDQ	8192
226 #define RIPV6RCVQ	8192
227 	V_rip6_sendspace = RIPV6SNDQ;
228 	V_rip6_recvspace = RIPV6RCVQ;
229 
230 	/* ICMPV6 parameters */
231 	V_icmp6_rediraccept = 1;	/* accept and process redirects */
232 	V_icmp6_redirtimeout = 10 * 60;	/* 10 minutes */
233 	V_icmp6errppslim = 100;		/* 100pps */
234 	/* control how to respond to NI queries */
235 	V_icmp6_nodeinfo = (ICMP6_NODEINFO_FQDNOK|ICMP6_NODEINFO_NODEADDROK);
236 
237 	/* UDP on IP6 parameters */
238 	V_udp6_sendspace = 9216;	/* really max datagram size */
239 	V_udp6_recvspace = 40 * (1024 + sizeof(struct sockaddr_in6));
240 					/* 40 1K datagrams */
241 	V_dad_init = 0;
242 
243 #ifdef DIAGNOSTIC
244 	if (sizeof(struct protosw) != sizeof(struct ip6protosw))
245 		panic("sizeof(protosw) != sizeof(ip6protosw)");
246 #endif
247 	pr = (struct ip6protosw *)pffindproto(PF_INET6, IPPROTO_RAW, SOCK_RAW);
248 	if (pr == 0)
249 		panic("ip6_init");
250 
251 	/* Initialize the entire ip6_protox[] array to IPPROTO_RAW. */
252 	for (i = 0; i < IPPROTO_MAX; i++)
253 		ip6_protox[i] = pr - inet6sw;
254 	/*
255 	 * Cycle through IP protocols and put them into the appropriate place
256 	 * in ip6_protox[].
257 	 */
258 	for (pr = (struct ip6protosw *)inet6domain.dom_protosw;
259 	    pr < (struct ip6protosw *)inet6domain.dom_protoswNPROTOSW; pr++)
260 		if (pr->pr_domain->dom_family == PF_INET6 &&
261 		    pr->pr_protocol && pr->pr_protocol != IPPROTO_RAW) {
262 			/* Be careful to only index valid IP protocols. */
263 			if (pr->pr_protocol < IPPROTO_MAX)
264 				ip6_protox[pr->pr_protocol] = pr - inet6sw;
265 		}
266 
267 	/* Initialize packet filter hooks. */
268 	inet6_pfil_hook.ph_type = PFIL_TYPE_AF;
269 	inet6_pfil_hook.ph_af = AF_INET6;
270 	if ((i = pfil_head_register(&inet6_pfil_hook)) != 0)
271 		printf("%s: WARNING: unable to register pfil hook, "
272 			"error %d\n", __func__, i);
273 
274 	ip6intrq.ifq_maxlen = V_ip6qmaxlen;
275 	mtx_init(&ip6intrq.ifq_mtx, "ip6_inq", NULL, MTX_DEF);
276 	netisr_register(NETISR_IPV6, ip6_input, &ip6intrq, 0);
277 	scope6_init();
278 	addrsel_policy_init();
279 	nd6_init();
280 	frag6_init();
281 	V_ip6_desync_factor = arc4random() % MAX_TEMP_DESYNC_FACTOR;
282 }
283 
284 static void
285 ip6_init2(void *dummy)
286 {
287 	INIT_VNET_INET6(curvnet);
288 
289 	/* nd6_timer_init */
290 	callout_init(&V_nd6_timer_ch, 0);
291 	callout_reset(&V_nd6_timer_ch, hz, nd6_timer, NULL);
292 
293 	/* timer for regeneranation of temporary addresses randomize ID */
294 	callout_init(&V_in6_tmpaddrtimer_ch, 0);
295 	callout_reset(&V_in6_tmpaddrtimer_ch,
296 		      (V_ip6_temp_preferred_lifetime - V_ip6_desync_factor -
297 		       V_ip6_temp_regen_advance) * hz,
298 		      in6_tmpaddrtimer, NULL);
299 }
300 
301 /* cheat */
302 /* This must be after route_init(), which is now SI_ORDER_THIRD */
303 SYSINIT(netinet6init2, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE, ip6_init2, NULL);
304 
305 void
306 ip6_input(struct mbuf *m)
307 {
308 	INIT_VNET_NET(curvnet);
309 	INIT_VNET_INET6(curvnet);
310 	struct ip6_hdr *ip6;
311 	int off = sizeof(struct ip6_hdr), nest;
312 	u_int32_t plen;
313 	u_int32_t rtalert = ~0;
314 	int nxt, ours = 0;
315 	struct ifnet *deliverifp = NULL, *ifp = NULL;
316 	struct in6_addr odst;
317 	int srcrt = 0;
318 	struct llentry *lle = NULL;
319 	struct sockaddr_in6 dst6;
320 
321 #ifdef IPSEC
322 	/*
323 	 * should the inner packet be considered authentic?
324 	 * see comment in ah4_input().
325 	 * NB: m cannot be NULL when passed to the input routine
326 	 */
327 
328 	m->m_flags &= ~M_AUTHIPHDR;
329 	m->m_flags &= ~M_AUTHIPDGM;
330 
331 #endif /* IPSEC */
332 
333 	/*
334 	 * make sure we don't have onion peering information into m_tag.
335 	 */
336 	ip6_delaux(m);
337 
338 	/*
339 	 * mbuf statistics
340 	 */
341 	if (m->m_flags & M_EXT) {
342 		if (m->m_next)
343 			V_ip6stat.ip6s_mext2m++;
344 		else
345 			V_ip6stat.ip6s_mext1++;
346 	} else {
347 #define M2MMAX	(sizeof(V_ip6stat.ip6s_m2m)/sizeof(V_ip6stat.ip6s_m2m[0]))
348 		if (m->m_next) {
349 			if (m->m_flags & M_LOOP) {
350 				V_ip6stat.ip6s_m2m[V_loif[0].if_index]++; /* XXX */
351 			} else if (m->m_pkthdr.rcvif->if_index < M2MMAX)
352 				V_ip6stat.ip6s_m2m[m->m_pkthdr.rcvif->if_index]++;
353 			else
354 				V_ip6stat.ip6s_m2m[0]++;
355 		} else
356 			V_ip6stat.ip6s_m1++;
357 #undef M2MMAX
358 	}
359 
360 	/* drop the packet if IPv6 operation is disabled on the IF */
361 	if ((ND_IFINFO(m->m_pkthdr.rcvif)->flags & ND6_IFF_IFDISABLED)) {
362 		m_freem(m);
363 		return;
364 	}
365 
366 	in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_receive);
367 	V_ip6stat.ip6s_total++;
368 
369 #ifndef PULLDOWN_TEST
370 	/*
371 	 * L2 bridge code and some other code can return mbuf chain
372 	 * that does not conform to KAME requirement.  too bad.
373 	 * XXX: fails to join if interface MTU > MCLBYTES.  jumbogram?
374 	 */
375 	if (m && m->m_next != NULL && m->m_pkthdr.len < MCLBYTES) {
376 		struct mbuf *n;
377 
378 		MGETHDR(n, M_DONTWAIT, MT_HEADER);
379 		if (n)
380 			M_MOVE_PKTHDR(n, m);
381 		if (n && n->m_pkthdr.len > MHLEN) {
382 			MCLGET(n, M_DONTWAIT);
383 			if ((n->m_flags & M_EXT) == 0) {
384 				m_freem(n);
385 				n = NULL;
386 			}
387 		}
388 		if (n == NULL) {
389 			m_freem(m);
390 			return;	/* ENOBUFS */
391 		}
392 
393 		m_copydata(m, 0, n->m_pkthdr.len, mtod(n, caddr_t));
394 		n->m_len = n->m_pkthdr.len;
395 		m_freem(m);
396 		m = n;
397 	}
398 	IP6_EXTHDR_CHECK(m, 0, sizeof(struct ip6_hdr), /* nothing */);
399 #endif
400 
401 	if (m->m_len < sizeof(struct ip6_hdr)) {
402 		struct ifnet *inifp;
403 		inifp = m->m_pkthdr.rcvif;
404 		if ((m = m_pullup(m, sizeof(struct ip6_hdr))) == NULL) {
405 			V_ip6stat.ip6s_toosmall++;
406 			in6_ifstat_inc(inifp, ifs6_in_hdrerr);
407 			return;
408 		}
409 	}
410 
411 	ip6 = mtod(m, struct ip6_hdr *);
412 
413 	if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION) {
414 		V_ip6stat.ip6s_badvers++;
415 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_hdrerr);
416 		goto bad;
417 	}
418 
419 	V_ip6stat.ip6s_nxthist[ip6->ip6_nxt]++;
420 
421 	/*
422 	 * Check against address spoofing/corruption.
423 	 */
424 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_src) ||
425 	    IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_dst)) {
426 		/*
427 		 * XXX: "badscope" is not very suitable for a multicast source.
428 		 */
429 		V_ip6stat.ip6s_badscope++;
430 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_addrerr);
431 		goto bad;
432 	}
433 	if (IN6_IS_ADDR_MC_INTFACELOCAL(&ip6->ip6_dst) &&
434 	    !(m->m_flags & M_LOOP)) {
435 		/*
436 		 * In this case, the packet should come from the loopback
437 		 * interface.  However, we cannot just check the if_flags,
438 		 * because ip6_mloopback() passes the "actual" interface
439 		 * as the outgoing/incoming interface.
440 		 */
441 		V_ip6stat.ip6s_badscope++;
442 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_addrerr);
443 		goto bad;
444 	}
445 
446 #ifdef ALTQ
447 	if (altq_input != NULL && (*altq_input)(m, AF_INET6) == 0) {
448 		/* packet is dropped by traffic conditioner */
449 		return;
450 	}
451 #endif
452 	/*
453 	 * The following check is not documented in specs.  A malicious
454 	 * party may be able to use IPv4 mapped addr to confuse tcp/udp stack
455 	 * and bypass security checks (act as if it was from 127.0.0.1 by using
456 	 * IPv6 src ::ffff:127.0.0.1).  Be cautious.
457 	 *
458 	 * This check chokes if we are in an SIIT cloud.  As none of BSDs
459 	 * support IPv4-less kernel compilation, we cannot support SIIT
460 	 * environment at all.  So, it makes more sense for us to reject any
461 	 * malicious packets for non-SIIT environment, than try to do a
462 	 * partial support for SIIT environment.
463 	 */
464 	if (IN6_IS_ADDR_V4MAPPED(&ip6->ip6_src) ||
465 	    IN6_IS_ADDR_V4MAPPED(&ip6->ip6_dst)) {
466 		V_ip6stat.ip6s_badscope++;
467 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_addrerr);
468 		goto bad;
469 	}
470 #if 0
471 	/*
472 	 * Reject packets with IPv4 compatible addresses (auto tunnel).
473 	 *
474 	 * The code forbids auto tunnel relay case in RFC1933 (the check is
475 	 * stronger than RFC1933).  We may want to re-enable it if mech-xx
476 	 * is revised to forbid relaying case.
477 	 */
478 	if (IN6_IS_ADDR_V4COMPAT(&ip6->ip6_src) ||
479 	    IN6_IS_ADDR_V4COMPAT(&ip6->ip6_dst)) {
480 		V_ip6stat.ip6s_badscope++;
481 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_addrerr);
482 		goto bad;
483 	}
484 #endif
485 
486 	/*
487 	 * Run through list of hooks for input packets.
488 	 *
489 	 * NB: Beware of the destination address changing
490 	 *     (e.g. by NAT rewriting).  When this happens,
491 	 *     tell ip6_forward to do the right thing.
492 	 */
493 	odst = ip6->ip6_dst;
494 
495 	/* Jump over all PFIL processing if hooks are not active. */
496 	if (!PFIL_HOOKED(&inet6_pfil_hook))
497 		goto passin;
498 
499 	if (pfil_run_hooks(&inet6_pfil_hook, &m, m->m_pkthdr.rcvif, PFIL_IN, NULL))
500 		return;
501 	if (m == NULL)			/* consumed by filter */
502 		return;
503 	ip6 = mtod(m, struct ip6_hdr *);
504 	srcrt = !IN6_ARE_ADDR_EQUAL(&odst, &ip6->ip6_dst);
505 
506 passin:
507 	/*
508 	 * Disambiguate address scope zones (if there is ambiguity).
509 	 * We first make sure that the original source or destination address
510 	 * is not in our internal form for scoped addresses.  Such addresses
511 	 * are not necessarily invalid spec-wise, but we cannot accept them due
512 	 * to the usage conflict.
513 	 * in6_setscope() then also checks and rejects the cases where src or
514 	 * dst are the loopback address and the receiving interface
515 	 * is not loopback.
516 	 */
517 	if (in6_clearscope(&ip6->ip6_src) || in6_clearscope(&ip6->ip6_dst)) {
518 		V_ip6stat.ip6s_badscope++; /* XXX */
519 		goto bad;
520 	}
521 	if (in6_setscope(&ip6->ip6_src, m->m_pkthdr.rcvif, NULL) ||
522 	    in6_setscope(&ip6->ip6_dst, m->m_pkthdr.rcvif, NULL)) {
523 		V_ip6stat.ip6s_badscope++;
524 		goto bad;
525 	}
526 
527 	/*
528 	 * Multicast check
529 	 */
530 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
531 		struct in6_multi *in6m = 0;
532 
533 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_mcast);
534 		/*
535 		 * See if we belong to the destination multicast group on the
536 		 * arrival interface.
537 		 */
538 		IN6_LOOKUP_MULTI(ip6->ip6_dst, m->m_pkthdr.rcvif, in6m);
539 		if (in6m)
540 			ours = 1;
541 		else if (!ip6_mrouter) {
542 			V_ip6stat.ip6s_notmember++;
543 			V_ip6stat.ip6s_cantforward++;
544 			in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_discard);
545 			goto bad;
546 		}
547 		deliverifp = m->m_pkthdr.rcvif;
548 		goto hbhcheck;
549 	}
550 
551 	/*
552 	 *  Unicast check
553 	 */
554 
555 	bzero(&dst6, sizeof(dst6));
556 	dst6.sin6_family = AF_INET6;
557 	dst6.sin6_len = sizeof(struct sockaddr_in6);
558 	dst6.sin6_addr = ip6->ip6_dst;
559 	ifp = m->m_pkthdr.rcvif;
560 	IF_AFDATA_LOCK(ifp);
561 	lle = lla_lookup(LLTABLE6(ifp), 0,
562 	     (struct sockaddr *)&dst6);
563 	IF_AFDATA_UNLOCK(ifp);
564 	if ((lle != NULL) && (lle->la_flags & LLE_IFADDR)) {
565 		ours = 1;
566 		deliverifp = ifp;
567 		LLE_RUNLOCK(lle);
568 		goto hbhcheck;
569 	}
570 	if (lle != NULL)
571 		LLE_RUNLOCK(lle);
572 
573 	if (V_ip6_forward_rt.ro_rt != NULL &&
574 	    (V_ip6_forward_rt.ro_rt->rt_flags & RTF_UP) != 0 &&
575 	    IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
576 	    &((struct sockaddr_in6 *)(&V_ip6_forward_rt.ro_dst))->sin6_addr))
577 		V_ip6stat.ip6s_forward_cachehit++;
578 	else {
579 		struct sockaddr_in6 *dst6;
580 
581 		if (V_ip6_forward_rt.ro_rt) {
582 			/* route is down or destination is different */
583 			V_ip6stat.ip6s_forward_cachemiss++;
584 			RTFREE(V_ip6_forward_rt.ro_rt);
585 			V_ip6_forward_rt.ro_rt = 0;
586 		}
587 
588 		bzero(&V_ip6_forward_rt.ro_dst, sizeof(struct sockaddr_in6));
589 		dst6 = (struct sockaddr_in6 *)&V_ip6_forward_rt.ro_dst;
590 		dst6->sin6_len = sizeof(struct sockaddr_in6);
591 		dst6->sin6_family = AF_INET6;
592 		dst6->sin6_addr = ip6->ip6_dst;
593 
594 		rtalloc((struct route *)&V_ip6_forward_rt);
595 	}
596 
597 #define rt6_key(r) ((struct sockaddr_in6 *)((r)->rt_nodes->rn_key))
598 
599 	/*
600 	 * Accept the packet if the forwarding interface to the destination
601 	 * according to the routing table is the loopback interface,
602 	 * unless the associated route has a gateway.
603 	 * Note that this approach causes to accept a packet if there is a
604 	 * route to the loopback interface for the destination of the packet.
605 	 * But we think it's even useful in some situations, e.g. when using
606 	 * a special daemon which wants to intercept the packet.
607 	 *
608 	 * XXX: some OSes automatically make a cloned route for the destination
609 	 * of an outgoing packet.  If the outgoing interface of the packet
610 	 * is a loopback one, the kernel would consider the packet to be
611 	 * accepted, even if we have no such address assinged on the interface.
612 	 * We check the cloned flag of the route entry to reject such cases,
613 	 * assuming that route entries for our own addresses are not made by
614 	 * cloning (it should be true because in6_addloop explicitly installs
615 	 * the host route).  However, we might have to do an explicit check
616 	 * while it would be less efficient.  Or, should we rather install a
617 	 * reject route for such a case?
618 	 */
619 	if (V_ip6_forward_rt.ro_rt &&
620 	    (V_ip6_forward_rt.ro_rt->rt_flags &
621 	     (RTF_HOST|RTF_GATEWAY)) == RTF_HOST &&
622 #ifdef RTF_WASCLONED
623 	    !(V_ip6_forward_rt.ro_rt->rt_flags & RTF_WASCLONED) &&
624 #endif
625 #ifdef RTF_CLONED
626 	    !(V_ip6_forward_rt.ro_rt->rt_flags & RTF_CLONED) &&
627 #endif
628 #if 0
629 	    /*
630 	     * The check below is redundant since the comparison of
631 	     * the destination and the key of the rtentry has
632 	     * already done through looking up the routing table.
633 	     */
634 	    IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
635 	    &rt6_key(V_ip6_forward_rt.ro_rt)->sin6_addr)
636 #endif
637 	    V_ip6_forward_rt.ro_rt->rt_ifp->if_type == IFT_LOOP) {
638 		struct in6_ifaddr *ia6 =
639 			(struct in6_ifaddr *)V_ip6_forward_rt.ro_rt->rt_ifa;
640 
641 		/*
642 		 * record address information into m_tag.
643 		 */
644 		(void)ip6_setdstifaddr(m, ia6);
645 
646 		/*
647 		 * packets to a tentative, duplicated, or somehow invalid
648 		 * address must not be accepted.
649 		 */
650 		if (!(ia6->ia6_flags & IN6_IFF_NOTREADY)) {
651 			/* this address is ready */
652 			ours = 1;
653 			deliverifp = ia6->ia_ifp;	/* correct? */
654 			/* Count the packet in the ip address stats */
655 			ia6->ia_ifa.if_ipackets++;
656 			ia6->ia_ifa.if_ibytes += m->m_pkthdr.len;
657 			goto hbhcheck;
658 		} else {
659 			char ip6bufs[INET6_ADDRSTRLEN];
660 			char ip6bufd[INET6_ADDRSTRLEN];
661 			/* address is not ready, so discard the packet. */
662 			nd6log((LOG_INFO,
663 			    "ip6_input: packet to an unready address %s->%s\n",
664 			    ip6_sprintf(ip6bufs, &ip6->ip6_src),
665 			    ip6_sprintf(ip6bufd, &ip6->ip6_dst)));
666 
667 			goto bad;
668 		}
669 	}
670 
671 	/*
672 	 * FAITH (Firewall Aided Internet Translator)
673 	 */
674 	if (V_ip6_keepfaith) {
675 		if (V_ip6_forward_rt.ro_rt && V_ip6_forward_rt.ro_rt->rt_ifp
676 		 && V_ip6_forward_rt.ro_rt->rt_ifp->if_type == IFT_FAITH) {
677 			/* XXX do we need more sanity checks? */
678 			ours = 1;
679 			deliverifp = V_ip6_forward_rt.ro_rt->rt_ifp; /* faith */
680 			goto hbhcheck;
681 		}
682 	}
683 
684 	/*
685 	 * Now there is no reason to process the packet if it's not our own
686 	 * and we're not a router.
687 	 */
688 	if (!V_ip6_forwarding) {
689 		V_ip6stat.ip6s_cantforward++;
690 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_discard);
691 		goto bad;
692 	}
693 
694   hbhcheck:
695 	/*
696 	 * record address information into m_tag, if we don't have one yet.
697 	 * note that we are unable to record it, if the address is not listed
698 	 * as our interface address (e.g. multicast addresses, addresses
699 	 * within FAITH prefixes and such).
700 	 */
701 	if (deliverifp && !ip6_getdstifaddr(m)) {
702 		struct in6_ifaddr *ia6;
703 
704 		ia6 = in6_ifawithifp(deliverifp, &ip6->ip6_dst);
705 		if (ia6) {
706 			if (!ip6_setdstifaddr(m, ia6)) {
707 				/*
708 				 * XXX maybe we should drop the packet here,
709 				 * as we could not provide enough information
710 				 * to the upper layers.
711 				 */
712 			}
713 		}
714 	}
715 
716 	/*
717 	 * Process Hop-by-Hop options header if it's contained.
718 	 * m may be modified in ip6_hopopts_input().
719 	 * If a JumboPayload option is included, plen will also be modified.
720 	 */
721 	plen = (u_int32_t)ntohs(ip6->ip6_plen);
722 	if (ip6->ip6_nxt == IPPROTO_HOPOPTS) {
723 		struct ip6_hbh *hbh;
724 
725 		if (ip6_hopopts_input(&plen, &rtalert, &m, &off)) {
726 #if 0	/*touches NULL pointer*/
727 			in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_discard);
728 #endif
729 			return;	/* m have already been freed */
730 		}
731 
732 		/* adjust pointer */
733 		ip6 = mtod(m, struct ip6_hdr *);
734 
735 		/*
736 		 * if the payload length field is 0 and the next header field
737 		 * indicates Hop-by-Hop Options header, then a Jumbo Payload
738 		 * option MUST be included.
739 		 */
740 		if (ip6->ip6_plen == 0 && plen == 0) {
741 			/*
742 			 * Note that if a valid jumbo payload option is
743 			 * contained, ip6_hopopts_input() must set a valid
744 			 * (non-zero) payload length to the variable plen.
745 			 */
746 			V_ip6stat.ip6s_badoptions++;
747 			in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_discard);
748 			in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_hdrerr);
749 			icmp6_error(m, ICMP6_PARAM_PROB,
750 				    ICMP6_PARAMPROB_HEADER,
751 				    (caddr_t)&ip6->ip6_plen - (caddr_t)ip6);
752 			return;
753 		}
754 #ifndef PULLDOWN_TEST
755 		/* ip6_hopopts_input() ensures that mbuf is contiguous */
756 		hbh = (struct ip6_hbh *)(ip6 + 1);
757 #else
758 		IP6_EXTHDR_GET(hbh, struct ip6_hbh *, m, sizeof(struct ip6_hdr),
759 			sizeof(struct ip6_hbh));
760 		if (hbh == NULL) {
761 			V_ip6stat.ip6s_tooshort++;
762 			return;
763 		}
764 #endif
765 		nxt = hbh->ip6h_nxt;
766 
767 		/*
768 		 * If we are acting as a router and the packet contains a
769 		 * router alert option, see if we know the option value.
770 		 * Currently, we only support the option value for MLD, in which
771 		 * case we should pass the packet to the multicast routing
772 		 * daemon.
773 		 */
774 		if (rtalert != ~0 && V_ip6_forwarding) {
775 			switch (rtalert) {
776 			case IP6OPT_RTALERT_MLD:
777 				ours = 1;
778 				break;
779 			default:
780 				/*
781 				 * RFC2711 requires unrecognized values must be
782 				 * silently ignored.
783 				 */
784 				break;
785 			}
786 		}
787 	} else
788 		nxt = ip6->ip6_nxt;
789 
790 	/*
791 	 * Check that the amount of data in the buffers
792 	 * is as at least much as the IPv6 header would have us expect.
793 	 * Trim mbufs if longer than we expect.
794 	 * Drop packet if shorter than we expect.
795 	 */
796 	if (m->m_pkthdr.len - sizeof(struct ip6_hdr) < plen) {
797 		V_ip6stat.ip6s_tooshort++;
798 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_truncated);
799 		goto bad;
800 	}
801 	if (m->m_pkthdr.len > sizeof(struct ip6_hdr) + plen) {
802 		if (m->m_len == m->m_pkthdr.len) {
803 			m->m_len = sizeof(struct ip6_hdr) + plen;
804 			m->m_pkthdr.len = sizeof(struct ip6_hdr) + plen;
805 		} else
806 			m_adj(m, sizeof(struct ip6_hdr) + plen - m->m_pkthdr.len);
807 	}
808 
809 	/*
810 	 * Forward if desirable.
811 	 */
812 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
813 		/*
814 		 * If we are acting as a multicast router, all
815 		 * incoming multicast packets are passed to the
816 		 * kernel-level multicast forwarding function.
817 		 * The packet is returned (relatively) intact; if
818 		 * ip6_mforward() returns a non-zero value, the packet
819 		 * must be discarded, else it may be accepted below.
820 		 */
821 		if (ip6_mrouter && ip6_mforward &&
822 		    ip6_mforward(ip6, m->m_pkthdr.rcvif, m)) {
823 			V_ip6stat.ip6s_cantforward++;
824 			m_freem(m);
825 			return;
826 		}
827 		if (!ours) {
828 			m_freem(m);
829 			return;
830 		}
831 	} else if (!ours) {
832 		ip6_forward(m, srcrt);
833 		return;
834 	}
835 
836 	ip6 = mtod(m, struct ip6_hdr *);
837 
838 	/*
839 	 * Malicious party may be able to use IPv4 mapped addr to confuse
840 	 * tcp/udp stack and bypass security checks (act as if it was from
841 	 * 127.0.0.1 by using IPv6 src ::ffff:127.0.0.1).  Be cautious.
842 	 *
843 	 * For SIIT end node behavior, you may want to disable the check.
844 	 * However, you will  become vulnerable to attacks using IPv4 mapped
845 	 * source.
846 	 */
847 	if (IN6_IS_ADDR_V4MAPPED(&ip6->ip6_src) ||
848 	    IN6_IS_ADDR_V4MAPPED(&ip6->ip6_dst)) {
849 		V_ip6stat.ip6s_badscope++;
850 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_addrerr);
851 		goto bad;
852 	}
853 
854 	/*
855 	 * Tell launch routine the next header
856 	 */
857 	V_ip6stat.ip6s_delivered++;
858 	in6_ifstat_inc(deliverifp, ifs6_in_deliver);
859 	nest = 0;
860 
861 	while (nxt != IPPROTO_DONE) {
862 		if (V_ip6_hdrnestlimit && (++nest > V_ip6_hdrnestlimit)) {
863 			V_ip6stat.ip6s_toomanyhdr++;
864 			goto bad;
865 		}
866 
867 		/*
868 		 * protection against faulty packet - there should be
869 		 * more sanity checks in header chain processing.
870 		 */
871 		if (m->m_pkthdr.len < off) {
872 			V_ip6stat.ip6s_tooshort++;
873 			in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_truncated);
874 			goto bad;
875 		}
876 
877 #ifdef IPSEC
878 		/*
879 		 * enforce IPsec policy checking if we are seeing last header.
880 		 * note that we do not visit this with protocols with pcb layer
881 		 * code - like udp/tcp/raw ip.
882 		 */
883 		if (ip6_ipsec_input(m, nxt))
884 			goto bad;
885 #endif /* IPSEC */
886 		nxt = (*inet6sw[ip6_protox[nxt]].pr_input)(&m, &off, nxt);
887 	}
888 	return;
889  bad:
890 	m_freem(m);
891 }
892 
893 /*
894  * set/grab in6_ifaddr correspond to IPv6 destination address.
895  * XXX backward compatibility wrapper
896  */
897 static struct ip6aux *
898 ip6_setdstifaddr(struct mbuf *m, struct in6_ifaddr *ia6)
899 {
900 	struct ip6aux *ip6a;
901 
902 	ip6a = ip6_addaux(m);
903 	if (ip6a)
904 		ip6a->ip6a_dstia6 = ia6;
905 	return ip6a;	/* NULL if failed to set */
906 }
907 
908 struct in6_ifaddr *
909 ip6_getdstifaddr(struct mbuf *m)
910 {
911 	struct ip6aux *ip6a;
912 
913 	ip6a = ip6_findaux(m);
914 	if (ip6a)
915 		return ip6a->ip6a_dstia6;
916 	else
917 		return NULL;
918 }
919 
920 /*
921  * Hop-by-Hop options header processing. If a valid jumbo payload option is
922  * included, the real payload length will be stored in plenp.
923  *
924  * rtalertp - XXX: should be stored more smart way
925  */
926 static int
927 ip6_hopopts_input(u_int32_t *plenp, u_int32_t *rtalertp,
928     struct mbuf **mp, int *offp)
929 {
930 	INIT_VNET_INET6(curvnet);
931 	struct mbuf *m = *mp;
932 	int off = *offp, hbhlen;
933 	struct ip6_hbh *hbh;
934 	u_int8_t *opt;
935 
936 	/* validation of the length of the header */
937 #ifndef PULLDOWN_TEST
938 	IP6_EXTHDR_CHECK(m, off, sizeof(*hbh), -1);
939 	hbh = (struct ip6_hbh *)(mtod(m, caddr_t) + off);
940 	hbhlen = (hbh->ip6h_len + 1) << 3;
941 
942 	IP6_EXTHDR_CHECK(m, off, hbhlen, -1);
943 	hbh = (struct ip6_hbh *)(mtod(m, caddr_t) + off);
944 #else
945 	IP6_EXTHDR_GET(hbh, struct ip6_hbh *, m,
946 		sizeof(struct ip6_hdr), sizeof(struct ip6_hbh));
947 	if (hbh == NULL) {
948 		V_ip6stat.ip6s_tooshort++;
949 		return -1;
950 	}
951 	hbhlen = (hbh->ip6h_len + 1) << 3;
952 	IP6_EXTHDR_GET(hbh, struct ip6_hbh *, m, sizeof(struct ip6_hdr),
953 		hbhlen);
954 	if (hbh == NULL) {
955 		V_ip6stat.ip6s_tooshort++;
956 		return -1;
957 	}
958 #endif
959 	off += hbhlen;
960 	hbhlen -= sizeof(struct ip6_hbh);
961 	opt = (u_int8_t *)hbh + sizeof(struct ip6_hbh);
962 
963 	if (ip6_process_hopopts(m, (u_int8_t *)hbh + sizeof(struct ip6_hbh),
964 				hbhlen, rtalertp, plenp) < 0)
965 		return (-1);
966 
967 	*offp = off;
968 	*mp = m;
969 	return (0);
970 }
971 
972 /*
973  * Search header for all Hop-by-hop options and process each option.
974  * This function is separate from ip6_hopopts_input() in order to
975  * handle a case where the sending node itself process its hop-by-hop
976  * options header. In such a case, the function is called from ip6_output().
977  *
978  * The function assumes that hbh header is located right after the IPv6 header
979  * (RFC2460 p7), opthead is pointer into data content in m, and opthead to
980  * opthead + hbhlen is located in continuous memory region.
981  */
982 int
983 ip6_process_hopopts(struct mbuf *m, u_int8_t *opthead, int hbhlen,
984     u_int32_t *rtalertp, u_int32_t *plenp)
985 {
986 	INIT_VNET_INET6(curvnet);
987 	struct ip6_hdr *ip6;
988 	int optlen = 0;
989 	u_int8_t *opt = opthead;
990 	u_int16_t rtalert_val;
991 	u_int32_t jumboplen;
992 	const int erroff = sizeof(struct ip6_hdr) + sizeof(struct ip6_hbh);
993 
994 	for (; hbhlen > 0; hbhlen -= optlen, opt += optlen) {
995 		switch (*opt) {
996 		case IP6OPT_PAD1:
997 			optlen = 1;
998 			break;
999 		case IP6OPT_PADN:
1000 			if (hbhlen < IP6OPT_MINLEN) {
1001 				V_ip6stat.ip6s_toosmall++;
1002 				goto bad;
1003 			}
1004 			optlen = *(opt + 1) + 2;
1005 			break;
1006 		case IP6OPT_ROUTER_ALERT:
1007 			/* XXX may need check for alignment */
1008 			if (hbhlen < IP6OPT_RTALERT_LEN) {
1009 				V_ip6stat.ip6s_toosmall++;
1010 				goto bad;
1011 			}
1012 			if (*(opt + 1) != IP6OPT_RTALERT_LEN - 2) {
1013 				/* XXX stat */
1014 				icmp6_error(m, ICMP6_PARAM_PROB,
1015 				    ICMP6_PARAMPROB_HEADER,
1016 				    erroff + opt + 1 - opthead);
1017 				return (-1);
1018 			}
1019 			optlen = IP6OPT_RTALERT_LEN;
1020 			bcopy((caddr_t)(opt + 2), (caddr_t)&rtalert_val, 2);
1021 			*rtalertp = ntohs(rtalert_val);
1022 			break;
1023 		case IP6OPT_JUMBO:
1024 			/* XXX may need check for alignment */
1025 			if (hbhlen < IP6OPT_JUMBO_LEN) {
1026 				V_ip6stat.ip6s_toosmall++;
1027 				goto bad;
1028 			}
1029 			if (*(opt + 1) != IP6OPT_JUMBO_LEN - 2) {
1030 				/* XXX stat */
1031 				icmp6_error(m, ICMP6_PARAM_PROB,
1032 				    ICMP6_PARAMPROB_HEADER,
1033 				    erroff + opt + 1 - opthead);
1034 				return (-1);
1035 			}
1036 			optlen = IP6OPT_JUMBO_LEN;
1037 
1038 			/*
1039 			 * IPv6 packets that have non 0 payload length
1040 			 * must not contain a jumbo payload option.
1041 			 */
1042 			ip6 = mtod(m, struct ip6_hdr *);
1043 			if (ip6->ip6_plen) {
1044 				V_ip6stat.ip6s_badoptions++;
1045 				icmp6_error(m, ICMP6_PARAM_PROB,
1046 				    ICMP6_PARAMPROB_HEADER,
1047 				    erroff + opt - opthead);
1048 				return (-1);
1049 			}
1050 
1051 			/*
1052 			 * We may see jumbolen in unaligned location, so
1053 			 * we'd need to perform bcopy().
1054 			 */
1055 			bcopy(opt + 2, &jumboplen, sizeof(jumboplen));
1056 			jumboplen = (u_int32_t)htonl(jumboplen);
1057 
1058 #if 1
1059 			/*
1060 			 * if there are multiple jumbo payload options,
1061 			 * *plenp will be non-zero and the packet will be
1062 			 * rejected.
1063 			 * the behavior may need some debate in ipngwg -
1064 			 * multiple options does not make sense, however,
1065 			 * there's no explicit mention in specification.
1066 			 */
1067 			if (*plenp != 0) {
1068 				V_ip6stat.ip6s_badoptions++;
1069 				icmp6_error(m, ICMP6_PARAM_PROB,
1070 				    ICMP6_PARAMPROB_HEADER,
1071 				    erroff + opt + 2 - opthead);
1072 				return (-1);
1073 			}
1074 #endif
1075 
1076 			/*
1077 			 * jumbo payload length must be larger than 65535.
1078 			 */
1079 			if (jumboplen <= IPV6_MAXPACKET) {
1080 				V_ip6stat.ip6s_badoptions++;
1081 				icmp6_error(m, ICMP6_PARAM_PROB,
1082 				    ICMP6_PARAMPROB_HEADER,
1083 				    erroff + opt + 2 - opthead);
1084 				return (-1);
1085 			}
1086 			*plenp = jumboplen;
1087 
1088 			break;
1089 		default:		/* unknown option */
1090 			if (hbhlen < IP6OPT_MINLEN) {
1091 				V_ip6stat.ip6s_toosmall++;
1092 				goto bad;
1093 			}
1094 			optlen = ip6_unknown_opt(opt, m,
1095 			    erroff + opt - opthead);
1096 			if (optlen == -1)
1097 				return (-1);
1098 			optlen += 2;
1099 			break;
1100 		}
1101 	}
1102 
1103 	return (0);
1104 
1105   bad:
1106 	m_freem(m);
1107 	return (-1);
1108 }
1109 
1110 /*
1111  * Unknown option processing.
1112  * The third argument `off' is the offset from the IPv6 header to the option,
1113  * which is necessary if the IPv6 header the and option header and IPv6 header
1114  * is not continuous in order to return an ICMPv6 error.
1115  */
1116 int
1117 ip6_unknown_opt(u_int8_t *optp, struct mbuf *m, int off)
1118 {
1119 	INIT_VNET_INET6(curvnet);
1120 	struct ip6_hdr *ip6;
1121 
1122 	switch (IP6OPT_TYPE(*optp)) {
1123 	case IP6OPT_TYPE_SKIP: /* ignore the option */
1124 		return ((int)*(optp + 1));
1125 	case IP6OPT_TYPE_DISCARD:	/* silently discard */
1126 		m_freem(m);
1127 		return (-1);
1128 	case IP6OPT_TYPE_FORCEICMP: /* send ICMP even if multicasted */
1129 		V_ip6stat.ip6s_badoptions++;
1130 		icmp6_error(m, ICMP6_PARAM_PROB, ICMP6_PARAMPROB_OPTION, off);
1131 		return (-1);
1132 	case IP6OPT_TYPE_ICMP: /* send ICMP if not multicasted */
1133 		V_ip6stat.ip6s_badoptions++;
1134 		ip6 = mtod(m, struct ip6_hdr *);
1135 		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
1136 		    (m->m_flags & (M_BCAST|M_MCAST)))
1137 			m_freem(m);
1138 		else
1139 			icmp6_error(m, ICMP6_PARAM_PROB,
1140 				    ICMP6_PARAMPROB_OPTION, off);
1141 		return (-1);
1142 	}
1143 
1144 	m_freem(m);		/* XXX: NOTREACHED */
1145 	return (-1);
1146 }
1147 
1148 /*
1149  * Create the "control" list for this pcb.
1150  * These functions will not modify mbuf chain at all.
1151  *
1152  * With KAME mbuf chain restriction:
1153  * The routine will be called from upper layer handlers like tcp6_input().
1154  * Thus the routine assumes that the caller (tcp6_input) have already
1155  * called IP6_EXTHDR_CHECK() and all the extension headers are located in the
1156  * very first mbuf on the mbuf chain.
1157  *
1158  * ip6_savecontrol_v4 will handle those options that are possible to be
1159  * set on a v4-mapped socket.
1160  * ip6_savecontrol will directly call ip6_savecontrol_v4 to handle those
1161  * options and handle the v6-only ones itself.
1162  */
1163 struct mbuf **
1164 ip6_savecontrol_v4(struct inpcb *inp, struct mbuf *m, struct mbuf **mp,
1165     int *v4only)
1166 {
1167 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
1168 
1169 #ifdef SO_TIMESTAMP
1170 	if ((inp->inp_socket->so_options & SO_TIMESTAMP) != 0) {
1171 		struct timeval tv;
1172 
1173 		microtime(&tv);
1174 		*mp = sbcreatecontrol((caddr_t) &tv, sizeof(tv),
1175 		    SCM_TIMESTAMP, SOL_SOCKET);
1176 		if (*mp)
1177 			mp = &(*mp)->m_next;
1178 	}
1179 #endif
1180 
1181 	if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION) {
1182 		if (v4only != NULL)
1183 			*v4only = 1;
1184 		return (mp);
1185 	}
1186 
1187 #define IS2292(inp, x, y)	(((inp)->inp_flags & IN6P_RFC2292) ? (x) : (y))
1188 	/* RFC 2292 sec. 5 */
1189 	if ((inp->inp_flags & IN6P_PKTINFO) != 0) {
1190 		struct in6_pktinfo pi6;
1191 
1192 		bcopy(&ip6->ip6_dst, &pi6.ipi6_addr, sizeof(struct in6_addr));
1193 		in6_clearscope(&pi6.ipi6_addr);	/* XXX */
1194 		pi6.ipi6_ifindex =
1195 		    (m && m->m_pkthdr.rcvif) ? m->m_pkthdr.rcvif->if_index : 0;
1196 
1197 		*mp = sbcreatecontrol((caddr_t) &pi6,
1198 		    sizeof(struct in6_pktinfo),
1199 		    IS2292(inp, IPV6_2292PKTINFO, IPV6_PKTINFO), IPPROTO_IPV6);
1200 		if (*mp)
1201 			mp = &(*mp)->m_next;
1202 	}
1203 
1204 	if ((inp->inp_flags & IN6P_HOPLIMIT) != 0) {
1205 		int hlim = ip6->ip6_hlim & 0xff;
1206 
1207 		*mp = sbcreatecontrol((caddr_t) &hlim, sizeof(int),
1208 		    IS2292(inp, IPV6_2292HOPLIMIT, IPV6_HOPLIMIT),
1209 		    IPPROTO_IPV6);
1210 		if (*mp)
1211 			mp = &(*mp)->m_next;
1212 	}
1213 
1214 	if (v4only != NULL)
1215 		*v4only = 0;
1216 	return (mp);
1217 }
1218 
1219 void
1220 ip6_savecontrol(struct inpcb *in6p, struct mbuf *m, struct mbuf **mp)
1221 {
1222 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
1223 	int v4only = 0;
1224 
1225 	mp = ip6_savecontrol_v4(in6p, m, mp, &v4only);
1226 	if (v4only)
1227 		return;
1228 
1229 	if ((in6p->inp_flags & IN6P_TCLASS) != 0) {
1230 		u_int32_t flowinfo;
1231 		int tclass;
1232 
1233 		flowinfo = (u_int32_t)ntohl(ip6->ip6_flow & IPV6_FLOWINFO_MASK);
1234 		flowinfo >>= 20;
1235 
1236 		tclass = flowinfo & 0xff;
1237 		*mp = sbcreatecontrol((caddr_t) &tclass, sizeof(tclass),
1238 		    IPV6_TCLASS, IPPROTO_IPV6);
1239 		if (*mp)
1240 			mp = &(*mp)->m_next;
1241 	}
1242 
1243 	/*
1244 	 * IPV6_HOPOPTS socket option.  Recall that we required super-user
1245 	 * privilege for the option (see ip6_ctloutput), but it might be too
1246 	 * strict, since there might be some hop-by-hop options which can be
1247 	 * returned to normal user.
1248 	 * See also RFC 2292 section 6 (or RFC 3542 section 8).
1249 	 */
1250 	if ((in6p->inp_flags & IN6P_HOPOPTS) != 0) {
1251 		/*
1252 		 * Check if a hop-by-hop options header is contatined in the
1253 		 * received packet, and if so, store the options as ancillary
1254 		 * data. Note that a hop-by-hop options header must be
1255 		 * just after the IPv6 header, which is assured through the
1256 		 * IPv6 input processing.
1257 		 */
1258 		if (ip6->ip6_nxt == IPPROTO_HOPOPTS) {
1259 			struct ip6_hbh *hbh;
1260 			int hbhlen = 0;
1261 #ifdef PULLDOWN_TEST
1262 			struct mbuf *ext;
1263 #endif
1264 
1265 #ifndef PULLDOWN_TEST
1266 			hbh = (struct ip6_hbh *)(ip6 + 1);
1267 			hbhlen = (hbh->ip6h_len + 1) << 3;
1268 #else
1269 			ext = ip6_pullexthdr(m, sizeof(struct ip6_hdr),
1270 			    ip6->ip6_nxt);
1271 			if (ext == NULL) {
1272 				V_ip6stat.ip6s_tooshort++;
1273 				return;
1274 			}
1275 			hbh = mtod(ext, struct ip6_hbh *);
1276 			hbhlen = (hbh->ip6h_len + 1) << 3;
1277 			if (hbhlen != ext->m_len) {
1278 				m_freem(ext);
1279 				V_ip6stat.ip6s_tooshort++;
1280 				return;
1281 			}
1282 #endif
1283 
1284 			/*
1285 			 * XXX: We copy the whole header even if a
1286 			 * jumbo payload option is included, the option which
1287 			 * is to be removed before returning according to
1288 			 * RFC2292.
1289 			 * Note: this constraint is removed in RFC3542
1290 			 */
1291 			*mp = sbcreatecontrol((caddr_t)hbh, hbhlen,
1292 			    IS2292(in6p, IPV6_2292HOPOPTS, IPV6_HOPOPTS),
1293 			    IPPROTO_IPV6);
1294 			if (*mp)
1295 				mp = &(*mp)->m_next;
1296 #ifdef PULLDOWN_TEST
1297 			m_freem(ext);
1298 #endif
1299 		}
1300 	}
1301 
1302 	if ((in6p->inp_flags & (IN6P_RTHDR | IN6P_DSTOPTS)) != 0) {
1303 		int nxt = ip6->ip6_nxt, off = sizeof(struct ip6_hdr);
1304 
1305 		/*
1306 		 * Search for destination options headers or routing
1307 		 * header(s) through the header chain, and stores each
1308 		 * header as ancillary data.
1309 		 * Note that the order of the headers remains in
1310 		 * the chain of ancillary data.
1311 		 */
1312 		while (1) {	/* is explicit loop prevention necessary? */
1313 			struct ip6_ext *ip6e = NULL;
1314 			int elen;
1315 #ifdef PULLDOWN_TEST
1316 			struct mbuf *ext = NULL;
1317 #endif
1318 
1319 			/*
1320 			 * if it is not an extension header, don't try to
1321 			 * pull it from the chain.
1322 			 */
1323 			switch (nxt) {
1324 			case IPPROTO_DSTOPTS:
1325 			case IPPROTO_ROUTING:
1326 			case IPPROTO_HOPOPTS:
1327 			case IPPROTO_AH: /* is it possible? */
1328 				break;
1329 			default:
1330 				goto loopend;
1331 			}
1332 
1333 #ifndef PULLDOWN_TEST
1334 			if (off + sizeof(*ip6e) > m->m_len)
1335 				goto loopend;
1336 			ip6e = (struct ip6_ext *)(mtod(m, caddr_t) + off);
1337 			if (nxt == IPPROTO_AH)
1338 				elen = (ip6e->ip6e_len + 2) << 2;
1339 			else
1340 				elen = (ip6e->ip6e_len + 1) << 3;
1341 			if (off + elen > m->m_len)
1342 				goto loopend;
1343 #else
1344 			ext = ip6_pullexthdr(m, off, nxt);
1345 			if (ext == NULL) {
1346 				V_ip6stat.ip6s_tooshort++;
1347 				return;
1348 			}
1349 			ip6e = mtod(ext, struct ip6_ext *);
1350 			if (nxt == IPPROTO_AH)
1351 				elen = (ip6e->ip6e_len + 2) << 2;
1352 			else
1353 				elen = (ip6e->ip6e_len + 1) << 3;
1354 			if (elen != ext->m_len) {
1355 				m_freem(ext);
1356 				V_ip6stat.ip6s_tooshort++;
1357 				return;
1358 			}
1359 #endif
1360 
1361 			switch (nxt) {
1362 			case IPPROTO_DSTOPTS:
1363 				if (!(in6p->inp_flags & IN6P_DSTOPTS))
1364 					break;
1365 
1366 				*mp = sbcreatecontrol((caddr_t)ip6e, elen,
1367 				    IS2292(in6p,
1368 					IPV6_2292DSTOPTS, IPV6_DSTOPTS),
1369 				    IPPROTO_IPV6);
1370 				if (*mp)
1371 					mp = &(*mp)->m_next;
1372 				break;
1373 			case IPPROTO_ROUTING:
1374 				if (!in6p->inp_flags & IN6P_RTHDR)
1375 					break;
1376 
1377 				*mp = sbcreatecontrol((caddr_t)ip6e, elen,
1378 				    IS2292(in6p, IPV6_2292RTHDR, IPV6_RTHDR),
1379 				    IPPROTO_IPV6);
1380 				if (*mp)
1381 					mp = &(*mp)->m_next;
1382 				break;
1383 			case IPPROTO_HOPOPTS:
1384 			case IPPROTO_AH: /* is it possible? */
1385 				break;
1386 
1387 			default:
1388 				/*
1389 				 * other cases have been filtered in the above.
1390 				 * none will visit this case.  here we supply
1391 				 * the code just in case (nxt overwritten or
1392 				 * other cases).
1393 				 */
1394 #ifdef PULLDOWN_TEST
1395 				m_freem(ext);
1396 #endif
1397 				goto loopend;
1398 
1399 			}
1400 
1401 			/* proceed with the next header. */
1402 			off += elen;
1403 			nxt = ip6e->ip6e_nxt;
1404 			ip6e = NULL;
1405 #ifdef PULLDOWN_TEST
1406 			m_freem(ext);
1407 			ext = NULL;
1408 #endif
1409 		}
1410 	  loopend:
1411 		;
1412 	}
1413 }
1414 #undef IS2292
1415 
1416 void
1417 ip6_notify_pmtu(struct inpcb *in6p, struct sockaddr_in6 *dst, u_int32_t *mtu)
1418 {
1419 	struct socket *so;
1420 	struct mbuf *m_mtu;
1421 	struct ip6_mtuinfo mtuctl;
1422 
1423 	so =  in6p->inp_socket;
1424 
1425 	if (mtu == NULL)
1426 		return;
1427 
1428 #ifdef DIAGNOSTIC
1429 	if (so == NULL)		/* I believe this is impossible */
1430 		panic("ip6_notify_pmtu: socket is NULL");
1431 #endif
1432 
1433 	bzero(&mtuctl, sizeof(mtuctl));	/* zero-clear for safety */
1434 	mtuctl.ip6m_mtu = *mtu;
1435 	mtuctl.ip6m_addr = *dst;
1436 	if (sa6_recoverscope(&mtuctl.ip6m_addr))
1437 		return;
1438 
1439 	if ((m_mtu = sbcreatecontrol((caddr_t)&mtuctl, sizeof(mtuctl),
1440 	    IPV6_PATHMTU, IPPROTO_IPV6)) == NULL)
1441 		return;
1442 
1443 	if (sbappendaddr(&so->so_rcv, (struct sockaddr *)dst, NULL, m_mtu)
1444 	    == 0) {
1445 		m_freem(m_mtu);
1446 		/* XXX: should count statistics */
1447 	} else
1448 		sorwakeup(so);
1449 
1450 	return;
1451 }
1452 
1453 #ifdef PULLDOWN_TEST
1454 /*
1455  * pull single extension header from mbuf chain.  returns single mbuf that
1456  * contains the result, or NULL on error.
1457  */
1458 static struct mbuf *
1459 ip6_pullexthdr(struct mbuf *m, size_t off, int nxt)
1460 {
1461 	struct ip6_ext ip6e;
1462 	size_t elen;
1463 	struct mbuf *n;
1464 
1465 #ifdef DIAGNOSTIC
1466 	switch (nxt) {
1467 	case IPPROTO_DSTOPTS:
1468 	case IPPROTO_ROUTING:
1469 	case IPPROTO_HOPOPTS:
1470 	case IPPROTO_AH: /* is it possible? */
1471 		break;
1472 	default:
1473 		printf("ip6_pullexthdr: invalid nxt=%d\n", nxt);
1474 	}
1475 #endif
1476 
1477 	m_copydata(m, off, sizeof(ip6e), (caddr_t)&ip6e);
1478 	if (nxt == IPPROTO_AH)
1479 		elen = (ip6e.ip6e_len + 2) << 2;
1480 	else
1481 		elen = (ip6e.ip6e_len + 1) << 3;
1482 
1483 	MGET(n, M_DONTWAIT, MT_DATA);
1484 	if (n && elen >= MLEN) {
1485 		MCLGET(n, M_DONTWAIT);
1486 		if ((n->m_flags & M_EXT) == 0) {
1487 			m_free(n);
1488 			n = NULL;
1489 		}
1490 	}
1491 	if (!n)
1492 		return NULL;
1493 
1494 	n->m_len = 0;
1495 	if (elen >= M_TRAILINGSPACE(n)) {
1496 		m_free(n);
1497 		return NULL;
1498 	}
1499 
1500 	m_copydata(m, off, elen, mtod(n, caddr_t));
1501 	n->m_len = elen;
1502 	return n;
1503 }
1504 #endif
1505 
1506 /*
1507  * Get pointer to the previous header followed by the header
1508  * currently processed.
1509  * XXX: This function supposes that
1510  *	M includes all headers,
1511  *	the next header field and the header length field of each header
1512  *	are valid, and
1513  *	the sum of each header length equals to OFF.
1514  * Because of these assumptions, this function must be called very
1515  * carefully. Moreover, it will not be used in the near future when
1516  * we develop `neater' mechanism to process extension headers.
1517  */
1518 char *
1519 ip6_get_prevhdr(struct mbuf *m, int off)
1520 {
1521 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
1522 
1523 	if (off == sizeof(struct ip6_hdr))
1524 		return (&ip6->ip6_nxt);
1525 	else {
1526 		int len, nxt;
1527 		struct ip6_ext *ip6e = NULL;
1528 
1529 		nxt = ip6->ip6_nxt;
1530 		len = sizeof(struct ip6_hdr);
1531 		while (len < off) {
1532 			ip6e = (struct ip6_ext *)(mtod(m, caddr_t) + len);
1533 
1534 			switch (nxt) {
1535 			case IPPROTO_FRAGMENT:
1536 				len += sizeof(struct ip6_frag);
1537 				break;
1538 			case IPPROTO_AH:
1539 				len += (ip6e->ip6e_len + 2) << 2;
1540 				break;
1541 			default:
1542 				len += (ip6e->ip6e_len + 1) << 3;
1543 				break;
1544 			}
1545 			nxt = ip6e->ip6e_nxt;
1546 		}
1547 		if (ip6e)
1548 			return (&ip6e->ip6e_nxt);
1549 		else
1550 			return NULL;
1551 	}
1552 }
1553 
1554 /*
1555  * get next header offset.  m will be retained.
1556  */
1557 int
1558 ip6_nexthdr(struct mbuf *m, int off, int proto, int *nxtp)
1559 {
1560 	struct ip6_hdr ip6;
1561 	struct ip6_ext ip6e;
1562 	struct ip6_frag fh;
1563 
1564 	/* just in case */
1565 	if (m == NULL)
1566 		panic("ip6_nexthdr: m == NULL");
1567 	if ((m->m_flags & M_PKTHDR) == 0 || m->m_pkthdr.len < off)
1568 		return -1;
1569 
1570 	switch (proto) {
1571 	case IPPROTO_IPV6:
1572 		if (m->m_pkthdr.len < off + sizeof(ip6))
1573 			return -1;
1574 		m_copydata(m, off, sizeof(ip6), (caddr_t)&ip6);
1575 		if (nxtp)
1576 			*nxtp = ip6.ip6_nxt;
1577 		off += sizeof(ip6);
1578 		return off;
1579 
1580 	case IPPROTO_FRAGMENT:
1581 		/*
1582 		 * terminate parsing if it is not the first fragment,
1583 		 * it does not make sense to parse through it.
1584 		 */
1585 		if (m->m_pkthdr.len < off + sizeof(fh))
1586 			return -1;
1587 		m_copydata(m, off, sizeof(fh), (caddr_t)&fh);
1588 		/* IP6F_OFF_MASK = 0xfff8(BigEndian), 0xf8ff(LittleEndian) */
1589 		if (fh.ip6f_offlg & IP6F_OFF_MASK)
1590 			return -1;
1591 		if (nxtp)
1592 			*nxtp = fh.ip6f_nxt;
1593 		off += sizeof(struct ip6_frag);
1594 		return off;
1595 
1596 	case IPPROTO_AH:
1597 		if (m->m_pkthdr.len < off + sizeof(ip6e))
1598 			return -1;
1599 		m_copydata(m, off, sizeof(ip6e), (caddr_t)&ip6e);
1600 		if (nxtp)
1601 			*nxtp = ip6e.ip6e_nxt;
1602 		off += (ip6e.ip6e_len + 2) << 2;
1603 		return off;
1604 
1605 	case IPPROTO_HOPOPTS:
1606 	case IPPROTO_ROUTING:
1607 	case IPPROTO_DSTOPTS:
1608 		if (m->m_pkthdr.len < off + sizeof(ip6e))
1609 			return -1;
1610 		m_copydata(m, off, sizeof(ip6e), (caddr_t)&ip6e);
1611 		if (nxtp)
1612 			*nxtp = ip6e.ip6e_nxt;
1613 		off += (ip6e.ip6e_len + 1) << 3;
1614 		return off;
1615 
1616 	case IPPROTO_NONE:
1617 	case IPPROTO_ESP:
1618 	case IPPROTO_IPCOMP:
1619 		/* give up */
1620 		return -1;
1621 
1622 	default:
1623 		return -1;
1624 	}
1625 
1626 	return -1;
1627 }
1628 
1629 /*
1630  * get offset for the last header in the chain.  m will be kept untainted.
1631  */
1632 int
1633 ip6_lasthdr(struct mbuf *m, int off, int proto, int *nxtp)
1634 {
1635 	int newoff;
1636 	int nxt;
1637 
1638 	if (!nxtp) {
1639 		nxt = -1;
1640 		nxtp = &nxt;
1641 	}
1642 	while (1) {
1643 		newoff = ip6_nexthdr(m, off, proto, nxtp);
1644 		if (newoff < 0)
1645 			return off;
1646 		else if (newoff < off)
1647 			return -1;	/* invalid */
1648 		else if (newoff == off)
1649 			return newoff;
1650 
1651 		off = newoff;
1652 		proto = *nxtp;
1653 	}
1654 }
1655 
1656 struct ip6aux *
1657 ip6_addaux(struct mbuf *m)
1658 {
1659 	struct m_tag *mtag;
1660 
1661 	mtag = m_tag_find(m, PACKET_TAG_IPV6_INPUT, NULL);
1662 	if (!mtag) {
1663 		mtag = m_tag_get(PACKET_TAG_IPV6_INPUT, sizeof(struct ip6aux),
1664 		    M_NOWAIT);
1665 		if (mtag) {
1666 			m_tag_prepend(m, mtag);
1667 			bzero(mtag + 1, sizeof(struct ip6aux));
1668 		}
1669 	}
1670 	return mtag ? (struct ip6aux *)(mtag + 1) : NULL;
1671 }
1672 
1673 struct ip6aux *
1674 ip6_findaux(struct mbuf *m)
1675 {
1676 	struct m_tag *mtag;
1677 
1678 	mtag = m_tag_find(m, PACKET_TAG_IPV6_INPUT, NULL);
1679 	return mtag ? (struct ip6aux *)(mtag + 1) : NULL;
1680 }
1681 
1682 void
1683 ip6_delaux(struct mbuf *m)
1684 {
1685 	struct m_tag *mtag;
1686 
1687 	mtag = m_tag_find(m, PACKET_TAG_IPV6_INPUT, NULL);
1688 	if (mtag)
1689 		m_tag_delete(m, mtag);
1690 }
1691 
1692 /*
1693  * System control for IP6
1694  */
1695 
1696 u_char	inet6ctlerrmap[PRC_NCMDS] = {
1697 	0,		0,		0,		0,
1698 	0,		EMSGSIZE,	EHOSTDOWN,	EHOSTUNREACH,
1699 	EHOSTUNREACH,	EHOSTUNREACH,	ECONNREFUSED,	ECONNREFUSED,
1700 	EMSGSIZE,	EHOSTUNREACH,	0,		0,
1701 	0,		0,		0,		0,
1702 	ENOPROTOOPT
1703 };
1704