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