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