xref: /netbsd-src/sys/netinet6/ip6_input.c (revision 001c68bd94f75ce9270b69227c4199fbf34ee396)
1 /*	$NetBSD: ip6_input.c,v 1.64 2003/06/30 08:00:59 itojun 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. All advertising materials mentioning features or use of this software
46  *    must display the following acknowledgement:
47  *	This product includes software developed by the University of
48  *	California, Berkeley and its contributors.
49  * 4. Neither the name of the University nor the names of its contributors
50  *    may be used to endorse or promote products derived from this software
51  *    without specific prior written permission.
52  *
53  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
54  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
57  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
58  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
59  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
61  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
62  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63  * SUCH DAMAGE.
64  *
65  *	@(#)ip_input.c	8.2 (Berkeley) 1/4/94
66  */
67 
68 #include <sys/cdefs.h>
69 __KERNEL_RCSID(0, "$NetBSD: ip6_input.c,v 1.64 2003/06/30 08:00:59 itojun Exp $");
70 
71 #include "opt_inet.h"
72 #include "opt_ipsec.h"
73 #include "opt_pfil_hooks.h"
74 
75 #include <sys/param.h>
76 #include <sys/systm.h>
77 #include <sys/malloc.h>
78 #include <sys/mbuf.h>
79 #include <sys/domain.h>
80 #include <sys/protosw.h>
81 #include <sys/socket.h>
82 #include <sys/socketvar.h>
83 #include <sys/errno.h>
84 #include <sys/time.h>
85 #include <sys/kernel.h>
86 #include <sys/syslog.h>
87 #include <sys/proc.h>
88 #include <sys/sysctl.h>
89 
90 #include <net/if.h>
91 #include <net/if_types.h>
92 #include <net/if_dl.h>
93 #include <net/route.h>
94 #include <net/netisr.h>
95 #ifdef PFIL_HOOKS
96 #include <net/pfil.h>
97 #endif
98 
99 #include <netinet/in.h>
100 #include <netinet/in_systm.h>
101 #ifdef INET
102 #include <netinet/ip.h>
103 #include <netinet/ip_icmp.h>
104 #endif /* INET */
105 #include <netinet/ip6.h>
106 #include <netinet6/in6_var.h>
107 #include <netinet6/ip6_var.h>
108 #include <netinet6/in6_pcb.h>
109 #include <netinet/icmp6.h>
110 #include <netinet6/in6_ifattach.h>
111 #include <netinet6/nd6.h>
112 
113 #ifdef IPSEC
114 #include <netinet6/ipsec.h>
115 #endif
116 
117 #include <netinet6/ip6protosw.h>
118 
119 /* we need it for NLOOP. */
120 #include "loop.h"
121 #include "faith.h"
122 #include "gif.h"
123 #include "bpfilter.h"
124 
125 #if NGIF > 0
126 #include <netinet6/in6_gif.h>
127 #endif
128 
129 #include <net/net_osdep.h>
130 
131 extern struct domain inet6domain;
132 
133 u_char ip6_protox[IPPROTO_MAX];
134 static int ip6qmaxlen = IFQ_MAXLEN;
135 struct in6_ifaddr *in6_ifaddr;
136 struct ifqueue ip6intrq;
137 
138 extern struct ifnet loif[NLOOP];
139 int ip6_forward_srcrt;			/* XXX */
140 int ip6_sourcecheck;			/* XXX */
141 int ip6_sourcecheck_interval;		/* XXX */
142 
143 #ifdef PFIL_HOOKS
144 struct pfil_head inet6_pfil_hook;
145 #endif
146 
147 struct ip6stat ip6stat;
148 
149 static void ip6_init2 __P((void *));
150 
151 static int ip6_hopopts_input __P((u_int32_t *, u_int32_t *, struct mbuf **, int *));
152 static struct mbuf *ip6_pullexthdr __P((struct mbuf *, size_t, int));
153 
154 /*
155  * IP6 initialization: fill in IP6 protocol switch table.
156  * All protocols not implemented in kernel go to raw IP6 protocol handler.
157  */
158 void
159 ip6_init()
160 {
161 	struct ip6protosw *pr;
162 	int i;
163 
164 	pr = (struct ip6protosw *)pffindproto(PF_INET6, IPPROTO_RAW, SOCK_RAW);
165 	if (pr == 0)
166 		panic("ip6_init");
167 	for (i = 0; i < IPPROTO_MAX; i++)
168 		ip6_protox[i] = pr - inet6sw;
169 	for (pr = (struct ip6protosw *)inet6domain.dom_protosw;
170 	    pr < (struct ip6protosw *)inet6domain.dom_protoswNPROTOSW; pr++)
171 		if (pr->pr_domain->dom_family == PF_INET6 &&
172 		    pr->pr_protocol && pr->pr_protocol != IPPROTO_RAW)
173 			ip6_protox[pr->pr_protocol] = pr - inet6sw;
174 	ip6intrq.ifq_maxlen = ip6qmaxlen;
175 	nd6_init();
176 	frag6_init();
177 	ip6_flow_seq = arc4random();
178 
179 	ip6_init2((void *)0);
180 
181 #ifdef PFIL_HOOKS
182 	/* Register our Packet Filter hook. */
183 	inet6_pfil_hook.ph_type = PFIL_TYPE_AF;
184 	inet6_pfil_hook.ph_af   = AF_INET6;
185 	i = pfil_head_register(&inet6_pfil_hook);
186 	if (i != 0)
187 		printf("ip6_init: WARNING: unable to register pfil hook, "
188 		    "error %d\n", i);
189 #endif /* PFIL_HOOKS */
190 }
191 
192 static void
193 ip6_init2(dummy)
194 	void *dummy;
195 {
196 
197 	/* nd6_timer_init */
198 	callout_init(&nd6_timer_ch);
199 	callout_reset(&nd6_timer_ch, hz, nd6_timer, NULL);
200 }
201 
202 /*
203  * IP6 input interrupt handling. Just pass the packet to ip6_input.
204  */
205 void
206 ip6intr()
207 {
208 	int s;
209 	struct mbuf *m;
210 
211 	for (;;) {
212 		s = splnet();
213 		IF_DEQUEUE(&ip6intrq, m);
214 		splx(s);
215 		if (m == 0)
216 			return;
217 		ip6_input(m);
218 	}
219 }
220 
221 extern struct	route_in6 ip6_forward_rt;
222 
223 void
224 ip6_input(m)
225 	struct mbuf *m;
226 {
227 	struct ip6_hdr *ip6;
228 	int off = sizeof(struct ip6_hdr), nest;
229 	u_int32_t plen;
230 	u_int32_t rtalert = ~0;
231 	int nxt, ours = 0;
232 	struct ifnet *deliverifp = NULL;
233 	int srcrt = 0;
234 
235 #ifdef IPSEC
236 	/*
237 	 * should the inner packet be considered authentic?
238 	 * see comment in ah4_input().
239 	 */
240 	m->m_flags &= ~M_AUTHIPHDR;
241 	m->m_flags &= ~M_AUTHIPDGM;
242 #endif
243 
244 	/*
245 	 * mbuf statistics
246 	 */
247 	if (m->m_flags & M_EXT) {
248 		if (m->m_next)
249 			ip6stat.ip6s_mext2m++;
250 		else
251 			ip6stat.ip6s_mext1++;
252 	} else {
253 #define M2MMAX	(sizeof(ip6stat.ip6s_m2m)/sizeof(ip6stat.ip6s_m2m[0]))
254 		if (m->m_next) {
255 			if (m->m_flags & M_LOOP) {
256 				ip6stat.ip6s_m2m[loif[0].if_index]++; /* XXX */
257 			} else if (m->m_pkthdr.rcvif->if_index < M2MMAX)
258 				ip6stat.ip6s_m2m[m->m_pkthdr.rcvif->if_index]++;
259 			else
260 				ip6stat.ip6s_m2m[0]++;
261 		} else
262 			ip6stat.ip6s_m1++;
263 #undef M2MMAX
264 	}
265 
266 	in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_receive);
267 	ip6stat.ip6s_total++;
268 
269 	/*
270 	 * If the IPv6 header is not aligned, slurp it up into a new
271 	 * mbuf with space for link headers, in the event we forward
272 	 * it.  OTherwise, if it is aligned, make sure the entire base
273 	 * IPv6 header is in the first mbuf of the chain.
274 	 */
275 	if (IP6_HDR_ALIGNED_P(mtod(m, caddr_t)) == 0) {
276 		struct ifnet *inifp = m->m_pkthdr.rcvif;
277 		if ((m = m_copyup(m, sizeof(struct ip6_hdr),
278 				  (max_linkhdr + 3) & ~3)) == NULL) {
279 			/* XXXJRT new stat, please */
280 			ip6stat.ip6s_toosmall++;
281 			in6_ifstat_inc(inifp, ifs6_in_hdrerr);
282 			return;
283 		}
284 	} else if (__predict_false(m->m_len < sizeof(struct ip6_hdr))) {
285 		struct ifnet *inifp = m->m_pkthdr.rcvif;
286 		if ((m = m_pullup(m, sizeof(struct ip6_hdr))) == NULL) {
287 			ip6stat.ip6s_toosmall++;
288 			in6_ifstat_inc(inifp, ifs6_in_hdrerr);
289 			return;
290 		}
291 	}
292 
293 	ip6 = mtod(m, struct ip6_hdr *);
294 
295 	if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION) {
296 		ip6stat.ip6s_badvers++;
297 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_hdrerr);
298 		goto bad;
299 	}
300 
301 #ifdef PFIL_HOOKS
302 	/*
303 	 * Run through list of hooks for input packets.  If there are any
304 	 * filters which require that additional packets in the flow are
305 	 * not fast-forwarded, they must clear the M_CANFASTFWD flag.
306 	 * Note that filters must _never_ set this flag, as another filter
307 	 * in the list may have previously cleared it.
308 	 */
309 	/*
310 	 * let ipfilter look at packet on the wire,
311 	 * not the decapsulated packet.
312 	 */
313 #ifdef IPSEC
314 	if (!ipsec_getnhist(m))
315 #else
316 	if (1)
317 #endif
318 	{
319 		struct in6_addr odst;
320 
321 		odst = ip6->ip6_dst;
322 		if (pfil_run_hooks(&inet6_pfil_hook, &m, m->m_pkthdr.rcvif,
323 				   PFIL_IN) != 0)
324 			return;
325 		if (m == NULL)
326 			return;
327 		ip6 = mtod(m, struct ip6_hdr *);
328 		srcrt = !IN6_ARE_ADDR_EQUAL(&odst, &ip6->ip6_dst);
329 	}
330 #endif /* PFIL_HOOKS */
331 
332 	ip6stat.ip6s_nxthist[ip6->ip6_nxt]++;
333 
334 #ifdef ALTQ
335 	if (altq_input != NULL && (*altq_input)(m, AF_INET6) == 0) {
336 		/* packet is dropped by traffic conditioner */
337 		return;
338 	}
339 #endif
340 
341 	/*
342 	 * Check against address spoofing/corruption.
343 	 */
344 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_src) ||
345 	    IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_dst)) {
346 		/*
347 		 * XXX: "badscope" is not very suitable for a multicast source.
348 		 */
349 		ip6stat.ip6s_badscope++;
350 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_addrerr);
351 		goto bad;
352 	}
353 	/*
354 	 * The following check is not documented in specs.  A malicious
355 	 * party may be able to use IPv4 mapped addr to confuse tcp/udp stack
356 	 * and bypass security checks (act as if it was from 127.0.0.1 by using
357 	 * IPv6 src ::ffff:127.0.0.1).  Be cautious.
358 	 *
359 	 * This check chokes if we are in an SIIT cloud.  As none of BSDs
360 	 * support IPv4-less kernel compilation, we cannot support SIIT
361 	 * environment at all.  So, it makes more sense for us to reject any
362 	 * malicious packets for non-SIIT environment, than try to do a
363 	 * partial support for SIIT environment.
364 	 */
365 	if (IN6_IS_ADDR_V4MAPPED(&ip6->ip6_src) ||
366 	    IN6_IS_ADDR_V4MAPPED(&ip6->ip6_dst)) {
367 		ip6stat.ip6s_badscope++;
368 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_addrerr);
369 		goto bad;
370 	}
371 #if 0
372 	/*
373 	 * Reject packets with IPv4 compatible addresses (auto tunnel).
374 	 *
375 	 * The code forbids auto tunnel relay case in RFC1933 (the check is
376 	 * stronger than RFC1933).  We may want to re-enable it if mech-xx
377 	 * is revised to forbid relaying case.
378 	 */
379 	if (IN6_IS_ADDR_V4COMPAT(&ip6->ip6_src) ||
380 	    IN6_IS_ADDR_V4COMPAT(&ip6->ip6_dst)) {
381 		ip6stat.ip6s_badscope++;
382 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_addrerr);
383 		goto bad;
384 	}
385 #endif
386 
387 	if (IN6_IS_ADDR_LOOPBACK(&ip6->ip6_src) ||
388 	    IN6_IS_ADDR_LOOPBACK(&ip6->ip6_dst)) {
389 		if (m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) {
390 			ours = 1;
391 			deliverifp = m->m_pkthdr.rcvif;
392 			goto hbhcheck;
393 		} else {
394 			ip6stat.ip6s_badscope++;
395 			in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_addrerr);
396 			goto bad;
397 		}
398 	}
399 
400 	/* drop packets if interface ID portion is already filled */
401 	if ((m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) == 0) {
402 		if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src) &&
403 		    ip6->ip6_src.s6_addr16[1]) {
404 			ip6stat.ip6s_badscope++;
405 			goto bad;
406 		}
407 		if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst) &&
408 		    ip6->ip6_dst.s6_addr16[1]) {
409 			ip6stat.ip6s_badscope++;
410 			goto bad;
411 		}
412 	}
413 
414 	if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src))
415 		ip6->ip6_src.s6_addr16[1]
416 			= htons(m->m_pkthdr.rcvif->if_index);
417 	if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst))
418 		ip6->ip6_dst.s6_addr16[1]
419 			= htons(m->m_pkthdr.rcvif->if_index);
420 
421 	/*
422 	 * We use rt->rt_ifp to determine if the address is ours or not.
423 	 * If rt_ifp is lo0, the address is ours.
424 	 * The problem here is, rt->rt_ifp for fe80::%lo0/64 is set to lo0,
425 	 * so any address under fe80::%lo0/64 will be mistakenly considered
426 	 * local.  The special case is supplied to handle the case properly
427 	 * by actually looking at interface addresses
428 	 * (using in6ifa_ifpwithaddr).
429 	 */
430 	if ((m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) != 0 &&
431 	    IN6_IS_ADDR_LINKLOCAL(&ip6->ip6_dst)) {
432 		if (!in6ifa_ifpwithaddr(m->m_pkthdr.rcvif, &ip6->ip6_dst)) {
433 			icmp6_error(m, ICMP6_DST_UNREACH,
434 			    ICMP6_DST_UNREACH_ADDR, 0);
435 			/* m is already freed */
436 			return;
437 		}
438 
439 		ours = 1;
440 		deliverifp = m->m_pkthdr.rcvif;
441 		goto hbhcheck;
442 	}
443 
444 	/*
445 	 * Multicast check
446 	 */
447 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
448 	  	struct	in6_multi *in6m = 0;
449 
450 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_mcast);
451 		/*
452 		 * See if we belong to the destination multicast group on the
453 		 * arrival interface.
454 		 */
455 		IN6_LOOKUP_MULTI(ip6->ip6_dst, m->m_pkthdr.rcvif, in6m);
456 		if (in6m)
457 			ours = 1;
458 		else if (!ip6_mrouter) {
459 			ip6stat.ip6s_notmember++;
460 			ip6stat.ip6s_cantforward++;
461 			in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_discard);
462 			goto bad;
463 		}
464 		deliverifp = m->m_pkthdr.rcvif;
465 		goto hbhcheck;
466 	}
467 
468 	/*
469 	 *  Unicast check
470 	 */
471 	if (ip6_forward_rt.ro_rt != NULL &&
472 	    (ip6_forward_rt.ro_rt->rt_flags & RTF_UP) != 0 &&
473 	    IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
474 			       &((struct sockaddr_in6 *)(&ip6_forward_rt.ro_dst))->sin6_addr))
475 		ip6stat.ip6s_forward_cachehit++;
476 	else {
477 		struct sockaddr_in6 *dst6;
478 
479 		if (ip6_forward_rt.ro_rt) {
480 			/* route is down or destination is different */
481 			ip6stat.ip6s_forward_cachemiss++;
482 			RTFREE(ip6_forward_rt.ro_rt);
483 			ip6_forward_rt.ro_rt = 0;
484 		}
485 
486 		bzero(&ip6_forward_rt.ro_dst, sizeof(struct sockaddr_in6));
487 		dst6 = (struct sockaddr_in6 *)&ip6_forward_rt.ro_dst;
488 		dst6->sin6_len = sizeof(struct sockaddr_in6);
489 		dst6->sin6_family = AF_INET6;
490 		dst6->sin6_addr = ip6->ip6_dst;
491 
492 		rtalloc((struct route *)&ip6_forward_rt);
493 	}
494 
495 #define rt6_key(r) ((struct sockaddr_in6 *)((r)->rt_nodes->rn_key))
496 
497 	/*
498 	 * Accept the packet if the forwarding interface to the destination
499 	 * according to the routing table is the loopback interface,
500 	 * unless the associated route has a gateway.
501 	 * Note that this approach causes to accept a packet if there is a
502 	 * route to the loopback interface for the destination of the packet.
503 	 * But we think it's even useful in some situations, e.g. when using
504 	 * a special daemon which wants to intercept the packet.
505 	 */
506 	if (ip6_forward_rt.ro_rt &&
507 	    (ip6_forward_rt.ro_rt->rt_flags &
508 	     (RTF_HOST|RTF_GATEWAY)) == RTF_HOST &&
509 	    !(ip6_forward_rt.ro_rt->rt_flags & RTF_CLONED) &&
510 #if 0
511 	    /*
512 	     * The check below is redundant since the comparison of
513 	     * the destination and the key of the rtentry has
514 	     * already done through looking up the routing table.
515 	     */
516 	    IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
517 	    &rt6_key(ip6_forward_rt.ro_rt)->sin6_addr) &&
518 #endif
519 	    ip6_forward_rt.ro_rt->rt_ifp->if_type == IFT_LOOP) {
520 		struct in6_ifaddr *ia6 =
521 			(struct in6_ifaddr *)ip6_forward_rt.ro_rt->rt_ifa;
522 		if (ia6->ia6_flags & IN6_IFF_ANYCAST)
523 			m->m_flags |= M_ANYCAST6;
524 		/*
525 		 * packets to a tentative, duplicated, or somehow invalid
526 		 * address must not be accepted.
527 		 */
528 		if (!(ia6->ia6_flags & IN6_IFF_NOTREADY)) {
529 			/* this address is ready */
530 			ours = 1;
531 			deliverifp = ia6->ia_ifp;	/* correct? */
532 			goto hbhcheck;
533 		} else {
534 			/* address is not ready, so discard the packet. */
535 			nd6log((LOG_INFO,
536 			    "ip6_input: packet to an unready address %s->%s\n",
537 			    ip6_sprintf(&ip6->ip6_src),
538 			    ip6_sprintf(&ip6->ip6_dst)));
539 
540 			goto bad;
541 		}
542 	}
543 
544 	/*
545 	 * FAITH (Firewall Aided Internet Translator)
546 	 */
547 #if defined(NFAITH) && 0 < NFAITH
548 	if (ip6_keepfaith) {
549 		if (ip6_forward_rt.ro_rt && ip6_forward_rt.ro_rt->rt_ifp
550 		 && ip6_forward_rt.ro_rt->rt_ifp->if_type == IFT_FAITH) {
551 			/* XXX do we need more sanity checks? */
552 			ours = 1;
553 			deliverifp = ip6_forward_rt.ro_rt->rt_ifp; /* faith */
554 			goto hbhcheck;
555 		}
556 	}
557 #endif
558 
559 #if 0
560     {
561 	/*
562 	 * Last resort: check in6_ifaddr for incoming interface.
563 	 * The code is here until I update the "goto ours hack" code above
564 	 * working right.
565 	 */
566 	struct ifaddr *ifa;
567 	for (ifa = m->m_pkthdr.rcvif->if_addrlist.tqh_first;
568 	     ifa;
569 	     ifa = ifa->ifa_list.tqe_next) {
570 		if (ifa->ifa_addr == NULL)
571 			continue;	/* just for safety */
572 		if (ifa->ifa_addr->sa_family != AF_INET6)
573 			continue;
574 		if (IN6_ARE_ADDR_EQUAL(IFA_IN6(ifa), &ip6->ip6_dst)) {
575 			ours = 1;
576 			deliverifp = ifa->ifa_ifp;
577 			goto hbhcheck;
578 		}
579 	}
580     }
581 #endif
582 
583 	/*
584 	 * Now there is no reason to process the packet if it's not our own
585 	 * and we're not a router.
586 	 */
587 	if (!ip6_forwarding) {
588 		ip6stat.ip6s_cantforward++;
589 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_discard);
590 		goto bad;
591 	}
592 
593   hbhcheck:
594 	/*
595 	 * Process Hop-by-Hop options header if it's contained.
596 	 * m may be modified in ip6_hopopts_input().
597 	 * If a JumboPayload option is included, plen will also be modified.
598 	 */
599 	plen = (u_int32_t)ntohs(ip6->ip6_plen);
600 	if (ip6->ip6_nxt == IPPROTO_HOPOPTS) {
601 		struct ip6_hbh *hbh;
602 
603 		if (ip6_hopopts_input(&plen, &rtalert, &m, &off)) {
604 #if 0	/*touches NULL pointer*/
605 			in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_discard);
606 #endif
607 			return;	/* m have already been freed */
608 		}
609 
610 		/* adjust pointer */
611 		ip6 = mtod(m, struct ip6_hdr *);
612 
613 		/*
614 		 * if the payload length field is 0 and the next header field
615 		 * indicates Hop-by-Hop Options header, then a Jumbo Payload
616 		 * option MUST be included.
617 		 */
618 		if (ip6->ip6_plen == 0 && plen == 0) {
619 			/*
620 			 * Note that if a valid jumbo payload option is
621 			 * contained, ip6_hoptops_input() must set a valid
622 			 * (non-zero) payload length to the variable plen.
623 			 */
624 			ip6stat.ip6s_badoptions++;
625 			in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_discard);
626 			in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_hdrerr);
627 			icmp6_error(m, ICMP6_PARAM_PROB,
628 				    ICMP6_PARAMPROB_HEADER,
629 				    (caddr_t)&ip6->ip6_plen - (caddr_t)ip6);
630 			return;
631 		}
632 		IP6_EXTHDR_GET(hbh, struct ip6_hbh *, m, sizeof(struct ip6_hdr),
633 			sizeof(struct ip6_hbh));
634 		if (hbh == NULL) {
635 			ip6stat.ip6s_tooshort++;
636 			return;
637 		}
638 		KASSERT(IP6_HDR_ALIGNED_P(hbh));
639 		nxt = hbh->ip6h_nxt;
640 
641 		/*
642 		 * accept the packet if a router alert option is included
643 		 * and we act as an IPv6 router.
644 		 */
645 		if (rtalert != ~0 && ip6_forwarding)
646 			ours = 1;
647 	} else
648 		nxt = ip6->ip6_nxt;
649 
650 	/*
651 	 * Check that the amount of data in the buffers
652 	 * is as at least much as the IPv6 header would have us expect.
653 	 * Trim mbufs if longer than we expect.
654 	 * Drop packet if shorter than we expect.
655 	 */
656 	if (m->m_pkthdr.len - sizeof(struct ip6_hdr) < plen) {
657 		ip6stat.ip6s_tooshort++;
658 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_truncated);
659 		goto bad;
660 	}
661 	if (m->m_pkthdr.len > sizeof(struct ip6_hdr) + plen) {
662 		if (m->m_len == m->m_pkthdr.len) {
663 			m->m_len = sizeof(struct ip6_hdr) + plen;
664 			m->m_pkthdr.len = sizeof(struct ip6_hdr) + plen;
665 		} else
666 			m_adj(m, sizeof(struct ip6_hdr) + plen - m->m_pkthdr.len);
667 	}
668 
669 	/*
670 	 * Forward if desirable.
671 	 */
672 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
673 		/*
674 		 * If we are acting as a multicast router, all
675 		 * incoming multicast packets are passed to the
676 		 * kernel-level multicast forwarding function.
677 		 * The packet is returned (relatively) intact; if
678 		 * ip6_mforward() returns a non-zero value, the packet
679 		 * must be discarded, else it may be accepted below.
680 		 */
681 		if (ip6_mrouter && ip6_mforward(ip6, m->m_pkthdr.rcvif, m)) {
682 			ip6stat.ip6s_cantforward++;
683 			m_freem(m);
684 			return;
685 		}
686 		if (!ours) {
687 			m_freem(m);
688 			return;
689 		}
690 	} else if (!ours) {
691 		ip6_forward(m, srcrt);
692 		return;
693 	}
694 
695 	ip6 = mtod(m, struct ip6_hdr *);
696 
697 	/*
698 	 * Malicious party may be able to use IPv4 mapped addr to confuse
699 	 * tcp/udp stack and bypass security checks (act as if it was from
700 	 * 127.0.0.1 by using IPv6 src ::ffff:127.0.0.1).  Be cautious.
701 	 *
702 	 * For SIIT end node behavior, you may want to disable the check.
703 	 * However, you will  become vulnerable to attacks using IPv4 mapped
704 	 * source.
705 	 */
706 	if (IN6_IS_ADDR_V4MAPPED(&ip6->ip6_src) ||
707 	    IN6_IS_ADDR_V4MAPPED(&ip6->ip6_dst)) {
708 		ip6stat.ip6s_badscope++;
709 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_addrerr);
710 		goto bad;
711 	}
712 
713 	/*
714 	 * Tell launch routine the next header
715 	 */
716 #ifdef IFA_STATS
717 	if (deliverifp != NULL) {
718 		struct in6_ifaddr *ia6;
719 		ia6 = in6_ifawithifp(deliverifp, &ip6->ip6_dst);
720 		if (ia6)
721 			ia6->ia_ifa.ifa_data.ifad_inbytes += m->m_pkthdr.len;
722 	}
723 #endif
724 	ip6stat.ip6s_delivered++;
725 	in6_ifstat_inc(deliverifp, ifs6_in_deliver);
726 	nest = 0;
727 
728 	while (nxt != IPPROTO_DONE) {
729 		if (ip6_hdrnestlimit && (++nest > ip6_hdrnestlimit)) {
730 			ip6stat.ip6s_toomanyhdr++;
731 			goto bad;
732 		}
733 
734 		/*
735 		 * protection against faulty packet - there should be
736 		 * more sanity checks in header chain processing.
737 		 */
738 		if (m->m_pkthdr.len < off) {
739 			ip6stat.ip6s_tooshort++;
740 			in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_truncated);
741 			goto bad;
742 		}
743 
744 #ifdef IPSEC
745 		/*
746 		 * enforce IPsec policy checking if we are seeing last header.
747 		 * note that we do not visit this with protocols with pcb layer
748 		 * code - like udp/tcp/raw ip.
749 		 */
750 		if ((inet6sw[ip6_protox[nxt]].pr_flags & PR_LASTHDR) != 0 &&
751 		    ipsec6_in_reject(m, NULL)) {
752 			ipsec6stat.in_polvio++;
753 			goto bad;
754 		}
755 #endif
756 
757 		nxt = (*inet6sw[ip6_protox[nxt]].pr_input)(&m, &off, nxt);
758 	}
759 	return;
760  bad:
761 	m_freem(m);
762 }
763 
764 /*
765  * Hop-by-Hop options header processing. If a valid jumbo payload option is
766  * included, the real payload length will be stored in plenp.
767  */
768 static int
769 ip6_hopopts_input(plenp, rtalertp, mp, offp)
770 	u_int32_t *plenp;
771 	u_int32_t *rtalertp;	/* XXX: should be stored more smart way */
772 	struct mbuf **mp;
773 	int *offp;
774 {
775 	struct mbuf *m = *mp;
776 	int off = *offp, hbhlen;
777 	struct ip6_hbh *hbh;
778 	u_int8_t *opt;
779 
780 	/* validation of the length of the header */
781 	IP6_EXTHDR_GET(hbh, struct ip6_hbh *, m,
782 		sizeof(struct ip6_hdr), sizeof(struct ip6_hbh));
783 	if (hbh == NULL) {
784 		ip6stat.ip6s_tooshort++;
785 		return -1;
786 	}
787 	hbhlen = (hbh->ip6h_len + 1) << 3;
788 	IP6_EXTHDR_GET(hbh, struct ip6_hbh *, m, sizeof(struct ip6_hdr),
789 		hbhlen);
790 	if (hbh == NULL) {
791 		ip6stat.ip6s_tooshort++;
792 		return -1;
793 	}
794 	KASSERT(IP6_HDR_ALIGNED_P(hbh));
795 	off += hbhlen;
796 	hbhlen -= sizeof(struct ip6_hbh);
797 	opt = (u_int8_t *)hbh + sizeof(struct ip6_hbh);
798 
799 	if (ip6_process_hopopts(m, (u_int8_t *)hbh + sizeof(struct ip6_hbh),
800 				hbhlen, rtalertp, plenp) < 0)
801 		return (-1);
802 
803 	*offp = off;
804 	*mp = m;
805 	return (0);
806 }
807 
808 /*
809  * Search header for all Hop-by-hop options and process each option.
810  * This function is separate from ip6_hopopts_input() in order to
811  * handle a case where the sending node itself process its hop-by-hop
812  * options header. In such a case, the function is called from ip6_output().
813  *
814  * The function assumes that hbh header is located right after the IPv6 header
815  * (RFC2460 p7), opthead is pointer into data content in m, and opthead to
816  * opthead + hbhlen is located in continuous memory region.
817  */
818 int
819 ip6_process_hopopts(m, opthead, hbhlen, rtalertp, plenp)
820 	struct mbuf *m;
821 	u_int8_t *opthead;
822 	int hbhlen;
823 	u_int32_t *rtalertp;
824 	u_int32_t *plenp;
825 {
826 	struct ip6_hdr *ip6;
827 	int optlen = 0;
828 	u_int8_t *opt = opthead;
829 	u_int16_t rtalert_val;
830 	u_int32_t jumboplen;
831 	const int erroff = sizeof(struct ip6_hdr) + sizeof(struct ip6_hbh);
832 
833 	for (; hbhlen > 0; hbhlen -= optlen, opt += optlen) {
834 		switch (*opt) {
835 		case IP6OPT_PAD1:
836 			optlen = 1;
837 			break;
838 		case IP6OPT_PADN:
839 			if (hbhlen < IP6OPT_MINLEN) {
840 				ip6stat.ip6s_toosmall++;
841 				goto bad;
842 			}
843 			optlen = *(opt + 1) + 2;
844 			break;
845 		case IP6OPT_RTALERT:
846 			/* XXX may need check for alignment */
847 			if (hbhlen < IP6OPT_RTALERT_LEN) {
848 				ip6stat.ip6s_toosmall++;
849 				goto bad;
850 			}
851 			if (*(opt + 1) != IP6OPT_RTALERT_LEN - 2) {
852 				/* XXX stat */
853 				icmp6_error(m, ICMP6_PARAM_PROB,
854 				    ICMP6_PARAMPROB_HEADER,
855 				    erroff + opt + 1 - opthead);
856 				return (-1);
857 			}
858 			optlen = IP6OPT_RTALERT_LEN;
859 			bcopy((caddr_t)(opt + 2), (caddr_t)&rtalert_val, 2);
860 			*rtalertp = ntohs(rtalert_val);
861 			break;
862 		case IP6OPT_JUMBO:
863 			/* XXX may need check for alignment */
864 			if (hbhlen < IP6OPT_JUMBO_LEN) {
865 				ip6stat.ip6s_toosmall++;
866 				goto bad;
867 			}
868 			if (*(opt + 1) != IP6OPT_JUMBO_LEN - 2) {
869 				/* XXX stat */
870 				icmp6_error(m, ICMP6_PARAM_PROB,
871 				    ICMP6_PARAMPROB_HEADER,
872 				    erroff + opt + 1 - opthead);
873 				return (-1);
874 			}
875 			optlen = IP6OPT_JUMBO_LEN;
876 
877 			/*
878 			 * IPv6 packets that have non 0 payload length
879 			 * must not contain a jumbo payload option.
880 			 */
881 			ip6 = mtod(m, struct ip6_hdr *);
882 			if (ip6->ip6_plen) {
883 				ip6stat.ip6s_badoptions++;
884 				icmp6_error(m, ICMP6_PARAM_PROB,
885 				    ICMP6_PARAMPROB_HEADER,
886 				    erroff + opt - opthead);
887 				return (-1);
888 			}
889 
890 			/*
891 			 * We may see jumbolen in unaligned location, so
892 			 * we'd need to perform bcopy().
893 			 */
894 			bcopy(opt + 2, &jumboplen, sizeof(jumboplen));
895 			jumboplen = (u_int32_t)htonl(jumboplen);
896 
897 #if 1
898 			/*
899 			 * if there are multiple jumbo payload options,
900 			 * *plenp will be non-zero and the packet will be
901 			 * rejected.
902 			 * the behavior may need some debate in ipngwg -
903 			 * multiple options does not make sense, however,
904 			 * there's no explicit mention in specification.
905 			 */
906 			if (*plenp != 0) {
907 				ip6stat.ip6s_badoptions++;
908 				icmp6_error(m, ICMP6_PARAM_PROB,
909 				    ICMP6_PARAMPROB_HEADER,
910 				    erroff + opt + 2 - opthead);
911 				return (-1);
912 			}
913 #endif
914 
915 			/*
916 			 * jumbo payload length must be larger than 65535.
917 			 */
918 			if (jumboplen <= IPV6_MAXPACKET) {
919 				ip6stat.ip6s_badoptions++;
920 				icmp6_error(m, ICMP6_PARAM_PROB,
921 				    ICMP6_PARAMPROB_HEADER,
922 				    erroff + opt + 2 - opthead);
923 				return (-1);
924 			}
925 			*plenp = jumboplen;
926 
927 			break;
928 		default:		/* unknown option */
929 			if (hbhlen < IP6OPT_MINLEN) {
930 				ip6stat.ip6s_toosmall++;
931 				goto bad;
932 			}
933 			optlen = ip6_unknown_opt(opt, m,
934 			    erroff + opt - opthead);
935 			if (optlen == -1)
936 				return (-1);
937 			optlen += 2;
938 			break;
939 		}
940 	}
941 
942 	return (0);
943 
944   bad:
945 	m_freem(m);
946 	return (-1);
947 }
948 
949 /*
950  * Unknown option processing.
951  * The third argument `off' is the offset from the IPv6 header to the option,
952  * which is necessary if the IPv6 header the and option header and IPv6 header
953  * is not continuous in order to return an ICMPv6 error.
954  */
955 int
956 ip6_unknown_opt(optp, m, off)
957 	u_int8_t *optp;
958 	struct mbuf *m;
959 	int off;
960 {
961 	struct ip6_hdr *ip6;
962 
963 	switch (IP6OPT_TYPE(*optp)) {
964 	case IP6OPT_TYPE_SKIP: /* ignore the option */
965 		return ((int)*(optp + 1));
966 	case IP6OPT_TYPE_DISCARD:	/* silently discard */
967 		m_freem(m);
968 		return (-1);
969 	case IP6OPT_TYPE_FORCEICMP: /* send ICMP even if multicasted */
970 		ip6stat.ip6s_badoptions++;
971 		icmp6_error(m, ICMP6_PARAM_PROB, ICMP6_PARAMPROB_OPTION, off);
972 		return (-1);
973 	case IP6OPT_TYPE_ICMP: /* send ICMP if not multicasted */
974 		ip6stat.ip6s_badoptions++;
975 		ip6 = mtod(m, struct ip6_hdr *);
976 		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
977 		    (m->m_flags & (M_BCAST|M_MCAST)))
978 			m_freem(m);
979 		else
980 			icmp6_error(m, ICMP6_PARAM_PROB,
981 				    ICMP6_PARAMPROB_OPTION, off);
982 		return (-1);
983 	}
984 
985 	m_freem(m);		/* XXX: NOTREACHED */
986 	return (-1);
987 }
988 
989 /*
990  * Create the "control" list for this pcb.
991  *
992  * The routine will be called from upper layer handlers like tcp6_input().
993  * Thus the routine assumes that the caller (tcp6_input) have already
994  * called IP6_EXTHDR_CHECK() and all the extension headers are located in the
995  * very first mbuf on the mbuf chain.
996  * We may want to add some infinite loop prevention or sanity checks for safety.
997  * (This applies only when you are using KAME mbuf chain restriction, i.e.
998  * you are using IP6_EXTHDR_CHECK() not m_pulldown())
999  */
1000 void
1001 ip6_savecontrol(in6p, mp, ip6, m)
1002 	struct in6pcb *in6p;
1003 	struct mbuf **mp;
1004 	struct ip6_hdr *ip6;
1005 	struct mbuf *m;
1006 {
1007 	struct proc *p = curproc;	/* XXX */
1008 	int privileged;
1009 
1010 	privileged = 0;
1011 	if (p && !suser(p->p_ucred, &p->p_acflag))
1012 		privileged++;
1013 
1014 #ifdef SO_TIMESTAMP
1015 	if (in6p->in6p_socket->so_options & SO_TIMESTAMP) {
1016 		struct timeval tv;
1017 
1018 		microtime(&tv);
1019 		*mp = sbcreatecontrol((caddr_t) &tv, sizeof(tv),
1020 		    SCM_TIMESTAMP, SOL_SOCKET);
1021 		if (*mp)
1022 			mp = &(*mp)->m_next;
1023 	}
1024 #endif
1025 	if (in6p->in6p_flags & IN6P_RECVDSTADDR) {
1026 		*mp = sbcreatecontrol((caddr_t) &ip6->ip6_dst,
1027 		    sizeof(struct in6_addr), IPV6_RECVDSTADDR, IPPROTO_IPV6);
1028 		if (*mp)
1029 			mp = &(*mp)->m_next;
1030 	}
1031 
1032 #ifdef noyet
1033 	/* options were tossed above */
1034 	if (in6p->in6p_flags & IN6P_RECVOPTS)
1035 		/* broken */
1036 	/* ip6_srcroute doesn't do what we want here, need to fix */
1037 	if (in6p->in6p_flags & IPV6P_RECVRETOPTS)
1038 		/* broken */
1039 #endif
1040 
1041 	/* RFC 2292 sec. 5 */
1042 	if ((in6p->in6p_flags & IN6P_PKTINFO) != 0) {
1043 		struct in6_pktinfo pi6;
1044 		bcopy(&ip6->ip6_dst, &pi6.ipi6_addr, sizeof(struct in6_addr));
1045 		if (IN6_IS_SCOPE_LINKLOCAL(&pi6.ipi6_addr))
1046 			pi6.ipi6_addr.s6_addr16[1] = 0;
1047 		pi6.ipi6_ifindex = (m && m->m_pkthdr.rcvif)
1048 					? m->m_pkthdr.rcvif->if_index
1049 					: 0;
1050 		*mp = sbcreatecontrol((caddr_t) &pi6,
1051 		    sizeof(struct in6_pktinfo), IPV6_PKTINFO, IPPROTO_IPV6);
1052 		if (*mp)
1053 			mp = &(*mp)->m_next;
1054 	}
1055 	if (in6p->in6p_flags & IN6P_HOPLIMIT) {
1056 		int hlim = ip6->ip6_hlim & 0xff;
1057 		*mp = sbcreatecontrol((caddr_t) &hlim, sizeof(int),
1058 		    IPV6_HOPLIMIT, IPPROTO_IPV6);
1059 		if (*mp)
1060 			mp = &(*mp)->m_next;
1061 	}
1062 	/* IN6P_NEXTHOP - for outgoing packet only */
1063 
1064 	/*
1065 	 * IPV6_HOPOPTS socket option. We require super-user privilege
1066 	 * for the option, but it might be too strict, since there might
1067 	 * be some hop-by-hop options which can be returned to normal user.
1068 	 * See RFC 2292 section 6.
1069 	 */
1070 	if ((in6p->in6p_flags & IN6P_HOPOPTS) != 0 && privileged) {
1071 		/*
1072 		 * Check if a hop-by-hop options header is contatined in the
1073 		 * received packet, and if so, store the options as ancillary
1074 		 * data. Note that a hop-by-hop options header must be
1075 		 * just after the IPv6 header, which fact is assured through
1076 		 * the IPv6 input processing.
1077 		 */
1078 		struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
1079 		if (ip6->ip6_nxt == IPPROTO_HOPOPTS) {
1080 			struct ip6_hbh *hbh;
1081 			int hbhlen;
1082 			struct mbuf *ext;
1083 
1084 			ext = ip6_pullexthdr(m, sizeof(struct ip6_hdr),
1085 			    ip6->ip6_nxt);
1086 			if (ext == NULL) {
1087 				ip6stat.ip6s_tooshort++;
1088 				return;
1089 			}
1090 			hbh = mtod(ext, struct ip6_hbh *);
1091 			hbhlen = (hbh->ip6h_len + 1) << 3;
1092 			if (hbhlen != ext->m_len) {
1093 				m_freem(ext);
1094 				ip6stat.ip6s_tooshort++;
1095 				return;
1096 			}
1097 
1098 			/*
1099 			 * XXX: We copy whole the header even if a jumbo
1100 			 * payload option is included, which option is to
1101 			 * be removed before returning in the RFC 2292.
1102 			 * But it's too painful operation...
1103 			 */
1104 			*mp = sbcreatecontrol((caddr_t)hbh, hbhlen,
1105 			    IPV6_HOPOPTS, IPPROTO_IPV6);
1106 			if (*mp)
1107 				mp = &(*mp)->m_next;
1108 			m_freem(ext);
1109 		}
1110 	}
1111 
1112 	/* IPV6_DSTOPTS and IPV6_RTHDR socket options */
1113 	if (in6p->in6p_flags & (IN6P_DSTOPTS | IN6P_RTHDR)) {
1114 		struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
1115 		int nxt = ip6->ip6_nxt, off = sizeof(struct ip6_hdr);
1116 
1117 		/*
1118 		 * Search for destination options headers or routing
1119 		 * header(s) through the header chain, and stores each
1120 		 * header as ancillary data.
1121 		 * Note that the order of the headers remains in
1122 		 * the chain of ancillary data.
1123 		 */
1124 		while (1) {	/* is explicit loop prevention necessary? */
1125 			struct ip6_ext *ip6e = NULL;
1126 			int elen;
1127 			struct mbuf *ext = NULL;
1128 
1129 			/*
1130 			 * if it is not an extension header, don't try to
1131 			 * pull it from the chain.
1132 			 */
1133 			switch (nxt) {
1134 			case IPPROTO_DSTOPTS:
1135 			case IPPROTO_ROUTING:
1136 			case IPPROTO_HOPOPTS:
1137 			case IPPROTO_AH: /* is it possible? */
1138 				break;
1139 			default:
1140 				goto loopend;
1141 			}
1142 
1143 			ext = ip6_pullexthdr(m, off, nxt);
1144 			if (ext == NULL) {
1145 				ip6stat.ip6s_tooshort++;
1146 				return;
1147 			}
1148 			ip6e = mtod(ext, struct ip6_ext *);
1149 			if (nxt == IPPROTO_AH)
1150 				elen = (ip6e->ip6e_len + 2) << 2;
1151 			else
1152 				elen = (ip6e->ip6e_len + 1) << 3;
1153 			if (elen != ext->m_len) {
1154 				m_freem(ext);
1155 				ip6stat.ip6s_tooshort++;
1156 				return;
1157 			}
1158 			KASSERT(IP6_HDR_ALIGNED_P(ip6e));
1159 
1160 			switch (nxt) {
1161 			case IPPROTO_DSTOPTS:
1162 				if (!in6p->in6p_flags & IN6P_DSTOPTS)
1163 					break;
1164 
1165 				/*
1166 				 * We also require super-user privilege for
1167 				 * the option.
1168 				 * See the comments on IN6_HOPOPTS.
1169 				 */
1170 				if (!privileged)
1171 					break;
1172 
1173 				*mp = sbcreatecontrol((caddr_t)ip6e, elen,
1174 				    IPV6_DSTOPTS, IPPROTO_IPV6);
1175 				if (*mp)
1176 					mp = &(*mp)->m_next;
1177 				break;
1178 
1179 			case IPPROTO_ROUTING:
1180 				if (!in6p->in6p_flags & IN6P_RTHDR)
1181 					break;
1182 
1183 				*mp = sbcreatecontrol((caddr_t)ip6e, elen,
1184 				    IPV6_RTHDR, IPPROTO_IPV6);
1185 				if (*mp)
1186 					mp = &(*mp)->m_next;
1187 				break;
1188 
1189 			case IPPROTO_HOPOPTS:
1190 			case IPPROTO_AH: /* is it possible? */
1191 				break;
1192 
1193 			default:
1194 				/*
1195 			 	 * other cases have been filtered in the above.
1196 				 * none will visit this case.  here we supply
1197 				 * the code just in case (nxt overwritten or
1198 				 * other cases).
1199 				 */
1200 				m_freem(ext);
1201 				goto loopend;
1202 
1203 			}
1204 
1205 			/* proceed with the next header. */
1206 			off += elen;
1207 			nxt = ip6e->ip6e_nxt;
1208 			ip6e = NULL;
1209 			m_freem(ext);
1210 			ext = NULL;
1211 		}
1212 	  loopend:
1213 	  	;
1214 	}
1215 }
1216 
1217 /*
1218  * pull single extension header from mbuf chain.  returns single mbuf that
1219  * contains the result, or NULL on error.
1220  */
1221 static struct mbuf *
1222 ip6_pullexthdr(m, off, nxt)
1223 	struct mbuf *m;
1224 	size_t off;
1225 	int nxt;
1226 {
1227 	struct ip6_ext ip6e;
1228 	size_t elen;
1229 	struct mbuf *n;
1230 
1231 #ifdef DIAGNOSTIC
1232 	switch (nxt) {
1233 	case IPPROTO_DSTOPTS:
1234 	case IPPROTO_ROUTING:
1235 	case IPPROTO_HOPOPTS:
1236 	case IPPROTO_AH: /* is it possible? */
1237 		break;
1238 	default:
1239 		printf("ip6_pullexthdr: invalid nxt=%d\n", nxt);
1240 	}
1241 #endif
1242 
1243 	m_copydata(m, off, sizeof(ip6e), (caddr_t)&ip6e);
1244 	if (nxt == IPPROTO_AH)
1245 		elen = (ip6e.ip6e_len + 2) << 2;
1246 	else
1247 		elen = (ip6e.ip6e_len + 1) << 3;
1248 
1249 	MGET(n, M_DONTWAIT, MT_DATA);
1250 	if (n && elen >= MLEN) {
1251 		MCLGET(n, M_DONTWAIT);
1252 		if ((n->m_flags & M_EXT) == 0) {
1253 			m_free(n);
1254 			n = NULL;
1255 		}
1256 	}
1257 	if (!n)
1258 		return NULL;
1259 
1260 	n->m_len = 0;
1261 	if (elen >= M_TRAILINGSPACE(n)) {
1262 		m_free(n);
1263 		return NULL;
1264 	}
1265 
1266 	m_copydata(m, off, elen, mtod(n, caddr_t));
1267 	n->m_len = elen;
1268 	return n;
1269 }
1270 
1271 /*
1272  * Get pointer to the previous header followed by the header
1273  * currently processed.
1274  * XXX: This function supposes that
1275  *	M includes all headers,
1276  *	the next header field and the header length field of each header
1277  *	are valid, and
1278  *	the sum of each header length equals to OFF.
1279  * Because of these assumptions, this function must be called very
1280  * carefully. Moreover, it will not be used in the near future when
1281  * we develop `neater' mechanism to process extension headers.
1282  */
1283 u_int8_t *
1284 ip6_get_prevhdr(m, off)
1285 	struct mbuf *m;
1286 	int off;
1287 {
1288 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
1289 
1290 	if (off == sizeof(struct ip6_hdr))
1291 		return (&ip6->ip6_nxt);
1292 	else {
1293 		int len, nxt;
1294 		struct ip6_ext *ip6e = NULL;
1295 
1296 		nxt = ip6->ip6_nxt;
1297 		len = sizeof(struct ip6_hdr);
1298 		while (len < off) {
1299 			ip6e = (struct ip6_ext *)(mtod(m, caddr_t) + len);
1300 
1301 			switch (nxt) {
1302 			case IPPROTO_FRAGMENT:
1303 				len += sizeof(struct ip6_frag);
1304 				break;
1305 			case IPPROTO_AH:
1306 				len += (ip6e->ip6e_len + 2) << 2;
1307 				break;
1308 			default:
1309 				len += (ip6e->ip6e_len + 1) << 3;
1310 				break;
1311 			}
1312 			nxt = ip6e->ip6e_nxt;
1313 		}
1314 		if (ip6e)
1315 			return (&ip6e->ip6e_nxt);
1316 		else
1317 			return NULL;
1318 	}
1319 }
1320 
1321 /*
1322  * get next header offset.  m will be retained.
1323  */
1324 int
1325 ip6_nexthdr(m, off, proto, nxtp)
1326 	struct mbuf *m;
1327 	int off;
1328 	int proto;
1329 	int *nxtp;
1330 {
1331 	struct ip6_hdr ip6;
1332 	struct ip6_ext ip6e;
1333 	struct ip6_frag fh;
1334 
1335 	/* just in case */
1336 	if (m == NULL)
1337 		panic("ip6_nexthdr: m == NULL");
1338 	if ((m->m_flags & M_PKTHDR) == 0 || m->m_pkthdr.len < off)
1339 		return -1;
1340 
1341 	switch (proto) {
1342 	case IPPROTO_IPV6:
1343 		if (m->m_pkthdr.len < off + sizeof(ip6))
1344 			return -1;
1345 		m_copydata(m, off, sizeof(ip6), (caddr_t)&ip6);
1346 		if (nxtp)
1347 			*nxtp = ip6.ip6_nxt;
1348 		off += sizeof(ip6);
1349 		return off;
1350 
1351 	case IPPROTO_FRAGMENT:
1352 		/*
1353 		 * terminate parsing if it is not the first fragment,
1354 		 * it does not make sense to parse through it.
1355 		 */
1356 		if (m->m_pkthdr.len < off + sizeof(fh))
1357 			return -1;
1358 		m_copydata(m, off, sizeof(fh), (caddr_t)&fh);
1359 		if ((ntohs(fh.ip6f_offlg) & IP6F_OFF_MASK) != 0)
1360 			return -1;
1361 		if (nxtp)
1362 			*nxtp = fh.ip6f_nxt;
1363 		off += sizeof(struct ip6_frag);
1364 		return off;
1365 
1366 	case IPPROTO_AH:
1367 		if (m->m_pkthdr.len < off + sizeof(ip6e))
1368 			return -1;
1369 		m_copydata(m, off, sizeof(ip6e), (caddr_t)&ip6e);
1370 		if (nxtp)
1371 			*nxtp = ip6e.ip6e_nxt;
1372 		off += (ip6e.ip6e_len + 2) << 2;
1373 		if (m->m_pkthdr.len < off)
1374 			return -1;
1375 		return off;
1376 
1377 	case IPPROTO_HOPOPTS:
1378 	case IPPROTO_ROUTING:
1379 	case IPPROTO_DSTOPTS:
1380 		if (m->m_pkthdr.len < off + sizeof(ip6e))
1381 			return -1;
1382 		m_copydata(m, off, sizeof(ip6e), (caddr_t)&ip6e);
1383 		if (nxtp)
1384 			*nxtp = ip6e.ip6e_nxt;
1385 		off += (ip6e.ip6e_len + 1) << 3;
1386 		if (m->m_pkthdr.len < off)
1387 			return -1;
1388 		return off;
1389 
1390 	case IPPROTO_NONE:
1391 	case IPPROTO_ESP:
1392 	case IPPROTO_IPCOMP:
1393 		/* give up */
1394 		return -1;
1395 
1396 	default:
1397 		return -1;
1398 	}
1399 }
1400 
1401 /*
1402  * get offset for the last header in the chain.  m will be kept untainted.
1403  */
1404 int
1405 ip6_lasthdr(m, off, proto, nxtp)
1406 	struct mbuf *m;
1407 	int off;
1408 	int proto;
1409 	int *nxtp;
1410 {
1411 	int newoff;
1412 	int nxt;
1413 
1414 	if (!nxtp) {
1415 		nxt = -1;
1416 		nxtp = &nxt;
1417 	}
1418 	while (1) {
1419 		newoff = ip6_nexthdr(m, off, proto, nxtp);
1420 		if (newoff < 0)
1421 			return off;
1422 		else if (newoff < off)
1423 			return -1;	/* invalid */
1424 		else if (newoff == off)
1425 			return newoff;
1426 
1427 		off = newoff;
1428 		proto = *nxtp;
1429 	}
1430 }
1431 
1432 /*
1433  * System control for IP6
1434  */
1435 
1436 u_char	inet6ctlerrmap[PRC_NCMDS] = {
1437 	0,		0,		0,		0,
1438 	0,		EMSGSIZE,	EHOSTDOWN,	EHOSTUNREACH,
1439 	EHOSTUNREACH,	EHOSTUNREACH,	ECONNREFUSED,	ECONNREFUSED,
1440 	EMSGSIZE,	EHOSTUNREACH,	0,		0,
1441 	0,		0,		0,		0,
1442 	ENOPROTOOPT
1443 };
1444 
1445 int
1446 ip6_sysctl(name, namelen, oldp, oldlenp, newp, newlen)
1447 	int *name;
1448 	u_int namelen;
1449 	void *oldp;
1450 	size_t *oldlenp;
1451 	void *newp;
1452 	size_t newlen;
1453 {
1454 	int old, error;
1455 
1456 	/* All sysctl names at this level are terminal. */
1457 	if (namelen != 1)
1458 		return ENOTDIR;
1459 
1460 	switch (name[0]) {
1461 
1462 	case IPV6CTL_FORWARDING:
1463 		return sysctl_int(oldp, oldlenp, newp, newlen,
1464 				  &ip6_forwarding);
1465 	case IPV6CTL_SENDREDIRECTS:
1466 		return sysctl_int(oldp, oldlenp, newp, newlen,
1467 				&ip6_sendredirects);
1468 	case IPV6CTL_DEFHLIM:
1469 		return sysctl_int(oldp, oldlenp, newp, newlen, &ip6_defhlim);
1470 	case IPV6CTL_MAXFRAGPACKETS:
1471 		return sysctl_int(oldp, oldlenp, newp, newlen,
1472 				&ip6_maxfragpackets);
1473 	case IPV6CTL_ACCEPT_RTADV:
1474 		return sysctl_int(oldp, oldlenp, newp, newlen,
1475 				&ip6_accept_rtadv);
1476 	case IPV6CTL_KEEPFAITH:
1477 		return sysctl_int(oldp, oldlenp, newp, newlen, &ip6_keepfaith);
1478 	case IPV6CTL_LOG_INTERVAL:
1479 		return sysctl_int(oldp, oldlenp, newp, newlen,
1480 				&ip6_log_interval);
1481 	case IPV6CTL_HDRNESTLIMIT:
1482 		return sysctl_int(oldp, oldlenp, newp, newlen,
1483 				&ip6_hdrnestlimit);
1484 	case IPV6CTL_DAD_COUNT:
1485 		return sysctl_int(oldp, oldlenp, newp, newlen, &ip6_dad_count);
1486 	case IPV6CTL_AUTO_FLOWLABEL:
1487 		return sysctl_int(oldp, oldlenp, newp, newlen,
1488 				&ip6_auto_flowlabel);
1489 	case IPV6CTL_DEFMCASTHLIM:
1490 		return sysctl_int(oldp, oldlenp, newp, newlen,
1491 				&ip6_defmcasthlim);
1492 #if NGIF > 0
1493 	case IPV6CTL_GIF_HLIM:
1494 		return sysctl_int(oldp, oldlenp, newp, newlen,
1495 				&ip6_gif_hlim);
1496 #endif
1497 	case IPV6CTL_KAME_VERSION:
1498 		return sysctl_rdstring(oldp, oldlenp, newp, __KAME_VERSION);
1499 	case IPV6CTL_USE_DEPRECATED:
1500 		return sysctl_int(oldp, oldlenp, newp, newlen,
1501 				&ip6_use_deprecated);
1502 	case IPV6CTL_RR_PRUNE:
1503 		return sysctl_int(oldp, oldlenp, newp, newlen, &ip6_rr_prune);
1504 	case IPV6CTL_V6ONLY:
1505 #ifdef INET6_BINDV6ONLY
1506 		return sysctl_rdint(oldp, oldlenp, newp, ip6_v6only);
1507 #else
1508 		return sysctl_int(oldp, oldlenp, newp, newlen, &ip6_v6only);
1509 #endif
1510 	case IPV6CTL_ANONPORTMIN:
1511 		old = ip6_anonportmin;
1512 		error = sysctl_int(oldp, oldlenp, newp, newlen,
1513 		    &ip6_anonportmin);
1514 		if (ip6_anonportmin >= ip6_anonportmax || ip6_anonportmin < 0 ||
1515 		    ip6_anonportmin > 65535
1516 #ifndef IPNOPRIVPORTS
1517 		    || ip6_anonportmin < IPV6PORT_RESERVED
1518 #endif
1519 		    ) {
1520 			ip6_anonportmin = old;
1521 			return (EINVAL);
1522 		}
1523 		return (error);
1524 	case IPV6CTL_ANONPORTMAX:
1525 		old = ip6_anonportmax;
1526 		error = sysctl_int(oldp, oldlenp, newp, newlen,
1527 		    &ip6_anonportmax);
1528 		if (ip6_anonportmin >= ip6_anonportmax || ip6_anonportmax < 0 ||
1529 		    ip6_anonportmax > 65535
1530 #ifndef IPNOPRIVPORTS
1531 		    || ip6_anonportmax < IPV6PORT_RESERVED
1532 #endif
1533 		    ) {
1534 			ip6_anonportmax = old;
1535 			return (EINVAL);
1536 		}
1537 		return (error);
1538 #ifndef IPNOPRIVPORTS
1539 	case IPV6CTL_LOWPORTMIN:
1540 		old = ip6_lowportmin;
1541 		error = sysctl_int(oldp, oldlenp, newp, newlen,
1542 		    &ip6_lowportmin);
1543 		if (ip6_lowportmin >= ip6_lowportmax ||
1544 		    ip6_lowportmin > IPV6PORT_RESERVEDMAX ||
1545 		    ip6_lowportmin < IPV6PORT_RESERVEDMIN) {
1546 			ip6_lowportmin = old;
1547 			return (EINVAL);
1548 		}
1549 		return (error);
1550 	case IPV6CTL_LOWPORTMAX:
1551 		old = ip6_lowportmax;
1552 		error = sysctl_int(oldp, oldlenp, newp, newlen,
1553 		    &ip6_lowportmax);
1554 		if (ip6_lowportmin >= ip6_lowportmax ||
1555 		    ip6_lowportmax > IPV6PORT_RESERVEDMAX ||
1556 		    ip6_lowportmax < IPV6PORT_RESERVEDMIN) {
1557 			ip6_lowportmax = old;
1558 			return (EINVAL);
1559 		}
1560 		return (error);
1561 #endif
1562 	case IPV6CTL_MAXFRAGS:
1563 		return sysctl_int(oldp, oldlenp, newp, newlen, &ip6_maxfrags);
1564 	default:
1565 		return EOPNOTSUPP;
1566 	}
1567 	/* NOTREACHED */
1568 }
1569