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