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