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