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