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