xref: /openbsd-src/sys/netinet6/ip6_input.c (revision 99fd087599a8791921855f21bd7e36130f39aadc)
1 /*	$OpenBSD: ip6_input.c,v 1.224 2019/12/30 14:52:00 bluhm Exp $	*/
2 /*	$KAME: ip6_input.c,v 1.188 2001/03/29 05:34:31 itojun Exp $	*/
3 
4 /*
5  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the project nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 /*
34  * Copyright (c) 1982, 1986, 1988, 1993
35  *	The Regents of the University of California.  All rights reserved.
36  *
37  * Redistribution and use in source and binary forms, with or without
38  * modification, are permitted provided that the following conditions
39  * are met:
40  * 1. Redistributions of source code must retain the above copyright
41  *    notice, this list of conditions and the following disclaimer.
42  * 2. Redistributions in binary form must reproduce the above copyright
43  *    notice, this list of conditions and the following disclaimer in the
44  *    documentation and/or other materials provided with the distribution.
45  * 3. Neither the name of the University nor the names of its contributors
46  *    may be used to endorse or promote products derived from this software
47  *    without specific prior written permission.
48  *
49  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
50  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
51  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
52  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
53  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
54  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
55  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
56  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
57  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
58  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
59  * SUCH DAMAGE.
60  *
61  *	@(#)ip_input.c	8.2 (Berkeley) 1/4/94
62  */
63 
64 #include "pf.h"
65 #include "carp.h"
66 
67 #include <sys/param.h>
68 #include <sys/systm.h>
69 #include <sys/mbuf.h>
70 #include <sys/domain.h>
71 #include <sys/sysctl.h>
72 #include <sys/protosw.h>
73 #include <sys/socket.h>
74 #include <sys/socketvar.h>
75 #include <sys/errno.h>
76 #include <sys/time.h>
77 #include <sys/timeout.h>
78 #include <sys/kernel.h>
79 #include <sys/syslog.h>
80 #include <sys/task.h>
81 
82 #include <net/if.h>
83 #include <net/if_var.h>
84 #include <net/if_types.h>
85 #include <net/route.h>
86 #include <net/netisr.h>
87 
88 #include <netinet/in.h>
89 
90 #include <netinet/ip.h>
91 
92 #include <netinet/in_pcb.h>
93 #include <netinet/ip_var.h>
94 #include <netinet6/in6_var.h>
95 #include <netinet6/in6_ifattach.h>
96 #include <netinet/ip6.h>
97 #include <netinet6/ip6_var.h>
98 #include <netinet/icmp6.h>
99 #include <netinet6/nd6.h>
100 
101 #include <netinet6/ip6protosw.h>
102 
103 #include "gif.h"
104 #include "bpfilter.h"
105 
106 #ifdef MROUTING
107 #include <netinet6/ip6_mroute.h>
108 #endif
109 
110 #if NPF > 0
111 #include <net/pfvar.h>
112 #endif
113 
114 #if NCARP > 0
115 #include <netinet/ip_carp.h>
116 #endif
117 
118 struct cpumem *ip6counters;
119 
120 uint8_t ip6_soiikey[IP6_SOIIKEY_LEN];
121 
122 int ip6_ours(struct mbuf **, int *, int, int);
123 int ip6_check_rh0hdr(struct mbuf *, int *);
124 int ip6_hbhchcheck(struct mbuf *, int *, int *, int *);
125 int ip6_hopopts_input(u_int32_t *, u_int32_t *, struct mbuf **, int *);
126 struct mbuf *ip6_pullexthdr(struct mbuf *, size_t, int);
127 int ip6_sysctl_soiikey(void *, size_t *, void *, size_t);
128 
129 static struct mbuf_queue	ip6send_mq;
130 
131 static void ip6_send_dispatch(void *);
132 static struct task ip6send_task =
133 	TASK_INITIALIZER(ip6_send_dispatch, &ip6send_mq);
134 
135 /*
136  * IP6 initialization: fill in IP6 protocol switch table.
137  * All protocols not implemented in kernel go to raw IP6 protocol handler.
138  */
139 void
140 ip6_init(void)
141 {
142 	const struct protosw *pr;
143 	int i;
144 
145 	pr = pffindproto(PF_INET6, IPPROTO_RAW, SOCK_RAW);
146 	if (pr == NULL)
147 		panic("%s", __func__);
148 	for (i = 0; i < IPPROTO_MAX; i++)
149 		ip6_protox[i] = pr - inet6sw;
150 	for (pr = inet6domain.dom_protosw;
151 	    pr < inet6domain.dom_protoswNPROTOSW; pr++)
152 		if (pr->pr_domain->dom_family == PF_INET6 &&
153 		    pr->pr_protocol && pr->pr_protocol != IPPROTO_RAW &&
154 		    pr->pr_protocol < IPPROTO_MAX)
155 			ip6_protox[pr->pr_protocol] = pr - inet6sw;
156 	ip6_randomid_init();
157 	nd6_init();
158 	frag6_init();
159 
160 	mq_init(&ip6send_mq, 64, IPL_SOFTNET);
161 
162 	ip6counters = counters_alloc(ip6s_ncounters);
163 }
164 
165 void
166 ipv6_input(struct ifnet *ifp, struct mbuf *m)
167 {
168 	int off, nxt;
169 
170 	off = 0;
171 	nxt = ip6_input_if(&m, &off, IPPROTO_IPV6, AF_UNSPEC, ifp);
172 	KASSERT(nxt == IPPROTO_DONE);
173 }
174 
175 int
176 ip6_input_if(struct mbuf **mp, int *offp, int nxt, int af, struct ifnet *ifp)
177 {
178 	struct mbuf *m = *mp;
179 	struct ip6_hdr *ip6;
180 	struct sockaddr_in6 sin6;
181 	struct rtentry *rt = NULL;
182 	int ours = 0;
183 	u_int16_t src_scope, dst_scope;
184 #if NPF > 0
185 	struct in6_addr odst;
186 #endif
187 	int srcrt = 0;
188 
189 	KASSERT(*offp == 0);
190 
191 	ip6stat_inc(ip6s_total);
192 
193 	if (m->m_len < sizeof(struct ip6_hdr)) {
194 		if ((m = *mp = m_pullup(m, sizeof(struct ip6_hdr))) == NULL) {
195 			ip6stat_inc(ip6s_toosmall);
196 			goto bad;
197 		}
198 	}
199 
200 	ip6 = mtod(m, struct ip6_hdr *);
201 
202 	if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION) {
203 		ip6stat_inc(ip6s_badvers);
204 		goto bad;
205 	}
206 
207 #if NCARP > 0
208 	if (carp_lsdrop(ifp, m, AF_INET6, ip6->ip6_src.s6_addr32,
209 	    ip6->ip6_dst.s6_addr32, (ip6->ip6_nxt == IPPROTO_ICMPV6 ? 0 : 1)))
210 		goto bad;
211 #endif
212 	ip6stat_inc(ip6s_nxthist + ip6->ip6_nxt);
213 
214 	/*
215 	 * Check against address spoofing/corruption.
216 	 */
217 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_src) ||
218 	    IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_dst)) {
219 		/*
220 		 * XXX: "badscope" is not very suitable for a multicast source.
221 		 */
222 		ip6stat_inc(ip6s_badscope);
223 		goto bad;
224 	}
225 	if ((IN6_IS_ADDR_LOOPBACK(&ip6->ip6_src) ||
226 	    IN6_IS_ADDR_LOOPBACK(&ip6->ip6_dst)) &&
227 	    (ifp->if_flags & IFF_LOOPBACK) == 0) {
228 		    ip6stat_inc(ip6s_badscope);
229 		    goto bad;
230 	}
231 	/* Drop packets if interface ID portion is already filled. */
232 	if (((IN6_IS_SCOPE_EMBED(&ip6->ip6_src) && ip6->ip6_src.s6_addr16[1]) ||
233 	    (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst) && ip6->ip6_dst.s6_addr16[1])) &&
234 	    (ifp->if_flags & IFF_LOOPBACK) == 0) {
235 		ip6stat_inc(ip6s_badscope);
236 		goto bad;
237 	}
238 	if (IN6_IS_ADDR_MC_INTFACELOCAL(&ip6->ip6_dst) &&
239 	    !(m->m_flags & M_LOOP)) {
240 		/*
241 		 * In this case, the packet should come from the loopback
242 		 * interface.  However, we cannot just check the if_flags,
243 		 * because ip6_mloopback() passes the "actual" interface
244 		 * as the outgoing/incoming interface.
245 		 */
246 		ip6stat_inc(ip6s_badscope);
247 		goto bad;
248 	}
249 
250 	/*
251 	 * The following check is not documented in specs.  A malicious
252 	 * party may be able to use IPv4 mapped addr to confuse tcp/udp stack
253 	 * and bypass security checks (act as if it was from 127.0.0.1 by using
254 	 * IPv6 src ::ffff:127.0.0.1).  Be cautious.
255 	 *
256 	 * This check chokes if we are in an SIIT cloud.  As none of BSDs
257 	 * support IPv4-less kernel compilation, we cannot support SIIT
258 	 * environment at all.  So, it makes more sense for us to reject any
259 	 * malicious packets for non-SIIT environment, than try to do a
260 	 * partial support for SIIT environment.
261 	 */
262 	if (IN6_IS_ADDR_V4MAPPED(&ip6->ip6_src) ||
263 	    IN6_IS_ADDR_V4MAPPED(&ip6->ip6_dst)) {
264 		ip6stat_inc(ip6s_badscope);
265 		goto bad;
266 	}
267 
268 	/*
269 	 * Reject packets with IPv4 compatible addresses (auto tunnel).
270 	 *
271 	 * The code forbids automatic tunneling as per RFC4213.
272 	 */
273 	if (IN6_IS_ADDR_V4COMPAT(&ip6->ip6_src) ||
274 	    IN6_IS_ADDR_V4COMPAT(&ip6->ip6_dst)) {
275 		ip6stat_inc(ip6s_badscope);
276 		goto bad;
277 	}
278 
279 	/*
280 	 * If the packet has been received on a loopback interface it
281 	 * can be destinated to any local address, not necessarily to
282 	 * an address configured on `ifp'.
283 	 */
284 	if (ifp->if_flags & IFF_LOOPBACK) {
285 		if (IN6_IS_SCOPE_EMBED(&ip6->ip6_src)) {
286 			src_scope = ip6->ip6_src.s6_addr16[1];
287 			ip6->ip6_src.s6_addr16[1] = 0;
288 		}
289 		if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst)) {
290 			dst_scope = ip6->ip6_dst.s6_addr16[1];
291 			ip6->ip6_dst.s6_addr16[1] = 0;
292 		}
293 	}
294 
295 #if NPF > 0
296 	/*
297 	 * Packet filter
298 	 */
299 	odst = ip6->ip6_dst;
300 	if (pf_test(AF_INET6, PF_IN, ifp, mp) != PF_PASS)
301 		goto bad;
302 	m = *mp;
303 	if (m == NULL)
304 		goto bad;
305 
306 	ip6 = mtod(m, struct ip6_hdr *);
307 	srcrt = !IN6_ARE_ADDR_EQUAL(&odst, &ip6->ip6_dst);
308 #endif
309 
310 	/*
311 	 * Without embedded scope ID we cannot find link-local
312 	 * addresses in the routing table.
313 	 */
314 	if (ifp->if_flags & IFF_LOOPBACK) {
315 		if (IN6_IS_SCOPE_EMBED(&ip6->ip6_src))
316 			ip6->ip6_src.s6_addr16[1] = src_scope;
317 		if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst))
318 			ip6->ip6_dst.s6_addr16[1] = dst_scope;
319 	} else {
320 		if (IN6_IS_SCOPE_EMBED(&ip6->ip6_src))
321 			ip6->ip6_src.s6_addr16[1] = htons(ifp->if_index);
322 		if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst))
323 			ip6->ip6_dst.s6_addr16[1] = htons(ifp->if_index);
324 	}
325 
326 	/*
327 	 * Be more secure than RFC5095 and scan for type 0 routing headers.
328 	 * If pf has already scanned the header chain, do not do it twice.
329 	 */
330 	if (!(m->m_pkthdr.pf.flags & PF_TAG_PROCESSED) &&
331 	    ip6_check_rh0hdr(m, offp)) {
332 		ip6stat_inc(ip6s_badoptions);
333 		icmp6_error(m, ICMP6_PARAM_PROB, ICMP6_PARAMPROB_HEADER, *offp);
334 		m = *mp = NULL;
335 		goto bad;
336 	}
337 
338 #if NPF > 0
339 	if (pf_ouraddr(m) == 1) {
340 		nxt = ip6_ours(mp, offp, nxt, af);
341 		goto out;
342 	}
343 #endif
344 
345 	/*
346 	 * Multicast check
347 	 */
348 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
349 		/*
350 		 * Make sure M_MCAST is set.  It should theoretically
351 		 * already be there, but let's play safe because upper
352 		 * layers check for this flag.
353 		 */
354 		m->m_flags |= M_MCAST;
355 
356 		/*
357 		 * See if we belong to the destination multicast group on the
358 		 * arrival interface.
359 		 */
360 		if (in6_hasmulti(&ip6->ip6_dst, ifp))
361 			ours = 1;
362 
363 #ifdef MROUTING
364 		if (ip6_mforwarding && ip6_mrouter[ifp->if_rdomain]) {
365 			int error;
366 
367 			if (ip6_hbhchcheck(m, offp, &nxt, &ours))
368 				goto out;
369 
370 			ip6 = mtod(m, struct ip6_hdr *);
371 
372 			/*
373 			 * If we are acting as a multicast router, all
374 			 * incoming multicast packets are passed to the
375 			 * kernel-level multicast forwarding function.
376 			 * The packet is returned (relatively) intact; if
377 			 * ip6_mforward() returns a non-zero value, the packet
378 			 * must be discarded, else it may be accepted below.
379 			 */
380 			KERNEL_LOCK();
381 			error = ip6_mforward(ip6, ifp, m);
382 			KERNEL_UNLOCK();
383 			if (error) {
384 				ip6stat_inc(ip6s_cantforward);
385 				goto bad;
386 			}
387 
388 			if (ours) {
389 				if (af == AF_UNSPEC) {
390 					KERNEL_LOCK();
391 					nxt = ip_deliver(mp, offp, nxt,
392 					    AF_INET6);
393 					KERNEL_UNLOCK();
394 				}
395 				goto out;
396 			}
397 			goto bad;
398 		}
399 #endif
400 		if (!ours) {
401 			ip6stat_inc(ip6s_notmember);
402 			if (!IN6_IS_ADDR_MC_LINKLOCAL(&ip6->ip6_dst))
403 				ip6stat_inc(ip6s_cantforward);
404 			goto bad;
405 		}
406 		nxt = ip6_ours(mp, offp, nxt, af);
407 		goto out;
408 	}
409 
410 
411 	/*
412 	 *  Unicast check
413 	 */
414 	memset(&sin6, 0, sizeof(struct sockaddr_in6));
415 	sin6.sin6_len = sizeof(struct sockaddr_in6);
416 	sin6.sin6_family = AF_INET6;
417 	sin6.sin6_addr = ip6->ip6_dst;
418 	rt = rtalloc_mpath(sin6tosa(&sin6), &ip6->ip6_src.s6_addr32[0],
419 	    m->m_pkthdr.ph_rtableid);
420 
421 	/*
422 	 * Accept the packet if the route to the destination is marked
423 	 * as local.
424 	 */
425 	if (rtisvalid(rt) && ISSET(rt->rt_flags, RTF_LOCAL)) {
426 		struct in6_ifaddr *ia6 = ifatoia6(rt->rt_ifa);
427 		if (ia6->ia6_flags & IN6_IFF_ANYCAST)
428 			m->m_flags |= M_ACAST;
429 
430 		if (ip6_forwarding == 0 && rt->rt_ifidx != ifp->if_index &&
431 		    !((ifp->if_flags & IFF_LOOPBACK) ||
432 		    (ifp->if_type == IFT_ENC) ||
433 		    (m->m_pkthdr.pf.flags & PF_TAG_TRANSLATE_LOCALHOST))) {
434 			/* received on wrong interface */
435 #if NCARP > 0
436 			struct ifnet *out_if;
437 
438 			/*
439 			 * Virtual IPs on carp interfaces need to be checked
440 			 * also against the parent interface and other carp
441 			 * interfaces sharing the same parent.
442 			 */
443 			out_if = if_get(rt->rt_ifidx);
444 			if (!(out_if && carp_strict_addr_chk(out_if, ifp))) {
445 				ip6stat_inc(ip6s_wrongif);
446 				if_put(out_if);
447 				goto bad;
448 			}
449 			if_put(out_if);
450 #else
451 			ip6stat_inc(ip6s_wrongif);
452 			goto bad;
453 #endif
454 		}
455 		/*
456 		 * packets to a tentative, duplicated, or somehow invalid
457 		 * address must not be accepted.
458 		 */
459 		if ((ia6->ia6_flags & (IN6_IFF_TENTATIVE|IN6_IFF_DUPLICATED))) {
460 			char src[INET6_ADDRSTRLEN], dst[INET6_ADDRSTRLEN];
461 
462 			inet_ntop(AF_INET6, &ip6->ip6_src, src, sizeof(src));
463 			inet_ntop(AF_INET6, &ip6->ip6_dst, dst, sizeof(dst));
464 			/* address is not ready, so discard the packet. */
465 			nd6log((LOG_INFO,
466 			    "%s: packet to an unready address %s->%s\n",
467 			    __func__, src, dst));
468 
469 			goto bad;
470 		} else {
471 			nxt = ip6_ours(mp, offp, nxt, af);
472 			goto out;
473 		}
474 	}
475 
476 #if NCARP > 0
477 	if (ip6->ip6_nxt == IPPROTO_ICMPV6 &&
478 	    carp_lsdrop(ifp, m, AF_INET6, ip6->ip6_src.s6_addr32,
479 	    ip6->ip6_dst.s6_addr32, 1))
480 		goto bad;
481 #endif
482 	/*
483 	 * Now there is no reason to process the packet if it's not our own
484 	 * and we're not a router.
485 	 */
486 	if (!ip6_forwarding) {
487 		ip6stat_inc(ip6s_cantforward);
488 		goto bad;
489 	}
490 
491 	if (ip6_hbhchcheck(m, offp, &nxt, &ours))
492 		goto out;
493 
494 	if (ours) {
495 		if (af == AF_UNSPEC) {
496 			KERNEL_LOCK();
497 			nxt = ip_deliver(mp, offp, nxt, AF_INET6);
498 			KERNEL_UNLOCK();
499 		}
500 		goto out;
501 	}
502 
503 #ifdef IPSEC
504 	if (ipsec_in_use) {
505 		int rv;
506 
507 		rv = ipsec_forward_check(m, *offp, AF_INET6);
508 		if (rv != 0) {
509 			ip6stat_inc(ip6s_cantforward);
510 			goto bad;
511 		}
512 		/*
513 		 * Fall through, forward packet. Outbound IPsec policy
514 		 * checking will occur in ip6_forward().
515 		 */
516 	}
517 #endif /* IPSEC */
518 
519 	ip6_forward(m, rt, srcrt);
520 	*mp = NULL;
521 	return IPPROTO_DONE;
522  bad:
523 	nxt = IPPROTO_DONE;
524 	m_freemp(mp);
525  out:
526 	rtfree(rt);
527 	return nxt;
528 }
529 
530 int
531 ip6_ours(struct mbuf **mp, int *offp, int nxt, int af)
532 {
533 	if (ip6_hbhchcheck(*mp, offp, &nxt, NULL))
534 		return IPPROTO_DONE;
535 
536 	/* Check wheter we are already in a IPv4/IPv6 local deliver loop. */
537 	if (af == AF_UNSPEC)
538 		nxt = ip_deliver(mp, offp, nxt, AF_INET6);
539 	return nxt;
540 }
541 
542 int
543 ip6_hbhchcheck(struct mbuf *m, int *offp, int *nxtp, int *oursp)
544 {
545 	struct ip6_hdr *ip6;
546 	u_int32_t plen, rtalert = ~0;
547 
548 	ip6 = mtod(m, struct ip6_hdr *);
549 
550 	/*
551 	 * Process Hop-by-Hop options header if it's contained.
552 	 * m may be modified in ip6_hopopts_input().
553 	 * If a JumboPayload option is included, plen will also be modified.
554 	 */
555 	plen = (u_int32_t)ntohs(ip6->ip6_plen);
556 	*offp = sizeof(struct ip6_hdr);
557 	if (ip6->ip6_nxt == IPPROTO_HOPOPTS) {
558 		struct ip6_hbh *hbh;
559 
560 		if (ip6_hopopts_input(&plen, &rtalert, &m, offp)) {
561 			goto bad;	/* m have already been freed */
562 		}
563 
564 		/* adjust pointer */
565 		ip6 = mtod(m, struct ip6_hdr *);
566 
567 		/*
568 		 * if the payload length field is 0 and the next header field
569 		 * indicates Hop-by-Hop Options header, then a Jumbo Payload
570 		 * option MUST be included.
571 		 */
572 		if (ip6->ip6_plen == 0 && plen == 0) {
573 			/*
574 			 * Note that if a valid jumbo payload option is
575 			 * contained, ip6_hopopts_input() must set a valid
576 			 * (non-zero) payload length to the variable plen.
577 			 */
578 			ip6stat_inc(ip6s_badoptions);
579 			icmp6_error(m, ICMP6_PARAM_PROB,
580 				    ICMP6_PARAMPROB_HEADER,
581 				    (caddr_t)&ip6->ip6_plen - (caddr_t)ip6);
582 			goto bad;
583 		}
584 		IP6_EXTHDR_GET(hbh, struct ip6_hbh *, m, sizeof(struct ip6_hdr),
585 			sizeof(struct ip6_hbh));
586 		if (hbh == NULL) {
587 			ip6stat_inc(ip6s_tooshort);
588 			goto bad;
589 		}
590 		*nxtp = hbh->ip6h_nxt;
591 
592 		/*
593 		 * accept the packet if a router alert option is included
594 		 * and we act as an IPv6 router.
595 		 */
596 		if (rtalert != ~0 && ip6_forwarding && oursp != NULL)
597 			*oursp = 1;
598 	} else
599 		*nxtp = ip6->ip6_nxt;
600 
601 	/*
602 	 * Check that the amount of data in the buffers
603 	 * is as at least much as the IPv6 header would have us expect.
604 	 * Trim mbufs if longer than we expect.
605 	 * Drop packet if shorter than we expect.
606 	 */
607 	if (m->m_pkthdr.len - sizeof(struct ip6_hdr) < plen) {
608 		ip6stat_inc(ip6s_tooshort);
609 		m_freem(m);
610 		goto bad;
611 	}
612 	if (m->m_pkthdr.len > sizeof(struct ip6_hdr) + plen) {
613 		if (m->m_len == m->m_pkthdr.len) {
614 			m->m_len = sizeof(struct ip6_hdr) + plen;
615 			m->m_pkthdr.len = sizeof(struct ip6_hdr) + plen;
616 		} else {
617 			m_adj(m,
618 			    sizeof(struct ip6_hdr) + plen - m->m_pkthdr.len);
619 		}
620 	}
621 
622 	return (0);
623 
624  bad:
625 	*nxtp = IPPROTO_DONE;
626 	return (-1);
627 }
628 
629 /* scan packet for RH0 routing header. Mostly stolen from pf.c:pf_test() */
630 int
631 ip6_check_rh0hdr(struct mbuf *m, int *offp)
632 {
633 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
634 	struct ip6_rthdr rthdr;
635 	struct ip6_ext opt6;
636 	u_int8_t proto = ip6->ip6_nxt;
637 	int done = 0, lim, off, rh_cnt = 0;
638 
639 	off = ((caddr_t)ip6 - m->m_data) + sizeof(struct ip6_hdr);
640 	lim = min(m->m_pkthdr.len, ntohs(ip6->ip6_plen) + sizeof(*ip6));
641 	do {
642 		switch (proto) {
643 		case IPPROTO_ROUTING:
644 			*offp = off;
645 			if (rh_cnt++) {
646 				/* more than one rh header present */
647 				return (1);
648 			}
649 
650 			if (off + sizeof(rthdr) > lim) {
651 				/* packet to short to make sense */
652 				return (1);
653 			}
654 
655 			m_copydata(m, off, sizeof(rthdr), (caddr_t)&rthdr);
656 
657 			if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
658 				*offp += offsetof(struct ip6_rthdr, ip6r_type);
659 				return (1);
660 			}
661 
662 			off += (rthdr.ip6r_len + 1) * 8;
663 			proto = rthdr.ip6r_nxt;
664 			break;
665 		case IPPROTO_AH:
666 		case IPPROTO_HOPOPTS:
667 		case IPPROTO_DSTOPTS:
668 			/* get next header and header length */
669 			if (off + sizeof(opt6) > lim) {
670 				/*
671 				 * Packet to short to make sense, we could
672 				 * reject the packet but as a router we
673 				 * should not do that so forward it.
674 				 */
675 				return (0);
676 			}
677 
678 			m_copydata(m, off, sizeof(opt6), (caddr_t)&opt6);
679 
680 			if (proto == IPPROTO_AH)
681 				off += (opt6.ip6e_len + 2) * 4;
682 			else
683 				off += (opt6.ip6e_len + 1) * 8;
684 			proto = opt6.ip6e_nxt;
685 			break;
686 		case IPPROTO_FRAGMENT:
687 		default:
688 			/* end of header stack */
689 			done = 1;
690 			break;
691 		}
692 	} while (!done);
693 
694 	return (0);
695 }
696 
697 /*
698  * Hop-by-Hop options header processing. If a valid jumbo payload option is
699  * included, the real payload length will be stored in plenp.
700  *
701  * rtalertp - XXX: should be stored in a more smart way
702  */
703 int
704 ip6_hopopts_input(u_int32_t *plenp, u_int32_t *rtalertp, struct mbuf **mp,
705     int *offp)
706 {
707 	struct mbuf *m = *mp;
708 	int off = *offp, hbhlen;
709 	struct ip6_hbh *hbh;
710 
711 	/* validation of the length of the header */
712 	IP6_EXTHDR_GET(hbh, struct ip6_hbh *, m,
713 		sizeof(struct ip6_hdr), sizeof(struct ip6_hbh));
714 	if (hbh == NULL) {
715 		ip6stat_inc(ip6s_tooshort);
716 		return -1;
717 	}
718 	hbhlen = (hbh->ip6h_len + 1) << 3;
719 	IP6_EXTHDR_GET(hbh, struct ip6_hbh *, m, sizeof(struct ip6_hdr),
720 		hbhlen);
721 	if (hbh == NULL) {
722 		ip6stat_inc(ip6s_tooshort);
723 		return -1;
724 	}
725 	off += hbhlen;
726 	hbhlen -= sizeof(struct ip6_hbh);
727 
728 	if (ip6_process_hopopts(m, (u_int8_t *)hbh + sizeof(struct ip6_hbh),
729 				hbhlen, rtalertp, plenp) < 0)
730 		return (-1);
731 
732 	*offp = off;
733 	*mp = m;
734 	return (0);
735 }
736 
737 /*
738  * Search header for all Hop-by-hop options and process each option.
739  * This function is separate from ip6_hopopts_input() in order to
740  * handle a case where the sending node itself process its hop-by-hop
741  * options header. In such a case, the function is called from ip6_output().
742  *
743  * The function assumes that hbh header is located right after the IPv6 header
744  * (RFC2460 p7), opthead is pointer into data content in m, and opthead to
745  * opthead + hbhlen is located in continuous memory region.
746  */
747 int
748 ip6_process_hopopts(struct mbuf *m, u_int8_t *opthead, int hbhlen,
749     u_int32_t *rtalertp, u_int32_t *plenp)
750 {
751 	struct ip6_hdr *ip6;
752 	int optlen = 0;
753 	u_int8_t *opt = opthead;
754 	u_int16_t rtalert_val;
755 	u_int32_t jumboplen;
756 	const int erroff = sizeof(struct ip6_hdr) + sizeof(struct ip6_hbh);
757 
758 	for (; hbhlen > 0; hbhlen -= optlen, opt += optlen) {
759 		switch (*opt) {
760 		case IP6OPT_PAD1:
761 			optlen = 1;
762 			break;
763 		case IP6OPT_PADN:
764 			if (hbhlen < IP6OPT_MINLEN) {
765 				ip6stat_inc(ip6s_toosmall);
766 				goto bad;
767 			}
768 			optlen = *(opt + 1) + 2;
769 			break;
770 		case IP6OPT_ROUTER_ALERT:
771 			/* XXX may need check for alignment */
772 			if (hbhlen < IP6OPT_RTALERT_LEN) {
773 				ip6stat_inc(ip6s_toosmall);
774 				goto bad;
775 			}
776 			if (*(opt + 1) != IP6OPT_RTALERT_LEN - 2) {
777 				/* XXX stat */
778 				icmp6_error(m, ICMP6_PARAM_PROB,
779 				    ICMP6_PARAMPROB_HEADER,
780 				    erroff + opt + 1 - opthead);
781 				return (-1);
782 			}
783 			optlen = IP6OPT_RTALERT_LEN;
784 			memcpy((caddr_t)&rtalert_val, (caddr_t)(opt + 2), 2);
785 			*rtalertp = ntohs(rtalert_val);
786 			break;
787 		case IP6OPT_JUMBO:
788 			/* XXX may need check for alignment */
789 			if (hbhlen < IP6OPT_JUMBO_LEN) {
790 				ip6stat_inc(ip6s_toosmall);
791 				goto bad;
792 			}
793 			if (*(opt + 1) != IP6OPT_JUMBO_LEN - 2) {
794 				/* XXX stat */
795 				icmp6_error(m, ICMP6_PARAM_PROB,
796 				    ICMP6_PARAMPROB_HEADER,
797 				    erroff + opt + 1 - opthead);
798 				return (-1);
799 			}
800 			optlen = IP6OPT_JUMBO_LEN;
801 
802 			/*
803 			 * IPv6 packets that have non 0 payload length
804 			 * must not contain a jumbo payload option.
805 			 */
806 			ip6 = mtod(m, struct ip6_hdr *);
807 			if (ip6->ip6_plen) {
808 				ip6stat_inc(ip6s_badoptions);
809 				icmp6_error(m, ICMP6_PARAM_PROB,
810 				    ICMP6_PARAMPROB_HEADER,
811 				    erroff + opt - opthead);
812 				return (-1);
813 			}
814 
815 			/*
816 			 * We may see jumbolen in unaligned location, so
817 			 * we'd need to perform memcpy().
818 			 */
819 			memcpy(&jumboplen, opt + 2, sizeof(jumboplen));
820 			jumboplen = (u_int32_t)htonl(jumboplen);
821 
822 #if 1
823 			/*
824 			 * if there are multiple jumbo payload options,
825 			 * *plenp will be non-zero and the packet will be
826 			 * rejected.
827 			 * the behavior may need some debate in ipngwg -
828 			 * multiple options does not make sense, however,
829 			 * there's no explicit mention in specification.
830 			 */
831 			if (*plenp != 0) {
832 				ip6stat_inc(ip6s_badoptions);
833 				icmp6_error(m, ICMP6_PARAM_PROB,
834 				    ICMP6_PARAMPROB_HEADER,
835 				    erroff + opt + 2 - opthead);
836 				return (-1);
837 			}
838 #endif
839 
840 			/*
841 			 * jumbo payload length must be larger than 65535.
842 			 */
843 			if (jumboplen <= IPV6_MAXPACKET) {
844 				ip6stat_inc(ip6s_badoptions);
845 				icmp6_error(m, ICMP6_PARAM_PROB,
846 				    ICMP6_PARAMPROB_HEADER,
847 				    erroff + opt + 2 - opthead);
848 				return (-1);
849 			}
850 			*plenp = jumboplen;
851 
852 			break;
853 		default:		/* unknown option */
854 			if (hbhlen < IP6OPT_MINLEN) {
855 				ip6stat_inc(ip6s_toosmall);
856 				goto bad;
857 			}
858 			optlen = ip6_unknown_opt(opt, m,
859 			    erroff + opt - opthead);
860 			if (optlen == -1)
861 				return (-1);
862 			optlen += 2;
863 			break;
864 		}
865 	}
866 
867 	return (0);
868 
869   bad:
870 	m_freem(m);
871 	return (-1);
872 }
873 
874 /*
875  * Unknown option processing.
876  * The third argument `off' is the offset from the IPv6 header to the option,
877  * which allows returning an ICMPv6 error even if the IPv6 header and the
878  * option header are not continuous.
879  */
880 int
881 ip6_unknown_opt(u_int8_t *optp, struct mbuf *m, int off)
882 {
883 	struct ip6_hdr *ip6;
884 
885 	switch (IP6OPT_TYPE(*optp)) {
886 	case IP6OPT_TYPE_SKIP: /* ignore the option */
887 		return ((int)*(optp + 1));
888 	case IP6OPT_TYPE_DISCARD:	/* silently discard */
889 		m_freem(m);
890 		return (-1);
891 	case IP6OPT_TYPE_FORCEICMP: /* send ICMP even if multicasted */
892 		ip6stat_inc(ip6s_badoptions);
893 		icmp6_error(m, ICMP6_PARAM_PROB, ICMP6_PARAMPROB_OPTION, off);
894 		return (-1);
895 	case IP6OPT_TYPE_ICMP: /* send ICMP if not multicasted */
896 		ip6stat_inc(ip6s_badoptions);
897 		ip6 = mtod(m, struct ip6_hdr *);
898 		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
899 		    (m->m_flags & (M_BCAST|M_MCAST)))
900 			m_freem(m);
901 		else
902 			icmp6_error(m, ICMP6_PARAM_PROB,
903 				    ICMP6_PARAMPROB_OPTION, off);
904 		return (-1);
905 	}
906 
907 	m_freem(m);		/* XXX: NOTREACHED */
908 	return (-1);
909 }
910 
911 /*
912  * Create the "control" list for this pcb.
913  *
914  * The routine will be called from upper layer handlers like udp_input().
915  * Thus the routine assumes that the caller (udp_input) have already
916  * called IP6_EXTHDR_CHECK() and all the extension headers are located in the
917  * very first mbuf on the mbuf chain.
918  * We may want to add some infinite loop prevention or sanity checks for safety.
919  * (This applies only when you are using KAME mbuf chain restriction, i.e.
920  * you are using IP6_EXTHDR_CHECK() not m_pulldown())
921  */
922 void
923 ip6_savecontrol(struct inpcb *in6p, struct mbuf *m, struct mbuf **mp)
924 {
925 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
926 
927 	if (in6p->inp_socket->so_options & SO_TIMESTAMP) {
928 		struct timeval tv;
929 
930 		m_microtime(m, &tv);
931 		*mp = sbcreatecontrol((caddr_t) &tv, sizeof(tv),
932 		    SCM_TIMESTAMP, SOL_SOCKET);
933 		if (*mp)
934 			mp = &(*mp)->m_next;
935 	}
936 
937 	/* RFC 2292 sec. 5 */
938 	if ((in6p->inp_flags & IN6P_PKTINFO) != 0) {
939 		struct in6_pktinfo pi6;
940 		memcpy(&pi6.ipi6_addr, &ip6->ip6_dst, sizeof(struct in6_addr));
941 		if (IN6_IS_SCOPE_EMBED(&pi6.ipi6_addr))
942 			pi6.ipi6_addr.s6_addr16[1] = 0;
943 		pi6.ipi6_ifindex = m ? m->m_pkthdr.ph_ifidx : 0;
944 		*mp = sbcreatecontrol((caddr_t) &pi6,
945 		    sizeof(struct in6_pktinfo),
946 		    IPV6_PKTINFO, IPPROTO_IPV6);
947 		if (*mp)
948 			mp = &(*mp)->m_next;
949 	}
950 
951 	if ((in6p->inp_flags & IN6P_HOPLIMIT) != 0) {
952 		int hlim = ip6->ip6_hlim & 0xff;
953 		*mp = sbcreatecontrol((caddr_t) &hlim, sizeof(int),
954 		    IPV6_HOPLIMIT, IPPROTO_IPV6);
955 		if (*mp)
956 			mp = &(*mp)->m_next;
957 	}
958 
959 	if ((in6p->inp_flags & IN6P_TCLASS) != 0) {
960 		u_int32_t flowinfo;
961 		int tclass;
962 
963 		flowinfo = (u_int32_t)ntohl(ip6->ip6_flow & IPV6_FLOWINFO_MASK);
964 		flowinfo >>= 20;
965 
966 		tclass = flowinfo & 0xff;
967 		*mp = sbcreatecontrol((caddr_t)&tclass, sizeof(tclass),
968 		    IPV6_TCLASS, IPPROTO_IPV6);
969 		if (*mp)
970 			mp = &(*mp)->m_next;
971 	}
972 
973 	/*
974 	 * IPV6_HOPOPTS socket option.  Recall that we required super-user
975 	 * privilege for the option (see ip6_ctloutput), but it might be too
976 	 * strict, since there might be some hop-by-hop options which can be
977 	 * returned to normal user.
978 	 * See also RFC 2292 section 6 (or RFC 3542 section 8).
979 	 */
980 	if ((in6p->inp_flags & IN6P_HOPOPTS) != 0) {
981 		/*
982 		 * Check if a hop-by-hop options header is contained in the
983 		 * received packet, and if so, store the options as ancillary
984 		 * data. Note that a hop-by-hop options header must be
985 		 * just after the IPv6 header, which is assured through the
986 		 * IPv6 input processing.
987 		 */
988 		struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
989 		if (ip6->ip6_nxt == IPPROTO_HOPOPTS) {
990 			struct ip6_hbh *hbh;
991 			int hbhlen = 0;
992 			struct mbuf *ext;
993 
994 			ext = ip6_pullexthdr(m, sizeof(struct ip6_hdr),
995 			    ip6->ip6_nxt);
996 			if (ext == NULL) {
997 				ip6stat_inc(ip6s_tooshort);
998 				return;
999 			}
1000 			hbh = mtod(ext, struct ip6_hbh *);
1001 			hbhlen = (hbh->ip6h_len + 1) << 3;
1002 			if (hbhlen != ext->m_len) {
1003 				m_freem(ext);
1004 				ip6stat_inc(ip6s_tooshort);
1005 				return;
1006 			}
1007 
1008 			/*
1009 			 * XXX: We copy the whole header even if a
1010 			 * jumbo payload option is included, the option which
1011 			 * is to be removed before returning according to
1012 			 * RFC2292.
1013 			 * Note: this constraint is removed in RFC3542.
1014 			 */
1015 			*mp = sbcreatecontrol((caddr_t)hbh, hbhlen,
1016 			    IPV6_HOPOPTS,
1017 			    IPPROTO_IPV6);
1018 			if (*mp)
1019 				mp = &(*mp)->m_next;
1020 			m_freem(ext);
1021 		}
1022 	}
1023 
1024 	/* IPV6_DSTOPTS and IPV6_RTHDR socket options */
1025 	if ((in6p->inp_flags & (IN6P_RTHDR | IN6P_DSTOPTS)) != 0) {
1026 		struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
1027 		int nxt = ip6->ip6_nxt, off = sizeof(struct ip6_hdr);
1028 
1029 		/*
1030 		 * Search for destination options headers or routing
1031 		 * header(s) through the header chain, and stores each
1032 		 * header as ancillary data.
1033 		 * Note that the order of the headers remains in
1034 		 * the chain of ancillary data.
1035 		 */
1036 		while (1) {	/* is explicit loop prevention necessary? */
1037 			struct ip6_ext *ip6e = NULL;
1038 			int elen;
1039 			struct mbuf *ext = NULL;
1040 
1041 			/*
1042 			 * if it is not an extension header, don't try to
1043 			 * pull it from the chain.
1044 			 */
1045 			switch (nxt) {
1046 			case IPPROTO_DSTOPTS:
1047 			case IPPROTO_ROUTING:
1048 			case IPPROTO_HOPOPTS:
1049 			case IPPROTO_AH: /* is it possible? */
1050 				break;
1051 			default:
1052 				goto loopend;
1053 			}
1054 
1055 			ext = ip6_pullexthdr(m, off, nxt);
1056 			if (ext == NULL) {
1057 				ip6stat_inc(ip6s_tooshort);
1058 				return;
1059 			}
1060 			ip6e = mtod(ext, struct ip6_ext *);
1061 			if (nxt == IPPROTO_AH)
1062 				elen = (ip6e->ip6e_len + 2) << 2;
1063 			else
1064 				elen = (ip6e->ip6e_len + 1) << 3;
1065 			if (elen != ext->m_len) {
1066 				m_freem(ext);
1067 				ip6stat_inc(ip6s_tooshort);
1068 				return;
1069 			}
1070 
1071 			switch (nxt) {
1072 			case IPPROTO_DSTOPTS:
1073 				if (!(in6p->inp_flags & IN6P_DSTOPTS))
1074 					break;
1075 
1076 				*mp = sbcreatecontrol((caddr_t)ip6e, elen,
1077 				    IPV6_DSTOPTS,
1078 				    IPPROTO_IPV6);
1079 				if (*mp)
1080 					mp = &(*mp)->m_next;
1081 				break;
1082 
1083 			case IPPROTO_ROUTING:
1084 				if (!(in6p->inp_flags & IN6P_RTHDR))
1085 					break;
1086 
1087 				*mp = sbcreatecontrol((caddr_t)ip6e, elen,
1088 				    IPV6_RTHDR,
1089 				    IPPROTO_IPV6);
1090 				if (*mp)
1091 					mp = &(*mp)->m_next;
1092 				break;
1093 
1094 			case IPPROTO_HOPOPTS:
1095 			case IPPROTO_AH: /* is it possible? */
1096 				break;
1097 
1098 			default:
1099 				/*
1100 				 * other cases have been filtered in the above.
1101 				 * none will visit this case.  here we supply
1102 				 * the code just in case (nxt overwritten or
1103 				 * other cases).
1104 				 */
1105 				m_freem(ext);
1106 				goto loopend;
1107 
1108 			}
1109 
1110 			/* proceed with the next header. */
1111 			off += elen;
1112 			nxt = ip6e->ip6e_nxt;
1113 			ip6e = NULL;
1114 			m_freem(ext);
1115 			ext = NULL;
1116 		}
1117 loopend:
1118 		;
1119 	}
1120 }
1121 
1122 /*
1123  * pull single extension header from mbuf chain.  returns single mbuf that
1124  * contains the result, or NULL on error.
1125  */
1126 struct mbuf *
1127 ip6_pullexthdr(struct mbuf *m, size_t off, int nxt)
1128 {
1129 	struct ip6_ext ip6e;
1130 	size_t elen;
1131 	struct mbuf *n;
1132 
1133 #ifdef DIAGNOSTIC
1134 	switch (nxt) {
1135 	case IPPROTO_DSTOPTS:
1136 	case IPPROTO_ROUTING:
1137 	case IPPROTO_HOPOPTS:
1138 	case IPPROTO_AH: /* is it possible? */
1139 		break;
1140 	default:
1141 		printf("ip6_pullexthdr: invalid nxt=%d\n", nxt);
1142 	}
1143 #endif
1144 
1145 	m_copydata(m, off, sizeof(ip6e), (caddr_t)&ip6e);
1146 	if (nxt == IPPROTO_AH)
1147 		elen = (ip6e.ip6e_len + 2) << 2;
1148 	else
1149 		elen = (ip6e.ip6e_len + 1) << 3;
1150 
1151 	MGET(n, M_DONTWAIT, MT_DATA);
1152 	if (n && elen >= MLEN) {
1153 		MCLGET(n, M_DONTWAIT);
1154 		if ((n->m_flags & M_EXT) == 0) {
1155 			m_free(n);
1156 			n = NULL;
1157 		}
1158 	}
1159 	if (!n)
1160 		return NULL;
1161 
1162 	n->m_len = 0;
1163 	if (elen >= m_trailingspace(n)) {
1164 		m_free(n);
1165 		return NULL;
1166 	}
1167 
1168 	m_copydata(m, off, elen, mtod(n, caddr_t));
1169 	n->m_len = elen;
1170 	return n;
1171 }
1172 
1173 /*
1174  * Get offset to the previous header followed by the header
1175  * currently processed.
1176  */
1177 int
1178 ip6_get_prevhdr(struct mbuf *m, int off)
1179 {
1180 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
1181 
1182 	if (off == sizeof(struct ip6_hdr)) {
1183 		return offsetof(struct ip6_hdr, ip6_nxt);
1184 	} else if (off < sizeof(struct ip6_hdr)) {
1185 		panic("%s: off < sizeof(struct ip6_hdr)", __func__);
1186 	} else {
1187 		int len, nlen, nxt;
1188 		struct ip6_ext ip6e;
1189 
1190 		nxt = ip6->ip6_nxt;
1191 		len = sizeof(struct ip6_hdr);
1192 		nlen = 0;
1193 		while (len < off) {
1194 			m_copydata(m, len, sizeof(ip6e), (caddr_t)&ip6e);
1195 
1196 			switch (nxt) {
1197 			case IPPROTO_FRAGMENT:
1198 				nlen = sizeof(struct ip6_frag);
1199 				break;
1200 			case IPPROTO_AH:
1201 				nlen = (ip6e.ip6e_len + 2) << 2;
1202 				break;
1203 			default:
1204 				nlen = (ip6e.ip6e_len + 1) << 3;
1205 				break;
1206 			}
1207 			len += nlen;
1208 			nxt = ip6e.ip6e_nxt;
1209 		}
1210 
1211 		return (len - nlen);
1212 	}
1213 }
1214 
1215 /*
1216  * get next header offset.  m will be retained.
1217  */
1218 int
1219 ip6_nexthdr(struct mbuf *m, int off, int proto, int *nxtp)
1220 {
1221 	struct ip6_hdr ip6;
1222 	struct ip6_ext ip6e;
1223 	struct ip6_frag fh;
1224 
1225 	/* just in case */
1226 	if (m == NULL)
1227 		panic("%s: m == NULL", __func__);
1228 	if ((m->m_flags & M_PKTHDR) == 0 || m->m_pkthdr.len < off)
1229 		return -1;
1230 
1231 	switch (proto) {
1232 	case IPPROTO_IPV6:
1233 		if (m->m_pkthdr.len < off + sizeof(ip6))
1234 			return -1;
1235 		m_copydata(m, off, sizeof(ip6), (caddr_t)&ip6);
1236 		if (nxtp)
1237 			*nxtp = ip6.ip6_nxt;
1238 		off += sizeof(ip6);
1239 		return off;
1240 
1241 	case IPPROTO_FRAGMENT:
1242 		/*
1243 		 * terminate parsing if it is not the first fragment,
1244 		 * it does not make sense to parse through it.
1245 		 */
1246 		if (m->m_pkthdr.len < off + sizeof(fh))
1247 			return -1;
1248 		m_copydata(m, off, sizeof(fh), (caddr_t)&fh);
1249 		if ((fh.ip6f_offlg & IP6F_OFF_MASK) != 0)
1250 			return -1;
1251 		if (nxtp)
1252 			*nxtp = fh.ip6f_nxt;
1253 		off += sizeof(struct ip6_frag);
1254 		return off;
1255 
1256 	case IPPROTO_AH:
1257 		if (m->m_pkthdr.len < off + sizeof(ip6e))
1258 			return -1;
1259 		m_copydata(m, off, sizeof(ip6e), (caddr_t)&ip6e);
1260 		if (nxtp)
1261 			*nxtp = ip6e.ip6e_nxt;
1262 		off += (ip6e.ip6e_len + 2) << 2;
1263 		if (m->m_pkthdr.len < off)
1264 			return -1;
1265 		return off;
1266 
1267 	case IPPROTO_HOPOPTS:
1268 	case IPPROTO_ROUTING:
1269 	case IPPROTO_DSTOPTS:
1270 		if (m->m_pkthdr.len < off + sizeof(ip6e))
1271 			return -1;
1272 		m_copydata(m, off, sizeof(ip6e), (caddr_t)&ip6e);
1273 		if (nxtp)
1274 			*nxtp = ip6e.ip6e_nxt;
1275 		off += (ip6e.ip6e_len + 1) << 3;
1276 		if (m->m_pkthdr.len < off)
1277 			return -1;
1278 		return off;
1279 
1280 	case IPPROTO_NONE:
1281 	case IPPROTO_ESP:
1282 	case IPPROTO_IPCOMP:
1283 		/* give up */
1284 		return -1;
1285 
1286 	default:
1287 		return -1;
1288 	}
1289 
1290 	return -1;
1291 }
1292 
1293 /*
1294  * get offset for the last header in the chain.  m will be kept untainted.
1295  */
1296 int
1297 ip6_lasthdr(struct mbuf *m, int off, int proto, int *nxtp)
1298 {
1299 	int newoff;
1300 	int nxt;
1301 
1302 	if (!nxtp) {
1303 		nxt = -1;
1304 		nxtp = &nxt;
1305 	}
1306 	while (1) {
1307 		newoff = ip6_nexthdr(m, off, proto, nxtp);
1308 		if (newoff < 0)
1309 			return off;
1310 		else if (newoff < off)
1311 			return -1;	/* invalid */
1312 		else if (newoff == off)
1313 			return newoff;
1314 
1315 		off = newoff;
1316 		proto = *nxtp;
1317 	}
1318 }
1319 
1320 /*
1321  * System control for IP6
1322  */
1323 
1324 const u_char inet6ctlerrmap[PRC_NCMDS] = {
1325 	0,		0,		0,		0,
1326 	0,		EMSGSIZE,	EHOSTDOWN,	EHOSTUNREACH,
1327 	EHOSTUNREACH,	EHOSTUNREACH,	ECONNREFUSED,	ECONNREFUSED,
1328 	EMSGSIZE,	EHOSTUNREACH,	0,		0,
1329 	0,		0,		0,		0,
1330 	ENOPROTOOPT
1331 };
1332 
1333 int *ipv6ctl_vars[IPV6CTL_MAXID] = IPV6CTL_VARS;
1334 
1335 int
1336 ip6_sysctl_ip6stat(void *oldp, size_t *oldlenp, void *newp)
1337 {
1338 	struct ip6stat *ip6stat;
1339 	int ret;
1340 
1341 	CTASSERT(sizeof(*ip6stat) == (ip6s_ncounters * sizeof(uint64_t)));
1342 
1343 	ip6stat = malloc(sizeof(*ip6stat), M_TEMP, M_WAITOK);
1344 	counters_read(ip6counters, (uint64_t *)ip6stat, ip6s_ncounters);
1345 	ret = sysctl_rdstruct(oldp, oldlenp, newp,
1346 	    ip6stat, sizeof(*ip6stat));
1347 	free(ip6stat, M_TEMP, sizeof(*ip6stat));
1348 
1349 	return (ret);
1350 }
1351 
1352 int
1353 ip6_sysctl_soiikey(void *oldp, size_t *oldlenp, void *newp, size_t newlen)
1354 {
1355 	uint8_t oldkey[IP6_SOIIKEY_LEN];
1356 	int error;
1357 
1358 	error = suser(curproc);
1359 	if (error != 0)
1360 		return (error);
1361 
1362 	memcpy(oldkey, ip6_soiikey, sizeof(oldkey));
1363 
1364 	error = sysctl_struct(oldp, oldlenp, newp, newlen, ip6_soiikey,
1365 	    sizeof(ip6_soiikey));
1366 
1367 	return (error);
1368 }
1369 
1370 int
1371 ip6_sysctl(int *name, u_int namelen, void *oldp, size_t *oldlenp,
1372     void *newp, size_t newlen)
1373 {
1374 #ifdef MROUTING
1375 	extern int ip6_mrtproto;
1376 	extern struct mrt6stat mrt6stat;
1377 #endif
1378 	int error;
1379 
1380 	/* Almost all sysctl names at this level are terminal. */
1381 	if (namelen != 1 && name[0] != IPV6CTL_IFQUEUE)
1382 		return (ENOTDIR);
1383 
1384 	switch (name[0]) {
1385 	case IPV6CTL_DAD_PENDING:
1386 		return sysctl_rdint(oldp, oldlenp, newp, ip6_dad_pending);
1387 	case IPV6CTL_STATS:
1388 		return (ip6_sysctl_ip6stat(oldp, oldlenp, newp));
1389 #ifdef MROUTING
1390 	case IPV6CTL_MRTSTATS:
1391 		if (newp != NULL)
1392 			return (EPERM);
1393 		NET_LOCK();
1394 		error = sysctl_struct(oldp, oldlenp, newp, newlen,
1395 		    &mrt6stat, sizeof(mrt6stat));
1396 		NET_UNLOCK();
1397 		return (error);
1398 	case IPV6CTL_MRTPROTO:
1399 		return sysctl_rdint(oldp, oldlenp, newp, ip6_mrtproto);
1400 	case IPV6CTL_MRTMIF:
1401 		if (newp)
1402 			return (EPERM);
1403 		NET_LOCK();
1404 		error = mrt6_sysctl_mif(oldp, oldlenp);
1405 		NET_UNLOCK();
1406 		return (error);
1407 	case IPV6CTL_MRTMFC:
1408 		if (newp)
1409 			return (EPERM);
1410 		NET_LOCK();
1411 		error = mrt6_sysctl_mfc(oldp, oldlenp);
1412 		NET_UNLOCK();
1413 		return (error);
1414 #else
1415 	case IPV6CTL_MRTSTATS:
1416 	case IPV6CTL_MRTPROTO:
1417 	case IPV6CTL_MRTMIF:
1418 	case IPV6CTL_MRTMFC:
1419 		return (EOPNOTSUPP);
1420 #endif
1421 	case IPV6CTL_MTUDISCTIMEOUT:
1422 		NET_LOCK();
1423 		error = sysctl_int(oldp, oldlenp, newp, newlen,
1424 		    &ip6_mtudisc_timeout);
1425 		if (icmp6_mtudisc_timeout_q != NULL)
1426 			rt_timer_queue_change(icmp6_mtudisc_timeout_q,
1427 			    ip6_mtudisc_timeout);
1428 		NET_UNLOCK();
1429 		return (error);
1430 	case IPV6CTL_IFQUEUE:
1431 		return (EOPNOTSUPP);
1432 	case IPV6CTL_SOIIKEY:
1433 		return (ip6_sysctl_soiikey(oldp, oldlenp, newp, newlen));
1434 	default:
1435 		if (name[0] < IPV6CTL_MAXID) {
1436 			NET_LOCK();
1437 			error = sysctl_int_arr(ipv6ctl_vars, name, namelen,
1438 			    oldp, oldlenp, newp, newlen);
1439 			NET_UNLOCK();
1440 			return (error);
1441 		}
1442 		return (EOPNOTSUPP);
1443 	}
1444 	/* NOTREACHED */
1445 }
1446 
1447 void
1448 ip6_send_dispatch(void *xmq)
1449 {
1450 	struct mbuf_queue *mq = xmq;
1451 	struct mbuf *m;
1452 	struct mbuf_list ml;
1453 
1454 	mq_delist(mq, &ml);
1455 	if (ml_empty(&ml))
1456 		return;
1457 
1458 	NET_RLOCK();
1459 	while ((m = ml_dequeue(&ml)) != NULL) {
1460 		/*
1461 		 * To avoid a "too big" situation at an intermediate router and
1462 		 * the path MTU discovery process, specify the IPV6_MINMTU
1463 		 * flag.  Note that only echo and node information replies are
1464 		 * affected, since the length of ICMP6 errors is limited to the
1465 		 * minimum MTU.
1466 		 */
1467 		ip6_output(m, NULL, NULL, IPV6_MINMTU, NULL, NULL);
1468 	}
1469 	NET_RUNLOCK();
1470 }
1471 
1472 void
1473 ip6_send(struct mbuf *m)
1474 {
1475 	mq_enqueue(&ip6send_mq, m);
1476 	task_add(net_tq(0), &ip6send_task);
1477 }
1478