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