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