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