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