xref: /freebsd/sys/netinet6/ip6_input.c (revision 036d2e814bf0f5d88ffb4b24c159320894541757)
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 **mp, uint32_t *plen, uint32_t *rtalert, int *off,
407     int *nxt, int *ours)
408 {
409 	struct mbuf *m;
410 	struct ip6_hdr *ip6;
411 	struct ip6_hbh *hbh;
412 
413 	if (ip6_hopopts_input(plen, rtalert, mp, off)) {
414 #if 0	/*touches NULL pointer*/
415 		in6_ifstat_inc((*mp)->m_pkthdr.rcvif, ifs6_in_discard);
416 #endif
417 		goto out;	/* m have already been freed */
418 	}
419 
420 	/* adjust pointer */
421 	m = *mp;
422 	ip6 = mtod(m, struct ip6_hdr *);
423 
424 	/*
425 	 * if the payload length field is 0 and the next header field
426 	 * indicates Hop-by-Hop Options header, then a Jumbo Payload
427 	 * option MUST be included.
428 	 */
429 	if (ip6->ip6_plen == 0 && *plen == 0) {
430 		/*
431 		 * Note that if a valid jumbo payload option is
432 		 * contained, ip6_hopopts_input() must set a valid
433 		 * (non-zero) payload length to the variable plen.
434 		 */
435 		IP6STAT_INC(ip6s_badoptions);
436 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_discard);
437 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_hdrerr);
438 		icmp6_error(m, ICMP6_PARAM_PROB,
439 			    ICMP6_PARAMPROB_HEADER,
440 			    (caddr_t)&ip6->ip6_plen - (caddr_t)ip6);
441 		goto out;
442 	}
443 #ifndef PULLDOWN_TEST
444 	/* ip6_hopopts_input() ensures that mbuf is contiguous */
445 	hbh = (struct ip6_hbh *)(ip6 + 1);
446 #else
447 	IP6_EXTHDR_GET(hbh, struct ip6_hbh *, m, sizeof(struct ip6_hdr),
448 		sizeof(struct ip6_hbh));
449 	if (hbh == NULL) {
450 		IP6STAT_INC(ip6s_tooshort);
451 		goto out;
452 	}
453 #endif
454 	*nxt = hbh->ip6h_nxt;
455 
456 	/*
457 	 * If we are acting as a router and the packet contains a
458 	 * router alert option, see if we know the option value.
459 	 * Currently, we only support the option value for MLD, in which
460 	 * case we should pass the packet to the multicast routing
461 	 * daemon.
462 	 */
463 	if (*rtalert != ~0) {
464 		switch (*rtalert) {
465 		case IP6OPT_RTALERT_MLD:
466 			if (V_ip6_forwarding)
467 				*ours = 1;
468 			break;
469 		default:
470 			/*
471 			 * RFC2711 requires unrecognized values must be
472 			 * silently ignored.
473 			 */
474 			break;
475 		}
476 	}
477 
478 	return (0);
479 
480 out:
481 	return (1);
482 }
483 
484 #ifdef RSS
485 /*
486  * IPv6 direct input routine.
487  *
488  * This is called when reinjecting completed fragments where
489  * all of the previous checking and book-keeping has been done.
490  */
491 void
492 ip6_direct_input(struct mbuf *m)
493 {
494 	int off, nxt;
495 	int nest;
496 	struct m_tag *mtag;
497 	struct ip6_direct_ctx *ip6dc;
498 
499 	mtag = m_tag_locate(m, MTAG_ABI_IPV6, IPV6_TAG_DIRECT, NULL);
500 	KASSERT(mtag != NULL, ("Reinjected packet w/o direct ctx tag!"));
501 
502 	ip6dc = (struct ip6_direct_ctx *)(mtag + 1);
503 	nxt = ip6dc->ip6dc_nxt;
504 	off = ip6dc->ip6dc_off;
505 
506 	nest = 0;
507 
508 	m_tag_delete(m, mtag);
509 
510 	while (nxt != IPPROTO_DONE) {
511 		if (V_ip6_hdrnestlimit && (++nest > V_ip6_hdrnestlimit)) {
512 			IP6STAT_INC(ip6s_toomanyhdr);
513 			goto bad;
514 		}
515 
516 		/*
517 		 * protection against faulty packet - there should be
518 		 * more sanity checks in header chain processing.
519 		 */
520 		if (m->m_pkthdr.len < off) {
521 			IP6STAT_INC(ip6s_tooshort);
522 			in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_truncated);
523 			goto bad;
524 		}
525 
526 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
527 		if (IPSEC_ENABLED(ipv6)) {
528 			if (IPSEC_INPUT(ipv6, m, off, nxt) != 0)
529 				return;
530 		}
531 #endif /* IPSEC */
532 
533 		nxt = (*inet6sw[ip6_protox[nxt]].pr_input)(&m, &off, nxt);
534 	}
535 	return;
536 bad:
537 	m_freem(m);
538 }
539 #endif
540 
541 void
542 ip6_input(struct mbuf *m)
543 {
544 	struct in6_addr odst;
545 	struct ip6_hdr *ip6;
546 	struct in6_ifaddr *ia;
547 	struct ifnet *rcvif;
548 	u_int32_t plen;
549 	u_int32_t rtalert = ~0;
550 	int off = sizeof(struct ip6_hdr), nest;
551 	int nxt, ours = 0;
552 	int srcrt = 0;
553 
554 	/*
555 	 * Drop the packet if IPv6 operation is disabled on the interface.
556 	 */
557 	rcvif = m->m_pkthdr.rcvif;
558 	if ((ND_IFINFO(rcvif)->flags & ND6_IFF_IFDISABLED))
559 		goto bad;
560 
561 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
562 	/*
563 	 * should the inner packet be considered authentic?
564 	 * see comment in ah4_input().
565 	 * NB: m cannot be NULL when passed to the input routine
566 	 */
567 
568 	m->m_flags &= ~M_AUTHIPHDR;
569 	m->m_flags &= ~M_AUTHIPDGM;
570 
571 #endif /* IPSEC */
572 
573 	if (m->m_flags & M_FASTFWD_OURS) {
574 		/*
575 		 * Firewall changed destination to local.
576 		 */
577 		ip6 = mtod(m, struct ip6_hdr *);
578 		goto passin;
579 	}
580 
581 	/*
582 	 * mbuf statistics
583 	 */
584 	if (m->m_flags & M_EXT) {
585 		if (m->m_next)
586 			IP6STAT_INC(ip6s_mext2m);
587 		else
588 			IP6STAT_INC(ip6s_mext1);
589 	} else {
590 		if (m->m_next) {
591 			if (m->m_flags & M_LOOP) {
592 				IP6STAT_INC(ip6s_m2m[V_loif->if_index]);
593 			} else if (rcvif->if_index < IP6S_M2MMAX)
594 				IP6STAT_INC(ip6s_m2m[rcvif->if_index]);
595 			else
596 				IP6STAT_INC(ip6s_m2m[0]);
597 		} else
598 			IP6STAT_INC(ip6s_m1);
599 	}
600 
601 	in6_ifstat_inc(rcvif, ifs6_in_receive);
602 	IP6STAT_INC(ip6s_total);
603 
604 #ifndef PULLDOWN_TEST
605 	/*
606 	 * L2 bridge code and some other code can return mbuf chain
607 	 * that does not conform to KAME requirement.  too bad.
608 	 * XXX: fails to join if interface MTU > MCLBYTES.  jumbogram?
609 	 */
610 	if (m && m->m_next != NULL && m->m_pkthdr.len < MCLBYTES) {
611 		struct mbuf *n;
612 
613 		if (m->m_pkthdr.len > MHLEN)
614 			n = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
615 		else
616 			n = m_gethdr(M_NOWAIT, MT_DATA);
617 		if (n == NULL)
618 			goto bad;
619 
620 		m_move_pkthdr(n, m);
621 		m_copydata(m, 0, n->m_pkthdr.len, mtod(n, caddr_t));
622 		n->m_len = n->m_pkthdr.len;
623 		m_freem(m);
624 		m = n;
625 	}
626 	IP6_EXTHDR_CHECK(m, 0, sizeof(struct ip6_hdr), /* nothing */);
627 #endif
628 
629 	if (m->m_len < sizeof(struct ip6_hdr)) {
630 		if ((m = m_pullup(m, sizeof(struct ip6_hdr))) == NULL) {
631 			IP6STAT_INC(ip6s_toosmall);
632 			in6_ifstat_inc(rcvif, ifs6_in_hdrerr);
633 			goto bad;
634 		}
635 	}
636 
637 	ip6 = mtod(m, struct ip6_hdr *);
638 	if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION) {
639 		IP6STAT_INC(ip6s_badvers);
640 		in6_ifstat_inc(rcvif, ifs6_in_hdrerr);
641 		goto bad;
642 	}
643 
644 	IP6STAT_INC(ip6s_nxthist[ip6->ip6_nxt]);
645 	IP_PROBE(receive, NULL, NULL, ip6, rcvif, NULL, ip6);
646 
647 	/*
648 	 * Check against address spoofing/corruption.
649 	 */
650 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_src) ||
651 	    IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_dst)) {
652 		/*
653 		 * XXX: "badscope" is not very suitable for a multicast source.
654 		 */
655 		IP6STAT_INC(ip6s_badscope);
656 		in6_ifstat_inc(rcvif, ifs6_in_addrerr);
657 		goto bad;
658 	}
659 	if (IN6_IS_ADDR_MC_INTFACELOCAL(&ip6->ip6_dst) &&
660 	    !(m->m_flags & M_LOOP)) {
661 		/*
662 		 * In this case, the packet should come from the loopback
663 		 * interface.  However, we cannot just check the if_flags,
664 		 * because ip6_mloopback() passes the "actual" interface
665 		 * as the outgoing/incoming interface.
666 		 */
667 		IP6STAT_INC(ip6s_badscope);
668 		in6_ifstat_inc(rcvif, ifs6_in_addrerr);
669 		goto bad;
670 	}
671 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) &&
672 	    IPV6_ADDR_MC_SCOPE(&ip6->ip6_dst) == 0) {
673 		/*
674 		 * RFC4291 2.7:
675 		 * Nodes must not originate a packet to a multicast address
676 		 * whose scop field contains the reserved value 0; if such
677 		 * a packet is received, it must be silently dropped.
678 		 */
679 		IP6STAT_INC(ip6s_badscope);
680 		in6_ifstat_inc(rcvif, ifs6_in_addrerr);
681 		goto bad;
682 	}
683 #ifdef ALTQ
684 	if (altq_input != NULL && (*altq_input)(m, AF_INET6) == 0) {
685 		/* packet is dropped by traffic conditioner */
686 		return;
687 	}
688 #endif
689 	/*
690 	 * The following check is not documented in specs.  A malicious
691 	 * party may be able to use IPv4 mapped addr to confuse tcp/udp stack
692 	 * and bypass security checks (act as if it was from 127.0.0.1 by using
693 	 * IPv6 src ::ffff:127.0.0.1).  Be cautious.
694 	 *
695 	 * This check chokes if we are in an SIIT cloud.  As none of BSDs
696 	 * support IPv4-less kernel compilation, we cannot support SIIT
697 	 * environment at all.  So, it makes more sense for us to reject any
698 	 * malicious packets for non-SIIT environment, than try to do a
699 	 * partial support for SIIT environment.
700 	 */
701 	if (IN6_IS_ADDR_V4MAPPED(&ip6->ip6_src) ||
702 	    IN6_IS_ADDR_V4MAPPED(&ip6->ip6_dst)) {
703 		IP6STAT_INC(ip6s_badscope);
704 		in6_ifstat_inc(rcvif, ifs6_in_addrerr);
705 		goto bad;
706 	}
707 #if 0
708 	/*
709 	 * Reject packets with IPv4 compatible addresses (auto tunnel).
710 	 *
711 	 * The code forbids auto tunnel relay case in RFC1933 (the check is
712 	 * stronger than RFC1933).  We may want to re-enable it if mech-xx
713 	 * is revised to forbid relaying case.
714 	 */
715 	if (IN6_IS_ADDR_V4COMPAT(&ip6->ip6_src) ||
716 	    IN6_IS_ADDR_V4COMPAT(&ip6->ip6_dst)) {
717 		IP6STAT_INC(ip6s_badscope);
718 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_addrerr);
719 		goto bad;
720 	}
721 #endif
722 	/*
723 	 * Try to forward the packet, but if we fail continue.
724 	 * ip6_tryforward() does not generate redirects, so fall
725 	 * through to normal processing if redirects are required.
726 	 * ip6_tryforward() does inbound and outbound packet firewall
727 	 * processing. If firewall has decided that destination becomes
728 	 * our local address, it sets M_FASTFWD_OURS flag. In this
729 	 * case skip another inbound firewall processing and update
730 	 * ip6 pointer.
731 	 */
732 	if (V_ip6_forwarding != 0 && V_ip6_sendredirects == 0
733 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
734 	    && (!IPSEC_ENABLED(ipv6) ||
735 	    IPSEC_CAPS(ipv6, m, IPSEC_CAP_OPERABLE) == 0)
736 #endif
737 	    ) {
738 		if ((m = ip6_tryforward(m)) == NULL)
739 			return;
740 		if (m->m_flags & M_FASTFWD_OURS) {
741 			ip6 = mtod(m, struct ip6_hdr *);
742 			goto passin;
743 		}
744 	}
745 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
746 	/*
747 	 * Bypass packet filtering for packets previously handled by IPsec.
748 	 */
749 	if (IPSEC_ENABLED(ipv6) &&
750 	    IPSEC_CAPS(ipv6, m, IPSEC_CAP_BYPASS_FILTER) != 0)
751 			goto passin;
752 #endif
753 	/*
754 	 * Run through list of hooks for input packets.
755 	 *
756 	 * NB: Beware of the destination address changing
757 	 *     (e.g. by NAT rewriting).  When this happens,
758 	 *     tell ip6_forward to do the right thing.
759 	 */
760 
761 	/* Jump over all PFIL processing if hooks are not active. */
762 	if (!PFIL_HOOKED_IN(V_inet6_pfil_head))
763 		goto passin;
764 
765 	odst = ip6->ip6_dst;
766 	if (pfil_run_hooks(V_inet6_pfil_head, &m, m->m_pkthdr.rcvif, PFIL_IN,
767 	    NULL) != PFIL_PASS)
768 		return;
769 	ip6 = mtod(m, struct ip6_hdr *);
770 	srcrt = !IN6_ARE_ADDR_EQUAL(&odst, &ip6->ip6_dst);
771 	if ((m->m_flags & (M_IP6_NEXTHOP | M_FASTFWD_OURS)) == M_IP6_NEXTHOP &&
772 	    m_tag_find(m, PACKET_TAG_IPFORWARD, NULL) != NULL) {
773 		/*
774 		 * Directly ship the packet on.  This allows forwarding
775 		 * packets originally destined to us to some other directly
776 		 * connected host.
777 		 */
778 		ip6_forward(m, 1);
779 		return;
780 	}
781 
782 passin:
783 	/*
784 	 * Disambiguate address scope zones (if there is ambiguity).
785 	 * We first make sure that the original source or destination address
786 	 * is not in our internal form for scoped addresses.  Such addresses
787 	 * are not necessarily invalid spec-wise, but we cannot accept them due
788 	 * to the usage conflict.
789 	 * in6_setscope() then also checks and rejects the cases where src or
790 	 * dst are the loopback address and the receiving interface
791 	 * is not loopback.
792 	 */
793 	if (in6_clearscope(&ip6->ip6_src) || in6_clearscope(&ip6->ip6_dst)) {
794 		IP6STAT_INC(ip6s_badscope); /* XXX */
795 		goto bad;
796 	}
797 	if (in6_setscope(&ip6->ip6_src, rcvif, NULL) ||
798 	    in6_setscope(&ip6->ip6_dst, rcvif, NULL)) {
799 		IP6STAT_INC(ip6s_badscope);
800 		goto bad;
801 	}
802 	if (m->m_flags & M_FASTFWD_OURS) {
803 		m->m_flags &= ~M_FASTFWD_OURS;
804 		ours = 1;
805 		goto hbhcheck;
806 	}
807 	/*
808 	 * Multicast check. Assume packet is for us to avoid
809 	 * prematurely taking locks.
810 	 */
811 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
812 		ours = 1;
813 		in6_ifstat_inc(rcvif, ifs6_in_mcast);
814 		goto hbhcheck;
815 	}
816 	/*
817 	 * Unicast check
818 	 * XXX: For now we keep link-local IPv6 addresses with embedded
819 	 *      scope zone id, therefore we use zero zoneid here.
820 	 */
821 	ia = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */);
822 	if (ia != NULL) {
823 		if (ia->ia6_flags & IN6_IFF_NOTREADY) {
824 			char ip6bufs[INET6_ADDRSTRLEN];
825 			char ip6bufd[INET6_ADDRSTRLEN];
826 			/* address is not ready, so discard the packet. */
827 			nd6log((LOG_INFO,
828 			    "ip6_input: packet to an unready address %s->%s\n",
829 			    ip6_sprintf(ip6bufs, &ip6->ip6_src),
830 			    ip6_sprintf(ip6bufd, &ip6->ip6_dst)));
831 			ifa_free(&ia->ia_ifa);
832 			goto bad;
833 		}
834 		/* Count the packet in the ip address stats */
835 		counter_u64_add(ia->ia_ifa.ifa_ipackets, 1);
836 		counter_u64_add(ia->ia_ifa.ifa_ibytes, m->m_pkthdr.len);
837 		ifa_free(&ia->ia_ifa);
838 		ours = 1;
839 		goto hbhcheck;
840 	}
841 
842 	/*
843 	 * Now there is no reason to process the packet if it's not our own
844 	 * and we're not a router.
845 	 */
846 	if (!V_ip6_forwarding) {
847 		IP6STAT_INC(ip6s_cantforward);
848 		goto bad;
849 	}
850 
851   hbhcheck:
852 	/*
853 	 * Process Hop-by-Hop options header if it's contained.
854 	 * m may be modified in ip6_hopopts_input().
855 	 * If a JumboPayload option is included, plen will also be modified.
856 	 */
857 	plen = (u_int32_t)ntohs(ip6->ip6_plen);
858 	if (ip6->ip6_nxt == IPPROTO_HOPOPTS) {
859 		if (ip6_input_hbh(&m, &plen, &rtalert, &off, &nxt, &ours) != 0)
860 			return;
861 	} else
862 		nxt = ip6->ip6_nxt;
863 
864 	/*
865 	 * Use mbuf flags to propagate Router Alert option to
866 	 * ICMPv6 layer, as hop-by-hop options have been stripped.
867 	 */
868 	if (rtalert != ~0)
869 		m->m_flags |= M_RTALERT_MLD;
870 
871 	/*
872 	 * Check that the amount of data in the buffers
873 	 * is as at least much as the IPv6 header would have us expect.
874 	 * Trim mbufs if longer than we expect.
875 	 * Drop packet if shorter than we expect.
876 	 */
877 	if (m->m_pkthdr.len - sizeof(struct ip6_hdr) < plen) {
878 		IP6STAT_INC(ip6s_tooshort);
879 		in6_ifstat_inc(rcvif, ifs6_in_truncated);
880 		goto bad;
881 	}
882 	if (m->m_pkthdr.len > sizeof(struct ip6_hdr) + plen) {
883 		if (m->m_len == m->m_pkthdr.len) {
884 			m->m_len = sizeof(struct ip6_hdr) + plen;
885 			m->m_pkthdr.len = sizeof(struct ip6_hdr) + plen;
886 		} else
887 			m_adj(m, sizeof(struct ip6_hdr) + plen - m->m_pkthdr.len);
888 	}
889 
890 	/*
891 	 * Forward if desirable.
892 	 */
893 	if (V_ip6_mrouter &&
894 	    IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
895 		/*
896 		 * If we are acting as a multicast router, all
897 		 * incoming multicast packets are passed to the
898 		 * kernel-level multicast forwarding function.
899 		 * The packet is returned (relatively) intact; if
900 		 * ip6_mforward() returns a non-zero value, the packet
901 		 * must be discarded, else it may be accepted below.
902 		 *
903 		 * XXX TODO: Check hlim and multicast scope here to avoid
904 		 * unnecessarily calling into ip6_mforward().
905 		 */
906 		if (ip6_mforward && ip6_mforward(ip6, rcvif, m)) {
907 			IP6STAT_INC(ip6s_cantforward);
908 			goto bad;
909 		}
910 	} else if (!ours) {
911 		ip6_forward(m, srcrt);
912 		return;
913 	}
914 
915 	ip6 = mtod(m, struct ip6_hdr *);
916 
917 	/*
918 	 * Malicious party may be able to use IPv4 mapped addr to confuse
919 	 * tcp/udp stack and bypass security checks (act as if it was from
920 	 * 127.0.0.1 by using IPv6 src ::ffff:127.0.0.1).  Be cautious.
921 	 *
922 	 * For SIIT end node behavior, you may want to disable the check.
923 	 * However, you will  become vulnerable to attacks using IPv4 mapped
924 	 * source.
925 	 */
926 	if (IN6_IS_ADDR_V4MAPPED(&ip6->ip6_src) ||
927 	    IN6_IS_ADDR_V4MAPPED(&ip6->ip6_dst)) {
928 		IP6STAT_INC(ip6s_badscope);
929 		in6_ifstat_inc(rcvif, ifs6_in_addrerr);
930 		goto bad;
931 	}
932 
933 	/*
934 	 * Tell launch routine the next header
935 	 */
936 	IP6STAT_INC(ip6s_delivered);
937 	in6_ifstat_inc(rcvif, ifs6_in_deliver);
938 	nest = 0;
939 
940 	while (nxt != IPPROTO_DONE) {
941 		if (V_ip6_hdrnestlimit && (++nest > V_ip6_hdrnestlimit)) {
942 			IP6STAT_INC(ip6s_toomanyhdr);
943 			goto bad;
944 		}
945 
946 		/*
947 		 * protection against faulty packet - there should be
948 		 * more sanity checks in header chain processing.
949 		 */
950 		if (m->m_pkthdr.len < off) {
951 			IP6STAT_INC(ip6s_tooshort);
952 			in6_ifstat_inc(rcvif, ifs6_in_truncated);
953 			goto bad;
954 		}
955 
956 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
957 		if (IPSEC_ENABLED(ipv6)) {
958 			if (IPSEC_INPUT(ipv6, m, off, nxt) != 0)
959 				return;
960 		}
961 #endif /* IPSEC */
962 
963 		nxt = (*inet6sw[ip6_protox[nxt]].pr_input)(&m, &off, nxt);
964 	}
965 	return;
966 bad:
967 	in6_ifstat_inc(rcvif, ifs6_in_discard);
968 	if (m != NULL)
969 		m_freem(m);
970 }
971 
972 /*
973  * Hop-by-Hop options header processing. If a valid jumbo payload option is
974  * included, the real payload length will be stored in plenp.
975  *
976  * rtalertp - XXX: should be stored more smart way
977  */
978 static int
979 ip6_hopopts_input(u_int32_t *plenp, u_int32_t *rtalertp,
980     struct mbuf **mp, int *offp)
981 {
982 	struct mbuf *m = *mp;
983 	int off = *offp, hbhlen;
984 	struct ip6_hbh *hbh;
985 
986 	/* validation of the length of the header */
987 #ifndef PULLDOWN_TEST
988 	IP6_EXTHDR_CHECK(m, off, sizeof(*hbh), -1);
989 	hbh = (struct ip6_hbh *)(mtod(m, caddr_t) + off);
990 	hbhlen = (hbh->ip6h_len + 1) << 3;
991 
992 	IP6_EXTHDR_CHECK(m, off, hbhlen, -1);
993 	hbh = (struct ip6_hbh *)(mtod(m, caddr_t) + off);
994 #else
995 	IP6_EXTHDR_GET(hbh, struct ip6_hbh *, m,
996 		sizeof(struct ip6_hdr), sizeof(struct ip6_hbh));
997 	if (hbh == NULL) {
998 		IP6STAT_INC(ip6s_tooshort);
999 		return -1;
1000 	}
1001 	hbhlen = (hbh->ip6h_len + 1) << 3;
1002 	IP6_EXTHDR_GET(hbh, struct ip6_hbh *, m, sizeof(struct ip6_hdr),
1003 		hbhlen);
1004 	if (hbh == NULL) {
1005 		IP6STAT_INC(ip6s_tooshort);
1006 		return -1;
1007 	}
1008 #endif
1009 	off += hbhlen;
1010 	hbhlen -= sizeof(struct ip6_hbh);
1011 	if (ip6_process_hopopts(m, (u_int8_t *)hbh + sizeof(struct ip6_hbh),
1012 				hbhlen, rtalertp, plenp) < 0)
1013 		return (-1);
1014 
1015 	*offp = off;
1016 	*mp = m;
1017 	return (0);
1018 }
1019 
1020 /*
1021  * Search header for all Hop-by-hop options and process each option.
1022  * This function is separate from ip6_hopopts_input() in order to
1023  * handle a case where the sending node itself process its hop-by-hop
1024  * options header. In such a case, the function is called from ip6_output().
1025  *
1026  * The function assumes that hbh header is located right after the IPv6 header
1027  * (RFC2460 p7), opthead is pointer into data content in m, and opthead to
1028  * opthead + hbhlen is located in contiguous memory region.
1029  */
1030 int
1031 ip6_process_hopopts(struct mbuf *m, u_int8_t *opthead, int hbhlen,
1032     u_int32_t *rtalertp, u_int32_t *plenp)
1033 {
1034 	struct ip6_hdr *ip6;
1035 	int optlen = 0;
1036 	u_int8_t *opt = opthead;
1037 	u_int16_t rtalert_val;
1038 	u_int32_t jumboplen;
1039 	const int erroff = sizeof(struct ip6_hdr) + sizeof(struct ip6_hbh);
1040 
1041 	for (; hbhlen > 0; hbhlen -= optlen, opt += optlen) {
1042 		switch (*opt) {
1043 		case IP6OPT_PAD1:
1044 			optlen = 1;
1045 			break;
1046 		case IP6OPT_PADN:
1047 			if (hbhlen < IP6OPT_MINLEN) {
1048 				IP6STAT_INC(ip6s_toosmall);
1049 				goto bad;
1050 			}
1051 			optlen = *(opt + 1) + 2;
1052 			break;
1053 		case IP6OPT_ROUTER_ALERT:
1054 			/* XXX may need check for alignment */
1055 			if (hbhlen < IP6OPT_RTALERT_LEN) {
1056 				IP6STAT_INC(ip6s_toosmall);
1057 				goto bad;
1058 			}
1059 			if (*(opt + 1) != IP6OPT_RTALERT_LEN - 2) {
1060 				/* XXX stat */
1061 				icmp6_error(m, ICMP6_PARAM_PROB,
1062 				    ICMP6_PARAMPROB_HEADER,
1063 				    erroff + opt + 1 - opthead);
1064 				return (-1);
1065 			}
1066 			optlen = IP6OPT_RTALERT_LEN;
1067 			bcopy((caddr_t)(opt + 2), (caddr_t)&rtalert_val, 2);
1068 			*rtalertp = ntohs(rtalert_val);
1069 			break;
1070 		case IP6OPT_JUMBO:
1071 			/* XXX may need check for alignment */
1072 			if (hbhlen < IP6OPT_JUMBO_LEN) {
1073 				IP6STAT_INC(ip6s_toosmall);
1074 				goto bad;
1075 			}
1076 			if (*(opt + 1) != IP6OPT_JUMBO_LEN - 2) {
1077 				/* XXX stat */
1078 				icmp6_error(m, ICMP6_PARAM_PROB,
1079 				    ICMP6_PARAMPROB_HEADER,
1080 				    erroff + opt + 1 - opthead);
1081 				return (-1);
1082 			}
1083 			optlen = IP6OPT_JUMBO_LEN;
1084 
1085 			/*
1086 			 * IPv6 packets that have non 0 payload length
1087 			 * must not contain a jumbo payload option.
1088 			 */
1089 			ip6 = mtod(m, struct ip6_hdr *);
1090 			if (ip6->ip6_plen) {
1091 				IP6STAT_INC(ip6s_badoptions);
1092 				icmp6_error(m, ICMP6_PARAM_PROB,
1093 				    ICMP6_PARAMPROB_HEADER,
1094 				    erroff + opt - opthead);
1095 				return (-1);
1096 			}
1097 
1098 			/*
1099 			 * We may see jumbolen in unaligned location, so
1100 			 * we'd need to perform bcopy().
1101 			 */
1102 			bcopy(opt + 2, &jumboplen, sizeof(jumboplen));
1103 			jumboplen = (u_int32_t)htonl(jumboplen);
1104 
1105 #if 1
1106 			/*
1107 			 * if there are multiple jumbo payload options,
1108 			 * *plenp will be non-zero and the packet will be
1109 			 * rejected.
1110 			 * the behavior may need some debate in ipngwg -
1111 			 * multiple options does not make sense, however,
1112 			 * there's no explicit mention in specification.
1113 			 */
1114 			if (*plenp != 0) {
1115 				IP6STAT_INC(ip6s_badoptions);
1116 				icmp6_error(m, ICMP6_PARAM_PROB,
1117 				    ICMP6_PARAMPROB_HEADER,
1118 				    erroff + opt + 2 - opthead);
1119 				return (-1);
1120 			}
1121 #endif
1122 
1123 			/*
1124 			 * jumbo payload length must be larger than 65535.
1125 			 */
1126 			if (jumboplen <= IPV6_MAXPACKET) {
1127 				IP6STAT_INC(ip6s_badoptions);
1128 				icmp6_error(m, ICMP6_PARAM_PROB,
1129 				    ICMP6_PARAMPROB_HEADER,
1130 				    erroff + opt + 2 - opthead);
1131 				return (-1);
1132 			}
1133 			*plenp = jumboplen;
1134 
1135 			break;
1136 		default:		/* unknown option */
1137 			if (hbhlen < IP6OPT_MINLEN) {
1138 				IP6STAT_INC(ip6s_toosmall);
1139 				goto bad;
1140 			}
1141 			optlen = ip6_unknown_opt(opt, m,
1142 			    erroff + opt - opthead);
1143 			if (optlen == -1)
1144 				return (-1);
1145 			optlen += 2;
1146 			break;
1147 		}
1148 	}
1149 
1150 	return (0);
1151 
1152   bad:
1153 	m_freem(m);
1154 	return (-1);
1155 }
1156 
1157 /*
1158  * Unknown option processing.
1159  * The third argument `off' is the offset from the IPv6 header to the option,
1160  * which is necessary if the IPv6 header the and option header and IPv6 header
1161  * is not contiguous in order to return an ICMPv6 error.
1162  */
1163 int
1164 ip6_unknown_opt(u_int8_t *optp, struct mbuf *m, int off)
1165 {
1166 	struct ip6_hdr *ip6;
1167 
1168 	switch (IP6OPT_TYPE(*optp)) {
1169 	case IP6OPT_TYPE_SKIP: /* ignore the option */
1170 		return ((int)*(optp + 1));
1171 	case IP6OPT_TYPE_DISCARD:	/* silently discard */
1172 		m_freem(m);
1173 		return (-1);
1174 	case IP6OPT_TYPE_FORCEICMP: /* send ICMP even if multicasted */
1175 		IP6STAT_INC(ip6s_badoptions);
1176 		icmp6_error(m, ICMP6_PARAM_PROB, ICMP6_PARAMPROB_OPTION, off);
1177 		return (-1);
1178 	case IP6OPT_TYPE_ICMP: /* send ICMP if not multicasted */
1179 		IP6STAT_INC(ip6s_badoptions);
1180 		ip6 = mtod(m, struct ip6_hdr *);
1181 		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
1182 		    (m->m_flags & (M_BCAST|M_MCAST)))
1183 			m_freem(m);
1184 		else
1185 			icmp6_error(m, ICMP6_PARAM_PROB,
1186 				    ICMP6_PARAMPROB_OPTION, off);
1187 		return (-1);
1188 	}
1189 
1190 	m_freem(m);		/* XXX: NOTREACHED */
1191 	return (-1);
1192 }
1193 
1194 /*
1195  * Create the "control" list for this pcb.
1196  * These functions will not modify mbuf chain at all.
1197  *
1198  * With KAME mbuf chain restriction:
1199  * The routine will be called from upper layer handlers like tcp6_input().
1200  * Thus the routine assumes that the caller (tcp6_input) have already
1201  * called IP6_EXTHDR_CHECK() and all the extension headers are located in the
1202  * very first mbuf on the mbuf chain.
1203  *
1204  * ip6_savecontrol_v4 will handle those options that are possible to be
1205  * set on a v4-mapped socket.
1206  * ip6_savecontrol will directly call ip6_savecontrol_v4 to handle those
1207  * options and handle the v6-only ones itself.
1208  */
1209 struct mbuf **
1210 ip6_savecontrol_v4(struct inpcb *inp, struct mbuf *m, struct mbuf **mp,
1211     int *v4only)
1212 {
1213 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
1214 
1215 #ifdef SO_TIMESTAMP
1216 	if ((inp->inp_socket->so_options & SO_TIMESTAMP) != 0) {
1217 		union {
1218 			struct timeval tv;
1219 			struct bintime bt;
1220 			struct timespec ts;
1221 		} t;
1222 		struct bintime boottimebin, bt1;
1223 		struct timespec ts1;
1224 		bool stamped;
1225 
1226 		stamped = false;
1227 		switch (inp->inp_socket->so_ts_clock) {
1228 		case SO_TS_REALTIME_MICRO:
1229 			if ((m->m_flags & (M_PKTHDR | M_TSTMP)) == (M_PKTHDR |
1230 			    M_TSTMP)) {
1231 				mbuf_tstmp2timespec(m, &ts1);
1232 				timespec2bintime(&ts1, &bt1);
1233 				getboottimebin(&boottimebin);
1234 				bintime_add(&bt1, &boottimebin);
1235 				bintime2timeval(&bt1, &t.tv);
1236 			} else {
1237 				microtime(&t.tv);
1238 			}
1239 			*mp = sbcreatecontrol((caddr_t) &t.tv, sizeof(t.tv),
1240 			    SCM_TIMESTAMP, SOL_SOCKET);
1241 			if (*mp != NULL) {
1242 				mp = &(*mp)->m_next;
1243 				stamped = true;
1244 			}
1245 			break;
1246 
1247 		case SO_TS_BINTIME:
1248 			if ((m->m_flags & (M_PKTHDR | M_TSTMP)) == (M_PKTHDR |
1249 			    M_TSTMP)) {
1250 				mbuf_tstmp2timespec(m, &ts1);
1251 				timespec2bintime(&ts1, &t.bt);
1252 				getboottimebin(&boottimebin);
1253 				bintime_add(&t.bt, &boottimebin);
1254 			} else {
1255 				bintime(&t.bt);
1256 			}
1257 			*mp = sbcreatecontrol((caddr_t)&t.bt, sizeof(t.bt),
1258 			    SCM_BINTIME, SOL_SOCKET);
1259 			if (*mp != NULL) {
1260 				mp = &(*mp)->m_next;
1261 				stamped = true;
1262 			}
1263 			break;
1264 
1265 		case SO_TS_REALTIME:
1266 			if ((m->m_flags & (M_PKTHDR | M_TSTMP)) == (M_PKTHDR |
1267 			    M_TSTMP)) {
1268 				mbuf_tstmp2timespec(m, &t.ts);
1269 				getboottimebin(&boottimebin);
1270 				bintime2timespec(&boottimebin, &ts1);
1271 				timespecadd(&t.ts, &ts1, &t.ts);
1272 			} else {
1273 				nanotime(&t.ts);
1274 			}
1275 			*mp = sbcreatecontrol((caddr_t)&t.ts, sizeof(t.ts),
1276 			    SCM_REALTIME, SOL_SOCKET);
1277 			if (*mp != NULL) {
1278 				mp = &(*mp)->m_next;
1279 				stamped = true;
1280 			}
1281 			break;
1282 
1283 		case SO_TS_MONOTONIC:
1284 			if ((m->m_flags & (M_PKTHDR | M_TSTMP)) == (M_PKTHDR |
1285 			    M_TSTMP))
1286 				mbuf_tstmp2timespec(m, &t.ts);
1287 			else
1288 				nanouptime(&t.ts);
1289 			*mp = sbcreatecontrol((caddr_t)&t.ts, sizeof(t.ts),
1290 			    SCM_MONOTONIC, SOL_SOCKET);
1291 			if (*mp != NULL) {
1292 				mp = &(*mp)->m_next;
1293 				stamped = true;
1294 			}
1295 			break;
1296 
1297 		default:
1298 			panic("unknown (corrupted) so_ts_clock");
1299 		}
1300 		if (stamped && (m->m_flags & (M_PKTHDR | M_TSTMP)) ==
1301 		    (M_PKTHDR | M_TSTMP)) {
1302 			struct sock_timestamp_info sti;
1303 
1304 			bzero(&sti, sizeof(sti));
1305 			sti.st_info_flags = ST_INFO_HW;
1306 			if ((m->m_flags & M_TSTMP_HPREC) != 0)
1307 				sti.st_info_flags |= ST_INFO_HW_HPREC;
1308 			*mp = sbcreatecontrol((caddr_t)&sti, sizeof(sti),
1309 			    SCM_TIME_INFO, SOL_SOCKET);
1310 			if (*mp != NULL)
1311 				mp = &(*mp)->m_next;
1312 		}
1313 	}
1314 #endif
1315 
1316 #define IS2292(inp, x, y)	(((inp)->inp_flags & IN6P_RFC2292) ? (x) : (y))
1317 	/* RFC 2292 sec. 5 */
1318 	if ((inp->inp_flags & IN6P_PKTINFO) != 0) {
1319 		struct in6_pktinfo pi6;
1320 
1321 		if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION) {
1322 #ifdef INET
1323 			struct ip *ip;
1324 
1325 			ip = mtod(m, struct ip *);
1326 			pi6.ipi6_addr.s6_addr32[0] = 0;
1327 			pi6.ipi6_addr.s6_addr32[1] = 0;
1328 			pi6.ipi6_addr.s6_addr32[2] = IPV6_ADDR_INT32_SMP;
1329 			pi6.ipi6_addr.s6_addr32[3] = ip->ip_dst.s_addr;
1330 #else
1331 			/* We won't hit this code */
1332 			bzero(&pi6.ipi6_addr, sizeof(struct in6_addr));
1333 #endif
1334 		} else {
1335 			bcopy(&ip6->ip6_dst, &pi6.ipi6_addr, sizeof(struct in6_addr));
1336 			in6_clearscope(&pi6.ipi6_addr);	/* XXX */
1337 		}
1338 		pi6.ipi6_ifindex =
1339 		    (m && m->m_pkthdr.rcvif) ? m->m_pkthdr.rcvif->if_index : 0;
1340 
1341 		*mp = sbcreatecontrol((caddr_t) &pi6,
1342 		    sizeof(struct in6_pktinfo),
1343 		    IS2292(inp, IPV6_2292PKTINFO, IPV6_PKTINFO), IPPROTO_IPV6);
1344 		if (*mp)
1345 			mp = &(*mp)->m_next;
1346 	}
1347 
1348 	if ((inp->inp_flags & IN6P_HOPLIMIT) != 0) {
1349 		int hlim;
1350 
1351 		if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION) {
1352 #ifdef INET
1353 			struct ip *ip;
1354 
1355 			ip = mtod(m, struct ip *);
1356 			hlim = ip->ip_ttl;
1357 #else
1358 			/* We won't hit this code */
1359 			hlim = 0;
1360 #endif
1361 		} else {
1362 			hlim = ip6->ip6_hlim & 0xff;
1363 		}
1364 		*mp = sbcreatecontrol((caddr_t) &hlim, sizeof(int),
1365 		    IS2292(inp, IPV6_2292HOPLIMIT, IPV6_HOPLIMIT),
1366 		    IPPROTO_IPV6);
1367 		if (*mp)
1368 			mp = &(*mp)->m_next;
1369 	}
1370 
1371 	if ((inp->inp_flags & IN6P_TCLASS) != 0) {
1372 		int tclass;
1373 
1374 		if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION) {
1375 #ifdef INET
1376 			struct ip *ip;
1377 
1378 			ip = mtod(m, struct ip *);
1379 			tclass = ip->ip_tos;
1380 #else
1381 			/* We won't hit this code */
1382 			tclass = 0;
1383 #endif
1384 		} else {
1385 			u_int32_t flowinfo;
1386 
1387 			flowinfo = (u_int32_t)ntohl(ip6->ip6_flow & IPV6_FLOWINFO_MASK);
1388 			flowinfo >>= 20;
1389 			tclass = flowinfo & 0xff;
1390 		}
1391 		*mp = sbcreatecontrol((caddr_t) &tclass, sizeof(int),
1392 		    IPV6_TCLASS, IPPROTO_IPV6);
1393 		if (*mp)
1394 			mp = &(*mp)->m_next;
1395 	}
1396 
1397 	if (v4only != NULL) {
1398 		if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION) {
1399 			*v4only = 1;
1400 		} else {
1401 			*v4only = 0;
1402 		}
1403 	}
1404 
1405 	return (mp);
1406 }
1407 
1408 void
1409 ip6_savecontrol(struct inpcb *inp, struct mbuf *m, struct mbuf **mp)
1410 {
1411 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
1412 	int v4only = 0;
1413 
1414 	mp = ip6_savecontrol_v4(inp, m, mp, &v4only);
1415 	if (v4only)
1416 		return;
1417 
1418 	/*
1419 	 * IPV6_HOPOPTS socket option.  Recall that we required super-user
1420 	 * privilege for the option (see ip6_ctloutput), but it might be too
1421 	 * strict, since there might be some hop-by-hop options which can be
1422 	 * returned to normal user.
1423 	 * See also RFC 2292 section 6 (or RFC 3542 section 8).
1424 	 */
1425 	if ((inp->inp_flags & IN6P_HOPOPTS) != 0) {
1426 		/*
1427 		 * Check if a hop-by-hop options header is contatined in the
1428 		 * received packet, and if so, store the options as ancillary
1429 		 * data. Note that a hop-by-hop options header must be
1430 		 * just after the IPv6 header, which is assured through the
1431 		 * IPv6 input processing.
1432 		 */
1433 		if (ip6->ip6_nxt == IPPROTO_HOPOPTS) {
1434 			struct ip6_hbh *hbh;
1435 			int hbhlen = 0;
1436 #ifdef PULLDOWN_TEST
1437 			struct mbuf *ext;
1438 #endif
1439 
1440 #ifndef PULLDOWN_TEST
1441 			hbh = (struct ip6_hbh *)(ip6 + 1);
1442 			hbhlen = (hbh->ip6h_len + 1) << 3;
1443 #else
1444 			ext = ip6_pullexthdr(m, sizeof(struct ip6_hdr),
1445 			    ip6->ip6_nxt);
1446 			if (ext == NULL) {
1447 				IP6STAT_INC(ip6s_tooshort);
1448 				return;
1449 			}
1450 			hbh = mtod(ext, struct ip6_hbh *);
1451 			hbhlen = (hbh->ip6h_len + 1) << 3;
1452 			if (hbhlen != ext->m_len) {
1453 				m_freem(ext);
1454 				IP6STAT_INC(ip6s_tooshort);
1455 				return;
1456 			}
1457 #endif
1458 
1459 			/*
1460 			 * XXX: We copy the whole header even if a
1461 			 * jumbo payload option is included, the option which
1462 			 * is to be removed before returning according to
1463 			 * RFC2292.
1464 			 * Note: this constraint is removed in RFC3542
1465 			 */
1466 			*mp = sbcreatecontrol((caddr_t)hbh, hbhlen,
1467 			    IS2292(inp, IPV6_2292HOPOPTS, IPV6_HOPOPTS),
1468 			    IPPROTO_IPV6);
1469 			if (*mp)
1470 				mp = &(*mp)->m_next;
1471 #ifdef PULLDOWN_TEST
1472 			m_freem(ext);
1473 #endif
1474 		}
1475 	}
1476 
1477 	if ((inp->inp_flags & (IN6P_RTHDR | IN6P_DSTOPTS)) != 0) {
1478 		int nxt = ip6->ip6_nxt, off = sizeof(struct ip6_hdr);
1479 
1480 		/*
1481 		 * Search for destination options headers or routing
1482 		 * header(s) through the header chain, and stores each
1483 		 * header as ancillary data.
1484 		 * Note that the order of the headers remains in
1485 		 * the chain of ancillary data.
1486 		 */
1487 		while (1) {	/* is explicit loop prevention necessary? */
1488 			struct ip6_ext *ip6e = NULL;
1489 			int elen;
1490 #ifdef PULLDOWN_TEST
1491 			struct mbuf *ext = NULL;
1492 #endif
1493 
1494 			/*
1495 			 * if it is not an extension header, don't try to
1496 			 * pull it from the chain.
1497 			 */
1498 			switch (nxt) {
1499 			case IPPROTO_DSTOPTS:
1500 			case IPPROTO_ROUTING:
1501 			case IPPROTO_HOPOPTS:
1502 			case IPPROTO_AH: /* is it possible? */
1503 				break;
1504 			default:
1505 				goto loopend;
1506 			}
1507 
1508 #ifndef PULLDOWN_TEST
1509 			if (off + sizeof(*ip6e) > m->m_len)
1510 				goto loopend;
1511 			ip6e = (struct ip6_ext *)(mtod(m, caddr_t) + off);
1512 			if (nxt == IPPROTO_AH)
1513 				elen = (ip6e->ip6e_len + 2) << 2;
1514 			else
1515 				elen = (ip6e->ip6e_len + 1) << 3;
1516 			if (off + elen > m->m_len)
1517 				goto loopend;
1518 #else
1519 			ext = ip6_pullexthdr(m, off, nxt);
1520 			if (ext == NULL) {
1521 				IP6STAT_INC(ip6s_tooshort);
1522 				return;
1523 			}
1524 			ip6e = mtod(ext, struct ip6_ext *);
1525 			if (nxt == IPPROTO_AH)
1526 				elen = (ip6e->ip6e_len + 2) << 2;
1527 			else
1528 				elen = (ip6e->ip6e_len + 1) << 3;
1529 			if (elen != ext->m_len) {
1530 				m_freem(ext);
1531 				IP6STAT_INC(ip6s_tooshort);
1532 				return;
1533 			}
1534 #endif
1535 
1536 			switch (nxt) {
1537 			case IPPROTO_DSTOPTS:
1538 				if (!(inp->inp_flags & IN6P_DSTOPTS))
1539 					break;
1540 
1541 				*mp = sbcreatecontrol((caddr_t)ip6e, elen,
1542 				    IS2292(inp,
1543 					IPV6_2292DSTOPTS, IPV6_DSTOPTS),
1544 				    IPPROTO_IPV6);
1545 				if (*mp)
1546 					mp = &(*mp)->m_next;
1547 				break;
1548 			case IPPROTO_ROUTING:
1549 				if (!(inp->inp_flags & IN6P_RTHDR))
1550 					break;
1551 
1552 				*mp = sbcreatecontrol((caddr_t)ip6e, elen,
1553 				    IS2292(inp, IPV6_2292RTHDR, IPV6_RTHDR),
1554 				    IPPROTO_IPV6);
1555 				if (*mp)
1556 					mp = &(*mp)->m_next;
1557 				break;
1558 			case IPPROTO_HOPOPTS:
1559 			case IPPROTO_AH: /* is it possible? */
1560 				break;
1561 
1562 			default:
1563 				/*
1564 				 * other cases have been filtered in the above.
1565 				 * none will visit this case.  here we supply
1566 				 * the code just in case (nxt overwritten or
1567 				 * other cases).
1568 				 */
1569 #ifdef PULLDOWN_TEST
1570 				m_freem(ext);
1571 #endif
1572 				goto loopend;
1573 
1574 			}
1575 
1576 			/* proceed with the next header. */
1577 			off += elen;
1578 			nxt = ip6e->ip6e_nxt;
1579 			ip6e = NULL;
1580 #ifdef PULLDOWN_TEST
1581 			m_freem(ext);
1582 			ext = NULL;
1583 #endif
1584 		}
1585 	  loopend:
1586 		;
1587 	}
1588 
1589 	if (inp->inp_flags2 & INP_RECVFLOWID) {
1590 		uint32_t flowid, flow_type;
1591 
1592 		flowid = m->m_pkthdr.flowid;
1593 		flow_type = M_HASHTYPE_GET(m);
1594 
1595 		/*
1596 		 * XXX should handle the failure of one or the
1597 		 * other - don't populate both?
1598 		 */
1599 		*mp = sbcreatecontrol((caddr_t) &flowid,
1600 		    sizeof(uint32_t), IPV6_FLOWID, IPPROTO_IPV6);
1601 		if (*mp)
1602 			mp = &(*mp)->m_next;
1603 		*mp = sbcreatecontrol((caddr_t) &flow_type,
1604 		    sizeof(uint32_t), IPV6_FLOWTYPE, IPPROTO_IPV6);
1605 		if (*mp)
1606 			mp = &(*mp)->m_next;
1607 	}
1608 
1609 #ifdef	RSS
1610 	if (inp->inp_flags2 & INP_RECVRSSBUCKETID) {
1611 		uint32_t flowid, flow_type;
1612 		uint32_t rss_bucketid;
1613 
1614 		flowid = m->m_pkthdr.flowid;
1615 		flow_type = M_HASHTYPE_GET(m);
1616 
1617 		if (rss_hash2bucket(flowid, flow_type, &rss_bucketid) == 0) {
1618 			*mp = sbcreatecontrol((caddr_t) &rss_bucketid,
1619 			   sizeof(uint32_t), IPV6_RSSBUCKETID, IPPROTO_IPV6);
1620 			if (*mp)
1621 				mp = &(*mp)->m_next;
1622 		}
1623 	}
1624 #endif
1625 
1626 }
1627 #undef IS2292
1628 
1629 void
1630 ip6_notify_pmtu(struct inpcb *inp, struct sockaddr_in6 *dst, u_int32_t mtu)
1631 {
1632 	struct socket *so;
1633 	struct mbuf *m_mtu;
1634 	struct ip6_mtuinfo mtuctl;
1635 
1636 	KASSERT(inp != NULL, ("%s: inp == NULL", __func__));
1637 	/*
1638 	 * Notify the error by sending IPV6_PATHMTU ancillary data if
1639 	 * application wanted to know the MTU value.
1640 	 * NOTE: we notify disconnected sockets, because some udp
1641 	 * applications keep sending sockets disconnected.
1642 	 * NOTE: our implementation doesn't notify connected sockets that has
1643 	 * foreign address that is different than given destination addresses
1644 	 * (this is permitted by RFC 3542).
1645 	 */
1646 	if ((inp->inp_flags & IN6P_MTU) == 0 || (
1647 	    !IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr) &&
1648 	    !IN6_ARE_ADDR_EQUAL(&inp->in6p_faddr, &dst->sin6_addr)))
1649 		return;
1650 
1651 	mtuctl.ip6m_mtu = mtu;
1652 	mtuctl.ip6m_addr = *dst;
1653 	if (sa6_recoverscope(&mtuctl.ip6m_addr))
1654 		return;
1655 
1656 	if ((m_mtu = sbcreatecontrol((caddr_t)&mtuctl, sizeof(mtuctl),
1657 	    IPV6_PATHMTU, IPPROTO_IPV6)) == NULL)
1658 		return;
1659 
1660 	so =  inp->inp_socket;
1661 	if (sbappendaddr(&so->so_rcv, (struct sockaddr *)dst, NULL, m_mtu)
1662 	    == 0) {
1663 		m_freem(m_mtu);
1664 		/* XXX: should count statistics */
1665 	} else
1666 		sorwakeup(so);
1667 }
1668 
1669 #ifdef PULLDOWN_TEST
1670 /*
1671  * pull single extension header from mbuf chain.  returns single mbuf that
1672  * contains the result, or NULL on error.
1673  */
1674 static struct mbuf *
1675 ip6_pullexthdr(struct mbuf *m, size_t off, int nxt)
1676 {
1677 	struct ip6_ext ip6e;
1678 	size_t elen;
1679 	struct mbuf *n;
1680 
1681 #ifdef DIAGNOSTIC
1682 	switch (nxt) {
1683 	case IPPROTO_DSTOPTS:
1684 	case IPPROTO_ROUTING:
1685 	case IPPROTO_HOPOPTS:
1686 	case IPPROTO_AH: /* is it possible? */
1687 		break;
1688 	default:
1689 		printf("ip6_pullexthdr: invalid nxt=%d\n", nxt);
1690 	}
1691 #endif
1692 
1693 	m_copydata(m, off, sizeof(ip6e), (caddr_t)&ip6e);
1694 	if (nxt == IPPROTO_AH)
1695 		elen = (ip6e.ip6e_len + 2) << 2;
1696 	else
1697 		elen = (ip6e.ip6e_len + 1) << 3;
1698 
1699 	if (elen > MLEN)
1700 		n = m_getcl(M_NOWAIT, MT_DATA, 0);
1701 	else
1702 		n = m_get(M_NOWAIT, MT_DATA);
1703 	if (n == NULL)
1704 		return NULL;
1705 
1706 	m_copydata(m, off, elen, mtod(n, caddr_t));
1707 	n->m_len = elen;
1708 	return n;
1709 }
1710 #endif
1711 
1712 /*
1713  * Get pointer to the previous header followed by the header
1714  * currently processed.
1715  */
1716 int
1717 ip6_get_prevhdr(const struct mbuf *m, int off)
1718 {
1719 	struct ip6_ext ip6e;
1720 	struct ip6_hdr *ip6;
1721 	int len, nlen, nxt;
1722 
1723 	if (off == sizeof(struct ip6_hdr))
1724 		return (offsetof(struct ip6_hdr, ip6_nxt));
1725 	if (off < sizeof(struct ip6_hdr))
1726 		panic("%s: off < sizeof(struct ip6_hdr)", __func__);
1727 
1728 	ip6 = mtod(m, struct ip6_hdr *);
1729 	nxt = ip6->ip6_nxt;
1730 	len = sizeof(struct ip6_hdr);
1731 	nlen = 0;
1732 	while (len < off) {
1733 		m_copydata(m, len, sizeof(ip6e), (caddr_t)&ip6e);
1734 		switch (nxt) {
1735 		case IPPROTO_FRAGMENT:
1736 			nlen = sizeof(struct ip6_frag);
1737 			break;
1738 		case IPPROTO_AH:
1739 			nlen = (ip6e.ip6e_len + 2) << 2;
1740 			break;
1741 		default:
1742 			nlen = (ip6e.ip6e_len + 1) << 3;
1743 		}
1744 		len += nlen;
1745 		nxt = ip6e.ip6e_nxt;
1746 	}
1747 	return (len - nlen);
1748 }
1749 
1750 /*
1751  * get next header offset.  m will be retained.
1752  */
1753 int
1754 ip6_nexthdr(const struct mbuf *m, int off, int proto, int *nxtp)
1755 {
1756 	struct ip6_hdr ip6;
1757 	struct ip6_ext ip6e;
1758 	struct ip6_frag fh;
1759 
1760 	/* just in case */
1761 	if (m == NULL)
1762 		panic("ip6_nexthdr: m == NULL");
1763 	if ((m->m_flags & M_PKTHDR) == 0 || m->m_pkthdr.len < off)
1764 		return -1;
1765 
1766 	switch (proto) {
1767 	case IPPROTO_IPV6:
1768 		if (m->m_pkthdr.len < off + sizeof(ip6))
1769 			return -1;
1770 		m_copydata(m, off, sizeof(ip6), (caddr_t)&ip6);
1771 		if (nxtp)
1772 			*nxtp = ip6.ip6_nxt;
1773 		off += sizeof(ip6);
1774 		return off;
1775 
1776 	case IPPROTO_FRAGMENT:
1777 		/*
1778 		 * terminate parsing if it is not the first fragment,
1779 		 * it does not make sense to parse through it.
1780 		 */
1781 		if (m->m_pkthdr.len < off + sizeof(fh))
1782 			return -1;
1783 		m_copydata(m, off, sizeof(fh), (caddr_t)&fh);
1784 		/* IP6F_OFF_MASK = 0xfff8(BigEndian), 0xf8ff(LittleEndian) */
1785 		if (fh.ip6f_offlg & IP6F_OFF_MASK)
1786 			return -1;
1787 		if (nxtp)
1788 			*nxtp = fh.ip6f_nxt;
1789 		off += sizeof(struct ip6_frag);
1790 		return off;
1791 
1792 	case IPPROTO_AH:
1793 		if (m->m_pkthdr.len < off + sizeof(ip6e))
1794 			return -1;
1795 		m_copydata(m, off, sizeof(ip6e), (caddr_t)&ip6e);
1796 		if (nxtp)
1797 			*nxtp = ip6e.ip6e_nxt;
1798 		off += (ip6e.ip6e_len + 2) << 2;
1799 		return off;
1800 
1801 	case IPPROTO_HOPOPTS:
1802 	case IPPROTO_ROUTING:
1803 	case IPPROTO_DSTOPTS:
1804 		if (m->m_pkthdr.len < off + sizeof(ip6e))
1805 			return -1;
1806 		m_copydata(m, off, sizeof(ip6e), (caddr_t)&ip6e);
1807 		if (nxtp)
1808 			*nxtp = ip6e.ip6e_nxt;
1809 		off += (ip6e.ip6e_len + 1) << 3;
1810 		return off;
1811 
1812 	case IPPROTO_NONE:
1813 	case IPPROTO_ESP:
1814 	case IPPROTO_IPCOMP:
1815 		/* give up */
1816 		return -1;
1817 
1818 	default:
1819 		return -1;
1820 	}
1821 
1822 	/* NOTREACHED */
1823 }
1824 
1825 /*
1826  * get offset for the last header in the chain.  m will be kept untainted.
1827  */
1828 int
1829 ip6_lasthdr(const struct mbuf *m, int off, int proto, int *nxtp)
1830 {
1831 	int newoff;
1832 	int nxt;
1833 
1834 	if (!nxtp) {
1835 		nxt = -1;
1836 		nxtp = &nxt;
1837 	}
1838 	while (1) {
1839 		newoff = ip6_nexthdr(m, off, proto, nxtp);
1840 		if (newoff < 0)
1841 			return off;
1842 		else if (newoff < off)
1843 			return -1;	/* invalid */
1844 		else if (newoff == off)
1845 			return newoff;
1846 
1847 		off = newoff;
1848 		proto = *nxtp;
1849 	}
1850 }
1851 
1852 /*
1853  * System control for IP6
1854  */
1855 
1856 u_char	inet6ctlerrmap[PRC_NCMDS] = {
1857 	0,		0,		0,		0,
1858 	0,		EMSGSIZE,	EHOSTDOWN,	EHOSTUNREACH,
1859 	EHOSTUNREACH,	EHOSTUNREACH,	ECONNREFUSED,	ECONNREFUSED,
1860 	EMSGSIZE,	EHOSTUNREACH,	0,		0,
1861 	0,		0,		EHOSTUNREACH,	0,
1862 	ENOPROTOOPT,	ECONNREFUSED
1863 };
1864