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