]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet6/ip6_input.c
Merge ^/head r287502 through r287526.
[FreeBSD/FreeBSD.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_ipfw.h"
69 #include "opt_ipsec.h"
70 #include "opt_route.h"
71 #include "opt_rss.h"
72
73 #include <sys/param.h>
74 #include <sys/systm.h>
75 #include <sys/malloc.h>
76 #include <sys/mbuf.h>
77 #include <sys/proc.h>
78 #include <sys/domain.h>
79 #include <sys/protosw.h>
80 #include <sys/sdt.h>
81 #include <sys/socket.h>
82 #include <sys/socketvar.h>
83 #include <sys/errno.h>
84 #include <sys/time.h>
85 #include <sys/kernel.h>
86 #include <sys/lock.h>
87 #include <sys/rmlock.h>
88 #include <sys/syslog.h>
89
90 #include <net/if.h>
91 #include <net/if_var.h>
92 #include <net/if_types.h>
93 #include <net/if_dl.h>
94 #include <net/route.h>
95 #include <net/netisr.h>
96 #include <net/rss_config.h>
97 #include <net/pfil.h>
98 #include <net/vnet.h>
99
100 #include <netinet/in.h>
101 #include <netinet/in_kdtrace.h>
102 #include <netinet/ip_var.h>
103 #include <netinet/in_systm.h>
104 #include <net/if_llatbl.h>
105 #ifdef INET
106 #include <netinet/ip.h>
107 #include <netinet/ip_icmp.h>
108 #endif /* INET */
109 #include <netinet/ip6.h>
110 #include <netinet6/in6_var.h>
111 #include <netinet6/ip6_var.h>
112 #include <netinet/in_pcb.h>
113 #include <netinet/icmp6.h>
114 #include <netinet6/scope6_var.h>
115 #include <netinet6/in6_ifattach.h>
116 #include <netinet6/nd6.h>
117 #include <netinet6/in6_rss.h>
118
119 #ifdef IPSEC
120 #include <netipsec/ipsec.h>
121 #include <netinet6/ip6_ipsec.h>
122 #include <netipsec/ipsec6.h>
123 #endif /* IPSEC */
124
125 #include <netinet6/ip6protosw.h>
126
127 extern struct domain inet6domain;
128
129 u_char ip6_protox[IPPROTO_MAX];
130 VNET_DEFINE(struct in6_ifaddrhead, in6_ifaddrhead);
131 VNET_DEFINE(struct in6_ifaddrlisthead *, in6_ifaddrhashtbl);
132 VNET_DEFINE(u_long, in6_ifaddrhmask);
133
134 static struct netisr_handler ip6_nh = {
135         .nh_name = "ip6",
136         .nh_handler = ip6_input,
137         .nh_proto = NETISR_IPV6,
138 #ifdef RSS
139         .nh_m2cpuid = rss_soft_m2cpuid_v6,
140         .nh_policy = NETISR_POLICY_CPU,
141         .nh_dispatch = NETISR_DISPATCH_HYBRID,
142 #else
143         .nh_policy = NETISR_POLICY_FLOW,
144 #endif
145 };
146
147 VNET_DECLARE(struct callout, in6_tmpaddrtimer_ch);
148 #define V_in6_tmpaddrtimer_ch           VNET(in6_tmpaddrtimer_ch)
149
150 VNET_DEFINE(struct pfil_head, inet6_pfil_hook);
151
152 VNET_PCPUSTAT_DEFINE(struct ip6stat, ip6stat);
153 VNET_PCPUSTAT_SYSINIT(ip6stat);
154 #ifdef VIMAGE
155 VNET_PCPUSTAT_SYSUNINIT(ip6stat);
156 #endif /* VIMAGE */
157
158 struct rmlock in6_ifaddr_lock;
159 RM_SYSINIT(in6_ifaddr_lock, &in6_ifaddr_lock, "in6_ifaddr_lock");
160
161 static void ip6_init2(void *);
162 static int ip6_hopopts_input(u_int32_t *, u_int32_t *, struct mbuf **, int *);
163 #ifdef PULLDOWN_TEST
164 static struct mbuf *ip6_pullexthdr(struct mbuf *, size_t, int);
165 #endif
166
167 /*
168  * IP6 initialization: fill in IP6 protocol switch table.
169  * All protocols not implemented in kernel go to raw IP6 protocol handler.
170  */
171 void
172 ip6_init(void)
173 {
174         struct protosw *pr;
175         int i;
176
177         TUNABLE_INT_FETCH("net.inet6.ip6.auto_linklocal",
178             &V_ip6_auto_linklocal);
179         TUNABLE_INT_FETCH("net.inet6.ip6.accept_rtadv", &V_ip6_accept_rtadv);
180         TUNABLE_INT_FETCH("net.inet6.ip6.no_radr", &V_ip6_no_radr);
181
182         TAILQ_INIT(&V_in6_ifaddrhead);
183         V_in6_ifaddrhashtbl = hashinit(IN6ADDR_NHASH, M_IFADDR,
184             &V_in6_ifaddrhmask);
185
186         /* Initialize packet filter hooks. */
187         V_inet6_pfil_hook.ph_type = PFIL_TYPE_AF;
188         V_inet6_pfil_hook.ph_af = AF_INET6;
189         if ((i = pfil_head_register(&V_inet6_pfil_hook)) != 0)
190                 printf("%s: WARNING: unable to register pfil hook, "
191                         "error %d\n", __func__, i);
192
193         scope6_init();
194         addrsel_policy_init();
195         nd6_init();
196         frag6_init();
197
198         V_ip6_desync_factor = arc4random() % MAX_TEMP_DESYNC_FACTOR;
199
200         /* Skip global initialization stuff for non-default instances. */
201         if (!IS_DEFAULT_VNET(curvnet))
202                 return;
203
204         pr = pffindproto(PF_INET6, IPPROTO_RAW, SOCK_RAW);
205         if (pr == NULL)
206                 panic("ip6_init");
207
208         /* Initialize the entire ip6_protox[] array to IPPROTO_RAW. */
209         for (i = 0; i < IPPROTO_MAX; i++)
210                 ip6_protox[i] = pr - inet6sw;
211         /*
212          * Cycle through IP protocols and put them into the appropriate place
213          * in ip6_protox[].
214          */
215         for (pr = inet6domain.dom_protosw;
216             pr < inet6domain.dom_protoswNPROTOSW; pr++)
217                 if (pr->pr_domain->dom_family == PF_INET6 &&
218                     pr->pr_protocol && pr->pr_protocol != IPPROTO_RAW) {
219                         /* Be careful to only index valid IP protocols. */
220                         if (pr->pr_protocol < IPPROTO_MAX)
221                                 ip6_protox[pr->pr_protocol] = pr - inet6sw;
222                 }
223
224         netisr_register(&ip6_nh);
225 }
226
227 /*
228  * The protocol to be inserted into ip6_protox[] must be already registered
229  * in inet6sw[], either statically or through pf_proto_register().
230  */
231 int
232 ip6proto_register(short ip6proto)
233 {
234         struct protosw *pr;
235
236         /* Sanity checks. */
237         if (ip6proto <= 0 || ip6proto >= IPPROTO_MAX)
238                 return (EPROTONOSUPPORT);
239
240         /*
241          * The protocol slot must not be occupied by another protocol
242          * already.  An index pointing to IPPROTO_RAW is unused.
243          */
244         pr = pffindproto(PF_INET6, IPPROTO_RAW, SOCK_RAW);
245         if (pr == NULL)
246                 return (EPFNOSUPPORT);
247         if (ip6_protox[ip6proto] != pr - inet6sw)       /* IPPROTO_RAW */
248                 return (EEXIST);
249
250         /*
251          * Find the protocol position in inet6sw[] and set the index.
252          */
253         for (pr = inet6domain.dom_protosw;
254             pr < inet6domain.dom_protoswNPROTOSW; pr++) {
255                 if (pr->pr_domain->dom_family == PF_INET6 &&
256                     pr->pr_protocol && pr->pr_protocol == ip6proto) {
257                         ip6_protox[pr->pr_protocol] = pr - inet6sw;
258                         return (0);
259                 }
260         }
261         return (EPROTONOSUPPORT);
262 }
263
264 int
265 ip6proto_unregister(short ip6proto)
266 {
267         struct protosw *pr;
268
269         /* Sanity checks. */
270         if (ip6proto <= 0 || ip6proto >= IPPROTO_MAX)
271                 return (EPROTONOSUPPORT);
272
273         /* Check if the protocol was indeed registered. */
274         pr = pffindproto(PF_INET6, IPPROTO_RAW, SOCK_RAW);
275         if (pr == NULL)
276                 return (EPFNOSUPPORT);
277         if (ip6_protox[ip6proto] == pr - inet6sw)       /* IPPROTO_RAW */
278                 return (ENOENT);
279
280         /* Reset the protocol slot to IPPROTO_RAW. */
281         ip6_protox[ip6proto] = pr - inet6sw;
282         return (0);
283 }
284
285 #ifdef VIMAGE
286 void
287 ip6_destroy()
288 {
289         int i;
290
291         if ((i = pfil_head_unregister(&V_inet6_pfil_hook)) != 0)
292                 printf("%s: WARNING: unable to unregister pfil hook, "
293                     "error %d\n", __func__, i);
294         hashdestroy(V_in6_ifaddrhashtbl, M_IFADDR, V_in6_ifaddrhmask);
295         nd6_destroy();
296         callout_drain(&V_in6_tmpaddrtimer_ch);
297 }
298 #endif
299
300 static int
301 ip6_init2_vnet(const void *unused __unused)
302 {
303
304         /* nd6_timer_init */
305         callout_init(&V_nd6_timer_ch, 0);
306         callout_reset(&V_nd6_timer_ch, hz, nd6_timer, curvnet);
307
308         /* timer for regeneranation of temporary addresses randomize ID */
309         callout_init(&V_in6_tmpaddrtimer_ch, 0);
310         callout_reset(&V_in6_tmpaddrtimer_ch,
311                       (V_ip6_temp_preferred_lifetime - V_ip6_desync_factor -
312                        V_ip6_temp_regen_advance) * hz,
313                       in6_tmpaddrtimer, curvnet);
314
315         return (0);
316 }
317
318 static void
319 ip6_init2(void *dummy)
320 {
321
322         ip6_init2_vnet(NULL);
323 }
324
325 /* cheat */
326 /* This must be after route_init(), which is now SI_ORDER_THIRD */
327 SYSINIT(netinet6init2, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE, ip6_init2, NULL);
328
329 static int
330 ip6_input_hbh(struct mbuf *m, uint32_t *plen, uint32_t *rtalert, int *off,
331     int *nxt, int *ours)
332 {
333         struct ip6_hdr *ip6;
334         struct ip6_hbh *hbh;
335
336         if (ip6_hopopts_input(plen, rtalert, &m, off)) {
337 #if 0   /*touches NULL pointer*/
338                 in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_discard);
339 #endif
340                 goto out;       /* m have already been freed */
341         }
342
343         /* adjust pointer */
344         ip6 = mtod(m, struct ip6_hdr *);
345
346         /*
347          * if the payload length field is 0 and the next header field
348          * indicates Hop-by-Hop Options header, then a Jumbo Payload
349          * option MUST be included.
350          */
351         if (ip6->ip6_plen == 0 && *plen == 0) {
352                 /*
353                  * Note that if a valid jumbo payload option is
354                  * contained, ip6_hopopts_input() must set a valid
355                  * (non-zero) payload length to the variable plen.
356                  */
357                 IP6STAT_INC(ip6s_badoptions);
358                 in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_discard);
359                 in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_hdrerr);
360                 icmp6_error(m, ICMP6_PARAM_PROB,
361                             ICMP6_PARAMPROB_HEADER,
362                             (caddr_t)&ip6->ip6_plen - (caddr_t)ip6);
363                 goto out;
364         }
365 #ifndef PULLDOWN_TEST
366         /* ip6_hopopts_input() ensures that mbuf is contiguous */
367         hbh = (struct ip6_hbh *)(ip6 + 1);
368 #else
369         IP6_EXTHDR_GET(hbh, struct ip6_hbh *, m, sizeof(struct ip6_hdr),
370                 sizeof(struct ip6_hbh));
371         if (hbh == NULL) {
372                 IP6STAT_INC(ip6s_tooshort);
373                 goto out;
374         }
375 #endif
376         *nxt = hbh->ip6h_nxt;
377
378         /*
379          * If we are acting as a router and the packet contains a
380          * router alert option, see if we know the option value.
381          * Currently, we only support the option value for MLD, in which
382          * case we should pass the packet to the multicast routing
383          * daemon.
384          */
385         if (*rtalert != ~0) {
386                 switch (*rtalert) {
387                 case IP6OPT_RTALERT_MLD:
388                         if (V_ip6_forwarding)
389                                 *ours = 1;
390                         break;
391                 default:
392                         /*
393                          * RFC2711 requires unrecognized values must be
394                          * silently ignored.
395                          */
396                         break;
397                 }
398         }
399
400         return (0);
401
402 out:
403         return (1);
404 }
405
406 void
407 ip6_input(struct mbuf *m)
408 {
409         struct in6_addr odst;
410         struct ip6_hdr *ip6;
411         struct in6_ifaddr *ia;
412         u_int32_t plen;
413         u_int32_t rtalert = ~0;
414         int off = sizeof(struct ip6_hdr), nest;
415         int nxt, ours = 0;
416         int srcrt = 0;
417
418 #ifdef IPSEC
419         /*
420          * should the inner packet be considered authentic?
421          * see comment in ah4_input().
422          * NB: m cannot be NULL when passed to the input routine
423          */
424
425         m->m_flags &= ~M_AUTHIPHDR;
426         m->m_flags &= ~M_AUTHIPDGM;
427
428 #endif /* IPSEC */
429
430         if (m->m_flags & M_FASTFWD_OURS) {
431                 /*
432                  * Firewall changed destination to local.
433                  */
434                 m->m_flags &= ~M_FASTFWD_OURS;
435                 ours = 1;
436                 ip6 = mtod(m, struct ip6_hdr *);
437                 goto hbhcheck;
438         }
439
440         /*
441          * mbuf statistics
442          */
443         if (m->m_flags & M_EXT) {
444                 if (m->m_next)
445                         IP6STAT_INC(ip6s_mext2m);
446                 else
447                         IP6STAT_INC(ip6s_mext1);
448         } else {
449                 if (m->m_next) {
450                         if (m->m_flags & M_LOOP) {
451                                 IP6STAT_INC(ip6s_m2m[V_loif->if_index]);
452                         } else if (m->m_pkthdr.rcvif->if_index < IP6S_M2MMAX)
453                                 IP6STAT_INC(
454                                     ip6s_m2m[m->m_pkthdr.rcvif->if_index]);
455                         else
456                                 IP6STAT_INC(ip6s_m2m[0]);
457                 } else
458                         IP6STAT_INC(ip6s_m1);
459         }
460
461         /* drop the packet if IPv6 operation is disabled on the IF */
462         if ((ND_IFINFO(m->m_pkthdr.rcvif)->flags & ND6_IFF_IFDISABLED))
463                 goto bad;
464
465         in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_receive);
466         IP6STAT_INC(ip6s_total);
467
468 #ifndef PULLDOWN_TEST
469         /*
470          * L2 bridge code and some other code can return mbuf chain
471          * that does not conform to KAME requirement.  too bad.
472          * XXX: fails to join if interface MTU > MCLBYTES.  jumbogram?
473          */
474         if (m && m->m_next != NULL && m->m_pkthdr.len < MCLBYTES) {
475                 struct mbuf *n;
476
477                 if (m->m_pkthdr.len > MHLEN)
478                         n = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
479                 else
480                         n = m_gethdr(M_NOWAIT, MT_DATA);
481                 if (n == NULL) {
482                         m_freem(m);
483                         return; /* ENOBUFS */
484                 }
485
486                 m_move_pkthdr(n, m);
487                 m_copydata(m, 0, n->m_pkthdr.len, mtod(n, caddr_t));
488                 n->m_len = n->m_pkthdr.len;
489                 m_freem(m);
490                 m = n;
491         }
492         IP6_EXTHDR_CHECK(m, 0, sizeof(struct ip6_hdr), /* nothing */);
493 #endif
494
495         if (m->m_len < sizeof(struct ip6_hdr)) {
496                 struct ifnet *inifp;
497                 inifp = m->m_pkthdr.rcvif;
498                 if ((m = m_pullup(m, sizeof(struct ip6_hdr))) == NULL) {
499                         IP6STAT_INC(ip6s_toosmall);
500                         in6_ifstat_inc(inifp, ifs6_in_hdrerr);
501                         return;
502                 }
503         }
504
505         ip6 = mtod(m, struct ip6_hdr *);
506
507         if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION) {
508                 IP6STAT_INC(ip6s_badvers);
509                 in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_hdrerr);
510                 goto bad;
511         }
512
513         IP6STAT_INC(ip6s_nxthist[ip6->ip6_nxt]);
514
515         IP_PROBE(receive, NULL, NULL, ip6, m->m_pkthdr.rcvif, NULL, ip6);
516
517         /*
518          * Check against address spoofing/corruption.
519          */
520         if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_src) ||
521             IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_dst)) {
522                 /*
523                  * XXX: "badscope" is not very suitable for a multicast source.
524                  */
525                 IP6STAT_INC(ip6s_badscope);
526                 in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_addrerr);
527                 goto bad;
528         }
529         if (IN6_IS_ADDR_MC_INTFACELOCAL(&ip6->ip6_dst) &&
530             !(m->m_flags & M_LOOP)) {
531                 /*
532                  * In this case, the packet should come from the loopback
533                  * interface.  However, we cannot just check the if_flags,
534                  * because ip6_mloopback() passes the "actual" interface
535                  * as the outgoing/incoming interface.
536                  */
537                 IP6STAT_INC(ip6s_badscope);
538                 in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_addrerr);
539                 goto bad;
540         }
541         if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) &&
542             IPV6_ADDR_MC_SCOPE(&ip6->ip6_dst) == 0) {
543                 /*
544                  * RFC4291 2.7:
545                  * Nodes must not originate a packet to a multicast address
546                  * whose scop field contains the reserved value 0; if such
547                  * a packet is received, it must be silently dropped.
548                  */
549                 IP6STAT_INC(ip6s_badscope);
550                 in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_addrerr);
551                 goto bad;
552         }
553 #ifdef ALTQ
554         if (altq_input != NULL && (*altq_input)(m, AF_INET6) == 0) {
555                 /* packet is dropped by traffic conditioner */
556                 return;
557         }
558 #endif
559         /*
560          * The following check is not documented in specs.  A malicious
561          * party may be able to use IPv4 mapped addr to confuse tcp/udp stack
562          * and bypass security checks (act as if it was from 127.0.0.1 by using
563          * IPv6 src ::ffff:127.0.0.1).  Be cautious.
564          *
565          * This check chokes if we are in an SIIT cloud.  As none of BSDs
566          * support IPv4-less kernel compilation, we cannot support SIIT
567          * environment at all.  So, it makes more sense for us to reject any
568          * malicious packets for non-SIIT environment, than try to do a
569          * partial support for SIIT environment.
570          */
571         if (IN6_IS_ADDR_V4MAPPED(&ip6->ip6_src) ||
572             IN6_IS_ADDR_V4MAPPED(&ip6->ip6_dst)) {
573                 IP6STAT_INC(ip6s_badscope);
574                 in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_addrerr);
575                 goto bad;
576         }
577 #if 0
578         /*
579          * Reject packets with IPv4 compatible addresses (auto tunnel).
580          *
581          * The code forbids auto tunnel relay case in RFC1933 (the check is
582          * stronger than RFC1933).  We may want to re-enable it if mech-xx
583          * is revised to forbid relaying case.
584          */
585         if (IN6_IS_ADDR_V4COMPAT(&ip6->ip6_src) ||
586             IN6_IS_ADDR_V4COMPAT(&ip6->ip6_dst)) {
587                 IP6STAT_INC(ip6s_badscope);
588                 in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_addrerr);
589                 goto bad;
590         }
591 #endif
592 #ifdef IPSEC
593         /*
594          * Bypass packet filtering for packets previously handled by IPsec.
595          */
596         if (ip6_ipsec_filtertunnel(m))
597                 goto passin;
598 #endif /* IPSEC */
599
600         /*
601          * Run through list of hooks for input packets.
602          *
603          * NB: Beware of the destination address changing
604          *     (e.g. by NAT rewriting).  When this happens,
605          *     tell ip6_forward to do the right thing.
606          */
607         odst = ip6->ip6_dst;
608
609         /* Jump over all PFIL processing if hooks are not active. */
610         if (!PFIL_HOOKED(&V_inet6_pfil_hook))
611                 goto passin;
612
613         if (pfil_run_hooks(&V_inet6_pfil_hook, &m,
614             m->m_pkthdr.rcvif, PFIL_IN, NULL))
615                 return;
616         if (m == NULL)                  /* consumed by filter */
617                 return;
618         ip6 = mtod(m, struct ip6_hdr *);
619         srcrt = !IN6_ARE_ADDR_EQUAL(&odst, &ip6->ip6_dst);
620
621         if (m->m_flags & M_FASTFWD_OURS) {
622                 m->m_flags &= ~M_FASTFWD_OURS;
623                 ours = 1;
624                 goto hbhcheck;
625         }
626         if ((m->m_flags & M_IP6_NEXTHOP) &&
627             m_tag_find(m, PACKET_TAG_IPFORWARD, NULL) != NULL) {
628                 /*
629                  * Directly ship the packet on.  This allows forwarding
630                  * packets originally destined to us to some other directly
631                  * connected host.
632                  */
633                 ip6_forward(m, 1);
634                 return;
635         }
636
637 passin:
638         /*
639          * Disambiguate address scope zones (if there is ambiguity).
640          * We first make sure that the original source or destination address
641          * is not in our internal form for scoped addresses.  Such addresses
642          * are not necessarily invalid spec-wise, but we cannot accept them due
643          * to the usage conflict.
644          * in6_setscope() then also checks and rejects the cases where src or
645          * dst are the loopback address and the receiving interface
646          * is not loopback.
647          */
648         if (in6_clearscope(&ip6->ip6_src) || in6_clearscope(&ip6->ip6_dst)) {
649                 IP6STAT_INC(ip6s_badscope); /* XXX */
650                 goto bad;
651         }
652         if (in6_setscope(&ip6->ip6_src, m->m_pkthdr.rcvif, NULL) ||
653             in6_setscope(&ip6->ip6_dst, m->m_pkthdr.rcvif, NULL)) {
654                 IP6STAT_INC(ip6s_badscope);
655                 goto bad;
656         }
657         /*
658          * Multicast check. Assume packet is for us to avoid
659          * prematurely taking locks.
660          */
661         if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
662                 ours = 1;
663                 in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_mcast);
664                 goto hbhcheck;
665         }
666         /*
667          * Unicast check
668          * XXX: For now we keep link-local IPv6 addresses with embedded
669          *      scope zone id, therefore we use zero zoneid here.
670          */
671         ia = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */);
672         if (ia != NULL) {
673                 if (ia->ia6_flags & IN6_IFF_NOTREADY) {
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                         ifa_free(&ia->ia_ifa);
682                         goto bad;
683                 }
684                 /* Count the packet in the ip address stats */
685                 counter_u64_add(ia->ia_ifa.ifa_ipackets, 1);
686                 counter_u64_add(ia->ia_ifa.ifa_ibytes, m->m_pkthdr.len);
687                 ifa_free(&ia->ia_ifa);
688                 ours = 1;
689                 goto hbhcheck;
690         }
691
692         /*
693          * Now there is no reason to process the packet if it's not our own
694          * and we're not a router.
695          */
696         if (!V_ip6_forwarding) {
697                 IP6STAT_INC(ip6s_cantforward);
698                 in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_discard);
699                 goto bad;
700         }
701
702   hbhcheck:
703         /*
704          * Process Hop-by-Hop options header if it's contained.
705          * m may be modified in ip6_hopopts_input().
706          * If a JumboPayload option is included, plen will also be modified.
707          */
708         plen = (u_int32_t)ntohs(ip6->ip6_plen);
709         if (ip6->ip6_nxt == IPPROTO_HOPOPTS) {
710                 if (ip6_input_hbh(m, &plen, &rtalert, &off, &nxt, &ours) != 0)
711                         return;
712         } else
713                 nxt = ip6->ip6_nxt;
714
715         /*
716          * Check that the amount of data in the buffers
717          * is as at least much as the IPv6 header would have us expect.
718          * Trim mbufs if longer than we expect.
719          * Drop packet if shorter than we expect.
720          */
721         if (m->m_pkthdr.len - sizeof(struct ip6_hdr) < plen) {
722                 IP6STAT_INC(ip6s_tooshort);
723                 in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_truncated);
724                 goto bad;
725         }
726         if (m->m_pkthdr.len > sizeof(struct ip6_hdr) + plen) {
727                 if (m->m_len == m->m_pkthdr.len) {
728                         m->m_len = sizeof(struct ip6_hdr) + plen;
729                         m->m_pkthdr.len = sizeof(struct ip6_hdr) + plen;
730                 } else
731                         m_adj(m, sizeof(struct ip6_hdr) + plen - m->m_pkthdr.len);
732         }
733
734         /*
735          * Forward if desirable.
736          */
737         if (V_ip6_mrouter &&
738             IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
739                 /*
740                  * If we are acting as a multicast router, all
741                  * incoming multicast packets are passed to the
742                  * kernel-level multicast forwarding function.
743                  * The packet is returned (relatively) intact; if
744                  * ip6_mforward() returns a non-zero value, the packet
745                  * must be discarded, else it may be accepted below.
746                  *
747                  * XXX TODO: Check hlim and multicast scope here to avoid
748                  * unnecessarily calling into ip6_mforward().
749                  */
750                 if (ip6_mforward &&
751                     ip6_mforward(ip6, m->m_pkthdr.rcvif, m)) {
752                         IP6STAT_INC(ip6s_cantforward);
753                         in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_discard);
754                         goto bad;
755                 }
756         } else if (!ours) {
757                 ip6_forward(m, srcrt);
758                 return;
759         }
760
761         ip6 = mtod(m, struct ip6_hdr *);
762
763         /*
764          * Malicious party may be able to use IPv4 mapped addr to confuse
765          * tcp/udp stack and bypass security checks (act as if it was from
766          * 127.0.0.1 by using IPv6 src ::ffff:127.0.0.1).  Be cautious.
767          *
768          * For SIIT end node behavior, you may want to disable the check.
769          * However, you will  become vulnerable to attacks using IPv4 mapped
770          * source.
771          */
772         if (IN6_IS_ADDR_V4MAPPED(&ip6->ip6_src) ||
773             IN6_IS_ADDR_V4MAPPED(&ip6->ip6_dst)) {
774                 IP6STAT_INC(ip6s_badscope);
775                 in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_addrerr);
776                 goto bad;
777         }
778
779         /*
780          * Tell launch routine the next header
781          */
782         IP6STAT_INC(ip6s_delivered);
783         in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_deliver);
784         nest = 0;
785
786         while (nxt != IPPROTO_DONE) {
787                 if (V_ip6_hdrnestlimit && (++nest > V_ip6_hdrnestlimit)) {
788                         IP6STAT_INC(ip6s_toomanyhdr);
789                         goto bad;
790                 }
791
792                 /*
793                  * protection against faulty packet - there should be
794                  * more sanity checks in header chain processing.
795                  */
796                 if (m->m_pkthdr.len < off) {
797                         IP6STAT_INC(ip6s_tooshort);
798                         in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_truncated);
799                         goto bad;
800                 }
801
802 #ifdef IPSEC
803                 /*
804                  * enforce IPsec policy checking if we are seeing last header.
805                  * note that we do not visit this with protocols with pcb layer
806                  * code - like udp/tcp/raw ip.
807                  */
808                 if (ip6_ipsec_input(m, nxt))
809                         goto bad;
810 #endif /* IPSEC */
811
812                 /*
813                  * Use mbuf flags to propagate Router Alert option to
814                  * ICMPv6 layer, as hop-by-hop options have been stripped.
815                  */
816                 if (nxt == IPPROTO_ICMPV6 && rtalert != ~0)
817                         m->m_flags |= M_RTALERT_MLD;
818
819                 nxt = (*inet6sw[ip6_protox[nxt]].pr_input)(&m, &off, nxt);
820         }
821         return;
822 bad:
823         m_freem(m);
824 }
825
826 /*
827  * Hop-by-Hop options header processing. If a valid jumbo payload option is
828  * included, the real payload length will be stored in plenp.
829  *
830  * rtalertp - XXX: should be stored more smart way
831  */
832 static int
833 ip6_hopopts_input(u_int32_t *plenp, u_int32_t *rtalertp,
834     struct mbuf **mp, int *offp)
835 {
836         struct mbuf *m = *mp;
837         int off = *offp, hbhlen;
838         struct ip6_hbh *hbh;
839
840         /* validation of the length of the header */
841 #ifndef PULLDOWN_TEST
842         IP6_EXTHDR_CHECK(m, off, sizeof(*hbh), -1);
843         hbh = (struct ip6_hbh *)(mtod(m, caddr_t) + off);
844         hbhlen = (hbh->ip6h_len + 1) << 3;
845
846         IP6_EXTHDR_CHECK(m, off, hbhlen, -1);
847         hbh = (struct ip6_hbh *)(mtod(m, caddr_t) + off);
848 #else
849         IP6_EXTHDR_GET(hbh, struct ip6_hbh *, m,
850                 sizeof(struct ip6_hdr), sizeof(struct ip6_hbh));
851         if (hbh == NULL) {
852                 IP6STAT_INC(ip6s_tooshort);
853                 return -1;
854         }
855         hbhlen = (hbh->ip6h_len + 1) << 3;
856         IP6_EXTHDR_GET(hbh, struct ip6_hbh *, m, sizeof(struct ip6_hdr),
857                 hbhlen);
858         if (hbh == NULL) {
859                 IP6STAT_INC(ip6s_tooshort);
860                 return -1;
861         }
862 #endif
863         off += hbhlen;
864         hbhlen -= sizeof(struct ip6_hbh);
865         if (ip6_process_hopopts(m, (u_int8_t *)hbh + sizeof(struct ip6_hbh),
866                                 hbhlen, rtalertp, plenp) < 0)
867                 return (-1);
868
869         *offp = off;
870         *mp = m;
871         return (0);
872 }
873
874 /*
875  * Search header for all Hop-by-hop options and process each option.
876  * This function is separate from ip6_hopopts_input() in order to
877  * handle a case where the sending node itself process its hop-by-hop
878  * options header. In such a case, the function is called from ip6_output().
879  *
880  * The function assumes that hbh header is located right after the IPv6 header
881  * (RFC2460 p7), opthead is pointer into data content in m, and opthead to
882  * opthead + hbhlen is located in contiguous memory region.
883  */
884 int
885 ip6_process_hopopts(struct mbuf *m, u_int8_t *opthead, int hbhlen,
886     u_int32_t *rtalertp, u_int32_t *plenp)
887 {
888         struct ip6_hdr *ip6;
889         int optlen = 0;
890         u_int8_t *opt = opthead;
891         u_int16_t rtalert_val;
892         u_int32_t jumboplen;
893         const int erroff = sizeof(struct ip6_hdr) + sizeof(struct ip6_hbh);
894
895         for (; hbhlen > 0; hbhlen -= optlen, opt += optlen) {
896                 switch (*opt) {
897                 case IP6OPT_PAD1:
898                         optlen = 1;
899                         break;
900                 case IP6OPT_PADN:
901                         if (hbhlen < IP6OPT_MINLEN) {
902                                 IP6STAT_INC(ip6s_toosmall);
903                                 goto bad;
904                         }
905                         optlen = *(opt + 1) + 2;
906                         break;
907                 case IP6OPT_ROUTER_ALERT:
908                         /* XXX may need check for alignment */
909                         if (hbhlen < IP6OPT_RTALERT_LEN) {
910                                 IP6STAT_INC(ip6s_toosmall);
911                                 goto bad;
912                         }
913                         if (*(opt + 1) != IP6OPT_RTALERT_LEN - 2) {
914                                 /* XXX stat */
915                                 icmp6_error(m, ICMP6_PARAM_PROB,
916                                     ICMP6_PARAMPROB_HEADER,
917                                     erroff + opt + 1 - opthead);
918                                 return (-1);
919                         }
920                         optlen = IP6OPT_RTALERT_LEN;
921                         bcopy((caddr_t)(opt + 2), (caddr_t)&rtalert_val, 2);
922                         *rtalertp = ntohs(rtalert_val);
923                         break;
924                 case IP6OPT_JUMBO:
925                         /* XXX may need check for alignment */
926                         if (hbhlen < IP6OPT_JUMBO_LEN) {
927                                 IP6STAT_INC(ip6s_toosmall);
928                                 goto bad;
929                         }
930                         if (*(opt + 1) != IP6OPT_JUMBO_LEN - 2) {
931                                 /* XXX stat */
932                                 icmp6_error(m, ICMP6_PARAM_PROB,
933                                     ICMP6_PARAMPROB_HEADER,
934                                     erroff + opt + 1 - opthead);
935                                 return (-1);
936                         }
937                         optlen = IP6OPT_JUMBO_LEN;
938
939                         /*
940                          * IPv6 packets that have non 0 payload length
941                          * must not contain a jumbo payload option.
942                          */
943                         ip6 = mtod(m, struct ip6_hdr *);
944                         if (ip6->ip6_plen) {
945                                 IP6STAT_INC(ip6s_badoptions);
946                                 icmp6_error(m, ICMP6_PARAM_PROB,
947                                     ICMP6_PARAMPROB_HEADER,
948                                     erroff + opt - opthead);
949                                 return (-1);
950                         }
951
952                         /*
953                          * We may see jumbolen in unaligned location, so
954                          * we'd need to perform bcopy().
955                          */
956                         bcopy(opt + 2, &jumboplen, sizeof(jumboplen));
957                         jumboplen = (u_int32_t)htonl(jumboplen);
958
959 #if 1
960                         /*
961                          * if there are multiple jumbo payload options,
962                          * *plenp will be non-zero and the packet will be
963                          * rejected.
964                          * the behavior may need some debate in ipngwg -
965                          * multiple options does not make sense, however,
966                          * there's no explicit mention in specification.
967                          */
968                         if (*plenp != 0) {
969                                 IP6STAT_INC(ip6s_badoptions);
970                                 icmp6_error(m, ICMP6_PARAM_PROB,
971                                     ICMP6_PARAMPROB_HEADER,
972                                     erroff + opt + 2 - opthead);
973                                 return (-1);
974                         }
975 #endif
976
977                         /*
978                          * jumbo payload length must be larger than 65535.
979                          */
980                         if (jumboplen <= IPV6_MAXPACKET) {
981                                 IP6STAT_INC(ip6s_badoptions);
982                                 icmp6_error(m, ICMP6_PARAM_PROB,
983                                     ICMP6_PARAMPROB_HEADER,
984                                     erroff + opt + 2 - opthead);
985                                 return (-1);
986                         }
987                         *plenp = jumboplen;
988
989                         break;
990                 default:                /* unknown option */
991                         if (hbhlen < IP6OPT_MINLEN) {
992                                 IP6STAT_INC(ip6s_toosmall);
993                                 goto bad;
994                         }
995                         optlen = ip6_unknown_opt(opt, m,
996                             erroff + opt - opthead);
997                         if (optlen == -1)
998                                 return (-1);
999                         optlen += 2;
1000                         break;
1001                 }
1002         }
1003
1004         return (0);
1005
1006   bad:
1007         m_freem(m);
1008         return (-1);
1009 }
1010
1011 /*
1012  * Unknown option processing.
1013  * The third argument `off' is the offset from the IPv6 header to the option,
1014  * which is necessary if the IPv6 header the and option header and IPv6 header
1015  * is not contiguous in order to return an ICMPv6 error.
1016  */
1017 int
1018 ip6_unknown_opt(u_int8_t *optp, struct mbuf *m, int off)
1019 {
1020         struct ip6_hdr *ip6;
1021
1022         switch (IP6OPT_TYPE(*optp)) {
1023         case IP6OPT_TYPE_SKIP: /* ignore the option */
1024                 return ((int)*(optp + 1));
1025         case IP6OPT_TYPE_DISCARD:       /* silently discard */
1026                 m_freem(m);
1027                 return (-1);
1028         case IP6OPT_TYPE_FORCEICMP: /* send ICMP even if multicasted */
1029                 IP6STAT_INC(ip6s_badoptions);
1030                 icmp6_error(m, ICMP6_PARAM_PROB, ICMP6_PARAMPROB_OPTION, off);
1031                 return (-1);
1032         case IP6OPT_TYPE_ICMP: /* send ICMP if not multicasted */
1033                 IP6STAT_INC(ip6s_badoptions);
1034                 ip6 = mtod(m, struct ip6_hdr *);
1035                 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
1036                     (m->m_flags & (M_BCAST|M_MCAST)))
1037                         m_freem(m);
1038                 else
1039                         icmp6_error(m, ICMP6_PARAM_PROB,
1040                                     ICMP6_PARAMPROB_OPTION, off);
1041                 return (-1);
1042         }
1043
1044         m_freem(m);             /* XXX: NOTREACHED */
1045         return (-1);
1046 }
1047
1048 /*
1049  * Create the "control" list for this pcb.
1050  * These functions will not modify mbuf chain at all.
1051  *
1052  * With KAME mbuf chain restriction:
1053  * The routine will be called from upper layer handlers like tcp6_input().
1054  * Thus the routine assumes that the caller (tcp6_input) have already
1055  * called IP6_EXTHDR_CHECK() and all the extension headers are located in the
1056  * very first mbuf on the mbuf chain.
1057  *
1058  * ip6_savecontrol_v4 will handle those options that are possible to be
1059  * set on a v4-mapped socket.
1060  * ip6_savecontrol will directly call ip6_savecontrol_v4 to handle those
1061  * options and handle the v6-only ones itself.
1062  */
1063 struct mbuf **
1064 ip6_savecontrol_v4(struct inpcb *inp, struct mbuf *m, struct mbuf **mp,
1065     int *v4only)
1066 {
1067         struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
1068
1069 #ifdef SO_TIMESTAMP
1070         if ((inp->inp_socket->so_options & SO_TIMESTAMP) != 0) {
1071                 struct timeval tv;
1072
1073                 microtime(&tv);
1074                 *mp = sbcreatecontrol((caddr_t) &tv, sizeof(tv),
1075                     SCM_TIMESTAMP, SOL_SOCKET);
1076                 if (*mp)
1077                         mp = &(*mp)->m_next;
1078         }
1079 #endif
1080
1081 #define IS2292(inp, x, y)       (((inp)->inp_flags & IN6P_RFC2292) ? (x) : (y))
1082         /* RFC 2292 sec. 5 */
1083         if ((inp->inp_flags & IN6P_PKTINFO) != 0) {
1084                 struct in6_pktinfo pi6;
1085
1086                 if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION) {
1087 #ifdef INET
1088                         struct ip *ip;
1089
1090                         ip = mtod(m, struct ip *);
1091                         pi6.ipi6_addr.s6_addr32[0] = 0;
1092                         pi6.ipi6_addr.s6_addr32[1] = 0;
1093                         pi6.ipi6_addr.s6_addr32[2] = IPV6_ADDR_INT32_SMP;
1094                         pi6.ipi6_addr.s6_addr32[3] = ip->ip_dst.s_addr;
1095 #else
1096                         /* We won't hit this code */
1097                         bzero(&pi6.ipi6_addr, sizeof(struct in6_addr));
1098 #endif
1099                 } else {        
1100                         bcopy(&ip6->ip6_dst, &pi6.ipi6_addr, sizeof(struct in6_addr));
1101                         in6_clearscope(&pi6.ipi6_addr); /* XXX */
1102                 }
1103                 pi6.ipi6_ifindex =
1104                     (m && m->m_pkthdr.rcvif) ? m->m_pkthdr.rcvif->if_index : 0;
1105
1106                 *mp = sbcreatecontrol((caddr_t) &pi6,
1107                     sizeof(struct in6_pktinfo),
1108                     IS2292(inp, IPV6_2292PKTINFO, IPV6_PKTINFO), IPPROTO_IPV6);
1109                 if (*mp)
1110                         mp = &(*mp)->m_next;
1111         }
1112
1113         if ((inp->inp_flags & IN6P_HOPLIMIT) != 0) {
1114                 int hlim;
1115
1116                 if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION) {
1117 #ifdef INET
1118                         struct ip *ip;
1119
1120                         ip = mtod(m, struct ip *);
1121                         hlim = ip->ip_ttl;
1122 #else
1123                         /* We won't hit this code */
1124                         hlim = 0;
1125 #endif
1126                 } else {
1127                         hlim = ip6->ip6_hlim & 0xff;
1128                 }
1129                 *mp = sbcreatecontrol((caddr_t) &hlim, sizeof(int),
1130                     IS2292(inp, IPV6_2292HOPLIMIT, IPV6_HOPLIMIT),
1131                     IPPROTO_IPV6);
1132                 if (*mp)
1133                         mp = &(*mp)->m_next;
1134         }
1135
1136         if ((inp->inp_flags & IN6P_TCLASS) != 0) {
1137                 int tclass;
1138
1139                 if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION) {
1140 #ifdef INET
1141                         struct ip *ip;
1142
1143                         ip = mtod(m, struct ip *);
1144                         tclass = ip->ip_tos;
1145 #else
1146                         /* We won't hit this code */
1147                         tclass = 0;
1148 #endif
1149                 } else {
1150                         u_int32_t flowinfo;
1151
1152                         flowinfo = (u_int32_t)ntohl(ip6->ip6_flow & IPV6_FLOWINFO_MASK);
1153                         flowinfo >>= 20;
1154                         tclass = flowinfo & 0xff;
1155                 }
1156                 *mp = sbcreatecontrol((caddr_t) &tclass, sizeof(int),
1157                     IPV6_TCLASS, IPPROTO_IPV6);
1158                 if (*mp)
1159                         mp = &(*mp)->m_next;
1160         }
1161
1162         if (v4only != NULL) {
1163                 if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION) {
1164                         *v4only = 1;
1165                 } else {
1166                         *v4only = 0;
1167                 }
1168         }
1169
1170         return (mp);
1171 }
1172
1173 void
1174 ip6_savecontrol(struct inpcb *in6p, struct mbuf *m, struct mbuf **mp)
1175 {
1176         struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
1177         int v4only = 0;
1178
1179         mp = ip6_savecontrol_v4(in6p, m, mp, &v4only);
1180         if (v4only)
1181                 return;
1182
1183         /*
1184          * IPV6_HOPOPTS socket option.  Recall that we required super-user
1185          * privilege for the option (see ip6_ctloutput), but it might be too
1186          * strict, since there might be some hop-by-hop options which can be
1187          * returned to normal user.
1188          * See also RFC 2292 section 6 (or RFC 3542 section 8).
1189          */
1190         if ((in6p->inp_flags & IN6P_HOPOPTS) != 0) {
1191                 /*
1192                  * Check if a hop-by-hop options header is contatined in the
1193                  * received packet, and if so, store the options as ancillary
1194                  * data. Note that a hop-by-hop options header must be
1195                  * just after the IPv6 header, which is assured through the
1196                  * IPv6 input processing.
1197                  */
1198                 if (ip6->ip6_nxt == IPPROTO_HOPOPTS) {
1199                         struct ip6_hbh *hbh;
1200                         int hbhlen = 0;
1201 #ifdef PULLDOWN_TEST
1202                         struct mbuf *ext;
1203 #endif
1204
1205 #ifndef PULLDOWN_TEST
1206                         hbh = (struct ip6_hbh *)(ip6 + 1);
1207                         hbhlen = (hbh->ip6h_len + 1) << 3;
1208 #else
1209                         ext = ip6_pullexthdr(m, sizeof(struct ip6_hdr),
1210                             ip6->ip6_nxt);
1211                         if (ext == NULL) {
1212                                 IP6STAT_INC(ip6s_tooshort);
1213                                 return;
1214                         }
1215                         hbh = mtod(ext, struct ip6_hbh *);
1216                         hbhlen = (hbh->ip6h_len + 1) << 3;
1217                         if (hbhlen != ext->m_len) {
1218                                 m_freem(ext);
1219                                 IP6STAT_INC(ip6s_tooshort);
1220                                 return;
1221                         }
1222 #endif
1223
1224                         /*
1225                          * XXX: We copy the whole header even if a
1226                          * jumbo payload option is included, the option which
1227                          * is to be removed before returning according to
1228                          * RFC2292.
1229                          * Note: this constraint is removed in RFC3542
1230                          */
1231                         *mp = sbcreatecontrol((caddr_t)hbh, hbhlen,
1232                             IS2292(in6p, IPV6_2292HOPOPTS, IPV6_HOPOPTS),
1233                             IPPROTO_IPV6);
1234                         if (*mp)
1235                                 mp = &(*mp)->m_next;
1236 #ifdef PULLDOWN_TEST
1237                         m_freem(ext);
1238 #endif
1239                 }
1240         }
1241
1242         if ((in6p->inp_flags & (IN6P_RTHDR | IN6P_DSTOPTS)) != 0) {
1243                 int nxt = ip6->ip6_nxt, off = sizeof(struct ip6_hdr);
1244
1245                 /*
1246                  * Search for destination options headers or routing
1247                  * header(s) through the header chain, and stores each
1248                  * header as ancillary data.
1249                  * Note that the order of the headers remains in
1250                  * the chain of ancillary data.
1251                  */
1252                 while (1) {     /* is explicit loop prevention necessary? */
1253                         struct ip6_ext *ip6e = NULL;
1254                         int elen;
1255 #ifdef PULLDOWN_TEST
1256                         struct mbuf *ext = NULL;
1257 #endif
1258
1259                         /*
1260                          * if it is not an extension header, don't try to
1261                          * pull it from the chain.
1262                          */
1263                         switch (nxt) {
1264                         case IPPROTO_DSTOPTS:
1265                         case IPPROTO_ROUTING:
1266                         case IPPROTO_HOPOPTS:
1267                         case IPPROTO_AH: /* is it possible? */
1268                                 break;
1269                         default:
1270                                 goto loopend;
1271                         }
1272
1273 #ifndef PULLDOWN_TEST
1274                         if (off + sizeof(*ip6e) > m->m_len)
1275                                 goto loopend;
1276                         ip6e = (struct ip6_ext *)(mtod(m, caddr_t) + off);
1277                         if (nxt == IPPROTO_AH)
1278                                 elen = (ip6e->ip6e_len + 2) << 2;
1279                         else
1280                                 elen = (ip6e->ip6e_len + 1) << 3;
1281                         if (off + elen > m->m_len)
1282                                 goto loopend;
1283 #else
1284                         ext = ip6_pullexthdr(m, off, nxt);
1285                         if (ext == NULL) {
1286                                 IP6STAT_INC(ip6s_tooshort);
1287                                 return;
1288                         }
1289                         ip6e = mtod(ext, struct ip6_ext *);
1290                         if (nxt == IPPROTO_AH)
1291                                 elen = (ip6e->ip6e_len + 2) << 2;
1292                         else
1293                                 elen = (ip6e->ip6e_len + 1) << 3;
1294                         if (elen != ext->m_len) {
1295                                 m_freem(ext);
1296                                 IP6STAT_INC(ip6s_tooshort);
1297                                 return;
1298                         }
1299 #endif
1300
1301                         switch (nxt) {
1302                         case IPPROTO_DSTOPTS:
1303                                 if (!(in6p->inp_flags & IN6P_DSTOPTS))
1304                                         break;
1305
1306                                 *mp = sbcreatecontrol((caddr_t)ip6e, elen,
1307                                     IS2292(in6p,
1308                                         IPV6_2292DSTOPTS, IPV6_DSTOPTS),
1309                                     IPPROTO_IPV6);
1310                                 if (*mp)
1311                                         mp = &(*mp)->m_next;
1312                                 break;
1313                         case IPPROTO_ROUTING:
1314                                 if (!(in6p->inp_flags & IN6P_RTHDR))
1315                                         break;
1316
1317                                 *mp = sbcreatecontrol((caddr_t)ip6e, elen,
1318                                     IS2292(in6p, IPV6_2292RTHDR, IPV6_RTHDR),
1319                                     IPPROTO_IPV6);
1320                                 if (*mp)
1321                                         mp = &(*mp)->m_next;
1322                                 break;
1323                         case IPPROTO_HOPOPTS:
1324                         case IPPROTO_AH: /* is it possible? */
1325                                 break;
1326
1327                         default:
1328                                 /*
1329                                  * other cases have been filtered in the above.
1330                                  * none will visit this case.  here we supply
1331                                  * the code just in case (nxt overwritten or
1332                                  * other cases).
1333                                  */
1334 #ifdef PULLDOWN_TEST
1335                                 m_freem(ext);
1336 #endif
1337                                 goto loopend;
1338
1339                         }
1340
1341                         /* proceed with the next header. */
1342                         off += elen;
1343                         nxt = ip6e->ip6e_nxt;
1344                         ip6e = NULL;
1345 #ifdef PULLDOWN_TEST
1346                         m_freem(ext);
1347                         ext = NULL;
1348 #endif
1349                 }
1350           loopend:
1351                 ;
1352         }
1353
1354         if (in6p->inp_flags2 & INP_RECVFLOWID) {
1355                 uint32_t flowid, flow_type;
1356
1357                 flowid = m->m_pkthdr.flowid;
1358                 flow_type = M_HASHTYPE_GET(m);
1359
1360                 /*
1361                  * XXX should handle the failure of one or the
1362                  * other - don't populate both?
1363                  */
1364                 *mp = sbcreatecontrol((caddr_t) &flowid,
1365                     sizeof(uint32_t), IPV6_FLOWID, IPPROTO_IPV6);
1366                 if (*mp)
1367                         mp = &(*mp)->m_next;
1368                 *mp = sbcreatecontrol((caddr_t) &flow_type,
1369                     sizeof(uint32_t), IPV6_FLOWTYPE, IPPROTO_IPV6);
1370                 if (*mp)
1371                         mp = &(*mp)->m_next;
1372         }
1373
1374 #ifdef  RSS
1375         if (in6p->inp_flags2 & INP_RECVRSSBUCKETID) {
1376                 uint32_t flowid, flow_type;
1377                 uint32_t rss_bucketid;
1378
1379                 flowid = m->m_pkthdr.flowid;
1380                 flow_type = M_HASHTYPE_GET(m);
1381
1382                 if (rss_hash2bucket(flowid, flow_type, &rss_bucketid) == 0) {
1383                         *mp = sbcreatecontrol((caddr_t) &rss_bucketid,
1384                            sizeof(uint32_t), IPV6_RSSBUCKETID, IPPROTO_IPV6);
1385                         if (*mp)
1386                                 mp = &(*mp)->m_next;
1387                 }
1388         }
1389 #endif
1390
1391 }
1392 #undef IS2292
1393
1394 void
1395 ip6_notify_pmtu(struct inpcb *inp, struct sockaddr_in6 *dst, u_int32_t mtu)
1396 {
1397         struct socket *so;
1398         struct mbuf *m_mtu;
1399         struct ip6_mtuinfo mtuctl;
1400
1401         KASSERT(inp != NULL, ("%s: inp == NULL", __func__));
1402         /*
1403          * Notify the error by sending IPV6_PATHMTU ancillary data if
1404          * application wanted to know the MTU value.
1405          * NOTE: we notify disconnected sockets, because some udp
1406          * applications keep sending sockets disconnected.
1407          * NOTE: our implementation doesn't notify connected sockets that has
1408          * foreign address that is different than given destination addresses
1409          * (this is permitted by RFC 3542).
1410          */
1411         if ((inp->inp_flags & IN6P_MTU) == 0 || (
1412             !IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr) &&
1413             !IN6_ARE_ADDR_EQUAL(&inp->in6p_faddr, &dst->sin6_addr)))
1414                 return;
1415
1416         mtuctl.ip6m_mtu = mtu;
1417         mtuctl.ip6m_addr = *dst;
1418         if (sa6_recoverscope(&mtuctl.ip6m_addr))
1419                 return;
1420
1421         if ((m_mtu = sbcreatecontrol((caddr_t)&mtuctl, sizeof(mtuctl),
1422             IPV6_PATHMTU, IPPROTO_IPV6)) == NULL)
1423                 return;
1424
1425         so =  inp->inp_socket;
1426         if (sbappendaddr(&so->so_rcv, (struct sockaddr *)dst, NULL, m_mtu)
1427             == 0) {
1428                 m_freem(m_mtu);
1429                 /* XXX: should count statistics */
1430         } else
1431                 sorwakeup(so);
1432 }
1433
1434 #ifdef PULLDOWN_TEST
1435 /*
1436  * pull single extension header from mbuf chain.  returns single mbuf that
1437  * contains the result, or NULL on error.
1438  */
1439 static struct mbuf *
1440 ip6_pullexthdr(struct mbuf *m, size_t off, int nxt)
1441 {
1442         struct ip6_ext ip6e;
1443         size_t elen;
1444         struct mbuf *n;
1445
1446 #ifdef DIAGNOSTIC
1447         switch (nxt) {
1448         case IPPROTO_DSTOPTS:
1449         case IPPROTO_ROUTING:
1450         case IPPROTO_HOPOPTS:
1451         case IPPROTO_AH: /* is it possible? */
1452                 break;
1453         default:
1454                 printf("ip6_pullexthdr: invalid nxt=%d\n", nxt);
1455         }
1456 #endif
1457
1458         m_copydata(m, off, sizeof(ip6e), (caddr_t)&ip6e);
1459         if (nxt == IPPROTO_AH)
1460                 elen = (ip6e.ip6e_len + 2) << 2;
1461         else
1462                 elen = (ip6e.ip6e_len + 1) << 3;
1463
1464         if (elen > MLEN)
1465                 n = m_getcl(M_NOWAIT, MT_DATA, 0);
1466         else
1467                 n = m_get(M_NOWAIT, MT_DATA);
1468         if (n == NULL)
1469                 return NULL;
1470
1471         m_copydata(m, off, elen, mtod(n, caddr_t));
1472         n->m_len = elen;
1473         return n;
1474 }
1475 #endif
1476
1477 /*
1478  * Get pointer to the previous header followed by the header
1479  * currently processed.
1480  * XXX: This function supposes that
1481  *      M includes all headers,
1482  *      the next header field and the header length field of each header
1483  *      are valid, and
1484  *      the sum of each header length equals to OFF.
1485  * Because of these assumptions, this function must be called very
1486  * carefully. Moreover, it will not be used in the near future when
1487  * we develop `neater' mechanism to process extension headers.
1488  */
1489 char *
1490 ip6_get_prevhdr(const struct mbuf *m, int off)
1491 {
1492         struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
1493
1494         if (off == sizeof(struct ip6_hdr))
1495                 return (&ip6->ip6_nxt);
1496         else {
1497                 int len, nxt;
1498                 struct ip6_ext *ip6e = NULL;
1499
1500                 nxt = ip6->ip6_nxt;
1501                 len = sizeof(struct ip6_hdr);
1502                 while (len < off) {
1503                         ip6e = (struct ip6_ext *)(mtod(m, caddr_t) + len);
1504
1505                         switch (nxt) {
1506                         case IPPROTO_FRAGMENT:
1507                                 len += sizeof(struct ip6_frag);
1508                                 break;
1509                         case IPPROTO_AH:
1510                                 len += (ip6e->ip6e_len + 2) << 2;
1511                                 break;
1512                         default:
1513                                 len += (ip6e->ip6e_len + 1) << 3;
1514                                 break;
1515                         }
1516                         nxt = ip6e->ip6e_nxt;
1517                 }
1518                 if (ip6e)
1519                         return (&ip6e->ip6e_nxt);
1520                 else
1521                         return NULL;
1522         }
1523 }
1524
1525 /*
1526  * get next header offset.  m will be retained.
1527  */
1528 int
1529 ip6_nexthdr(const struct mbuf *m, int off, int proto, int *nxtp)
1530 {
1531         struct ip6_hdr ip6;
1532         struct ip6_ext ip6e;
1533         struct ip6_frag fh;
1534
1535         /* just in case */
1536         if (m == NULL)
1537                 panic("ip6_nexthdr: m == NULL");
1538         if ((m->m_flags & M_PKTHDR) == 0 || m->m_pkthdr.len < off)
1539                 return -1;
1540
1541         switch (proto) {
1542         case IPPROTO_IPV6:
1543                 if (m->m_pkthdr.len < off + sizeof(ip6))
1544                         return -1;
1545                 m_copydata(m, off, sizeof(ip6), (caddr_t)&ip6);
1546                 if (nxtp)
1547                         *nxtp = ip6.ip6_nxt;
1548                 off += sizeof(ip6);
1549                 return off;
1550
1551         case IPPROTO_FRAGMENT:
1552                 /*
1553                  * terminate parsing if it is not the first fragment,
1554                  * it does not make sense to parse through it.
1555                  */
1556                 if (m->m_pkthdr.len < off + sizeof(fh))
1557                         return -1;
1558                 m_copydata(m, off, sizeof(fh), (caddr_t)&fh);
1559                 /* IP6F_OFF_MASK = 0xfff8(BigEndian), 0xf8ff(LittleEndian) */
1560                 if (fh.ip6f_offlg & IP6F_OFF_MASK)
1561                         return -1;
1562                 if (nxtp)
1563                         *nxtp = fh.ip6f_nxt;
1564                 off += sizeof(struct ip6_frag);
1565                 return off;
1566
1567         case IPPROTO_AH:
1568                 if (m->m_pkthdr.len < off + sizeof(ip6e))
1569                         return -1;
1570                 m_copydata(m, off, sizeof(ip6e), (caddr_t)&ip6e);
1571                 if (nxtp)
1572                         *nxtp = ip6e.ip6e_nxt;
1573                 off += (ip6e.ip6e_len + 2) << 2;
1574                 return off;
1575
1576         case IPPROTO_HOPOPTS:
1577         case IPPROTO_ROUTING:
1578         case IPPROTO_DSTOPTS:
1579                 if (m->m_pkthdr.len < off + sizeof(ip6e))
1580                         return -1;
1581                 m_copydata(m, off, sizeof(ip6e), (caddr_t)&ip6e);
1582                 if (nxtp)
1583                         *nxtp = ip6e.ip6e_nxt;
1584                 off += (ip6e.ip6e_len + 1) << 3;
1585                 return off;
1586
1587         case IPPROTO_NONE:
1588         case IPPROTO_ESP:
1589         case IPPROTO_IPCOMP:
1590                 /* give up */
1591                 return -1;
1592
1593         default:
1594                 return -1;
1595         }
1596
1597         /* NOTREACHED */
1598 }
1599
1600 /*
1601  * get offset for the last header in the chain.  m will be kept untainted.
1602  */
1603 int
1604 ip6_lasthdr(const struct mbuf *m, int off, int proto, int *nxtp)
1605 {
1606         int newoff;
1607         int nxt;
1608
1609         if (!nxtp) {
1610                 nxt = -1;
1611                 nxtp = &nxt;
1612         }
1613         while (1) {
1614                 newoff = ip6_nexthdr(m, off, proto, nxtp);
1615                 if (newoff < 0)
1616                         return off;
1617                 else if (newoff < off)
1618                         return -1;      /* invalid */
1619                 else if (newoff == off)
1620                         return newoff;
1621
1622                 off = newoff;
1623                 proto = *nxtp;
1624         }
1625 }
1626
1627 /*
1628  * System control for IP6
1629  */
1630
1631 u_char  inet6ctlerrmap[PRC_NCMDS] = {
1632         0,              0,              0,              0,
1633         0,              EMSGSIZE,       EHOSTDOWN,      EHOSTUNREACH,
1634         EHOSTUNREACH,   EHOSTUNREACH,   ECONNREFUSED,   ECONNREFUSED,
1635         EMSGSIZE,       EHOSTUNREACH,   0,              0,
1636         0,              0,              0,              0,
1637         ENOPROTOOPT
1638 };