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