xref: /freebsd/sys/netinet6/ip6_input.c (revision 6e660824a82f590542932de52f128db584029893)
1 /*-
2  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the project nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *	$KAME: ip6_input.c,v 1.259 2002/01/21 04:58:09 jinmei Exp $
30  */
31 
32 /*-
33  * Copyright (c) 1982, 1986, 1988, 1993
34  *	The Regents of the University of California.  All rights reserved.
35  *
36  * Redistribution and use in source and binary forms, with or without
37  * modification, are permitted provided that the following conditions
38  * are met:
39  * 1. Redistributions of source code must retain the above copyright
40  *    notice, this list of conditions and the following disclaimer.
41  * 2. Redistributions in binary form must reproduce the above copyright
42  *    notice, this list of conditions and the following disclaimer in the
43  *    documentation and/or other materials provided with the distribution.
44  * 4. Neither the name of the University nor the names of its contributors
45  *    may be used to endorse or promote products derived from this software
46  *    without specific prior written permission.
47  *
48  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58  * SUCH DAMAGE.
59  *
60  *	@(#)ip_input.c	8.2 (Berkeley) 1/4/94
61  */
62 
63 #include <sys/cdefs.h>
64 __FBSDID("$FreeBSD$");
65 
66 #include "opt_inet.h"
67 #include "opt_inet6.h"
68 #include "opt_ipfw.h"
69 #include "opt_ipsec.h"
70 #include "opt_route.h"
71 
72 #include <sys/param.h>
73 #include <sys/systm.h>
74 #include <sys/malloc.h>
75 #include <sys/mbuf.h>
76 #include <sys/proc.h>
77 #include <sys/domain.h>
78 #include <sys/protosw.h>
79 #include <sys/socket.h>
80 #include <sys/socketvar.h>
81 #include <sys/errno.h>
82 #include <sys/time.h>
83 #include <sys/kernel.h>
84 #include <sys/syslog.h>
85 
86 #include <net/if.h>
87 #include <net/if_types.h>
88 #include <net/if_dl.h>
89 #include <net/route.h>
90 #include <net/netisr.h>
91 #include <net/pfil.h>
92 #include <net/vnet.h>
93 
94 #include <netinet/in.h>
95 #include <netinet/ip_var.h>
96 #include <netinet/in_systm.h>
97 #include <net/if_llatbl.h>
98 #ifdef INET
99 #include <netinet/ip.h>
100 #include <netinet/ip_icmp.h>
101 #endif /* INET */
102 #include <netinet/ip6.h>
103 #include <netinet6/in6_var.h>
104 #include <netinet6/ip6_var.h>
105 #include <netinet/in_pcb.h>
106 #include <netinet/icmp6.h>
107 #include <netinet6/scope6_var.h>
108 #include <netinet6/in6_ifattach.h>
109 #include <netinet6/nd6.h>
110 
111 #ifdef IPSEC
112 #include <netipsec/ipsec.h>
113 #include <netinet6/ip6_ipsec.h>
114 #include <netipsec/ipsec6.h>
115 #endif /* IPSEC */
116 
117 #include <netinet6/ip6protosw.h>
118 
119 #ifdef FLOWTABLE
120 #include <net/flowtable.h>
121 VNET_DECLARE(int, ip6_output_flowtable_size);
122 #define	V_ip6_output_flowtable_size	VNET(ip6_output_flowtable_size)
123 #endif
124 
125 extern struct domain inet6domain;
126 
127 u_char ip6_protox[IPPROTO_MAX];
128 VNET_DEFINE(struct in6_ifaddrhead, in6_ifaddrhead);
129 VNET_DEFINE(struct in6_ifaddrlisthead *, in6_ifaddrhashtbl);
130 VNET_DEFINE(u_long, in6_ifaddrhmask);
131 
132 static struct netisr_handler ip6_nh = {
133 	.nh_name = "ip6",
134 	.nh_handler = ip6_input,
135 	.nh_proto = NETISR_IPV6,
136 	.nh_policy = NETISR_POLICY_FLOW,
137 };
138 
139 VNET_DECLARE(struct callout, in6_tmpaddrtimer_ch);
140 #define	V_in6_tmpaddrtimer_ch		VNET(in6_tmpaddrtimer_ch)
141 
142 VNET_DEFINE(struct pfil_head, inet6_pfil_hook);
143 
144 VNET_PCPUSTAT_DEFINE(struct ip6stat, ip6stat);
145 VNET_PCPUSTAT_SYSINIT(ip6stat);
146 #ifdef VIMAGE
147 VNET_PCPUSTAT_SYSUNINIT(ip6stat);
148 #endif /* VIMAGE */
149 
150 struct rwlock in6_ifaddr_lock;
151 RW_SYSINIT(in6_ifaddr_lock, &in6_ifaddr_lock, "in6_ifaddr_lock");
152 
153 static void ip6_init2(void *);
154 static struct ip6aux *ip6_setdstifaddr(struct mbuf *, struct in6_ifaddr *);
155 static struct ip6aux *ip6_addaux(struct mbuf *);
156 static struct ip6aux *ip6_findaux(struct mbuf *m);
157 static void ip6_delaux (struct mbuf *);
158 static int ip6_hopopts_input(u_int32_t *, u_int32_t *, struct mbuf **, int *);
159 #ifdef PULLDOWN_TEST
160 static struct mbuf *ip6_pullexthdr(struct mbuf *, size_t, int);
161 #endif
162 
163 /*
164  * IP6 initialization: fill in IP6 protocol switch table.
165  * All protocols not implemented in kernel go to raw IP6 protocol handler.
166  */
167 void
168 ip6_init(void)
169 {
170 	struct ip6protosw *pr;
171 	int i;
172 
173 	TUNABLE_INT_FETCH("net.inet6.ip6.auto_linklocal",
174 	    &V_ip6_auto_linklocal);
175 	TUNABLE_INT_FETCH("net.inet6.ip6.accept_rtadv", &V_ip6_accept_rtadv);
176 	TUNABLE_INT_FETCH("net.inet6.ip6.no_radr", &V_ip6_no_radr);
177 
178 	TAILQ_INIT(&V_in6_ifaddrhead);
179 	V_in6_ifaddrhashtbl = hashinit(IN6ADDR_NHASH, M_IFADDR,
180 	    &V_in6_ifaddrhmask);
181 
182 	/* Initialize packet filter hooks. */
183 	V_inet6_pfil_hook.ph_type = PFIL_TYPE_AF;
184 	V_inet6_pfil_hook.ph_af = AF_INET6;
185 	if ((i = pfil_head_register(&V_inet6_pfil_hook)) != 0)
186 		printf("%s: WARNING: unable to register pfil hook, "
187 			"error %d\n", __func__, i);
188 
189 	scope6_init();
190 	addrsel_policy_init();
191 	nd6_init();
192 	frag6_init();
193 
194 #ifdef FLOWTABLE
195 	if (TUNABLE_INT_FETCH("net.inet6.ip6.output_flowtable_size",
196 		&V_ip6_output_flowtable_size)) {
197 		if (V_ip6_output_flowtable_size < 256)
198 			V_ip6_output_flowtable_size = 256;
199 		if (!powerof2(V_ip6_output_flowtable_size)) {
200 			printf("flowtable must be power of 2 size\n");
201 			V_ip6_output_flowtable_size = 2048;
202 		}
203 	} else {
204 		/*
205 		 * round up to the next power of 2
206 		 */
207 		V_ip6_output_flowtable_size = 1 << fls((1024 + maxusers * 64)-1);
208 	}
209 	V_ip6_ft = flowtable_alloc("ipv6", V_ip6_output_flowtable_size, FL_IPV6|FL_PCPU);
210 #endif
211 
212 	V_ip6_desync_factor = arc4random() % MAX_TEMP_DESYNC_FACTOR;
213 
214 	/* Skip global initialization stuff for non-default instances. */
215 	if (!IS_DEFAULT_VNET(curvnet))
216 		return;
217 
218 #ifdef DIAGNOSTIC
219 	if (sizeof(struct protosw) != sizeof(struct ip6protosw))
220 		panic("sizeof(protosw) != sizeof(ip6protosw)");
221 #endif
222 	pr = (struct ip6protosw *)pffindproto(PF_INET6, IPPROTO_RAW, SOCK_RAW);
223 	if (pr == NULL)
224 		panic("ip6_init");
225 
226 	/* Initialize the entire ip6_protox[] array to IPPROTO_RAW. */
227 	for (i = 0; i < IPPROTO_MAX; i++)
228 		ip6_protox[i] = pr - inet6sw;
229 	/*
230 	 * Cycle through IP protocols and put them into the appropriate place
231 	 * in ip6_protox[].
232 	 */
233 	for (pr = (struct ip6protosw *)inet6domain.dom_protosw;
234 	    pr < (struct ip6protosw *)inet6domain.dom_protoswNPROTOSW; pr++)
235 		if (pr->pr_domain->dom_family == PF_INET6 &&
236 		    pr->pr_protocol && pr->pr_protocol != IPPROTO_RAW) {
237 			/* Be careful to only index valid IP protocols. */
238 			if (pr->pr_protocol < IPPROTO_MAX)
239 				ip6_protox[pr->pr_protocol] = pr - inet6sw;
240 		}
241 
242 	netisr_register(&ip6_nh);
243 }
244 
245 /*
246  * The protocol to be inserted into ip6_protox[] must be already registered
247  * in inet6sw[], either statically or through pf_proto_register().
248  */
249 int
250 ip6proto_register(short ip6proto)
251 {
252 	struct ip6protosw *pr;
253 
254 	/* Sanity checks. */
255 	if (ip6proto <= 0 || ip6proto >= IPPROTO_MAX)
256 		return (EPROTONOSUPPORT);
257 
258 	/*
259 	 * The protocol slot must not be occupied by another protocol
260 	 * already.  An index pointing to IPPROTO_RAW is unused.
261 	 */
262 	pr = (struct ip6protosw *)pffindproto(PF_INET6, IPPROTO_RAW, SOCK_RAW);
263 	if (pr == NULL)
264 		return (EPFNOSUPPORT);
265 	if (ip6_protox[ip6proto] != pr - inet6sw)	/* IPPROTO_RAW */
266 		return (EEXIST);
267 
268 	/*
269 	 * Find the protocol position in inet6sw[] and set the index.
270 	 */
271 	for (pr = (struct ip6protosw *)inet6domain.dom_protosw;
272 	    pr < (struct ip6protosw *)inet6domain.dom_protoswNPROTOSW; pr++) {
273 		if (pr->pr_domain->dom_family == PF_INET6 &&
274 		    pr->pr_protocol && pr->pr_protocol == ip6proto) {
275 			ip6_protox[pr->pr_protocol] = pr - inet6sw;
276 			return (0);
277 		}
278 	}
279 	return (EPROTONOSUPPORT);
280 }
281 
282 int
283 ip6proto_unregister(short ip6proto)
284 {
285 	struct ip6protosw *pr;
286 
287 	/* Sanity checks. */
288 	if (ip6proto <= 0 || ip6proto >= IPPROTO_MAX)
289 		return (EPROTONOSUPPORT);
290 
291 	/* Check if the protocol was indeed registered. */
292 	pr = (struct ip6protosw *)pffindproto(PF_INET6, IPPROTO_RAW, SOCK_RAW);
293 	if (pr == NULL)
294 		return (EPFNOSUPPORT);
295 	if (ip6_protox[ip6proto] == pr - inet6sw)	/* IPPROTO_RAW */
296 		return (ENOENT);
297 
298 	/* Reset the protocol slot to IPPROTO_RAW. */
299 	ip6_protox[ip6proto] = pr - inet6sw;
300 	return (0);
301 }
302 
303 #ifdef VIMAGE
304 void
305 ip6_destroy()
306 {
307 
308 	hashdestroy(V_in6_ifaddrhashtbl, M_IFADDR, V_in6_ifaddrhmask);
309 	nd6_destroy();
310 	callout_drain(&V_in6_tmpaddrtimer_ch);
311 }
312 #endif
313 
314 static int
315 ip6_init2_vnet(const void *unused __unused)
316 {
317 
318 	/* nd6_timer_init */
319 	callout_init(&V_nd6_timer_ch, 0);
320 	callout_reset(&V_nd6_timer_ch, hz, nd6_timer, curvnet);
321 
322 	/* timer for regeneranation of temporary addresses randomize ID */
323 	callout_init(&V_in6_tmpaddrtimer_ch, 0);
324 	callout_reset(&V_in6_tmpaddrtimer_ch,
325 		      (V_ip6_temp_preferred_lifetime - V_ip6_desync_factor -
326 		       V_ip6_temp_regen_advance) * hz,
327 		      in6_tmpaddrtimer, curvnet);
328 
329 	return (0);
330 }
331 
332 static void
333 ip6_init2(void *dummy)
334 {
335 
336 	ip6_init2_vnet(NULL);
337 }
338 
339 /* cheat */
340 /* This must be after route_init(), which is now SI_ORDER_THIRD */
341 SYSINIT(netinet6init2, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE, ip6_init2, NULL);
342 
343 static int
344 ip6_input_hbh(struct mbuf *m, uint32_t *plen, uint32_t *rtalert, int *off,
345     int *nxt, int *ours)
346 {
347 	struct ip6_hdr *ip6;
348 	struct ip6_hbh *hbh;
349 
350 	if (ip6_hopopts_input(plen, rtalert, &m, off)) {
351 #if 0	/*touches NULL pointer*/
352 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_discard);
353 #endif
354 		goto out;	/* m have already been freed */
355 	}
356 
357 	/* adjust pointer */
358 	ip6 = mtod(m, struct ip6_hdr *);
359 
360 	/*
361 	 * if the payload length field is 0 and the next header field
362 	 * indicates Hop-by-Hop Options header, then a Jumbo Payload
363 	 * option MUST be included.
364 	 */
365 	if (ip6->ip6_plen == 0 && *plen == 0) {
366 		/*
367 		 * Note that if a valid jumbo payload option is
368 		 * contained, ip6_hopopts_input() must set a valid
369 		 * (non-zero) payload length to the variable plen.
370 		 */
371 		IP6STAT_INC(ip6s_badoptions);
372 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_discard);
373 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_hdrerr);
374 		icmp6_error(m, ICMP6_PARAM_PROB,
375 			    ICMP6_PARAMPROB_HEADER,
376 			    (caddr_t)&ip6->ip6_plen - (caddr_t)ip6);
377 		goto out;
378 	}
379 #ifndef PULLDOWN_TEST
380 	/* ip6_hopopts_input() ensures that mbuf is contiguous */
381 	hbh = (struct ip6_hbh *)(ip6 + 1);
382 #else
383 	IP6_EXTHDR_GET(hbh, struct ip6_hbh *, m, sizeof(struct ip6_hdr),
384 		sizeof(struct ip6_hbh));
385 	if (hbh == NULL) {
386 		IP6STAT_INC(ip6s_tooshort);
387 		goto out;
388 	}
389 #endif
390 	*nxt = hbh->ip6h_nxt;
391 
392 	/*
393 	 * If we are acting as a router and the packet contains a
394 	 * router alert option, see if we know the option value.
395 	 * Currently, we only support the option value for MLD, in which
396 	 * case we should pass the packet to the multicast routing
397 	 * daemon.
398 	 */
399 	if (*rtalert != ~0) {
400 		switch (*rtalert) {
401 		case IP6OPT_RTALERT_MLD:
402 			if (V_ip6_forwarding)
403 				*ours = 1;
404 			break;
405 		default:
406 			/*
407 			 * RFC2711 requires unrecognized values must be
408 			 * silently ignored.
409 			 */
410 			break;
411 		}
412 	}
413 
414 	return (0);
415 
416 out:
417 	return (1);
418 }
419 
420 void
421 ip6_input(struct mbuf *m)
422 {
423 	struct ip6_hdr *ip6;
424 	int off = sizeof(struct ip6_hdr), nest;
425 	u_int32_t plen;
426 	u_int32_t rtalert = ~0;
427 	int nxt, ours = 0;
428 	struct ifnet *deliverifp = NULL, *ifp = NULL;
429 	struct in6_addr odst;
430 	struct route_in6 rin6;
431 	int srcrt = 0;
432 	struct llentry *lle = NULL;
433 	struct sockaddr_in6 dst6, *dst;
434 
435 	bzero(&rin6, sizeof(struct route_in6));
436 #ifdef IPSEC
437 	/*
438 	 * should the inner packet be considered authentic?
439 	 * see comment in ah4_input().
440 	 * NB: m cannot be NULL when passed to the input routine
441 	 */
442 
443 	m->m_flags &= ~M_AUTHIPHDR;
444 	m->m_flags &= ~M_AUTHIPDGM;
445 
446 #endif /* IPSEC */
447 
448 	/*
449 	 * make sure we don't have onion peering information into m_tag.
450 	 */
451 	ip6_delaux(m);
452 
453 	if (m->m_flags & M_FASTFWD_OURS) {
454 		/*
455 		 * Firewall changed destination to local.
456 		 */
457 		m->m_flags &= ~M_FASTFWD_OURS;
458 		ours = 1;
459 		deliverifp = m->m_pkthdr.rcvif;
460 		ip6 = mtod(m, struct ip6_hdr *);
461 		goto hbhcheck;
462 	}
463 
464 	/*
465 	 * mbuf statistics
466 	 */
467 	if (m->m_flags & M_EXT) {
468 		if (m->m_next)
469 			IP6STAT_INC(ip6s_mext2m);
470 		else
471 			IP6STAT_INC(ip6s_mext1);
472 	} else {
473 		if (m->m_next) {
474 			if (m->m_flags & M_LOOP) {
475 				IP6STAT_INC(ip6s_m2m[V_loif->if_index]);
476 			} else if (m->m_pkthdr.rcvif->if_index < IP6S_M2MMAX)
477 				IP6STAT_INC(
478 				    ip6s_m2m[m->m_pkthdr.rcvif->if_index]);
479 			else
480 				IP6STAT_INC(ip6s_m2m[0]);
481 		} else
482 			IP6STAT_INC(ip6s_m1);
483 	}
484 
485 	/* drop the packet if IPv6 operation is disabled on the IF */
486 	if ((ND_IFINFO(m->m_pkthdr.rcvif)->flags & ND6_IFF_IFDISABLED)) {
487 		m_freem(m);
488 		return;
489 	}
490 
491 	in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_receive);
492 	IP6STAT_INC(ip6s_total);
493 
494 #ifndef PULLDOWN_TEST
495 	/*
496 	 * L2 bridge code and some other code can return mbuf chain
497 	 * that does not conform to KAME requirement.  too bad.
498 	 * XXX: fails to join if interface MTU > MCLBYTES.  jumbogram?
499 	 */
500 	if (m && m->m_next != NULL && m->m_pkthdr.len < MCLBYTES) {
501 		struct mbuf *n;
502 
503 		if (m->m_pkthdr.len > MHLEN)
504 			n = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
505 		else
506 			n = m_gethdr(M_NOWAIT, MT_DATA);
507 		if (n == NULL) {
508 			m_freem(m);
509 			return;	/* ENOBUFS */
510 		}
511 
512 		m_move_pkthdr(n, m);
513 		m_copydata(m, 0, n->m_pkthdr.len, mtod(n, caddr_t));
514 		n->m_len = n->m_pkthdr.len;
515 		m_freem(m);
516 		m = n;
517 	}
518 	IP6_EXTHDR_CHECK(m, 0, sizeof(struct ip6_hdr), /* nothing */);
519 #endif
520 
521 	if (m->m_len < sizeof(struct ip6_hdr)) {
522 		struct ifnet *inifp;
523 		inifp = m->m_pkthdr.rcvif;
524 		if ((m = m_pullup(m, sizeof(struct ip6_hdr))) == NULL) {
525 			IP6STAT_INC(ip6s_toosmall);
526 			in6_ifstat_inc(inifp, ifs6_in_hdrerr);
527 			return;
528 		}
529 	}
530 
531 	ip6 = mtod(m, struct ip6_hdr *);
532 
533 	if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION) {
534 		IP6STAT_INC(ip6s_badvers);
535 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_hdrerr);
536 		goto bad;
537 	}
538 
539 	IP6STAT_INC(ip6s_nxthist[ip6->ip6_nxt]);
540 
541 	/*
542 	 * Check against address spoofing/corruption.
543 	 */
544 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_src) ||
545 	    IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_dst)) {
546 		/*
547 		 * XXX: "badscope" is not very suitable for a multicast source.
548 		 */
549 		IP6STAT_INC(ip6s_badscope);
550 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_addrerr);
551 		goto bad;
552 	}
553 	if (IN6_IS_ADDR_MC_INTFACELOCAL(&ip6->ip6_dst) &&
554 	    !(m->m_flags & M_LOOP)) {
555 		/*
556 		 * In this case, the packet should come from the loopback
557 		 * interface.  However, we cannot just check the if_flags,
558 		 * because ip6_mloopback() passes the "actual" interface
559 		 * as the outgoing/incoming interface.
560 		 */
561 		IP6STAT_INC(ip6s_badscope);
562 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_addrerr);
563 		goto bad;
564 	}
565 
566 #ifdef ALTQ
567 	if (altq_input != NULL && (*altq_input)(m, AF_INET6) == 0) {
568 		/* packet is dropped by traffic conditioner */
569 		return;
570 	}
571 #endif
572 	/*
573 	 * The following check is not documented in specs.  A malicious
574 	 * party may be able to use IPv4 mapped addr to confuse tcp/udp stack
575 	 * and bypass security checks (act as if it was from 127.0.0.1 by using
576 	 * IPv6 src ::ffff:127.0.0.1).  Be cautious.
577 	 *
578 	 * This check chokes if we are in an SIIT cloud.  As none of BSDs
579 	 * support IPv4-less kernel compilation, we cannot support SIIT
580 	 * environment at all.  So, it makes more sense for us to reject any
581 	 * malicious packets for non-SIIT environment, than try to do a
582 	 * partial support for SIIT environment.
583 	 */
584 	if (IN6_IS_ADDR_V4MAPPED(&ip6->ip6_src) ||
585 	    IN6_IS_ADDR_V4MAPPED(&ip6->ip6_dst)) {
586 		IP6STAT_INC(ip6s_badscope);
587 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_addrerr);
588 		goto bad;
589 	}
590 #if 0
591 	/*
592 	 * Reject packets with IPv4 compatible addresses (auto tunnel).
593 	 *
594 	 * The code forbids auto tunnel relay case in RFC1933 (the check is
595 	 * stronger than RFC1933).  We may want to re-enable it if mech-xx
596 	 * is revised to forbid relaying case.
597 	 */
598 	if (IN6_IS_ADDR_V4COMPAT(&ip6->ip6_src) ||
599 	    IN6_IS_ADDR_V4COMPAT(&ip6->ip6_dst)) {
600 		IP6STAT_INC(ip6s_badscope);
601 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_addrerr);
602 		goto bad;
603 	}
604 #endif
605 #ifdef IPSEC
606 	/*
607 	 * Bypass packet filtering for packets previously handled by IPsec.
608 	 */
609 	if (ip6_ipsec_filtertunnel(m))
610 		goto passin;
611 #endif /* IPSEC */
612 
613 	/*
614 	 * Run through list of hooks for input packets.
615 	 *
616 	 * NB: Beware of the destination address changing
617 	 *     (e.g. by NAT rewriting).  When this happens,
618 	 *     tell ip6_forward to do the right thing.
619 	 */
620 	odst = ip6->ip6_dst;
621 
622 	/* Jump over all PFIL processing if hooks are not active. */
623 	if (!PFIL_HOOKED(&V_inet6_pfil_hook))
624 		goto passin;
625 
626 	if (pfil_run_hooks(&V_inet6_pfil_hook, &m,
627 	    m->m_pkthdr.rcvif, PFIL_IN, NULL))
628 		return;
629 	if (m == NULL)			/* consumed by filter */
630 		return;
631 	ip6 = mtod(m, struct ip6_hdr *);
632 	srcrt = !IN6_ARE_ADDR_EQUAL(&odst, &ip6->ip6_dst);
633 
634 	if (m->m_flags & M_FASTFWD_OURS) {
635 		m->m_flags &= ~M_FASTFWD_OURS;
636 		ours = 1;
637 		deliverifp = m->m_pkthdr.rcvif;
638 		goto hbhcheck;
639 	}
640 	if ((m->m_flags & M_IP6_NEXTHOP) &&
641 	    m_tag_find(m, PACKET_TAG_IPFORWARD, NULL) != NULL) {
642 		/*
643 		 * Directly ship the packet on.  This allows forwarding
644 		 * packets originally destined to us to some other directly
645 		 * connected host.
646 		 */
647 		ip6_forward(m, 1);
648 		goto out;
649 	}
650 
651 passin:
652 	/*
653 	 * Disambiguate address scope zones (if there is ambiguity).
654 	 * We first make sure that the original source or destination address
655 	 * is not in our internal form for scoped addresses.  Such addresses
656 	 * are not necessarily invalid spec-wise, but we cannot accept them due
657 	 * to the usage conflict.
658 	 * in6_setscope() then also checks and rejects the cases where src or
659 	 * dst are the loopback address and the receiving interface
660 	 * is not loopback.
661 	 */
662 	if (in6_clearscope(&ip6->ip6_src) || in6_clearscope(&ip6->ip6_dst)) {
663 		IP6STAT_INC(ip6s_badscope); /* XXX */
664 		goto bad;
665 	}
666 	if (in6_setscope(&ip6->ip6_src, m->m_pkthdr.rcvif, NULL) ||
667 	    in6_setscope(&ip6->ip6_dst, m->m_pkthdr.rcvif, NULL)) {
668 		IP6STAT_INC(ip6s_badscope);
669 		goto bad;
670 	}
671 
672 	/*
673 	 * Multicast check. Assume packet is for us to avoid
674 	 * prematurely taking locks.
675 	 */
676 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
677 		ours = 1;
678 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_mcast);
679 		deliverifp = m->m_pkthdr.rcvif;
680 		goto hbhcheck;
681 	}
682 
683 	/*
684 	 *  Unicast check
685 	 */
686 
687 	bzero(&dst6, sizeof(dst6));
688 	dst6.sin6_family = AF_INET6;
689 	dst6.sin6_len = sizeof(struct sockaddr_in6);
690 	dst6.sin6_addr = ip6->ip6_dst;
691 	ifp = m->m_pkthdr.rcvif;
692 	IF_AFDATA_RLOCK(ifp);
693 	lle = lla_lookup(LLTABLE6(ifp), 0,
694 	     (struct sockaddr *)&dst6);
695 	IF_AFDATA_RUNLOCK(ifp);
696 	if ((lle != NULL) && (lle->la_flags & LLE_IFADDR)) {
697 		struct ifaddr *ifa;
698 		struct in6_ifaddr *ia6;
699 		int bad;
700 
701 		bad = 1;
702 #define	sa_equal(a1, a2)						\
703 	(bcmp((a1), (a2), ((a1))->sin6_len) == 0)
704 		IF_ADDR_RLOCK(ifp);
705 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
706 			if (ifa->ifa_addr->sa_family != dst6.sin6_family)
707 				continue;
708 			if (sa_equal(&dst6, ifa->ifa_addr))
709 				break;
710 		}
711 		KASSERT(ifa != NULL, ("%s: ifa not found for lle %p",
712 		    __func__, lle));
713 #undef sa_equal
714 
715 		ia6 = (struct in6_ifaddr *)ifa;
716 		if (!(ia6->ia6_flags & IN6_IFF_NOTREADY)) {
717 			/* Count the packet in the ip address stats */
718 			ia6->ia_ifa.if_ipackets++;
719 			ia6->ia_ifa.if_ibytes += m->m_pkthdr.len;
720 
721 			/*
722 			 * record address information into m_tag.
723 			 */
724 			(void)ip6_setdstifaddr(m, ia6);
725 
726 			bad = 0;
727 		} else {
728 			char ip6bufs[INET6_ADDRSTRLEN];
729 			char ip6bufd[INET6_ADDRSTRLEN];
730 			/* address is not ready, so discard the packet. */
731 			nd6log((LOG_INFO,
732 			    "ip6_input: packet to an unready address %s->%s\n",
733 			    ip6_sprintf(ip6bufs, &ip6->ip6_src),
734 			    ip6_sprintf(ip6bufd, &ip6->ip6_dst)));
735 		}
736 		IF_ADDR_RUNLOCK(ifp);
737 		LLE_RUNLOCK(lle);
738 		if (bad)
739 			goto bad;
740 		else {
741 			ours = 1;
742 			deliverifp = ifp;
743 			goto hbhcheck;
744 		}
745 	}
746 	if (lle != NULL)
747 		LLE_RUNLOCK(lle);
748 
749 	dst = &rin6.ro_dst;
750 	dst->sin6_len = sizeof(struct sockaddr_in6);
751 	dst->sin6_family = AF_INET6;
752 	dst->sin6_addr = ip6->ip6_dst;
753 	rin6.ro_rt = in6_rtalloc1((struct sockaddr *)dst, 0, 0, M_GETFIB(m));
754 	if (rin6.ro_rt)
755 		RT_UNLOCK(rin6.ro_rt);
756 
757 #define rt6_key(r) ((struct sockaddr_in6 *)((r)->rt_nodes->rn_key))
758 
759 	/*
760 	 * Accept the packet if the forwarding interface to the destination
761 	 * according to the routing table is the loopback interface,
762 	 * unless the associated route has a gateway.
763 	 * Note that this approach causes to accept a packet if there is a
764 	 * route to the loopback interface for the destination of the packet.
765 	 * But we think it's even useful in some situations, e.g. when using
766 	 * a special daemon which wants to intercept the packet.
767 	 *
768 	 * XXX: some OSes automatically make a cloned route for the destination
769 	 * of an outgoing packet.  If the outgoing interface of the packet
770 	 * is a loopback one, the kernel would consider the packet to be
771 	 * accepted, even if we have no such address assinged on the interface.
772 	 * We check the cloned flag of the route entry to reject such cases,
773 	 * assuming that route entries for our own addresses are not made by
774 	 * cloning (it should be true because in6_addloop explicitly installs
775 	 * the host route).  However, we might have to do an explicit check
776 	 * while it would be less efficient.  Or, should we rather install a
777 	 * reject route for such a case?
778 	 */
779 	if (rin6.ro_rt &&
780 	    (rin6.ro_rt->rt_flags &
781 	     (RTF_HOST|RTF_GATEWAY)) == RTF_HOST &&
782 #ifdef RTF_WASCLONED
783 	    !(rin6.ro_rt->rt_flags & RTF_WASCLONED) &&
784 #endif
785 #ifdef RTF_CLONED
786 	    !(rin6.ro_rt->rt_flags & RTF_CLONED) &&
787 #endif
788 #if 0
789 	    /*
790 	     * The check below is redundant since the comparison of
791 	     * the destination and the key of the rtentry has
792 	     * already done through looking up the routing table.
793 	     */
794 	    IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
795 	    &rt6_key(rin6.ro_rt)->sin6_addr)
796 #endif
797 	    rin6.ro_rt->rt_ifp->if_type == IFT_LOOP) {
798 		int free_ia6 = 0;
799 		struct in6_ifaddr *ia6;
800 
801 		/*
802 		 * found the loopback route to the interface address
803 		 */
804 		if (rin6.ro_rt->rt_gateway->sa_family == AF_LINK) {
805 			struct sockaddr_in6 dest6;
806 
807 			bzero(&dest6, sizeof(dest6));
808 			dest6.sin6_family = AF_INET6;
809 			dest6.sin6_len = sizeof(dest6);
810 			dest6.sin6_addr = ip6->ip6_dst;
811 			ia6 = (struct in6_ifaddr *)
812 			    ifa_ifwithaddr((struct sockaddr *)&dest6);
813 			if (ia6 == NULL)
814 				goto bad;
815 			free_ia6 = 1;
816 		}
817 		else
818 			ia6 = (struct in6_ifaddr *)rin6.ro_rt->rt_ifa;
819 
820 		/*
821 		 * record address information into m_tag.
822 		 */
823 		(void)ip6_setdstifaddr(m, ia6);
824 
825 		/*
826 		 * packets to a tentative, duplicated, or somehow invalid
827 		 * address must not be accepted.
828 		 */
829 		if (!(ia6->ia6_flags & IN6_IFF_NOTREADY)) {
830 			/* this address is ready */
831 			ours = 1;
832 			deliverifp = ia6->ia_ifp;	/* correct? */
833 			/* Count the packet in the ip address stats */
834 			ia6->ia_ifa.if_ipackets++;
835 			ia6->ia_ifa.if_ibytes += m->m_pkthdr.len;
836 			if (ia6 != NULL && free_ia6 != 0)
837 				ifa_free(&ia6->ia_ifa);
838 			goto hbhcheck;
839 		} else {
840 			char ip6bufs[INET6_ADDRSTRLEN];
841 			char ip6bufd[INET6_ADDRSTRLEN];
842 			/* address is not ready, so discard the packet. */
843 			nd6log((LOG_INFO,
844 			    "ip6_input: packet to an unready address %s->%s\n",
845 			    ip6_sprintf(ip6bufs, &ip6->ip6_src),
846 			    ip6_sprintf(ip6bufd, &ip6->ip6_dst)));
847 
848 			if (ia6 != NULL && free_ia6 != 0)
849 				ifa_free(&ia6->ia_ifa);
850 			goto bad;
851 		}
852 	}
853 
854 	/*
855 	 * FAITH (Firewall Aided Internet Translator)
856 	 */
857 	if (V_ip6_keepfaith) {
858 		if (rin6.ro_rt && rin6.ro_rt->rt_ifp &&
859 		    rin6.ro_rt->rt_ifp->if_type == IFT_FAITH) {
860 			/* XXX do we need more sanity checks? */
861 			ours = 1;
862 			deliverifp = rin6.ro_rt->rt_ifp; /* faith */
863 			goto hbhcheck;
864 		}
865 	}
866 
867 	/*
868 	 * Now there is no reason to process the packet if it's not our own
869 	 * and we're not a router.
870 	 */
871 	if (!V_ip6_forwarding) {
872 		IP6STAT_INC(ip6s_cantforward);
873 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_discard);
874 		goto bad;
875 	}
876 
877   hbhcheck:
878 	/*
879 	 * record address information into m_tag, if we don't have one yet.
880 	 * note that we are unable to record it, if the address is not listed
881 	 * as our interface address (e.g. multicast addresses, addresses
882 	 * within FAITH prefixes and such).
883 	 */
884 	if (deliverifp) {
885 		struct in6_ifaddr *ia6;
886 
887  		if ((ia6 = ip6_getdstifaddr(m)) != NULL) {
888 			ifa_free(&ia6->ia_ifa);
889 		} else {
890 			ia6 = in6_ifawithifp(deliverifp, &ip6->ip6_dst);
891 			if (ia6) {
892 				if (!ip6_setdstifaddr(m, ia6)) {
893 					/*
894 					 * XXX maybe we should drop the packet here,
895 					 * as we could not provide enough information
896 					 * to the upper layers.
897 					 */
898 				}
899 				ifa_free(&ia6->ia_ifa);
900 			}
901 		}
902 	}
903 
904 	/*
905 	 * Process Hop-by-Hop options header if it's contained.
906 	 * m may be modified in ip6_hopopts_input().
907 	 * If a JumboPayload option is included, plen will also be modified.
908 	 */
909 	plen = (u_int32_t)ntohs(ip6->ip6_plen);
910 	if (ip6->ip6_nxt == IPPROTO_HOPOPTS) {
911 		int error;
912 
913 		error = ip6_input_hbh(m, &plen, &rtalert, &off, &nxt, &ours);
914 		if (error != 0)
915 			goto out;
916 	} else
917 		nxt = ip6->ip6_nxt;
918 
919 	/*
920 	 * Check that the amount of data in the buffers
921 	 * is as at least much as the IPv6 header would have us expect.
922 	 * Trim mbufs if longer than we expect.
923 	 * Drop packet if shorter than we expect.
924 	 */
925 	if (m->m_pkthdr.len - sizeof(struct ip6_hdr) < plen) {
926 		IP6STAT_INC(ip6s_tooshort);
927 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_truncated);
928 		goto bad;
929 	}
930 	if (m->m_pkthdr.len > sizeof(struct ip6_hdr) + plen) {
931 		if (m->m_len == m->m_pkthdr.len) {
932 			m->m_len = sizeof(struct ip6_hdr) + plen;
933 			m->m_pkthdr.len = sizeof(struct ip6_hdr) + plen;
934 		} else
935 			m_adj(m, sizeof(struct ip6_hdr) + plen - m->m_pkthdr.len);
936 	}
937 
938 	/*
939 	 * Forward if desirable.
940 	 */
941 	if (V_ip6_mrouter &&
942 	    IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
943 		/*
944 		 * If we are acting as a multicast router, all
945 		 * incoming multicast packets are passed to the
946 		 * kernel-level multicast forwarding function.
947 		 * The packet is returned (relatively) intact; if
948 		 * ip6_mforward() returns a non-zero value, the packet
949 		 * must be discarded, else it may be accepted below.
950 		 *
951 		 * XXX TODO: Check hlim and multicast scope here to avoid
952 		 * unnecessarily calling into ip6_mforward().
953 		 */
954 		if (ip6_mforward &&
955 		    ip6_mforward(ip6, m->m_pkthdr.rcvif, m)) {
956 			IP6STAT_INC(ip6s_cantforward);
957 			in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_discard);
958 			goto bad;
959 		}
960 	} else if (!ours) {
961 		ip6_forward(m, srcrt);
962 		goto out;
963 	}
964 
965 	ip6 = mtod(m, struct ip6_hdr *);
966 
967 	/*
968 	 * Malicious party may be able to use IPv4 mapped addr to confuse
969 	 * tcp/udp stack and bypass security checks (act as if it was from
970 	 * 127.0.0.1 by using IPv6 src ::ffff:127.0.0.1).  Be cautious.
971 	 *
972 	 * For SIIT end node behavior, you may want to disable the check.
973 	 * However, you will  become vulnerable to attacks using IPv4 mapped
974 	 * source.
975 	 */
976 	if (IN6_IS_ADDR_V4MAPPED(&ip6->ip6_src) ||
977 	    IN6_IS_ADDR_V4MAPPED(&ip6->ip6_dst)) {
978 		IP6STAT_INC(ip6s_badscope);
979 		in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_addrerr);
980 		goto bad;
981 	}
982 
983 	/*
984 	 * Tell launch routine the next header
985 	 */
986 	IP6STAT_INC(ip6s_delivered);
987 	in6_ifstat_inc(deliverifp, ifs6_in_deliver);
988 	nest = 0;
989 
990 	while (nxt != IPPROTO_DONE) {
991 		if (V_ip6_hdrnestlimit && (++nest > V_ip6_hdrnestlimit)) {
992 			IP6STAT_INC(ip6s_toomanyhdr);
993 			goto bad;
994 		}
995 
996 		/*
997 		 * protection against faulty packet - there should be
998 		 * more sanity checks in header chain processing.
999 		 */
1000 		if (m->m_pkthdr.len < off) {
1001 			IP6STAT_INC(ip6s_tooshort);
1002 			in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_truncated);
1003 			goto bad;
1004 		}
1005 
1006 #ifdef IPSEC
1007 		/*
1008 		 * enforce IPsec policy checking if we are seeing last header.
1009 		 * note that we do not visit this with protocols with pcb layer
1010 		 * code - like udp/tcp/raw ip.
1011 		 */
1012 		if (ip6_ipsec_input(m, nxt))
1013 			goto bad;
1014 #endif /* IPSEC */
1015 
1016 		/*
1017 		 * Use mbuf flags to propagate Router Alert option to
1018 		 * ICMPv6 layer, as hop-by-hop options have been stripped.
1019 		 */
1020 		if (nxt == IPPROTO_ICMPV6 && rtalert != ~0)
1021 			m->m_flags |= M_RTALERT_MLD;
1022 
1023 		nxt = (*inet6sw[ip6_protox[nxt]].pr_input)(&m, &off, nxt);
1024 	}
1025 	goto out;
1026 bad:
1027 	m_freem(m);
1028 out:
1029 	if (rin6.ro_rt)
1030 		RTFREE(rin6.ro_rt);
1031 }
1032 
1033 /*
1034  * set/grab in6_ifaddr correspond to IPv6 destination address.
1035  * XXX backward compatibility wrapper
1036  *
1037  * XXXRW: We should bump the refcount on ia6 before sticking it in the m_tag,
1038  * and then bump it when the tag is copied, and release it when the tag is
1039  * freed.  Unfortunately, m_tags don't support deep copies (yet), so instead
1040  * we just bump the ia refcount when we receive it.  This should be fixed.
1041  */
1042 static struct ip6aux *
1043 ip6_setdstifaddr(struct mbuf *m, struct in6_ifaddr *ia6)
1044 {
1045 	struct ip6aux *ip6a;
1046 
1047 	ip6a = ip6_addaux(m);
1048 	if (ip6a)
1049 		ip6a->ip6a_dstia6 = ia6;
1050 	return ip6a;	/* NULL if failed to set */
1051 }
1052 
1053 struct in6_ifaddr *
1054 ip6_getdstifaddr(struct mbuf *m)
1055 {
1056 	struct ip6aux *ip6a;
1057 	struct in6_ifaddr *ia;
1058 
1059 	ip6a = ip6_findaux(m);
1060 	if (ip6a) {
1061 		ia = ip6a->ip6a_dstia6;
1062 		ifa_ref(&ia->ia_ifa);
1063 		return ia;
1064 	} else
1065 		return NULL;
1066 }
1067 
1068 /*
1069  * Hop-by-Hop options header processing. If a valid jumbo payload option is
1070  * included, the real payload length will be stored in plenp.
1071  *
1072  * rtalertp - XXX: should be stored more smart way
1073  */
1074 static int
1075 ip6_hopopts_input(u_int32_t *plenp, u_int32_t *rtalertp,
1076     struct mbuf **mp, int *offp)
1077 {
1078 	struct mbuf *m = *mp;
1079 	int off = *offp, hbhlen;
1080 	struct ip6_hbh *hbh;
1081 	u_int8_t *opt;
1082 
1083 	/* validation of the length of the header */
1084 #ifndef PULLDOWN_TEST
1085 	IP6_EXTHDR_CHECK(m, off, sizeof(*hbh), -1);
1086 	hbh = (struct ip6_hbh *)(mtod(m, caddr_t) + off);
1087 	hbhlen = (hbh->ip6h_len + 1) << 3;
1088 
1089 	IP6_EXTHDR_CHECK(m, off, hbhlen, -1);
1090 	hbh = (struct ip6_hbh *)(mtod(m, caddr_t) + off);
1091 #else
1092 	IP6_EXTHDR_GET(hbh, struct ip6_hbh *, m,
1093 		sizeof(struct ip6_hdr), sizeof(struct ip6_hbh));
1094 	if (hbh == NULL) {
1095 		IP6STAT_INC(ip6s_tooshort);
1096 		return -1;
1097 	}
1098 	hbhlen = (hbh->ip6h_len + 1) << 3;
1099 	IP6_EXTHDR_GET(hbh, struct ip6_hbh *, m, sizeof(struct ip6_hdr),
1100 		hbhlen);
1101 	if (hbh == NULL) {
1102 		IP6STAT_INC(ip6s_tooshort);
1103 		return -1;
1104 	}
1105 #endif
1106 	off += hbhlen;
1107 	hbhlen -= sizeof(struct ip6_hbh);
1108 	opt = (u_int8_t *)hbh + sizeof(struct ip6_hbh);
1109 
1110 	if (ip6_process_hopopts(m, (u_int8_t *)hbh + sizeof(struct ip6_hbh),
1111 				hbhlen, rtalertp, plenp) < 0)
1112 		return (-1);
1113 
1114 	*offp = off;
1115 	*mp = m;
1116 	return (0);
1117 }
1118 
1119 /*
1120  * Search header for all Hop-by-hop options and process each option.
1121  * This function is separate from ip6_hopopts_input() in order to
1122  * handle a case where the sending node itself process its hop-by-hop
1123  * options header. In such a case, the function is called from ip6_output().
1124  *
1125  * The function assumes that hbh header is located right after the IPv6 header
1126  * (RFC2460 p7), opthead is pointer into data content in m, and opthead to
1127  * opthead + hbhlen is located in contiguous memory region.
1128  */
1129 int
1130 ip6_process_hopopts(struct mbuf *m, u_int8_t *opthead, int hbhlen,
1131     u_int32_t *rtalertp, u_int32_t *plenp)
1132 {
1133 	struct ip6_hdr *ip6;
1134 	int optlen = 0;
1135 	u_int8_t *opt = opthead;
1136 	u_int16_t rtalert_val;
1137 	u_int32_t jumboplen;
1138 	const int erroff = sizeof(struct ip6_hdr) + sizeof(struct ip6_hbh);
1139 
1140 	for (; hbhlen > 0; hbhlen -= optlen, opt += optlen) {
1141 		switch (*opt) {
1142 		case IP6OPT_PAD1:
1143 			optlen = 1;
1144 			break;
1145 		case IP6OPT_PADN:
1146 			if (hbhlen < IP6OPT_MINLEN) {
1147 				IP6STAT_INC(ip6s_toosmall);
1148 				goto bad;
1149 			}
1150 			optlen = *(opt + 1) + 2;
1151 			break;
1152 		case IP6OPT_ROUTER_ALERT:
1153 			/* XXX may need check for alignment */
1154 			if (hbhlen < IP6OPT_RTALERT_LEN) {
1155 				IP6STAT_INC(ip6s_toosmall);
1156 				goto bad;
1157 			}
1158 			if (*(opt + 1) != IP6OPT_RTALERT_LEN - 2) {
1159 				/* XXX stat */
1160 				icmp6_error(m, ICMP6_PARAM_PROB,
1161 				    ICMP6_PARAMPROB_HEADER,
1162 				    erroff + opt + 1 - opthead);
1163 				return (-1);
1164 			}
1165 			optlen = IP6OPT_RTALERT_LEN;
1166 			bcopy((caddr_t)(opt + 2), (caddr_t)&rtalert_val, 2);
1167 			*rtalertp = ntohs(rtalert_val);
1168 			break;
1169 		case IP6OPT_JUMBO:
1170 			/* XXX may need check for alignment */
1171 			if (hbhlen < IP6OPT_JUMBO_LEN) {
1172 				IP6STAT_INC(ip6s_toosmall);
1173 				goto bad;
1174 			}
1175 			if (*(opt + 1) != IP6OPT_JUMBO_LEN - 2) {
1176 				/* XXX stat */
1177 				icmp6_error(m, ICMP6_PARAM_PROB,
1178 				    ICMP6_PARAMPROB_HEADER,
1179 				    erroff + opt + 1 - opthead);
1180 				return (-1);
1181 			}
1182 			optlen = IP6OPT_JUMBO_LEN;
1183 
1184 			/*
1185 			 * IPv6 packets that have non 0 payload length
1186 			 * must not contain a jumbo payload option.
1187 			 */
1188 			ip6 = mtod(m, struct ip6_hdr *);
1189 			if (ip6->ip6_plen) {
1190 				IP6STAT_INC(ip6s_badoptions);
1191 				icmp6_error(m, ICMP6_PARAM_PROB,
1192 				    ICMP6_PARAMPROB_HEADER,
1193 				    erroff + opt - opthead);
1194 				return (-1);
1195 			}
1196 
1197 			/*
1198 			 * We may see jumbolen in unaligned location, so
1199 			 * we'd need to perform bcopy().
1200 			 */
1201 			bcopy(opt + 2, &jumboplen, sizeof(jumboplen));
1202 			jumboplen = (u_int32_t)htonl(jumboplen);
1203 
1204 #if 1
1205 			/*
1206 			 * if there are multiple jumbo payload options,
1207 			 * *plenp will be non-zero and the packet will be
1208 			 * rejected.
1209 			 * the behavior may need some debate in ipngwg -
1210 			 * multiple options does not make sense, however,
1211 			 * there's no explicit mention in specification.
1212 			 */
1213 			if (*plenp != 0) {
1214 				IP6STAT_INC(ip6s_badoptions);
1215 				icmp6_error(m, ICMP6_PARAM_PROB,
1216 				    ICMP6_PARAMPROB_HEADER,
1217 				    erroff + opt + 2 - opthead);
1218 				return (-1);
1219 			}
1220 #endif
1221 
1222 			/*
1223 			 * jumbo payload length must be larger than 65535.
1224 			 */
1225 			if (jumboplen <= IPV6_MAXPACKET) {
1226 				IP6STAT_INC(ip6s_badoptions);
1227 				icmp6_error(m, ICMP6_PARAM_PROB,
1228 				    ICMP6_PARAMPROB_HEADER,
1229 				    erroff + opt + 2 - opthead);
1230 				return (-1);
1231 			}
1232 			*plenp = jumboplen;
1233 
1234 			break;
1235 		default:		/* unknown option */
1236 			if (hbhlen < IP6OPT_MINLEN) {
1237 				IP6STAT_INC(ip6s_toosmall);
1238 				goto bad;
1239 			}
1240 			optlen = ip6_unknown_opt(opt, m,
1241 			    erroff + opt - opthead);
1242 			if (optlen == -1)
1243 				return (-1);
1244 			optlen += 2;
1245 			break;
1246 		}
1247 	}
1248 
1249 	return (0);
1250 
1251   bad:
1252 	m_freem(m);
1253 	return (-1);
1254 }
1255 
1256 /*
1257  * Unknown option processing.
1258  * The third argument `off' is the offset from the IPv6 header to the option,
1259  * which is necessary if the IPv6 header the and option header and IPv6 header
1260  * is not contiguous in order to return an ICMPv6 error.
1261  */
1262 int
1263 ip6_unknown_opt(u_int8_t *optp, struct mbuf *m, int off)
1264 {
1265 	struct ip6_hdr *ip6;
1266 
1267 	switch (IP6OPT_TYPE(*optp)) {
1268 	case IP6OPT_TYPE_SKIP: /* ignore the option */
1269 		return ((int)*(optp + 1));
1270 	case IP6OPT_TYPE_DISCARD:	/* silently discard */
1271 		m_freem(m);
1272 		return (-1);
1273 	case IP6OPT_TYPE_FORCEICMP: /* send ICMP even if multicasted */
1274 		IP6STAT_INC(ip6s_badoptions);
1275 		icmp6_error(m, ICMP6_PARAM_PROB, ICMP6_PARAMPROB_OPTION, off);
1276 		return (-1);
1277 	case IP6OPT_TYPE_ICMP: /* send ICMP if not multicasted */
1278 		IP6STAT_INC(ip6s_badoptions);
1279 		ip6 = mtod(m, struct ip6_hdr *);
1280 		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
1281 		    (m->m_flags & (M_BCAST|M_MCAST)))
1282 			m_freem(m);
1283 		else
1284 			icmp6_error(m, ICMP6_PARAM_PROB,
1285 				    ICMP6_PARAMPROB_OPTION, off);
1286 		return (-1);
1287 	}
1288 
1289 	m_freem(m);		/* XXX: NOTREACHED */
1290 	return (-1);
1291 }
1292 
1293 /*
1294  * Create the "control" list for this pcb.
1295  * These functions will not modify mbuf chain at all.
1296  *
1297  * With KAME mbuf chain restriction:
1298  * The routine will be called from upper layer handlers like tcp6_input().
1299  * Thus the routine assumes that the caller (tcp6_input) have already
1300  * called IP6_EXTHDR_CHECK() and all the extension headers are located in the
1301  * very first mbuf on the mbuf chain.
1302  *
1303  * ip6_savecontrol_v4 will handle those options that are possible to be
1304  * set on a v4-mapped socket.
1305  * ip6_savecontrol will directly call ip6_savecontrol_v4 to handle those
1306  * options and handle the v6-only ones itself.
1307  */
1308 struct mbuf **
1309 ip6_savecontrol_v4(struct inpcb *inp, struct mbuf *m, struct mbuf **mp,
1310     int *v4only)
1311 {
1312 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
1313 
1314 #ifdef SO_TIMESTAMP
1315 	if ((inp->inp_socket->so_options & SO_TIMESTAMP) != 0) {
1316 		struct timeval tv;
1317 
1318 		microtime(&tv);
1319 		*mp = sbcreatecontrol((caddr_t) &tv, sizeof(tv),
1320 		    SCM_TIMESTAMP, SOL_SOCKET);
1321 		if (*mp)
1322 			mp = &(*mp)->m_next;
1323 	}
1324 #endif
1325 
1326 #define IS2292(inp, x, y)	(((inp)->inp_flags & IN6P_RFC2292) ? (x) : (y))
1327 	/* RFC 2292 sec. 5 */
1328 	if ((inp->inp_flags & IN6P_PKTINFO) != 0) {
1329 		struct in6_pktinfo pi6;
1330 
1331 		if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION) {
1332 #ifdef INET
1333 			struct ip *ip;
1334 
1335 			ip = mtod(m, struct ip *);
1336 			pi6.ipi6_addr.s6_addr32[0] = 0;
1337 			pi6.ipi6_addr.s6_addr32[1] = 0;
1338 			pi6.ipi6_addr.s6_addr32[2] = IPV6_ADDR_INT32_SMP;
1339 			pi6.ipi6_addr.s6_addr32[3] = ip->ip_dst.s_addr;
1340 #else
1341 			/* We won't hit this code */
1342 			bzero(&pi6.ipi6_addr, sizeof(struct in6_addr));
1343 #endif
1344 		} else {
1345 			bcopy(&ip6->ip6_dst, &pi6.ipi6_addr, sizeof(struct in6_addr));
1346 			in6_clearscope(&pi6.ipi6_addr);	/* XXX */
1347 		}
1348 		pi6.ipi6_ifindex =
1349 		    (m && m->m_pkthdr.rcvif) ? m->m_pkthdr.rcvif->if_index : 0;
1350 
1351 		*mp = sbcreatecontrol((caddr_t) &pi6,
1352 		    sizeof(struct in6_pktinfo),
1353 		    IS2292(inp, IPV6_2292PKTINFO, IPV6_PKTINFO), IPPROTO_IPV6);
1354 		if (*mp)
1355 			mp = &(*mp)->m_next;
1356 	}
1357 
1358 	if ((inp->inp_flags & IN6P_HOPLIMIT) != 0) {
1359 		int hlim;
1360 
1361 		if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION) {
1362 #ifdef INET
1363 			struct ip *ip;
1364 
1365 			ip = mtod(m, struct ip *);
1366 			hlim = ip->ip_ttl;
1367 #else
1368 			/* We won't hit this code */
1369 			hlim = 0;
1370 #endif
1371 		} else {
1372 			hlim = ip6->ip6_hlim & 0xff;
1373 		}
1374 		*mp = sbcreatecontrol((caddr_t) &hlim, sizeof(int),
1375 		    IS2292(inp, IPV6_2292HOPLIMIT, IPV6_HOPLIMIT),
1376 		    IPPROTO_IPV6);
1377 		if (*mp)
1378 			mp = &(*mp)->m_next;
1379 	}
1380 
1381 	if ((inp->inp_flags & IN6P_TCLASS) != 0) {
1382 		int tclass;
1383 
1384 		if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION) {
1385 #ifdef INET
1386 			struct ip *ip;
1387 
1388 			ip = mtod(m, struct ip *);
1389 			tclass = ip->ip_tos;
1390 #else
1391 			/* We won't hit this code */
1392 			tclass = 0;
1393 #endif
1394 		} else {
1395 			u_int32_t flowinfo;
1396 
1397 			flowinfo = (u_int32_t)ntohl(ip6->ip6_flow & IPV6_FLOWINFO_MASK);
1398 			flowinfo >>= 20;
1399 			tclass = flowinfo & 0xff;
1400 		}
1401 		*mp = sbcreatecontrol((caddr_t) &tclass, sizeof(int),
1402 		    IPV6_TCLASS, IPPROTO_IPV6);
1403 		if (*mp)
1404 			mp = &(*mp)->m_next;
1405 	}
1406 
1407 	if (v4only != NULL) {
1408 		if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION) {
1409 			*v4only = 1;
1410 		} else {
1411 			*v4only = 0;
1412 		}
1413 	}
1414 
1415 	return (mp);
1416 }
1417 
1418 void
1419 ip6_savecontrol(struct inpcb *in6p, struct mbuf *m, struct mbuf **mp)
1420 {
1421 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
1422 	int v4only = 0;
1423 
1424 	mp = ip6_savecontrol_v4(in6p, m, mp, &v4only);
1425 	if (v4only)
1426 		return;
1427 
1428 	/*
1429 	 * IPV6_HOPOPTS socket option.  Recall that we required super-user
1430 	 * privilege for the option (see ip6_ctloutput), but it might be too
1431 	 * strict, since there might be some hop-by-hop options which can be
1432 	 * returned to normal user.
1433 	 * See also RFC 2292 section 6 (or RFC 3542 section 8).
1434 	 */
1435 	if ((in6p->inp_flags & IN6P_HOPOPTS) != 0) {
1436 		/*
1437 		 * Check if a hop-by-hop options header is contatined in the
1438 		 * received packet, and if so, store the options as ancillary
1439 		 * data. Note that a hop-by-hop options header must be
1440 		 * just after the IPv6 header, which is assured through the
1441 		 * IPv6 input processing.
1442 		 */
1443 		if (ip6->ip6_nxt == IPPROTO_HOPOPTS) {
1444 			struct ip6_hbh *hbh;
1445 			int hbhlen = 0;
1446 #ifdef PULLDOWN_TEST
1447 			struct mbuf *ext;
1448 #endif
1449 
1450 #ifndef PULLDOWN_TEST
1451 			hbh = (struct ip6_hbh *)(ip6 + 1);
1452 			hbhlen = (hbh->ip6h_len + 1) << 3;
1453 #else
1454 			ext = ip6_pullexthdr(m, sizeof(struct ip6_hdr),
1455 			    ip6->ip6_nxt);
1456 			if (ext == NULL) {
1457 				IP6STAT_INC(ip6s_tooshort);
1458 				return;
1459 			}
1460 			hbh = mtod(ext, struct ip6_hbh *);
1461 			hbhlen = (hbh->ip6h_len + 1) << 3;
1462 			if (hbhlen != ext->m_len) {
1463 				m_freem(ext);
1464 				IP6STAT_INC(ip6s_tooshort);
1465 				return;
1466 			}
1467 #endif
1468 
1469 			/*
1470 			 * XXX: We copy the whole header even if a
1471 			 * jumbo payload option is included, the option which
1472 			 * is to be removed before returning according to
1473 			 * RFC2292.
1474 			 * Note: this constraint is removed in RFC3542
1475 			 */
1476 			*mp = sbcreatecontrol((caddr_t)hbh, hbhlen,
1477 			    IS2292(in6p, IPV6_2292HOPOPTS, IPV6_HOPOPTS),
1478 			    IPPROTO_IPV6);
1479 			if (*mp)
1480 				mp = &(*mp)->m_next;
1481 #ifdef PULLDOWN_TEST
1482 			m_freem(ext);
1483 #endif
1484 		}
1485 	}
1486 
1487 	if ((in6p->inp_flags & (IN6P_RTHDR | IN6P_DSTOPTS)) != 0) {
1488 		int nxt = ip6->ip6_nxt, off = sizeof(struct ip6_hdr);
1489 
1490 		/*
1491 		 * Search for destination options headers or routing
1492 		 * header(s) through the header chain, and stores each
1493 		 * header as ancillary data.
1494 		 * Note that the order of the headers remains in
1495 		 * the chain of ancillary data.
1496 		 */
1497 		while (1) {	/* is explicit loop prevention necessary? */
1498 			struct ip6_ext *ip6e = NULL;
1499 			int elen;
1500 #ifdef PULLDOWN_TEST
1501 			struct mbuf *ext = NULL;
1502 #endif
1503 
1504 			/*
1505 			 * if it is not an extension header, don't try to
1506 			 * pull it from the chain.
1507 			 */
1508 			switch (nxt) {
1509 			case IPPROTO_DSTOPTS:
1510 			case IPPROTO_ROUTING:
1511 			case IPPROTO_HOPOPTS:
1512 			case IPPROTO_AH: /* is it possible? */
1513 				break;
1514 			default:
1515 				goto loopend;
1516 			}
1517 
1518 #ifndef PULLDOWN_TEST
1519 			if (off + sizeof(*ip6e) > m->m_len)
1520 				goto loopend;
1521 			ip6e = (struct ip6_ext *)(mtod(m, caddr_t) + off);
1522 			if (nxt == IPPROTO_AH)
1523 				elen = (ip6e->ip6e_len + 2) << 2;
1524 			else
1525 				elen = (ip6e->ip6e_len + 1) << 3;
1526 			if (off + elen > m->m_len)
1527 				goto loopend;
1528 #else
1529 			ext = ip6_pullexthdr(m, off, nxt);
1530 			if (ext == NULL) {
1531 				IP6STAT_INC(ip6s_tooshort);
1532 				return;
1533 			}
1534 			ip6e = mtod(ext, struct ip6_ext *);
1535 			if (nxt == IPPROTO_AH)
1536 				elen = (ip6e->ip6e_len + 2) << 2;
1537 			else
1538 				elen = (ip6e->ip6e_len + 1) << 3;
1539 			if (elen != ext->m_len) {
1540 				m_freem(ext);
1541 				IP6STAT_INC(ip6s_tooshort);
1542 				return;
1543 			}
1544 #endif
1545 
1546 			switch (nxt) {
1547 			case IPPROTO_DSTOPTS:
1548 				if (!(in6p->inp_flags & IN6P_DSTOPTS))
1549 					break;
1550 
1551 				*mp = sbcreatecontrol((caddr_t)ip6e, elen,
1552 				    IS2292(in6p,
1553 					IPV6_2292DSTOPTS, IPV6_DSTOPTS),
1554 				    IPPROTO_IPV6);
1555 				if (*mp)
1556 					mp = &(*mp)->m_next;
1557 				break;
1558 			case IPPROTO_ROUTING:
1559 				if (!(in6p->inp_flags & IN6P_RTHDR))
1560 					break;
1561 
1562 				*mp = sbcreatecontrol((caddr_t)ip6e, elen,
1563 				    IS2292(in6p, IPV6_2292RTHDR, IPV6_RTHDR),
1564 				    IPPROTO_IPV6);
1565 				if (*mp)
1566 					mp = &(*mp)->m_next;
1567 				break;
1568 			case IPPROTO_HOPOPTS:
1569 			case IPPROTO_AH: /* is it possible? */
1570 				break;
1571 
1572 			default:
1573 				/*
1574 				 * other cases have been filtered in the above.
1575 				 * none will visit this case.  here we supply
1576 				 * the code just in case (nxt overwritten or
1577 				 * other cases).
1578 				 */
1579 #ifdef PULLDOWN_TEST
1580 				m_freem(ext);
1581 #endif
1582 				goto loopend;
1583 
1584 			}
1585 
1586 			/* proceed with the next header. */
1587 			off += elen;
1588 			nxt = ip6e->ip6e_nxt;
1589 			ip6e = NULL;
1590 #ifdef PULLDOWN_TEST
1591 			m_freem(ext);
1592 			ext = NULL;
1593 #endif
1594 		}
1595 	  loopend:
1596 		;
1597 	}
1598 }
1599 #undef IS2292
1600 
1601 void
1602 ip6_notify_pmtu(struct inpcb *in6p, struct sockaddr_in6 *dst, u_int32_t *mtu)
1603 {
1604 	struct socket *so;
1605 	struct mbuf *m_mtu;
1606 	struct ip6_mtuinfo mtuctl;
1607 
1608 	so =  in6p->inp_socket;
1609 
1610 	if (mtu == NULL)
1611 		return;
1612 
1613 #ifdef DIAGNOSTIC
1614 	if (so == NULL)		/* I believe this is impossible */
1615 		panic("ip6_notify_pmtu: socket is NULL");
1616 #endif
1617 
1618 	bzero(&mtuctl, sizeof(mtuctl));	/* zero-clear for safety */
1619 	mtuctl.ip6m_mtu = *mtu;
1620 	mtuctl.ip6m_addr = *dst;
1621 	if (sa6_recoverscope(&mtuctl.ip6m_addr))
1622 		return;
1623 
1624 	if ((m_mtu = sbcreatecontrol((caddr_t)&mtuctl, sizeof(mtuctl),
1625 	    IPV6_PATHMTU, IPPROTO_IPV6)) == NULL)
1626 		return;
1627 
1628 	if (sbappendaddr(&so->so_rcv, (struct sockaddr *)dst, NULL, m_mtu)
1629 	    == 0) {
1630 		m_freem(m_mtu);
1631 		/* XXX: should count statistics */
1632 	} else
1633 		sorwakeup(so);
1634 
1635 	return;
1636 }
1637 
1638 #ifdef PULLDOWN_TEST
1639 /*
1640  * pull single extension header from mbuf chain.  returns single mbuf that
1641  * contains the result, or NULL on error.
1642  */
1643 static struct mbuf *
1644 ip6_pullexthdr(struct mbuf *m, size_t off, int nxt)
1645 {
1646 	struct ip6_ext ip6e;
1647 	size_t elen;
1648 	struct mbuf *n;
1649 
1650 #ifdef DIAGNOSTIC
1651 	switch (nxt) {
1652 	case IPPROTO_DSTOPTS:
1653 	case IPPROTO_ROUTING:
1654 	case IPPROTO_HOPOPTS:
1655 	case IPPROTO_AH: /* is it possible? */
1656 		break;
1657 	default:
1658 		printf("ip6_pullexthdr: invalid nxt=%d\n", nxt);
1659 	}
1660 #endif
1661 
1662 	m_copydata(m, off, sizeof(ip6e), (caddr_t)&ip6e);
1663 	if (nxt == IPPROTO_AH)
1664 		elen = (ip6e.ip6e_len + 2) << 2;
1665 	else
1666 		elen = (ip6e.ip6e_len + 1) << 3;
1667 
1668 	if (elen > MLEN)
1669 		n = m_getcl(M_NOWAIT, MT_DATA, 0);
1670 	else
1671 		n = m_get(M_NOWAIT, MT_DATA);
1672 	if (n == NULL)
1673 		return NULL;
1674 
1675 	m_copydata(m, off, elen, mtod(n, caddr_t));
1676 	n->m_len = elen;
1677 	return n;
1678 }
1679 #endif
1680 
1681 /*
1682  * Get pointer to the previous header followed by the header
1683  * currently processed.
1684  * XXX: This function supposes that
1685  *	M includes all headers,
1686  *	the next header field and the header length field of each header
1687  *	are valid, and
1688  *	the sum of each header length equals to OFF.
1689  * Because of these assumptions, this function must be called very
1690  * carefully. Moreover, it will not be used in the near future when
1691  * we develop `neater' mechanism to process extension headers.
1692  */
1693 char *
1694 ip6_get_prevhdr(struct mbuf *m, int off)
1695 {
1696 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
1697 
1698 	if (off == sizeof(struct ip6_hdr))
1699 		return (&ip6->ip6_nxt);
1700 	else {
1701 		int len, nxt;
1702 		struct ip6_ext *ip6e = NULL;
1703 
1704 		nxt = ip6->ip6_nxt;
1705 		len = sizeof(struct ip6_hdr);
1706 		while (len < off) {
1707 			ip6e = (struct ip6_ext *)(mtod(m, caddr_t) + len);
1708 
1709 			switch (nxt) {
1710 			case IPPROTO_FRAGMENT:
1711 				len += sizeof(struct ip6_frag);
1712 				break;
1713 			case IPPROTO_AH:
1714 				len += (ip6e->ip6e_len + 2) << 2;
1715 				break;
1716 			default:
1717 				len += (ip6e->ip6e_len + 1) << 3;
1718 				break;
1719 			}
1720 			nxt = ip6e->ip6e_nxt;
1721 		}
1722 		if (ip6e)
1723 			return (&ip6e->ip6e_nxt);
1724 		else
1725 			return NULL;
1726 	}
1727 }
1728 
1729 /*
1730  * get next header offset.  m will be retained.
1731  */
1732 int
1733 ip6_nexthdr(struct mbuf *m, int off, int proto, int *nxtp)
1734 {
1735 	struct ip6_hdr ip6;
1736 	struct ip6_ext ip6e;
1737 	struct ip6_frag fh;
1738 
1739 	/* just in case */
1740 	if (m == NULL)
1741 		panic("ip6_nexthdr: m == NULL");
1742 	if ((m->m_flags & M_PKTHDR) == 0 || m->m_pkthdr.len < off)
1743 		return -1;
1744 
1745 	switch (proto) {
1746 	case IPPROTO_IPV6:
1747 		if (m->m_pkthdr.len < off + sizeof(ip6))
1748 			return -1;
1749 		m_copydata(m, off, sizeof(ip6), (caddr_t)&ip6);
1750 		if (nxtp)
1751 			*nxtp = ip6.ip6_nxt;
1752 		off += sizeof(ip6);
1753 		return off;
1754 
1755 	case IPPROTO_FRAGMENT:
1756 		/*
1757 		 * terminate parsing if it is not the first fragment,
1758 		 * it does not make sense to parse through it.
1759 		 */
1760 		if (m->m_pkthdr.len < off + sizeof(fh))
1761 			return -1;
1762 		m_copydata(m, off, sizeof(fh), (caddr_t)&fh);
1763 		/* IP6F_OFF_MASK = 0xfff8(BigEndian), 0xf8ff(LittleEndian) */
1764 		if (fh.ip6f_offlg & IP6F_OFF_MASK)
1765 			return -1;
1766 		if (nxtp)
1767 			*nxtp = fh.ip6f_nxt;
1768 		off += sizeof(struct ip6_frag);
1769 		return off;
1770 
1771 	case IPPROTO_AH:
1772 		if (m->m_pkthdr.len < off + sizeof(ip6e))
1773 			return -1;
1774 		m_copydata(m, off, sizeof(ip6e), (caddr_t)&ip6e);
1775 		if (nxtp)
1776 			*nxtp = ip6e.ip6e_nxt;
1777 		off += (ip6e.ip6e_len + 2) << 2;
1778 		return off;
1779 
1780 	case IPPROTO_HOPOPTS:
1781 	case IPPROTO_ROUTING:
1782 	case IPPROTO_DSTOPTS:
1783 		if (m->m_pkthdr.len < off + sizeof(ip6e))
1784 			return -1;
1785 		m_copydata(m, off, sizeof(ip6e), (caddr_t)&ip6e);
1786 		if (nxtp)
1787 			*nxtp = ip6e.ip6e_nxt;
1788 		off += (ip6e.ip6e_len + 1) << 3;
1789 		return off;
1790 
1791 	case IPPROTO_NONE:
1792 	case IPPROTO_ESP:
1793 	case IPPROTO_IPCOMP:
1794 		/* give up */
1795 		return -1;
1796 
1797 	default:
1798 		return -1;
1799 	}
1800 
1801 	return -1;
1802 }
1803 
1804 /*
1805  * get offset for the last header in the chain.  m will be kept untainted.
1806  */
1807 int
1808 ip6_lasthdr(struct mbuf *m, int off, int proto, int *nxtp)
1809 {
1810 	int newoff;
1811 	int nxt;
1812 
1813 	if (!nxtp) {
1814 		nxt = -1;
1815 		nxtp = &nxt;
1816 	}
1817 	while (1) {
1818 		newoff = ip6_nexthdr(m, off, proto, nxtp);
1819 		if (newoff < 0)
1820 			return off;
1821 		else if (newoff < off)
1822 			return -1;	/* invalid */
1823 		else if (newoff == off)
1824 			return newoff;
1825 
1826 		off = newoff;
1827 		proto = *nxtp;
1828 	}
1829 }
1830 
1831 static struct ip6aux *
1832 ip6_addaux(struct mbuf *m)
1833 {
1834 	struct m_tag *mtag;
1835 
1836 	mtag = m_tag_find(m, PACKET_TAG_IPV6_INPUT, NULL);
1837 	if (!mtag) {
1838 		mtag = m_tag_get(PACKET_TAG_IPV6_INPUT, sizeof(struct ip6aux),
1839 		    M_NOWAIT);
1840 		if (mtag) {
1841 			m_tag_prepend(m, mtag);
1842 			bzero(mtag + 1, sizeof(struct ip6aux));
1843 		}
1844 	}
1845 	return mtag ? (struct ip6aux *)(mtag + 1) : NULL;
1846 }
1847 
1848 static struct ip6aux *
1849 ip6_findaux(struct mbuf *m)
1850 {
1851 	struct m_tag *mtag;
1852 
1853 	mtag = m_tag_find(m, PACKET_TAG_IPV6_INPUT, NULL);
1854 	return mtag ? (struct ip6aux *)(mtag + 1) : NULL;
1855 }
1856 
1857 static void
1858 ip6_delaux(struct mbuf *m)
1859 {
1860 	struct m_tag *mtag;
1861 
1862 	mtag = m_tag_find(m, PACKET_TAG_IPV6_INPUT, NULL);
1863 	if (mtag)
1864 		m_tag_delete(m, mtag);
1865 }
1866 
1867 /*
1868  * System control for IP6
1869  */
1870 
1871 u_char	inet6ctlerrmap[PRC_NCMDS] = {
1872 	0,		0,		0,		0,
1873 	0,		EMSGSIZE,	EHOSTDOWN,	EHOSTUNREACH,
1874 	EHOSTUNREACH,	EHOSTUNREACH,	ECONNREFUSED,	ECONNREFUSED,
1875 	EMSGSIZE,	EHOSTUNREACH,	0,		0,
1876 	0,		0,		0,		0,
1877 	ENOPROTOOPT
1878 };
1879