xref: /freebsd/sys/netinet6/ip6_input.c (revision ff0ba87247820afbdfdc1b307c803f7923d0e4d3)
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_ipfw.h"
69 #include "opt_ipsec.h"
70 #include "opt_route.h"
71 
72 #include <sys/param.h>
73 #include <sys/systm.h>
74 #include <sys/malloc.h>
75 #include <sys/mbuf.h>
76 #include <sys/proc.h>
77 #include <sys/domain.h>
78 #include <sys/protosw.h>
79 #include <sys/sdt.h>
80 #include <sys/socket.h>
81 #include <sys/socketvar.h>
82 #include <sys/errno.h>
83 #include <sys/time.h>
84 #include <sys/kernel.h>
85 #include <sys/syslog.h>
86 
87 #include <net/if.h>
88 #include <net/if_var.h>
89 #include <net/if_types.h>
90 #include <net/if_dl.h>
91 #include <net/route.h>
92 #include <net/netisr.h>
93 #include <net/pfil.h>
94 #include <net/vnet.h>
95 
96 #include <netinet/in.h>
97 #include <netinet/in_kdtrace.h>
98 #include <netinet/ip_var.h>
99 #include <netinet/in_systm.h>
100 #include <net/if_llatbl.h>
101 #ifdef INET
102 #include <netinet/ip.h>
103 #include <netinet/ip_icmp.h>
104 #endif /* INET */
105 #include <netinet/ip6.h>
106 #include <netinet6/in6_var.h>
107 #include <netinet6/ip6_var.h>
108 #include <netinet/in_pcb.h>
109 #include <netinet/icmp6.h>
110 #include <netinet6/scope6_var.h>
111 #include <netinet6/in6_ifattach.h>
112 #include <netinet6/nd6.h>
113 
114 #ifdef IPSEC
115 #include <netipsec/ipsec.h>
116 #include <netinet6/ip6_ipsec.h>
117 #include <netipsec/ipsec6.h>
118 #endif /* IPSEC */
119 
120 #include <netinet6/ip6protosw.h>
121 
122 extern struct domain inet6domain;
123 
124 u_char ip6_protox[IPPROTO_MAX];
125 VNET_DEFINE(struct in6_ifaddrhead, in6_ifaddrhead);
126 VNET_DEFINE(struct in6_ifaddrlisthead *, in6_ifaddrhashtbl);
127 VNET_DEFINE(u_long, in6_ifaddrhmask);
128 
129 static struct netisr_handler ip6_nh = {
130 	.nh_name = "ip6",
131 	.nh_handler = ip6_input,
132 	.nh_proto = NETISR_IPV6,
133 	.nh_policy = NETISR_POLICY_FLOW,
134 };
135 
136 VNET_DECLARE(struct callout, in6_tmpaddrtimer_ch);
137 #define	V_in6_tmpaddrtimer_ch		VNET(in6_tmpaddrtimer_ch)
138 
139 VNET_DEFINE(struct pfil_head, inet6_pfil_hook);
140 
141 VNET_PCPUSTAT_DEFINE(struct ip6stat, ip6stat);
142 VNET_PCPUSTAT_SYSINIT(ip6stat);
143 #ifdef VIMAGE
144 VNET_PCPUSTAT_SYSUNINIT(ip6stat);
145 #endif /* VIMAGE */
146 
147 struct rwlock in6_ifaddr_lock;
148 RW_SYSINIT(in6_ifaddr_lock, &in6_ifaddr_lock, "in6_ifaddr_lock");
149 
150 static void ip6_init2(void *);
151 static int ip6_hopopts_input(u_int32_t *, u_int32_t *, struct mbuf **, int *);
152 #ifdef PULLDOWN_TEST
153 static struct mbuf *ip6_pullexthdr(struct mbuf *, size_t, int);
154 #endif
155 
156 /*
157  * IP6 initialization: fill in IP6 protocol switch table.
158  * All protocols not implemented in kernel go to raw IP6 protocol handler.
159  */
160 void
161 ip6_init(void)
162 {
163 	struct protosw *pr;
164 	int i;
165 
166 	TUNABLE_INT_FETCH("net.inet6.ip6.auto_linklocal",
167 	    &V_ip6_auto_linklocal);
168 	TUNABLE_INT_FETCH("net.inet6.ip6.accept_rtadv", &V_ip6_accept_rtadv);
169 	TUNABLE_INT_FETCH("net.inet6.ip6.no_radr", &V_ip6_no_radr);
170 
171 	TAILQ_INIT(&V_in6_ifaddrhead);
172 	V_in6_ifaddrhashtbl = hashinit(IN6ADDR_NHASH, M_IFADDR,
173 	    &V_in6_ifaddrhmask);
174 
175 	/* Initialize packet filter hooks. */
176 	V_inet6_pfil_hook.ph_type = PFIL_TYPE_AF;
177 	V_inet6_pfil_hook.ph_af = AF_INET6;
178 	if ((i = pfil_head_register(&V_inet6_pfil_hook)) != 0)
179 		printf("%s: WARNING: unable to register pfil hook, "
180 			"error %d\n", __func__, i);
181 
182 	scope6_init();
183 	addrsel_policy_init();
184 	nd6_init();
185 	frag6_init();
186 
187 	V_ip6_desync_factor = arc4random() % MAX_TEMP_DESYNC_FACTOR;
188 
189 	/* Skip global initialization stuff for non-default instances. */
190 	if (!IS_DEFAULT_VNET(curvnet))
191 		return;
192 
193 	pr = pffindproto(PF_INET6, IPPROTO_RAW, SOCK_RAW);
194 	if (pr == NULL)
195 		panic("ip6_init");
196 
197 	/* Initialize the entire ip6_protox[] array to IPPROTO_RAW. */
198 	for (i = 0; i < IPPROTO_MAX; i++)
199 		ip6_protox[i] = pr - inet6sw;
200 	/*
201 	 * Cycle through IP protocols and put them into the appropriate place
202 	 * in ip6_protox[].
203 	 */
204 	for (pr = inet6domain.dom_protosw;
205 	    pr < inet6domain.dom_protoswNPROTOSW; pr++)
206 		if (pr->pr_domain->dom_family == PF_INET6 &&
207 		    pr->pr_protocol && pr->pr_protocol != IPPROTO_RAW) {
208 			/* Be careful to only index valid IP protocols. */
209 			if (pr->pr_protocol < IPPROTO_MAX)
210 				ip6_protox[pr->pr_protocol] = pr - inet6sw;
211 		}
212 
213 	netisr_register(&ip6_nh);
214 }
215 
216 /*
217  * The protocol to be inserted into ip6_protox[] must be already registered
218  * in inet6sw[], either statically or through pf_proto_register().
219  */
220 int
221 ip6proto_register(short ip6proto)
222 {
223 	struct protosw *pr;
224 
225 	/* Sanity checks. */
226 	if (ip6proto <= 0 || ip6proto >= IPPROTO_MAX)
227 		return (EPROTONOSUPPORT);
228 
229 	/*
230 	 * The protocol slot must not be occupied by another protocol
231 	 * already.  An index pointing to IPPROTO_RAW is unused.
232 	 */
233 	pr = pffindproto(PF_INET6, IPPROTO_RAW, SOCK_RAW);
234 	if (pr == NULL)
235 		return (EPFNOSUPPORT);
236 	if (ip6_protox[ip6proto] != pr - inet6sw)	/* IPPROTO_RAW */
237 		return (EEXIST);
238 
239 	/*
240 	 * Find the protocol position in inet6sw[] and set the index.
241 	 */
242 	for (pr = inet6domain.dom_protosw;
243 	    pr < inet6domain.dom_protoswNPROTOSW; pr++) {
244 		if (pr->pr_domain->dom_family == PF_INET6 &&
245 		    pr->pr_protocol && pr->pr_protocol == ip6proto) {
246 			ip6_protox[pr->pr_protocol] = pr - inet6sw;
247 			return (0);
248 		}
249 	}
250 	return (EPROTONOSUPPORT);
251 }
252 
253 int
254 ip6proto_unregister(short ip6proto)
255 {
256 	struct protosw *pr;
257 
258 	/* Sanity checks. */
259 	if (ip6proto <= 0 || ip6proto >= IPPROTO_MAX)
260 		return (EPROTONOSUPPORT);
261 
262 	/* Check if the protocol was indeed registered. */
263 	pr = pffindproto(PF_INET6, IPPROTO_RAW, SOCK_RAW);
264 	if (pr == NULL)
265 		return (EPFNOSUPPORT);
266 	if (ip6_protox[ip6proto] == pr - inet6sw)	/* IPPROTO_RAW */
267 		return (ENOENT);
268 
269 	/* Reset the protocol slot to IPPROTO_RAW. */
270 	ip6_protox[ip6proto] = pr - inet6sw;
271 	return (0);
272 }
273 
274 #ifdef VIMAGE
275 void
276 ip6_destroy()
277 {
278 	int i;
279 
280 	if ((i = pfil_head_unregister(&V_inet6_pfil_hook)) != 0)
281 		printf("%s: WARNING: unable to unregister pfil hook, "
282 		    "error %d\n", __func__, i);
283 	hashdestroy(V_in6_ifaddrhashtbl, M_IFADDR, V_in6_ifaddrhmask);
284 	nd6_destroy();
285 	callout_drain(&V_in6_tmpaddrtimer_ch);
286 }
287 #endif
288 
289 static int
290 ip6_init2_vnet(const void *unused __unused)
291 {
292 
293 	/* nd6_timer_init */
294 	callout_init(&V_nd6_timer_ch, 0);
295 	callout_reset(&V_nd6_timer_ch, hz, nd6_timer, curvnet);
296 
297 	/* timer for regeneranation of temporary addresses randomize ID */
298 	callout_init(&V_in6_tmpaddrtimer_ch, 0);
299 	callout_reset(&V_in6_tmpaddrtimer_ch,
300 		      (V_ip6_temp_preferred_lifetime - V_ip6_desync_factor -
301 		       V_ip6_temp_regen_advance) * hz,
302 		      in6_tmpaddrtimer, curvnet);
303 
304 	return (0);
305 }
306 
307 static void
308 ip6_init2(void *dummy)
309 {
310 
311 	ip6_init2_vnet(NULL);
312 }
313 
314 /* cheat */
315 /* This must be after route_init(), which is now SI_ORDER_THIRD */
316 SYSINIT(netinet6init2, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE, ip6_init2, NULL);
317 
318 static int
319 ip6_input_hbh(struct mbuf *m, uint32_t *plen, uint32_t *rtalert, int *off,
320     int *nxt, int *ours)
321 {
322 	struct ip6_hdr *ip6;
323 	struct ip6_hbh *hbh;
324 
325 	if (ip6_hopopts_input(plen, rtalert, &m, off)) {
326 #if 0	/*touches NULL pointer*/
327 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_discard);
328 #endif
329 		goto out;	/* m have already been freed */
330 	}
331 
332 	/* adjust pointer */
333 	ip6 = mtod(m, struct ip6_hdr *);
334 
335 	/*
336 	 * if the payload length field is 0 and the next header field
337 	 * indicates Hop-by-Hop Options header, then a Jumbo Payload
338 	 * option MUST be included.
339 	 */
340 	if (ip6->ip6_plen == 0 && *plen == 0) {
341 		/*
342 		 * Note that if a valid jumbo payload option is
343 		 * contained, ip6_hopopts_input() must set a valid
344 		 * (non-zero) payload length to the variable plen.
345 		 */
346 		IP6STAT_INC(ip6s_badoptions);
347 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_discard);
348 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_hdrerr);
349 		icmp6_error(m, ICMP6_PARAM_PROB,
350 			    ICMP6_PARAMPROB_HEADER,
351 			    (caddr_t)&ip6->ip6_plen - (caddr_t)ip6);
352 		goto out;
353 	}
354 #ifndef PULLDOWN_TEST
355 	/* ip6_hopopts_input() ensures that mbuf is contiguous */
356 	hbh = (struct ip6_hbh *)(ip6 + 1);
357 #else
358 	IP6_EXTHDR_GET(hbh, struct ip6_hbh *, m, sizeof(struct ip6_hdr),
359 		sizeof(struct ip6_hbh));
360 	if (hbh == NULL) {
361 		IP6STAT_INC(ip6s_tooshort);
362 		goto out;
363 	}
364 #endif
365 	*nxt = hbh->ip6h_nxt;
366 
367 	/*
368 	 * If we are acting as a router and the packet contains a
369 	 * router alert option, see if we know the option value.
370 	 * Currently, we only support the option value for MLD, in which
371 	 * case we should pass the packet to the multicast routing
372 	 * daemon.
373 	 */
374 	if (*rtalert != ~0) {
375 		switch (*rtalert) {
376 		case IP6OPT_RTALERT_MLD:
377 			if (V_ip6_forwarding)
378 				*ours = 1;
379 			break;
380 		default:
381 			/*
382 			 * RFC2711 requires unrecognized values must be
383 			 * silently ignored.
384 			 */
385 			break;
386 		}
387 	}
388 
389 	return (0);
390 
391 out:
392 	return (1);
393 }
394 
395 void
396 ip6_input(struct mbuf *m)
397 {
398 	struct in6_addr odst;
399 	struct ip6_hdr *ip6;
400 	struct in6_ifaddr *ia;
401 	u_int32_t plen;
402 	u_int32_t rtalert = ~0;
403 	int off = sizeof(struct ip6_hdr), nest;
404 	int nxt, ours = 0;
405 	int srcrt = 0;
406 
407 #ifdef IPSEC
408 	/*
409 	 * should the inner packet be considered authentic?
410 	 * see comment in ah4_input().
411 	 * NB: m cannot be NULL when passed to the input routine
412 	 */
413 
414 	m->m_flags &= ~M_AUTHIPHDR;
415 	m->m_flags &= ~M_AUTHIPDGM;
416 
417 #endif /* IPSEC */
418 
419 	if (m->m_flags & M_FASTFWD_OURS) {
420 		/*
421 		 * Firewall changed destination to local.
422 		 */
423 		m->m_flags &= ~M_FASTFWD_OURS;
424 		ours = 1;
425 		ip6 = mtod(m, struct ip6_hdr *);
426 		goto hbhcheck;
427 	}
428 
429 	/*
430 	 * mbuf statistics
431 	 */
432 	if (m->m_flags & M_EXT) {
433 		if (m->m_next)
434 			IP6STAT_INC(ip6s_mext2m);
435 		else
436 			IP6STAT_INC(ip6s_mext1);
437 	} else {
438 		if (m->m_next) {
439 			if (m->m_flags & M_LOOP) {
440 				IP6STAT_INC(ip6s_m2m[V_loif->if_index]);
441 			} else if (m->m_pkthdr.rcvif->if_index < IP6S_M2MMAX)
442 				IP6STAT_INC(
443 				    ip6s_m2m[m->m_pkthdr.rcvif->if_index]);
444 			else
445 				IP6STAT_INC(ip6s_m2m[0]);
446 		} else
447 			IP6STAT_INC(ip6s_m1);
448 	}
449 
450 	/* drop the packet if IPv6 operation is disabled on the IF */
451 	if ((ND_IFINFO(m->m_pkthdr.rcvif)->flags & ND6_IFF_IFDISABLED))
452 		goto bad;
453 
454 	in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_receive);
455 	IP6STAT_INC(ip6s_total);
456 
457 #ifndef PULLDOWN_TEST
458 	/*
459 	 * L2 bridge code and some other code can return mbuf chain
460 	 * that does not conform to KAME requirement.  too bad.
461 	 * XXX: fails to join if interface MTU > MCLBYTES.  jumbogram?
462 	 */
463 	if (m && m->m_next != NULL && m->m_pkthdr.len < MCLBYTES) {
464 		struct mbuf *n;
465 
466 		if (m->m_pkthdr.len > MHLEN)
467 			n = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
468 		else
469 			n = m_gethdr(M_NOWAIT, MT_DATA);
470 		if (n == NULL) {
471 			m_freem(m);
472 			return;	/* ENOBUFS */
473 		}
474 
475 		m_move_pkthdr(n, m);
476 		m_copydata(m, 0, n->m_pkthdr.len, mtod(n, caddr_t));
477 		n->m_len = n->m_pkthdr.len;
478 		m_freem(m);
479 		m = n;
480 	}
481 	IP6_EXTHDR_CHECK(m, 0, sizeof(struct ip6_hdr), /* nothing */);
482 #endif
483 
484 	if (m->m_len < sizeof(struct ip6_hdr)) {
485 		struct ifnet *inifp;
486 		inifp = m->m_pkthdr.rcvif;
487 		if ((m = m_pullup(m, sizeof(struct ip6_hdr))) == NULL) {
488 			IP6STAT_INC(ip6s_toosmall);
489 			in6_ifstat_inc(inifp, ifs6_in_hdrerr);
490 			return;
491 		}
492 	}
493 
494 	ip6 = mtod(m, struct ip6_hdr *);
495 
496 	if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION) {
497 		IP6STAT_INC(ip6s_badvers);
498 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_hdrerr);
499 		goto bad;
500 	}
501 
502 	IP6STAT_INC(ip6s_nxthist[ip6->ip6_nxt]);
503 
504 	IP_PROBE(receive, NULL, NULL, ip6, m->m_pkthdr.rcvif, NULL, ip6);
505 
506 	/*
507 	 * Check against address spoofing/corruption.
508 	 */
509 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_src) ||
510 	    IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_dst)) {
511 		/*
512 		 * XXX: "badscope" is not very suitable for a multicast source.
513 		 */
514 		IP6STAT_INC(ip6s_badscope);
515 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_addrerr);
516 		goto bad;
517 	}
518 	if (IN6_IS_ADDR_MC_INTFACELOCAL(&ip6->ip6_dst) &&
519 	    !(m->m_flags & M_LOOP)) {
520 		/*
521 		 * In this case, the packet should come from the loopback
522 		 * interface.  However, we cannot just check the if_flags,
523 		 * because ip6_mloopback() passes the "actual" interface
524 		 * as the outgoing/incoming interface.
525 		 */
526 		IP6STAT_INC(ip6s_badscope);
527 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_addrerr);
528 		goto bad;
529 	}
530 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) &&
531 	    IPV6_ADDR_MC_SCOPE(&ip6->ip6_dst) == 0) {
532 		/*
533 		 * RFC4291 2.7:
534 		 * Nodes must not originate a packet to a multicast address
535 		 * whose scop field contains the reserved value 0; if such
536 		 * a packet is received, it must be silently dropped.
537 		 */
538 		IP6STAT_INC(ip6s_badscope);
539 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_addrerr);
540 		goto bad;
541 	}
542 #ifdef ALTQ
543 	if (altq_input != NULL && (*altq_input)(m, AF_INET6) == 0) {
544 		/* packet is dropped by traffic conditioner */
545 		return;
546 	}
547 #endif
548 	/*
549 	 * The following check is not documented in specs.  A malicious
550 	 * party may be able to use IPv4 mapped addr to confuse tcp/udp stack
551 	 * and bypass security checks (act as if it was from 127.0.0.1 by using
552 	 * IPv6 src ::ffff:127.0.0.1).  Be cautious.
553 	 *
554 	 * This check chokes if we are in an SIIT cloud.  As none of BSDs
555 	 * support IPv4-less kernel compilation, we cannot support SIIT
556 	 * environment at all.  So, it makes more sense for us to reject any
557 	 * malicious packets for non-SIIT environment, than try to do a
558 	 * partial support for SIIT environment.
559 	 */
560 	if (IN6_IS_ADDR_V4MAPPED(&ip6->ip6_src) ||
561 	    IN6_IS_ADDR_V4MAPPED(&ip6->ip6_dst)) {
562 		IP6STAT_INC(ip6s_badscope);
563 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_addrerr);
564 		goto bad;
565 	}
566 #if 0
567 	/*
568 	 * Reject packets with IPv4 compatible addresses (auto tunnel).
569 	 *
570 	 * The code forbids auto tunnel relay case in RFC1933 (the check is
571 	 * stronger than RFC1933).  We may want to re-enable it if mech-xx
572 	 * is revised to forbid relaying case.
573 	 */
574 	if (IN6_IS_ADDR_V4COMPAT(&ip6->ip6_src) ||
575 	    IN6_IS_ADDR_V4COMPAT(&ip6->ip6_dst)) {
576 		IP6STAT_INC(ip6s_badscope);
577 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_addrerr);
578 		goto bad;
579 	}
580 #endif
581 #ifdef IPSEC
582 	/*
583 	 * Bypass packet filtering for packets previously handled by IPsec.
584 	 */
585 	if (ip6_ipsec_filtertunnel(m))
586 		goto passin;
587 #endif /* IPSEC */
588 
589 	/*
590 	 * Run through list of hooks for input packets.
591 	 *
592 	 * NB: Beware of the destination address changing
593 	 *     (e.g. by NAT rewriting).  When this happens,
594 	 *     tell ip6_forward to do the right thing.
595 	 */
596 	odst = ip6->ip6_dst;
597 
598 	/* Jump over all PFIL processing if hooks are not active. */
599 	if (!PFIL_HOOKED(&V_inet6_pfil_hook))
600 		goto passin;
601 
602 	if (pfil_run_hooks(&V_inet6_pfil_hook, &m,
603 	    m->m_pkthdr.rcvif, PFIL_IN, NULL))
604 		return;
605 	if (m == NULL)			/* consumed by filter */
606 		return;
607 	ip6 = mtod(m, struct ip6_hdr *);
608 	srcrt = !IN6_ARE_ADDR_EQUAL(&odst, &ip6->ip6_dst);
609 
610 	if (m->m_flags & M_FASTFWD_OURS) {
611 		m->m_flags &= ~M_FASTFWD_OURS;
612 		ours = 1;
613 		goto hbhcheck;
614 	}
615 	if ((m->m_flags & M_IP6_NEXTHOP) &&
616 	    m_tag_find(m, PACKET_TAG_IPFORWARD, NULL) != NULL) {
617 		/*
618 		 * Directly ship the packet on.  This allows forwarding
619 		 * packets originally destined to us to some other directly
620 		 * connected host.
621 		 */
622 		ip6_forward(m, 1);
623 		return;
624 	}
625 
626 passin:
627 	/*
628 	 * Disambiguate address scope zones (if there is ambiguity).
629 	 * We first make sure that the original source or destination address
630 	 * is not in our internal form for scoped addresses.  Such addresses
631 	 * are not necessarily invalid spec-wise, but we cannot accept them due
632 	 * to the usage conflict.
633 	 * in6_setscope() then also checks and rejects the cases where src or
634 	 * dst are the loopback address and the receiving interface
635 	 * is not loopback.
636 	 */
637 	if (in6_clearscope(&ip6->ip6_src) || in6_clearscope(&ip6->ip6_dst)) {
638 		IP6STAT_INC(ip6s_badscope); /* XXX */
639 		goto bad;
640 	}
641 	if (in6_setscope(&ip6->ip6_src, m->m_pkthdr.rcvif, NULL) ||
642 	    in6_setscope(&ip6->ip6_dst, m->m_pkthdr.rcvif, NULL)) {
643 		IP6STAT_INC(ip6s_badscope);
644 		goto bad;
645 	}
646 	/*
647 	 * Multicast check. Assume packet is for us to avoid
648 	 * prematurely taking locks.
649 	 */
650 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
651 		ours = 1;
652 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_mcast);
653 		goto hbhcheck;
654 	}
655 	/*
656 	 * Unicast check
657 	 * XXX: For now we keep link-local IPv6 addresses with embedded
658 	 *      scope zone id, therefore we use zero zoneid here.
659 	 */
660 	ia = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */);
661 	if (ia != NULL) {
662 		if (ia->ia6_flags & IN6_IFF_NOTREADY) {
663 			char ip6bufs[INET6_ADDRSTRLEN];
664 			char ip6bufd[INET6_ADDRSTRLEN];
665 			/* address is not ready, so discard the packet. */
666 			nd6log((LOG_INFO,
667 			    "ip6_input: packet to an unready address %s->%s\n",
668 			    ip6_sprintf(ip6bufs, &ip6->ip6_src),
669 			    ip6_sprintf(ip6bufd, &ip6->ip6_dst)));
670 			ifa_free(&ia->ia_ifa);
671 			goto bad;
672 		}
673 		/* Count the packet in the ip address stats */
674 		counter_u64_add(ia->ia_ifa.ifa_ipackets, 1);
675 		counter_u64_add(ia->ia_ifa.ifa_ibytes, m->m_pkthdr.len);
676 		ifa_free(&ia->ia_ifa);
677 		ours = 1;
678 		goto hbhcheck;
679 	}
680 
681 	/*
682 	 * Now there is no reason to process the packet if it's not our own
683 	 * and we're not a router.
684 	 */
685 	if (!V_ip6_forwarding) {
686 		IP6STAT_INC(ip6s_cantforward);
687 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_discard);
688 		goto bad;
689 	}
690 
691   hbhcheck:
692 	/*
693 	 * Process Hop-by-Hop options header if it's contained.
694 	 * m may be modified in ip6_hopopts_input().
695 	 * If a JumboPayload option is included, plen will also be modified.
696 	 */
697 	plen = (u_int32_t)ntohs(ip6->ip6_plen);
698 	if (ip6->ip6_nxt == IPPROTO_HOPOPTS) {
699 		if (ip6_input_hbh(m, &plen, &rtalert, &off, &nxt, &ours) != 0)
700 			return;
701 	} else
702 		nxt = ip6->ip6_nxt;
703 
704 	/*
705 	 * Check that the amount of data in the buffers
706 	 * is as at least much as the IPv6 header would have us expect.
707 	 * Trim mbufs if longer than we expect.
708 	 * Drop packet if shorter than we expect.
709 	 */
710 	if (m->m_pkthdr.len - sizeof(struct ip6_hdr) < plen) {
711 		IP6STAT_INC(ip6s_tooshort);
712 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_truncated);
713 		goto bad;
714 	}
715 	if (m->m_pkthdr.len > sizeof(struct ip6_hdr) + plen) {
716 		if (m->m_len == m->m_pkthdr.len) {
717 			m->m_len = sizeof(struct ip6_hdr) + plen;
718 			m->m_pkthdr.len = sizeof(struct ip6_hdr) + plen;
719 		} else
720 			m_adj(m, sizeof(struct ip6_hdr) + plen - m->m_pkthdr.len);
721 	}
722 
723 	/*
724 	 * Forward if desirable.
725 	 */
726 	if (V_ip6_mrouter &&
727 	    IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
728 		/*
729 		 * If we are acting as a multicast router, all
730 		 * incoming multicast packets are passed to the
731 		 * kernel-level multicast forwarding function.
732 		 * The packet is returned (relatively) intact; if
733 		 * ip6_mforward() returns a non-zero value, the packet
734 		 * must be discarded, else it may be accepted below.
735 		 *
736 		 * XXX TODO: Check hlim and multicast scope here to avoid
737 		 * unnecessarily calling into ip6_mforward().
738 		 */
739 		if (ip6_mforward &&
740 		    ip6_mforward(ip6, m->m_pkthdr.rcvif, m)) {
741 			IP6STAT_INC(ip6s_cantforward);
742 			in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_discard);
743 			goto bad;
744 		}
745 	} else if (!ours) {
746 		ip6_forward(m, srcrt);
747 		return;
748 	}
749 
750 	ip6 = mtod(m, struct ip6_hdr *);
751 
752 	/*
753 	 * Malicious party may be able to use IPv4 mapped addr to confuse
754 	 * tcp/udp stack and bypass security checks (act as if it was from
755 	 * 127.0.0.1 by using IPv6 src ::ffff:127.0.0.1).  Be cautious.
756 	 *
757 	 * For SIIT end node behavior, you may want to disable the check.
758 	 * However, you will  become vulnerable to attacks using IPv4 mapped
759 	 * source.
760 	 */
761 	if (IN6_IS_ADDR_V4MAPPED(&ip6->ip6_src) ||
762 	    IN6_IS_ADDR_V4MAPPED(&ip6->ip6_dst)) {
763 		IP6STAT_INC(ip6s_badscope);
764 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_addrerr);
765 		goto bad;
766 	}
767 
768 	/*
769 	 * Tell launch routine the next header
770 	 */
771 	IP6STAT_INC(ip6s_delivered);
772 	in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_deliver);
773 	nest = 0;
774 
775 	while (nxt != IPPROTO_DONE) {
776 		if (V_ip6_hdrnestlimit && (++nest > V_ip6_hdrnestlimit)) {
777 			IP6STAT_INC(ip6s_toomanyhdr);
778 			goto bad;
779 		}
780 
781 		/*
782 		 * protection against faulty packet - there should be
783 		 * more sanity checks in header chain processing.
784 		 */
785 		if (m->m_pkthdr.len < off) {
786 			IP6STAT_INC(ip6s_tooshort);
787 			in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_truncated);
788 			goto bad;
789 		}
790 
791 #ifdef IPSEC
792 		/*
793 		 * enforce IPsec policy checking if we are seeing last header.
794 		 * note that we do not visit this with protocols with pcb layer
795 		 * code - like udp/tcp/raw ip.
796 		 */
797 		if (ip6_ipsec_input(m, nxt))
798 			goto bad;
799 #endif /* IPSEC */
800 
801 		/*
802 		 * Use mbuf flags to propagate Router Alert option to
803 		 * ICMPv6 layer, as hop-by-hop options have been stripped.
804 		 */
805 		if (nxt == IPPROTO_ICMPV6 && rtalert != ~0)
806 			m->m_flags |= M_RTALERT_MLD;
807 
808 		nxt = (*inet6sw[ip6_protox[nxt]].pr_input)(&m, &off, nxt);
809 	}
810 	return;
811 bad:
812 	m_freem(m);
813 }
814 
815 /*
816  * Hop-by-Hop options header processing. If a valid jumbo payload option is
817  * included, the real payload length will be stored in plenp.
818  *
819  * rtalertp - XXX: should be stored more smart way
820  */
821 static int
822 ip6_hopopts_input(u_int32_t *plenp, u_int32_t *rtalertp,
823     struct mbuf **mp, int *offp)
824 {
825 	struct mbuf *m = *mp;
826 	int off = *offp, hbhlen;
827 	struct ip6_hbh *hbh;
828 
829 	/* validation of the length of the header */
830 #ifndef PULLDOWN_TEST
831 	IP6_EXTHDR_CHECK(m, off, sizeof(*hbh), -1);
832 	hbh = (struct ip6_hbh *)(mtod(m, caddr_t) + off);
833 	hbhlen = (hbh->ip6h_len + 1) << 3;
834 
835 	IP6_EXTHDR_CHECK(m, off, hbhlen, -1);
836 	hbh = (struct ip6_hbh *)(mtod(m, caddr_t) + off);
837 #else
838 	IP6_EXTHDR_GET(hbh, struct ip6_hbh *, m,
839 		sizeof(struct ip6_hdr), sizeof(struct ip6_hbh));
840 	if (hbh == NULL) {
841 		IP6STAT_INC(ip6s_tooshort);
842 		return -1;
843 	}
844 	hbhlen = (hbh->ip6h_len + 1) << 3;
845 	IP6_EXTHDR_GET(hbh, struct ip6_hbh *, m, sizeof(struct ip6_hdr),
846 		hbhlen);
847 	if (hbh == NULL) {
848 		IP6STAT_INC(ip6s_tooshort);
849 		return -1;
850 	}
851 #endif
852 	off += hbhlen;
853 	hbhlen -= sizeof(struct ip6_hbh);
854 	if (ip6_process_hopopts(m, (u_int8_t *)hbh + sizeof(struct ip6_hbh),
855 				hbhlen, rtalertp, plenp) < 0)
856 		return (-1);
857 
858 	*offp = off;
859 	*mp = m;
860 	return (0);
861 }
862 
863 /*
864  * Search header for all Hop-by-hop options and process each option.
865  * This function is separate from ip6_hopopts_input() in order to
866  * handle a case where the sending node itself process its hop-by-hop
867  * options header. In such a case, the function is called from ip6_output().
868  *
869  * The function assumes that hbh header is located right after the IPv6 header
870  * (RFC2460 p7), opthead is pointer into data content in m, and opthead to
871  * opthead + hbhlen is located in contiguous memory region.
872  */
873 int
874 ip6_process_hopopts(struct mbuf *m, u_int8_t *opthead, int hbhlen,
875     u_int32_t *rtalertp, u_int32_t *plenp)
876 {
877 	struct ip6_hdr *ip6;
878 	int optlen = 0;
879 	u_int8_t *opt = opthead;
880 	u_int16_t rtalert_val;
881 	u_int32_t jumboplen;
882 	const int erroff = sizeof(struct ip6_hdr) + sizeof(struct ip6_hbh);
883 
884 	for (; hbhlen > 0; hbhlen -= optlen, opt += optlen) {
885 		switch (*opt) {
886 		case IP6OPT_PAD1:
887 			optlen = 1;
888 			break;
889 		case IP6OPT_PADN:
890 			if (hbhlen < IP6OPT_MINLEN) {
891 				IP6STAT_INC(ip6s_toosmall);
892 				goto bad;
893 			}
894 			optlen = *(opt + 1) + 2;
895 			break;
896 		case IP6OPT_ROUTER_ALERT:
897 			/* XXX may need check for alignment */
898 			if (hbhlen < IP6OPT_RTALERT_LEN) {
899 				IP6STAT_INC(ip6s_toosmall);
900 				goto bad;
901 			}
902 			if (*(opt + 1) != IP6OPT_RTALERT_LEN - 2) {
903 				/* XXX stat */
904 				icmp6_error(m, ICMP6_PARAM_PROB,
905 				    ICMP6_PARAMPROB_HEADER,
906 				    erroff + opt + 1 - opthead);
907 				return (-1);
908 			}
909 			optlen = IP6OPT_RTALERT_LEN;
910 			bcopy((caddr_t)(opt + 2), (caddr_t)&rtalert_val, 2);
911 			*rtalertp = ntohs(rtalert_val);
912 			break;
913 		case IP6OPT_JUMBO:
914 			/* XXX may need check for alignment */
915 			if (hbhlen < IP6OPT_JUMBO_LEN) {
916 				IP6STAT_INC(ip6s_toosmall);
917 				goto bad;
918 			}
919 			if (*(opt + 1) != IP6OPT_JUMBO_LEN - 2) {
920 				/* XXX stat */
921 				icmp6_error(m, ICMP6_PARAM_PROB,
922 				    ICMP6_PARAMPROB_HEADER,
923 				    erroff + opt + 1 - opthead);
924 				return (-1);
925 			}
926 			optlen = IP6OPT_JUMBO_LEN;
927 
928 			/*
929 			 * IPv6 packets that have non 0 payload length
930 			 * must not contain a jumbo payload option.
931 			 */
932 			ip6 = mtod(m, struct ip6_hdr *);
933 			if (ip6->ip6_plen) {
934 				IP6STAT_INC(ip6s_badoptions);
935 				icmp6_error(m, ICMP6_PARAM_PROB,
936 				    ICMP6_PARAMPROB_HEADER,
937 				    erroff + opt - opthead);
938 				return (-1);
939 			}
940 
941 			/*
942 			 * We may see jumbolen in unaligned location, so
943 			 * we'd need to perform bcopy().
944 			 */
945 			bcopy(opt + 2, &jumboplen, sizeof(jumboplen));
946 			jumboplen = (u_int32_t)htonl(jumboplen);
947 
948 #if 1
949 			/*
950 			 * if there are multiple jumbo payload options,
951 			 * *plenp will be non-zero and the packet will be
952 			 * rejected.
953 			 * the behavior may need some debate in ipngwg -
954 			 * multiple options does not make sense, however,
955 			 * there's no explicit mention in specification.
956 			 */
957 			if (*plenp != 0) {
958 				IP6STAT_INC(ip6s_badoptions);
959 				icmp6_error(m, ICMP6_PARAM_PROB,
960 				    ICMP6_PARAMPROB_HEADER,
961 				    erroff + opt + 2 - opthead);
962 				return (-1);
963 			}
964 #endif
965 
966 			/*
967 			 * jumbo payload length must be larger than 65535.
968 			 */
969 			if (jumboplen <= IPV6_MAXPACKET) {
970 				IP6STAT_INC(ip6s_badoptions);
971 				icmp6_error(m, ICMP6_PARAM_PROB,
972 				    ICMP6_PARAMPROB_HEADER,
973 				    erroff + opt + 2 - opthead);
974 				return (-1);
975 			}
976 			*plenp = jumboplen;
977 
978 			break;
979 		default:		/* unknown option */
980 			if (hbhlen < IP6OPT_MINLEN) {
981 				IP6STAT_INC(ip6s_toosmall);
982 				goto bad;
983 			}
984 			optlen = ip6_unknown_opt(opt, m,
985 			    erroff + opt - opthead);
986 			if (optlen == -1)
987 				return (-1);
988 			optlen += 2;
989 			break;
990 		}
991 	}
992 
993 	return (0);
994 
995   bad:
996 	m_freem(m);
997 	return (-1);
998 }
999 
1000 /*
1001  * Unknown option processing.
1002  * The third argument `off' is the offset from the IPv6 header to the option,
1003  * which is necessary if the IPv6 header the and option header and IPv6 header
1004  * is not contiguous in order to return an ICMPv6 error.
1005  */
1006 int
1007 ip6_unknown_opt(u_int8_t *optp, struct mbuf *m, int off)
1008 {
1009 	struct ip6_hdr *ip6;
1010 
1011 	switch (IP6OPT_TYPE(*optp)) {
1012 	case IP6OPT_TYPE_SKIP: /* ignore the option */
1013 		return ((int)*(optp + 1));
1014 	case IP6OPT_TYPE_DISCARD:	/* silently discard */
1015 		m_freem(m);
1016 		return (-1);
1017 	case IP6OPT_TYPE_FORCEICMP: /* send ICMP even if multicasted */
1018 		IP6STAT_INC(ip6s_badoptions);
1019 		icmp6_error(m, ICMP6_PARAM_PROB, ICMP6_PARAMPROB_OPTION, off);
1020 		return (-1);
1021 	case IP6OPT_TYPE_ICMP: /* send ICMP if not multicasted */
1022 		IP6STAT_INC(ip6s_badoptions);
1023 		ip6 = mtod(m, struct ip6_hdr *);
1024 		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
1025 		    (m->m_flags & (M_BCAST|M_MCAST)))
1026 			m_freem(m);
1027 		else
1028 			icmp6_error(m, ICMP6_PARAM_PROB,
1029 				    ICMP6_PARAMPROB_OPTION, off);
1030 		return (-1);
1031 	}
1032 
1033 	m_freem(m);		/* XXX: NOTREACHED */
1034 	return (-1);
1035 }
1036 
1037 /*
1038  * Create the "control" list for this pcb.
1039  * These functions will not modify mbuf chain at all.
1040  *
1041  * With KAME mbuf chain restriction:
1042  * The routine will be called from upper layer handlers like tcp6_input().
1043  * Thus the routine assumes that the caller (tcp6_input) have already
1044  * called IP6_EXTHDR_CHECK() and all the extension headers are located in the
1045  * very first mbuf on the mbuf chain.
1046  *
1047  * ip6_savecontrol_v4 will handle those options that are possible to be
1048  * set on a v4-mapped socket.
1049  * ip6_savecontrol will directly call ip6_savecontrol_v4 to handle those
1050  * options and handle the v6-only ones itself.
1051  */
1052 struct mbuf **
1053 ip6_savecontrol_v4(struct inpcb *inp, struct mbuf *m, struct mbuf **mp,
1054     int *v4only)
1055 {
1056 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
1057 
1058 #ifdef SO_TIMESTAMP
1059 	if ((inp->inp_socket->so_options & SO_TIMESTAMP) != 0) {
1060 		struct timeval tv;
1061 
1062 		microtime(&tv);
1063 		*mp = sbcreatecontrol((caddr_t) &tv, sizeof(tv),
1064 		    SCM_TIMESTAMP, SOL_SOCKET);
1065 		if (*mp)
1066 			mp = &(*mp)->m_next;
1067 	}
1068 #endif
1069 
1070 #define IS2292(inp, x, y)	(((inp)->inp_flags & IN6P_RFC2292) ? (x) : (y))
1071 	/* RFC 2292 sec. 5 */
1072 	if ((inp->inp_flags & IN6P_PKTINFO) != 0) {
1073 		struct in6_pktinfo pi6;
1074 
1075 		if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION) {
1076 #ifdef INET
1077 			struct ip *ip;
1078 
1079 			ip = mtod(m, struct ip *);
1080 			pi6.ipi6_addr.s6_addr32[0] = 0;
1081 			pi6.ipi6_addr.s6_addr32[1] = 0;
1082 			pi6.ipi6_addr.s6_addr32[2] = IPV6_ADDR_INT32_SMP;
1083 			pi6.ipi6_addr.s6_addr32[3] = ip->ip_dst.s_addr;
1084 #else
1085 			/* We won't hit this code */
1086 			bzero(&pi6.ipi6_addr, sizeof(struct in6_addr));
1087 #endif
1088 		} else {
1089 			bcopy(&ip6->ip6_dst, &pi6.ipi6_addr, sizeof(struct in6_addr));
1090 			in6_clearscope(&pi6.ipi6_addr);	/* XXX */
1091 		}
1092 		pi6.ipi6_ifindex =
1093 		    (m && m->m_pkthdr.rcvif) ? m->m_pkthdr.rcvif->if_index : 0;
1094 
1095 		*mp = sbcreatecontrol((caddr_t) &pi6,
1096 		    sizeof(struct in6_pktinfo),
1097 		    IS2292(inp, IPV6_2292PKTINFO, IPV6_PKTINFO), IPPROTO_IPV6);
1098 		if (*mp)
1099 			mp = &(*mp)->m_next;
1100 	}
1101 
1102 	if ((inp->inp_flags & IN6P_HOPLIMIT) != 0) {
1103 		int hlim;
1104 
1105 		if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION) {
1106 #ifdef INET
1107 			struct ip *ip;
1108 
1109 			ip = mtod(m, struct ip *);
1110 			hlim = ip->ip_ttl;
1111 #else
1112 			/* We won't hit this code */
1113 			hlim = 0;
1114 #endif
1115 		} else {
1116 			hlim = ip6->ip6_hlim & 0xff;
1117 		}
1118 		*mp = sbcreatecontrol((caddr_t) &hlim, sizeof(int),
1119 		    IS2292(inp, IPV6_2292HOPLIMIT, IPV6_HOPLIMIT),
1120 		    IPPROTO_IPV6);
1121 		if (*mp)
1122 			mp = &(*mp)->m_next;
1123 	}
1124 
1125 	if ((inp->inp_flags & IN6P_TCLASS) != 0) {
1126 		int tclass;
1127 
1128 		if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION) {
1129 #ifdef INET
1130 			struct ip *ip;
1131 
1132 			ip = mtod(m, struct ip *);
1133 			tclass = ip->ip_tos;
1134 #else
1135 			/* We won't hit this code */
1136 			tclass = 0;
1137 #endif
1138 		} else {
1139 			u_int32_t flowinfo;
1140 
1141 			flowinfo = (u_int32_t)ntohl(ip6->ip6_flow & IPV6_FLOWINFO_MASK);
1142 			flowinfo >>= 20;
1143 			tclass = flowinfo & 0xff;
1144 		}
1145 		*mp = sbcreatecontrol((caddr_t) &tclass, sizeof(int),
1146 		    IPV6_TCLASS, IPPROTO_IPV6);
1147 		if (*mp)
1148 			mp = &(*mp)->m_next;
1149 	}
1150 
1151 	if (v4only != NULL) {
1152 		if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION) {
1153 			*v4only = 1;
1154 		} else {
1155 			*v4only = 0;
1156 		}
1157 	}
1158 
1159 	return (mp);
1160 }
1161 
1162 void
1163 ip6_savecontrol(struct inpcb *in6p, struct mbuf *m, struct mbuf **mp)
1164 {
1165 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
1166 	int v4only = 0;
1167 
1168 	mp = ip6_savecontrol_v4(in6p, m, mp, &v4only);
1169 	if (v4only)
1170 		return;
1171 
1172 	/*
1173 	 * IPV6_HOPOPTS socket option.  Recall that we required super-user
1174 	 * privilege for the option (see ip6_ctloutput), but it might be too
1175 	 * strict, since there might be some hop-by-hop options which can be
1176 	 * returned to normal user.
1177 	 * See also RFC 2292 section 6 (or RFC 3542 section 8).
1178 	 */
1179 	if ((in6p->inp_flags & IN6P_HOPOPTS) != 0) {
1180 		/*
1181 		 * Check if a hop-by-hop options header is contatined in the
1182 		 * received packet, and if so, store the options as ancillary
1183 		 * data. Note that a hop-by-hop options header must be
1184 		 * just after the IPv6 header, which is assured through the
1185 		 * IPv6 input processing.
1186 		 */
1187 		if (ip6->ip6_nxt == IPPROTO_HOPOPTS) {
1188 			struct ip6_hbh *hbh;
1189 			int hbhlen = 0;
1190 #ifdef PULLDOWN_TEST
1191 			struct mbuf *ext;
1192 #endif
1193 
1194 #ifndef PULLDOWN_TEST
1195 			hbh = (struct ip6_hbh *)(ip6 + 1);
1196 			hbhlen = (hbh->ip6h_len + 1) << 3;
1197 #else
1198 			ext = ip6_pullexthdr(m, sizeof(struct ip6_hdr),
1199 			    ip6->ip6_nxt);
1200 			if (ext == NULL) {
1201 				IP6STAT_INC(ip6s_tooshort);
1202 				return;
1203 			}
1204 			hbh = mtod(ext, struct ip6_hbh *);
1205 			hbhlen = (hbh->ip6h_len + 1) << 3;
1206 			if (hbhlen != ext->m_len) {
1207 				m_freem(ext);
1208 				IP6STAT_INC(ip6s_tooshort);
1209 				return;
1210 			}
1211 #endif
1212 
1213 			/*
1214 			 * XXX: We copy the whole header even if a
1215 			 * jumbo payload option is included, the option which
1216 			 * is to be removed before returning according to
1217 			 * RFC2292.
1218 			 * Note: this constraint is removed in RFC3542
1219 			 */
1220 			*mp = sbcreatecontrol((caddr_t)hbh, hbhlen,
1221 			    IS2292(in6p, IPV6_2292HOPOPTS, IPV6_HOPOPTS),
1222 			    IPPROTO_IPV6);
1223 			if (*mp)
1224 				mp = &(*mp)->m_next;
1225 #ifdef PULLDOWN_TEST
1226 			m_freem(ext);
1227 #endif
1228 		}
1229 	}
1230 
1231 	if ((in6p->inp_flags & (IN6P_RTHDR | IN6P_DSTOPTS)) != 0) {
1232 		int nxt = ip6->ip6_nxt, off = sizeof(struct ip6_hdr);
1233 
1234 		/*
1235 		 * Search for destination options headers or routing
1236 		 * header(s) through the header chain, and stores each
1237 		 * header as ancillary data.
1238 		 * Note that the order of the headers remains in
1239 		 * the chain of ancillary data.
1240 		 */
1241 		while (1) {	/* is explicit loop prevention necessary? */
1242 			struct ip6_ext *ip6e = NULL;
1243 			int elen;
1244 #ifdef PULLDOWN_TEST
1245 			struct mbuf *ext = NULL;
1246 #endif
1247 
1248 			/*
1249 			 * if it is not an extension header, don't try to
1250 			 * pull it from the chain.
1251 			 */
1252 			switch (nxt) {
1253 			case IPPROTO_DSTOPTS:
1254 			case IPPROTO_ROUTING:
1255 			case IPPROTO_HOPOPTS:
1256 			case IPPROTO_AH: /* is it possible? */
1257 				break;
1258 			default:
1259 				goto loopend;
1260 			}
1261 
1262 #ifndef PULLDOWN_TEST
1263 			if (off + sizeof(*ip6e) > m->m_len)
1264 				goto loopend;
1265 			ip6e = (struct ip6_ext *)(mtod(m, caddr_t) + off);
1266 			if (nxt == IPPROTO_AH)
1267 				elen = (ip6e->ip6e_len + 2) << 2;
1268 			else
1269 				elen = (ip6e->ip6e_len + 1) << 3;
1270 			if (off + elen > m->m_len)
1271 				goto loopend;
1272 #else
1273 			ext = ip6_pullexthdr(m, off, nxt);
1274 			if (ext == NULL) {
1275 				IP6STAT_INC(ip6s_tooshort);
1276 				return;
1277 			}
1278 			ip6e = mtod(ext, struct ip6_ext *);
1279 			if (nxt == IPPROTO_AH)
1280 				elen = (ip6e->ip6e_len + 2) << 2;
1281 			else
1282 				elen = (ip6e->ip6e_len + 1) << 3;
1283 			if (elen != ext->m_len) {
1284 				m_freem(ext);
1285 				IP6STAT_INC(ip6s_tooshort);
1286 				return;
1287 			}
1288 #endif
1289 
1290 			switch (nxt) {
1291 			case IPPROTO_DSTOPTS:
1292 				if (!(in6p->inp_flags & IN6P_DSTOPTS))
1293 					break;
1294 
1295 				*mp = sbcreatecontrol((caddr_t)ip6e, elen,
1296 				    IS2292(in6p,
1297 					IPV6_2292DSTOPTS, IPV6_DSTOPTS),
1298 				    IPPROTO_IPV6);
1299 				if (*mp)
1300 					mp = &(*mp)->m_next;
1301 				break;
1302 			case IPPROTO_ROUTING:
1303 				if (!(in6p->inp_flags & IN6P_RTHDR))
1304 					break;
1305 
1306 				*mp = sbcreatecontrol((caddr_t)ip6e, elen,
1307 				    IS2292(in6p, IPV6_2292RTHDR, IPV6_RTHDR),
1308 				    IPPROTO_IPV6);
1309 				if (*mp)
1310 					mp = &(*mp)->m_next;
1311 				break;
1312 			case IPPROTO_HOPOPTS:
1313 			case IPPROTO_AH: /* is it possible? */
1314 				break;
1315 
1316 			default:
1317 				/*
1318 				 * other cases have been filtered in the above.
1319 				 * none will visit this case.  here we supply
1320 				 * the code just in case (nxt overwritten or
1321 				 * other cases).
1322 				 */
1323 #ifdef PULLDOWN_TEST
1324 				m_freem(ext);
1325 #endif
1326 				goto loopend;
1327 
1328 			}
1329 
1330 			/* proceed with the next header. */
1331 			off += elen;
1332 			nxt = ip6e->ip6e_nxt;
1333 			ip6e = NULL;
1334 #ifdef PULLDOWN_TEST
1335 			m_freem(ext);
1336 			ext = NULL;
1337 #endif
1338 		}
1339 	  loopend:
1340 		;
1341 	}
1342 }
1343 #undef IS2292
1344 
1345 void
1346 ip6_notify_pmtu(struct inpcb *in6p, struct sockaddr_in6 *dst, u_int32_t *mtu)
1347 {
1348 	struct socket *so;
1349 	struct mbuf *m_mtu;
1350 	struct ip6_mtuinfo mtuctl;
1351 
1352 	so =  in6p->inp_socket;
1353 
1354 	if (mtu == NULL)
1355 		return;
1356 
1357 #ifdef DIAGNOSTIC
1358 	if (so == NULL)		/* I believe this is impossible */
1359 		panic("ip6_notify_pmtu: socket is NULL");
1360 #endif
1361 
1362 	bzero(&mtuctl, sizeof(mtuctl));	/* zero-clear for safety */
1363 	mtuctl.ip6m_mtu = *mtu;
1364 	mtuctl.ip6m_addr = *dst;
1365 	if (sa6_recoverscope(&mtuctl.ip6m_addr))
1366 		return;
1367 
1368 	if ((m_mtu = sbcreatecontrol((caddr_t)&mtuctl, sizeof(mtuctl),
1369 	    IPV6_PATHMTU, IPPROTO_IPV6)) == NULL)
1370 		return;
1371 
1372 	if (sbappendaddr(&so->so_rcv, (struct sockaddr *)dst, NULL, m_mtu)
1373 	    == 0) {
1374 		m_freem(m_mtu);
1375 		/* XXX: should count statistics */
1376 	} else
1377 		sorwakeup(so);
1378 
1379 	return;
1380 }
1381 
1382 #ifdef PULLDOWN_TEST
1383 /*
1384  * pull single extension header from mbuf chain.  returns single mbuf that
1385  * contains the result, or NULL on error.
1386  */
1387 static struct mbuf *
1388 ip6_pullexthdr(struct mbuf *m, size_t off, int nxt)
1389 {
1390 	struct ip6_ext ip6e;
1391 	size_t elen;
1392 	struct mbuf *n;
1393 
1394 #ifdef DIAGNOSTIC
1395 	switch (nxt) {
1396 	case IPPROTO_DSTOPTS:
1397 	case IPPROTO_ROUTING:
1398 	case IPPROTO_HOPOPTS:
1399 	case IPPROTO_AH: /* is it possible? */
1400 		break;
1401 	default:
1402 		printf("ip6_pullexthdr: invalid nxt=%d\n", nxt);
1403 	}
1404 #endif
1405 
1406 	m_copydata(m, off, sizeof(ip6e), (caddr_t)&ip6e);
1407 	if (nxt == IPPROTO_AH)
1408 		elen = (ip6e.ip6e_len + 2) << 2;
1409 	else
1410 		elen = (ip6e.ip6e_len + 1) << 3;
1411 
1412 	if (elen > MLEN)
1413 		n = m_getcl(M_NOWAIT, MT_DATA, 0);
1414 	else
1415 		n = m_get(M_NOWAIT, MT_DATA);
1416 	if (n == NULL)
1417 		return NULL;
1418 
1419 	m_copydata(m, off, elen, mtod(n, caddr_t));
1420 	n->m_len = elen;
1421 	return n;
1422 }
1423 #endif
1424 
1425 /*
1426  * Get pointer to the previous header followed by the header
1427  * currently processed.
1428  * XXX: This function supposes that
1429  *	M includes all headers,
1430  *	the next header field and the header length field of each header
1431  *	are valid, and
1432  *	the sum of each header length equals to OFF.
1433  * Because of these assumptions, this function must be called very
1434  * carefully. Moreover, it will not be used in the near future when
1435  * we develop `neater' mechanism to process extension headers.
1436  */
1437 char *
1438 ip6_get_prevhdr(struct mbuf *m, int off)
1439 {
1440 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
1441 
1442 	if (off == sizeof(struct ip6_hdr))
1443 		return (&ip6->ip6_nxt);
1444 	else {
1445 		int len, nxt;
1446 		struct ip6_ext *ip6e = NULL;
1447 
1448 		nxt = ip6->ip6_nxt;
1449 		len = sizeof(struct ip6_hdr);
1450 		while (len < off) {
1451 			ip6e = (struct ip6_ext *)(mtod(m, caddr_t) + len);
1452 
1453 			switch (nxt) {
1454 			case IPPROTO_FRAGMENT:
1455 				len += sizeof(struct ip6_frag);
1456 				break;
1457 			case IPPROTO_AH:
1458 				len += (ip6e->ip6e_len + 2) << 2;
1459 				break;
1460 			default:
1461 				len += (ip6e->ip6e_len + 1) << 3;
1462 				break;
1463 			}
1464 			nxt = ip6e->ip6e_nxt;
1465 		}
1466 		if (ip6e)
1467 			return (&ip6e->ip6e_nxt);
1468 		else
1469 			return NULL;
1470 	}
1471 }
1472 
1473 /*
1474  * get next header offset.  m will be retained.
1475  */
1476 int
1477 ip6_nexthdr(struct mbuf *m, int off, int proto, int *nxtp)
1478 {
1479 	struct ip6_hdr ip6;
1480 	struct ip6_ext ip6e;
1481 	struct ip6_frag fh;
1482 
1483 	/* just in case */
1484 	if (m == NULL)
1485 		panic("ip6_nexthdr: m == NULL");
1486 	if ((m->m_flags & M_PKTHDR) == 0 || m->m_pkthdr.len < off)
1487 		return -1;
1488 
1489 	switch (proto) {
1490 	case IPPROTO_IPV6:
1491 		if (m->m_pkthdr.len < off + sizeof(ip6))
1492 			return -1;
1493 		m_copydata(m, off, sizeof(ip6), (caddr_t)&ip6);
1494 		if (nxtp)
1495 			*nxtp = ip6.ip6_nxt;
1496 		off += sizeof(ip6);
1497 		return off;
1498 
1499 	case IPPROTO_FRAGMENT:
1500 		/*
1501 		 * terminate parsing if it is not the first fragment,
1502 		 * it does not make sense to parse through it.
1503 		 */
1504 		if (m->m_pkthdr.len < off + sizeof(fh))
1505 			return -1;
1506 		m_copydata(m, off, sizeof(fh), (caddr_t)&fh);
1507 		/* IP6F_OFF_MASK = 0xfff8(BigEndian), 0xf8ff(LittleEndian) */
1508 		if (fh.ip6f_offlg & IP6F_OFF_MASK)
1509 			return -1;
1510 		if (nxtp)
1511 			*nxtp = fh.ip6f_nxt;
1512 		off += sizeof(struct ip6_frag);
1513 		return off;
1514 
1515 	case IPPROTO_AH:
1516 		if (m->m_pkthdr.len < off + sizeof(ip6e))
1517 			return -1;
1518 		m_copydata(m, off, sizeof(ip6e), (caddr_t)&ip6e);
1519 		if (nxtp)
1520 			*nxtp = ip6e.ip6e_nxt;
1521 		off += (ip6e.ip6e_len + 2) << 2;
1522 		return off;
1523 
1524 	case IPPROTO_HOPOPTS:
1525 	case IPPROTO_ROUTING:
1526 	case IPPROTO_DSTOPTS:
1527 		if (m->m_pkthdr.len < off + sizeof(ip6e))
1528 			return -1;
1529 		m_copydata(m, off, sizeof(ip6e), (caddr_t)&ip6e);
1530 		if (nxtp)
1531 			*nxtp = ip6e.ip6e_nxt;
1532 		off += (ip6e.ip6e_len + 1) << 3;
1533 		return off;
1534 
1535 	case IPPROTO_NONE:
1536 	case IPPROTO_ESP:
1537 	case IPPROTO_IPCOMP:
1538 		/* give up */
1539 		return -1;
1540 
1541 	default:
1542 		return -1;
1543 	}
1544 
1545 	return -1;
1546 }
1547 
1548 /*
1549  * get offset for the last header in the chain.  m will be kept untainted.
1550  */
1551 int
1552 ip6_lasthdr(struct mbuf *m, int off, int proto, int *nxtp)
1553 {
1554 	int newoff;
1555 	int nxt;
1556 
1557 	if (!nxtp) {
1558 		nxt = -1;
1559 		nxtp = &nxt;
1560 	}
1561 	while (1) {
1562 		newoff = ip6_nexthdr(m, off, proto, nxtp);
1563 		if (newoff < 0)
1564 			return off;
1565 		else if (newoff < off)
1566 			return -1;	/* invalid */
1567 		else if (newoff == off)
1568 			return newoff;
1569 
1570 		off = newoff;
1571 		proto = *nxtp;
1572 	}
1573 }
1574 
1575 /*
1576  * System control for IP6
1577  */
1578 
1579 u_char	inet6ctlerrmap[PRC_NCMDS] = {
1580 	0,		0,		0,		0,
1581 	0,		EMSGSIZE,	EHOSTDOWN,	EHOSTUNREACH,
1582 	EHOSTUNREACH,	EHOSTUNREACH,	ECONNREFUSED,	ECONNREFUSED,
1583 	EMSGSIZE,	EHOSTUNREACH,	0,		0,
1584 	0,		0,		0,		0,
1585 	ENOPROTOOPT
1586 };
1587