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