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