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