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