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