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