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