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