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