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