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