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