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