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