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