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