xref: /xnu-8792.81.2/bsd/netinet6/ip6_output.c (revision 19c3b8c28c31cb8130e034cfb5df6bf9ba342d90)
1 /*
2  * Copyright (c) 2000-2022 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 
29 /*
30  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
31  * All rights reserved.
32  *
33  * Redistribution and use in source and binary forms, with or without
34  * modification, are permitted provided that the following conditions
35  * are met:
36  * 1. Redistributions of source code must retain the above copyright
37  *    notice, this list of conditions and the following disclaimer.
38  * 2. Redistributions in binary form must reproduce the above copyright
39  *    notice, this list of conditions and the following disclaimer in the
40  *    documentation and/or other materials provided with the distribution.
41  * 3. Neither the name of the project nor the names of its contributors
42  *    may be used to endorse or promote products derived from this software
43  *    without specific prior written permission.
44  *
45  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
46  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
47  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
48  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
49  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
50  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
51  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
53  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
54  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
55  * SUCH DAMAGE.
56  */
57 
58 /*
59  * Copyright (c) 1982, 1986, 1988, 1990, 1993
60  *	The Regents of the University of California.  All rights reserved.
61  *
62  * Redistribution and use in source and binary forms, with or without
63  * modification, are permitted provided that the following conditions
64  * are met:
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer.
67  * 2. Redistributions in binary form must reproduce the above copyright
68  *    notice, this list of conditions and the following disclaimer in the
69  *    documentation and/or other materials provided with the distribution.
70  * 3. All advertising materials mentioning features or use of this software
71  *    must display the following acknowledgement:
72  *	This product includes software developed by the University of
73  *	California, Berkeley and its contributors.
74  * 4. Neither the name of the University nor the names of its contributors
75  *    may be used to endorse or promote products derived from this software
76  *    without specific prior written permission.
77  *
78  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
79  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
80  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
81  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
82  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
83  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
84  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
85  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
86  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
87  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
88  * SUCH DAMAGE.
89  *
90  *	@(#)ip_output.c	8.3 (Berkeley) 1/21/94
91  */
92 /*
93  * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
94  * support for mandatory and extensible security protections.  This notice
95  * is included in support of clause 2.2 (b) of the Apple Public License,
96  * Version 2.0.
97  */
98 
99 #include <sys/param.h>
100 #include <sys/malloc.h>
101 #include <sys/mbuf.h>
102 #include <sys/errno.h>
103 #include <sys/protosw.h>
104 #include <sys/socket.h>
105 #include <sys/socketvar.h>
106 #include <sys/systm.h>
107 #include <sys/kernel.h>
108 #include <sys/proc.h>
109 #include <sys/kauth.h>
110 #include <sys/mcache.h>
111 #include <sys/sysctl.h>
112 #include <kern/zalloc.h>
113 #include <libkern/OSByteOrder.h>
114 
115 #include <pexpert/pexpert.h>
116 #include <mach/sdt.h>
117 
118 #include <net/if.h>
119 #include <net/route.h>
120 #include <net/dlil.h>
121 #include <net/net_api_stats.h>
122 #include <net/net_osdep.h>
123 #include <net/net_perf.h>
124 
125 #include <netinet/ip.h>
126 #include <netinet/in.h>
127 #include <netinet/in_var.h>
128 #include <netinet/ip_var.h>
129 #include <netinet6/in6_var.h>
130 #include <netinet/ip6.h>
131 #include <netinet/kpi_ipfilter_var.h>
132 #include <netinet/in_tclass.h>
133 
134 #include <netinet6/ip6protosw.h>
135 #include <netinet/icmp6.h>
136 #include <netinet6/ip6_var.h>
137 #include <netinet/in_pcb.h>
138 #include <netinet6/nd6.h>
139 #include <netinet6/scope6_var.h>
140 #if IPSEC
141 #include <netinet6/ipsec.h>
142 #include <netinet6/ipsec6.h>
143 #include <netkey/key.h>
144 extern int ipsec_bypass;
145 #endif /* IPSEC */
146 
147 #if NECP
148 #include <net/necp.h>
149 #endif /* NECP */
150 
151 #if DUMMYNET
152 #include <netinet/ip_dummynet.h>
153 #endif /* DUMMYNET */
154 
155 #if PF
156 #include <net/pfvar.h>
157 #endif /* PF */
158 
159 static int sysctl_reset_ip6_output_stats SYSCTL_HANDLER_ARGS;
160 static int sysctl_ip6_output_measure_bins SYSCTL_HANDLER_ARGS;
161 static int sysctl_ip6_output_getperf SYSCTL_HANDLER_ARGS;
162 static int ip6_copyexthdr(struct mbuf **, caddr_t, int);
163 static void ip6_out_cksum_stats(int, u_int32_t);
164 static int ip6_insert_jumboopt(struct ip6_exthdrs *, u_int32_t);
165 static int ip6_insertfraghdr(struct mbuf *, struct mbuf *, int,
166     struct ip6_frag **);
167 static int ip6_getpmtu(struct route_in6 *, struct route_in6 *,
168     struct ifnet *, struct in6_addr *, uint32_t, u_int32_t *);
169 static int ip6_pcbopts(struct ip6_pktopts **, struct mbuf *, struct socket *,
170     struct sockopt *sopt);
171 static int ip6_pcbopt(int, u_char *, int, struct ip6_pktopts **, int);
172 static int ip6_getpcbopt(struct ip6_pktopts *, int, struct sockopt *);
173 static int copypktopts(struct ip6_pktopts *, struct ip6_pktopts *, zalloc_flags_t);
174 static void im6o_trace(struct ip6_moptions *, int);
175 static int ip6_setpktopt(int, u_char *, int, struct ip6_pktopts *, int,
176     int, int);
177 static int ip6_splithdr(struct mbuf *, struct ip6_exthdrs *);
178 static void ip6_output_checksum(struct ifnet *, uint32_t, struct mbuf *,
179     int, uint32_t, uint32_t);
180 extern int udp_ctloutput(struct socket *, struct sockopt *);
181 static int ip6_fragment_packet(struct mbuf **m,
182     struct ip6_pktopts *opt, struct ip6_out_args * ip6oa,
183     struct ip6_exthdrs *exthdrsp, struct ifnet *ifp,
184     uint32_t mtu, uint32_t unfragpartlen,
185     int nxt0, uint32_t optlen);
186 
187 SYSCTL_DECL(_net_inet6_ip6);
188 
189 static int ip6_output_measure = 0;
190 SYSCTL_PROC(_net_inet6_ip6, OID_AUTO, output_perf,
191     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
192     &ip6_output_measure, 0, sysctl_reset_ip6_output_stats, "I", "Do time measurement");
193 
194 static uint64_t ip6_output_measure_bins = 0;
195 SYSCTL_PROC(_net_inet6_ip6, OID_AUTO, output_perf_bins,
196     CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED, &ip6_output_measure_bins, 0,
197     sysctl_ip6_output_measure_bins, "I",
198     "bins for chaining performance data histogram");
199 
200 static net_perf_t net_perf;
201 SYSCTL_PROC(_net_inet6_ip6, OID_AUTO, output_perf_data,
202     CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED,
203     0, 0, sysctl_ip6_output_getperf, "S,net_perf",
204     "IP6 output performance data (struct net_perf, net/net_perf.h)");
205 
206 #define IM6O_TRACE_HIST_SIZE    32      /* size of trace history */
207 
208 /* For gdb */
209 __private_extern__ unsigned int im6o_trace_hist_size = IM6O_TRACE_HIST_SIZE;
210 
211 struct ip6_moptions_dbg {
212 	struct ip6_moptions     im6o;                   /* ip6_moptions */
213 	u_int16_t               im6o_refhold_cnt;       /* # of IM6O_ADDREF */
214 	u_int16_t               im6o_refrele_cnt;       /* # of IM6O_REMREF */
215 	/*
216 	 * Alloc and free callers.
217 	 */
218 	ctrace_t                im6o_alloc;
219 	ctrace_t                im6o_free;
220 	/*
221 	 * Circular lists of IM6O_ADDREF and IM6O_REMREF callers.
222 	 */
223 	ctrace_t                im6o_refhold[IM6O_TRACE_HIST_SIZE];
224 	ctrace_t                im6o_refrele[IM6O_TRACE_HIST_SIZE];
225 };
226 
227 #if DEBUG
228 static unsigned int im6o_debug = 1;     /* debugging (enabled) */
229 #else
230 static unsigned int im6o_debug;         /* debugging (disabled) */
231 #endif /* !DEBUG */
232 
233 static struct zone *im6o_zone;          /* zone for ip6_moptions */
234 #define IM6O_ZONE_NAME          "ip6_moptions"  /* zone name */
235 
236 /*
237  * ip6_output() calls ip6_output_list() to do the work
238  */
239 int
ip6_output(struct mbuf * m0,struct ip6_pktopts * opt,struct route_in6 * ro,int flags,struct ip6_moptions * im6o,struct ifnet ** ifpp,struct ip6_out_args * ip6oa)240 ip6_output(struct mbuf *m0, struct ip6_pktopts *opt,
241     struct route_in6 *ro, int flags, struct ip6_moptions *im6o,
242     struct ifnet **ifpp, struct ip6_out_args *ip6oa)
243 {
244 	return ip6_output_list(m0, 0, opt, ro, flags, im6o, ifpp, ip6oa);
245 }
246 
247 /*
248  * IP6 output. Each packet in mbuf chain m contains a skeletal IP6
249  * header (with pri, len, nxt, hlim, src, dst).
250  * This function may modify ver and hlim only.
251  * The mbuf chain containing the packet will be freed.
252  * The mbuf opt, if present, will not be freed.
253  *
254  * If ro is non-NULL and has valid ro->ro_rt, route lookup would be
255  * skipped and ro->ro_rt would be used.  Otherwise the result of route
256  * lookup is stored in ro->ro_rt.
257  *
258  * type of "mtu": rt_rmx.rmx_mtu is u_int32_t, ifnet.ifr_mtu is int, and
259  * nd_ifinfo.linkmtu is u_int32_t.  so we use u_int32_t to hold largest one,
260  * which is rt_rmx.rmx_mtu.
261  */
262 int
ip6_output_list(struct mbuf * m0,int packetchain,struct ip6_pktopts * opt,struct route_in6 * ro,int flags,struct ip6_moptions * im6o,struct ifnet ** ifpp,struct ip6_out_args * ip6oa)263 ip6_output_list(struct mbuf *m0, int packetchain, struct ip6_pktopts *opt,
264     struct route_in6 *ro, int flags, struct ip6_moptions *im6o,
265     struct ifnet **ifpp, struct ip6_out_args *ip6oa)
266 {
267 	struct ip6_hdr *ip6;
268 	u_char *nexthdrp;
269 	struct ifnet *ifp = NULL, *origifp = NULL;      /* refcnt'd */
270 	struct ifnet **ifpp_save = ifpp;
271 	struct mbuf *m, *mprev;
272 	struct mbuf *sendchain = NULL, *sendchain_last = NULL;
273 	struct mbuf *inputchain = NULL;
274 	int nxt0 = 0;
275 	struct route_in6 *ro_pmtu = NULL;
276 	struct rtentry *rt = NULL;
277 	struct sockaddr_in6 *dst = NULL, src_sa, dst_sa;
278 	int error = 0;
279 	struct in6_ifaddr *ia = NULL, *src_ia = NULL;
280 	u_int32_t mtu = 0;
281 	u_int32_t optlen = 0, plen = 0, unfragpartlen = 0;
282 	struct ip6_rthdr *rh;
283 	struct in6_addr finaldst;
284 	ipfilter_t inject_filter_ref;
285 	struct ipf_pktopts *ippo = NULL;
286 	struct flowadv *adv = NULL;
287 	uint32_t pktcnt = 0;
288 	uint32_t packets_processed = 0;
289 	struct timeval start_tv;
290 #if PF
291 	boolean_t skip_pf = (ip6oa != NULL) &&
292 	    (ip6oa->ip6oa_flags & IP6OAF_SKIP_PF);
293 #endif
294 
295 #if DUMMYNET
296 	struct m_tag *tag;
297 	struct ip6_out_args saved_ip6oa;
298 	struct sockaddr_in6 dst_buf;
299 #endif /* DUMMYNET */
300 #if IPSEC
301 	struct socket *so = NULL;
302 	struct secpolicy *sp = NULL;
303 	struct route_in6 *ipsec_saved_route = NULL;
304 	boolean_t needipsectun = FALSE;
305 #endif /* IPSEC */
306 #if NECP
307 	necp_kernel_policy_result necp_result = 0;
308 	necp_kernel_policy_result_parameter necp_result_parameter;
309 	necp_kernel_policy_id necp_matched_policy_id = 0;
310 #endif /* NECP */
311 	struct {
312 		struct ipf_pktopts ipf_pktopts;
313 		struct ip6_exthdrs exthdrs;
314 		struct route_in6 ip6route;
315 #if IPSEC
316 		struct ipsec_output_state ipsec_state;
317 #endif /* IPSEC */
318 #if NECP
319 		struct route_in6 necp_route;
320 #endif /* NECP */
321 #if DUMMYNET
322 		struct route_in6 saved_route;
323 		struct route_in6 saved_ro_pmtu;
324 		struct ip_fw_args args;
325 #endif /* DUMMYNET */
326 	} ip6obz;
327 #define ipf_pktopts     ip6obz.ipf_pktopts
328 #define exthdrs         ip6obz.exthdrs
329 #define ip6route        ip6obz.ip6route
330 #define ipsec_state     ip6obz.ipsec_state
331 #define necp_route      ip6obz.necp_route
332 #define saved_route     ip6obz.saved_route
333 #define saved_ro_pmtu   ip6obz.saved_ro_pmtu
334 #define args            ip6obz.args
335 	union {
336 		struct {
337 			boolean_t select_srcif : 1;
338 			boolean_t hdrsplit : 1;
339 			boolean_t route_selected : 1;
340 			boolean_t dontfrag : 1;
341 #if IPSEC
342 			boolean_t needipsec : 1;
343 			boolean_t noipsec : 1;
344 #endif /* IPSEC */
345 		};
346 		uint32_t raw;
347 	} ip6obf = { .raw = 0 };
348 
349 	if (ip6_output_measure) {
350 		net_perf_start_time(&net_perf, &start_tv);
351 	}
352 
353 	VERIFY(m0->m_flags & M_PKTHDR);
354 
355 	/* zero out {saved_route, saved_ro_pmtu, ip6route, exthdrs, args} */
356 	bzero(&ip6obz, sizeof(ip6obz));
357 
358 #if DUMMYNET
359 	if (SLIST_EMPTY(&m0->m_pkthdr.tags)) {
360 		goto tags_done;
361 	}
362 
363 	/* Grab info from mtags prepended to the chain */
364 	if ((tag = m_tag_locate(m0, KERNEL_MODULE_TAG_ID,
365 	    KERNEL_TAG_TYPE_DUMMYNET, NULL)) != NULL) {
366 		struct dn_pkt_tag       *dn_tag;
367 
368 		/*
369 		 * ip6_output_list() cannot handle chains of packets reinjected
370 		 * by dummynet. The same restriction applies to
371 		 * ip_output_list().
372 		 */
373 		VERIFY(0 == packetchain);
374 
375 		dn_tag = (struct dn_pkt_tag *)(tag + 1);
376 		args.fwa_pf_rule = dn_tag->dn_pf_rule;
377 
378 		bcopy(&dn_tag->dn_dst6, &dst_buf, sizeof(dst_buf));
379 		dst = &dst_buf;
380 		ifp = dn_tag->dn_ifp;
381 		if (ifp != NULL) {
382 			ifnet_reference(ifp);
383 		}
384 		flags = dn_tag->dn_flags;
385 		if (dn_tag->dn_flags & IPV6_OUTARGS) {
386 			saved_ip6oa = dn_tag->dn_ip6oa;
387 			ip6oa = &saved_ip6oa;
388 		}
389 
390 		saved_route = dn_tag->dn_ro6;
391 		ro = &saved_route;
392 		saved_ro_pmtu = dn_tag->dn_ro6_pmtu;
393 		ro_pmtu = &saved_ro_pmtu;
394 		origifp = dn_tag->dn_origifp;
395 		if (origifp != NULL) {
396 			ifnet_reference(origifp);
397 		}
398 		mtu = dn_tag->dn_mtu;
399 		unfragpartlen = dn_tag->dn_unfragpartlen;
400 
401 		bcopy(&dn_tag->dn_exthdrs, &exthdrs, sizeof(exthdrs));
402 
403 		m_tag_delete(m0, tag);
404 	}
405 
406 tags_done:
407 #endif /* DUMMYNET */
408 
409 	m = m0;
410 
411 #if IPSEC
412 	if (ipsec_bypass == 0) {
413 		so = ipsec_getsocket(m);
414 		if (so != NULL) {
415 			(void) ipsec_setsocket(m, NULL);
416 		}
417 		/* If packet is bound to an interface, check bound policies */
418 		if ((flags & IPV6_OUTARGS) &&
419 		    (ip6oa->ip6oa_flags & IP6OAF_BOUND_IF) &&
420 		    ip6oa->ip6oa_boundif != IFSCOPE_NONE) {
421 			/* ip6obf.noipsec is a bitfield, use temp integer */
422 			int noipsec = 0;
423 
424 			if (ipsec6_getpolicybyinterface(m, IPSEC_DIR_OUTBOUND,
425 			    flags, ip6oa, &noipsec, &sp) != 0) {
426 				goto bad;
427 			}
428 
429 			ip6obf.noipsec = (noipsec != 0);
430 		}
431 	}
432 #endif /* IPSEC */
433 
434 	ippo = &ipf_pktopts;
435 
436 	if (flags & IPV6_OUTARGS) {
437 		/*
438 		 * In the forwarding case, only the ifscope value is used,
439 		 * as source interface selection doesn't take place.
440 		 */
441 		if ((ip6obf.select_srcif = (!(flags & (IPV6_FORWARDING |
442 		    IPV6_UNSPECSRC | IPV6_FLAG_NOSRCIFSEL)) &&
443 		    (ip6oa->ip6oa_flags & IP6OAF_SELECT_SRCIF)))) {
444 			ipf_pktopts.ippo_flags |= IPPOF_SELECT_SRCIF;
445 		}
446 
447 		if ((ip6oa->ip6oa_flags & IP6OAF_BOUND_IF) &&
448 		    ip6oa->ip6oa_boundif != IFSCOPE_NONE) {
449 			ipf_pktopts.ippo_flags |= (IPPOF_BOUND_IF |
450 			    (ip6oa->ip6oa_boundif << IPPOF_SHIFT_IFSCOPE));
451 		}
452 
453 		if (ip6oa->ip6oa_flags & IP6OAF_BOUND_SRCADDR) {
454 			ipf_pktopts.ippo_flags |= IPPOF_BOUND_SRCADDR;
455 		}
456 	} else {
457 		ip6obf.select_srcif = FALSE;
458 		if (flags & IPV6_OUTARGS) {
459 			ip6oa->ip6oa_boundif = IFSCOPE_NONE;
460 			ip6oa->ip6oa_flags &= ~(IP6OAF_SELECT_SRCIF |
461 			    IP6OAF_BOUND_IF | IP6OAF_BOUND_SRCADDR);
462 		}
463 	}
464 
465 	if (flags & IPV6_OUTARGS) {
466 		if (ip6oa->ip6oa_flags & IP6OAF_NO_CELLULAR) {
467 			ipf_pktopts.ippo_flags |= IPPOF_NO_IFT_CELLULAR;
468 		}
469 		if (ip6oa->ip6oa_flags & IP6OAF_NO_EXPENSIVE) {
470 			ipf_pktopts.ippo_flags |= IPPOF_NO_IFF_EXPENSIVE;
471 		}
472 		if (ip6oa->ip6oa_flags & IP6OAF_NO_CONSTRAINED) {
473 			ipf_pktopts.ippo_flags |= IPPOF_NO_IFF_CONSTRAINED;
474 		}
475 		adv = &ip6oa->ip6oa_flowadv;
476 		adv->code = FADV_SUCCESS;
477 		ip6oa->ip6oa_flags &= ~IP6OAF_RET_MASK;
478 	}
479 
480 	/*
481 	 * Clear out ifpp to be filled in after determining route. ifpp_save is
482 	 * used to keep old value to release reference properly and dtrace
483 	 * ipsec tunnel traffic properly.
484 	 */
485 	if (ifpp != NULL && *ifpp != NULL) {
486 		*ifpp = NULL;
487 	}
488 
489 #if DUMMYNET
490 	if (args.fwa_pf_rule) {
491 		ip6 = mtod(m, struct ip6_hdr *);
492 		VERIFY(ro != NULL);     /* ro == saved_route */
493 		goto check_with_pf;
494 	}
495 #endif /* DUMMYNET */
496 
497 #if NECP
498 	/*
499 	 * Since all packets are assumed to come from same socket, necp lookup
500 	 * only needs to happen once per function entry.
501 	 */
502 	necp_matched_policy_id = necp_ip6_output_find_policy_match(m, flags,
503 	    (flags & IPV6_OUTARGS) ? ip6oa : NULL, ro ? ro->ro_rt : NULL, &necp_result,
504 	    &necp_result_parameter);
505 #endif /* NECP */
506 
507 	/*
508 	 * If a chain was passed in, prepare for ther first iteration. For all
509 	 * other iterations, this work will be done at evaluateloop: label.
510 	 */
511 	if (packetchain) {
512 		/*
513 		 * Remove m from the chain during processing to avoid
514 		 * accidental frees on entire list.
515 		 */
516 		inputchain = m->m_nextpkt;
517 		m->m_nextpkt = NULL;
518 	}
519 
520 loopit:
521 	packets_processed++;
522 	m->m_pkthdr.pkt_flags &= ~(PKTF_LOOP | PKTF_IFAINFO);
523 	ip6 = mtod(m, struct ip6_hdr *);
524 	nxt0 = ip6->ip6_nxt;
525 	finaldst = ip6->ip6_dst;
526 	ip6obf.hdrsplit = FALSE;
527 	ro_pmtu = NULL;
528 
529 	if (!SLIST_EMPTY(&m->m_pkthdr.tags)) {
530 		inject_filter_ref = ipf_get_inject_filter(m);
531 	} else {
532 		inject_filter_ref = NULL;
533 	}
534 
535 #define MAKE_EXTHDR(hp, mp) do {                                        \
536 	if (hp != NULL) {                                               \
537 	        struct ip6_ext *eh = (struct ip6_ext *)(hp);            \
538 	        error = ip6_copyexthdr((mp), (caddr_t)(hp),             \
539 	            ((eh)->ip6e_len + 1) << 3);                         \
540 	        if (error)                                              \
541 	                goto freehdrs;                                  \
542 	}                                                               \
543 } while (0)
544 
545 	if (opt != NULL) {
546 		/* Hop-by-Hop options header */
547 		MAKE_EXTHDR(opt->ip6po_hbh, &exthdrs.ip6e_hbh);
548 		/* Destination options header(1st part) */
549 		if (opt->ip6po_rthdr) {
550 			/*
551 			 * Destination options header(1st part)
552 			 * This only makes sense with a routing header.
553 			 * See Section 9.2 of RFC 3542.
554 			 * Disabling this part just for MIP6 convenience is
555 			 * a bad idea.  We need to think carefully about a
556 			 * way to make the advanced API coexist with MIP6
557 			 * options, which might automatically be inserted in
558 			 * the kernel.
559 			 */
560 			MAKE_EXTHDR(opt->ip6po_dest1, &exthdrs.ip6e_dest1);
561 		}
562 		/* Routing header */
563 		MAKE_EXTHDR(opt->ip6po_rthdr, &exthdrs.ip6e_rthdr);
564 		/* Destination options header(2nd part) */
565 		MAKE_EXTHDR(opt->ip6po_dest2, &exthdrs.ip6e_dest2);
566 	}
567 
568 #undef MAKE_EXTHDR
569 
570 #if NECP
571 	if (necp_matched_policy_id) {
572 		necp_mark_packet_from_ip(m, necp_matched_policy_id);
573 
574 		switch (necp_result) {
575 		case NECP_KERNEL_POLICY_RESULT_PASS:
576 			if (necp_result_parameter.pass_flags & NECP_KERNEL_POLICY_PASS_NO_SKIP_IPSEC) {
577 				break;
578 			}
579 			goto skip_ipsec;
580 		case NECP_KERNEL_POLICY_RESULT_DROP:
581 			error = EHOSTUNREACH;
582 			ip6stat.ip6s_necp_policy_drop++;
583 			goto freehdrs;
584 		case NECP_KERNEL_POLICY_RESULT_SOCKET_DIVERT:
585 			/*
586 			 * Flow divert packets should be blocked at the IP
587 			 * layer.
588 			 */
589 			error = EHOSTUNREACH;
590 			ip6stat.ip6s_necp_policy_drop++;
591 			goto freehdrs;
592 		case NECP_KERNEL_POLICY_RESULT_IP_TUNNEL: {
593 			/*
594 			 * Verify that the packet is being routed to the tunnel
595 			 */
596 			struct ifnet *policy_ifp =
597 			    necp_get_ifnet_from_result_parameter(
598 				&necp_result_parameter);
599 
600 			/*
601 			 * Update the QOS marking policy if
602 			 * 1. upper layer asks it to do so
603 			 * 2. net_qos_policy_restricted is not set
604 			 * 3. qos_marking_gencount doesn't match necp_kernel_socket_policies_gencount (checked in necp_lookup_current_qos_marking)
605 			 */
606 			if (ip6oa != NULL && (ip6oa->ip6oa_flags & IP6OAF_REDO_QOSMARKING_POLICY) &&
607 			    net_qos_policy_restricted != 0) {
608 				bool qos_marking = (ip6oa->ip6oa_flags & IP6OAF_QOSMARKING_ALLOWED) != 0;
609 				qos_marking = necp_lookup_current_qos_marking(&ip6oa->qos_marking_gencount, NULL, policy_ifp, necp_result_parameter.route_rule_id, qos_marking);
610 				if (qos_marking) {
611 					ip6oa->ip6oa_flags |= IP6OAF_QOSMARKING_ALLOWED;
612 				} else {
613 					ip6oa->ip6oa_flags &= ~IP6OAF_QOSMARKING_ALLOWED;
614 				}
615 			}
616 
617 			if (policy_ifp == ifp) {
618 				goto skip_ipsec;
619 			} else {
620 				if (necp_packet_can_rebind_to_ifnet(m,
621 				    policy_ifp, (struct route *)&necp_route,
622 				    AF_INET6)) {
623 					/*
624 					 * Set scoped index to the tunnel
625 					 * interface, since it is compatible
626 					 * with the packet. This will only work
627 					 * for callers who pass IPV6_OUTARGS,
628 					 * but that covers all of the clients
629 					 * we care about today.
630 					 */
631 					if (flags & IPV6_OUTARGS) {
632 						ip6oa->ip6oa_boundif =
633 						    policy_ifp->if_index;
634 						ip6oa->ip6oa_flags |=
635 						    IP6OAF_BOUND_IF;
636 					}
637 					if (opt != NULL
638 					    && opt->ip6po_pktinfo != NULL) {
639 						opt->ip6po_pktinfo->
640 						ipi6_ifindex =
641 						    policy_ifp->if_index;
642 					}
643 					ro = &necp_route;
644 					goto skip_ipsec;
645 				} else {
646 					error = ENETUNREACH;
647 					ip6stat.ip6s_necp_policy_drop++;
648 					goto freehdrs;
649 				}
650 			}
651 		}
652 		default:
653 			break;
654 		}
655 	}
656 #endif /* NECP */
657 
658 #if IPSEC
659 	if (ipsec_bypass != 0 || ip6obf.noipsec) {
660 		goto skip_ipsec;
661 	}
662 
663 	if (sp == NULL) {
664 		/* get a security policy for this packet */
665 		if (so != NULL) {
666 			sp = ipsec6_getpolicybysock(m, IPSEC_DIR_OUTBOUND,
667 			    so, &error);
668 		} else {
669 			sp = ipsec6_getpolicybyaddr(m, IPSEC_DIR_OUTBOUND,
670 			    0, &error);
671 		}
672 		if (sp == NULL) {
673 			IPSEC_STAT_INCREMENT(ipsec6stat.out_inval);
674 			goto freehdrs;
675 		}
676 	}
677 
678 	error = 0;
679 
680 	/* check policy */
681 	switch (sp->policy) {
682 	case IPSEC_POLICY_DISCARD:
683 	case IPSEC_POLICY_GENERATE:
684 		/*
685 		 * This packet is just discarded.
686 		 */
687 		IPSEC_STAT_INCREMENT(ipsec6stat.out_polvio);
688 		goto freehdrs;
689 
690 	case IPSEC_POLICY_BYPASS:
691 	case IPSEC_POLICY_NONE:
692 		/* no need to do IPsec. */
693 		ip6obf.needipsec = FALSE;
694 		break;
695 
696 	case IPSEC_POLICY_IPSEC:
697 		if (sp->req == NULL) {
698 			/* acquire a policy */
699 			error = key_spdacquire(sp);
700 			goto freehdrs;
701 		}
702 		if (sp->ipsec_if) {
703 			goto skip_ipsec;
704 		} else {
705 			ip6obf.needipsec = TRUE;
706 		}
707 		break;
708 
709 	case IPSEC_POLICY_ENTRUST:
710 	default:
711 		printf("%s: Invalid policy found: %d\n", __func__, sp->policy);
712 		break;
713 	}
714 skip_ipsec:
715 #endif /* IPSEC */
716 
717 	/*
718 	 * Calculate the total length of the extension header chain.
719 	 * Keep the length of the unfragmentable part for fragmentation.
720 	 */
721 	optlen = 0;
722 	if (exthdrs.ip6e_hbh != NULL) {
723 		optlen += exthdrs.ip6e_hbh->m_len;
724 	}
725 	if (exthdrs.ip6e_dest1 != NULL) {
726 		optlen += exthdrs.ip6e_dest1->m_len;
727 	}
728 	if (exthdrs.ip6e_rthdr != NULL) {
729 		optlen += exthdrs.ip6e_rthdr->m_len;
730 	}
731 	unfragpartlen = optlen + sizeof(struct ip6_hdr);
732 
733 	/* NOTE: we don't add AH/ESP length here. do that later. */
734 	if (exthdrs.ip6e_dest2 != NULL) {
735 		optlen += exthdrs.ip6e_dest2->m_len;
736 	}
737 
738 	/*
739 	 * If we need IPsec, or there is at least one extension header,
740 	 * separate IP6 header from the payload.
741 	 */
742 	if ((
743 #if IPSEC
744 		    ip6obf.needipsec ||
745 #endif /* IPSEC */
746 		    optlen) && !ip6obf.hdrsplit) {
747 		if ((error = ip6_splithdr(m, &exthdrs)) != 0) {
748 			m = NULL;
749 			goto freehdrs;
750 		}
751 		m = exthdrs.ip6e_ip6;
752 		ip6obf.hdrsplit = TRUE;
753 	}
754 
755 	/* adjust pointer */
756 	ip6 = mtod(m, struct ip6_hdr *);
757 
758 	/* adjust mbuf packet header length */
759 	m->m_pkthdr.len += optlen;
760 	plen = m->m_pkthdr.len - sizeof(*ip6);
761 
762 	/* If this is a jumbo payload, insert a jumbo payload option. */
763 	if (plen > IPV6_MAXPACKET) {
764 		if (!ip6obf.hdrsplit) {
765 			if ((error = ip6_splithdr(m, &exthdrs)) != 0) {
766 				m = NULL;
767 				goto freehdrs;
768 			}
769 			m = exthdrs.ip6e_ip6;
770 			ip6obf.hdrsplit = TRUE;
771 		}
772 		/* adjust pointer */
773 		ip6 = mtod(m, struct ip6_hdr *);
774 		if ((error = ip6_insert_jumboopt(&exthdrs, plen)) != 0) {
775 			goto freehdrs;
776 		}
777 		ip6->ip6_plen = 0;
778 	} else {
779 		ip6->ip6_plen = htons((uint16_t)plen);
780 	}
781 	/*
782 	 * Concatenate headers and fill in next header fields.
783 	 * Here we have, on "m"
784 	 *	IPv6 payload
785 	 * and we insert headers accordingly.  Finally, we should be getting:
786 	 *	IPv6 hbh dest1 rthdr ah* [esp* dest2 payload]
787 	 *
788 	 * during the header composing process, "m" points to IPv6 header.
789 	 * "mprev" points to an extension header prior to esp.
790 	 */
791 	nexthdrp = &ip6->ip6_nxt;
792 	mprev = m;
793 
794 	/*
795 	 * we treat dest2 specially.  this makes IPsec processing
796 	 * much easier.  the goal here is to make mprev point the
797 	 * mbuf prior to dest2.
798 	 *
799 	 * result: IPv6 dest2 payload
800 	 * m and mprev will point to IPv6 header.
801 	 */
802 	if (exthdrs.ip6e_dest2 != NULL) {
803 		if (!ip6obf.hdrsplit) {
804 			panic("assumption failed: hdr not split");
805 			/* NOTREACHED */
806 		}
807 		exthdrs.ip6e_dest2->m_next = m->m_next;
808 		m->m_next = exthdrs.ip6e_dest2;
809 		*mtod(exthdrs.ip6e_dest2, u_char *) = ip6->ip6_nxt;
810 		ip6->ip6_nxt = IPPROTO_DSTOPTS;
811 	}
812 
813 #define MAKE_CHAIN(m, mp, p, i) do {                                    \
814 	if (m != NULL) {                                                \
815 	        if (!ip6obf.hdrsplit) {                                 \
816 	                panic("assumption failed: hdr not split");      \
817 	/* NOTREACHED */                                \
818 	        }                                                       \
819 	        *mtod((m), u_char *) = *(p);                            \
820 	        *(p) = (i);                                             \
821 	        p = mtod((m), u_char *);                                \
822 	        (m)->m_next = (mp)->m_next;                             \
823 	        (mp)->m_next = (m);                                     \
824 	        (mp) = (m);                                             \
825 	}                                                               \
826 } while (0)
827 	/*
828 	 * result: IPv6 hbh dest1 rthdr dest2 payload
829 	 * m will point to IPv6 header.  mprev will point to the
830 	 * extension header prior to dest2 (rthdr in the above case).
831 	 */
832 	MAKE_CHAIN(exthdrs.ip6e_hbh, mprev, nexthdrp, IPPROTO_HOPOPTS);
833 	MAKE_CHAIN(exthdrs.ip6e_dest1, mprev, nexthdrp, IPPROTO_DSTOPTS);
834 	MAKE_CHAIN(exthdrs.ip6e_rthdr, mprev, nexthdrp, IPPROTO_ROUTING);
835 
836 	/* It is no longer safe to free the pointers in exthdrs. */
837 	exthdrs.merged = TRUE;
838 
839 #undef MAKE_CHAIN
840 
841 #if IPSEC
842 	if (ip6obf.needipsec && (m->m_pkthdr.csum_flags & CSUM_DELAY_IPV6_DATA)) {
843 		in6_delayed_cksum_offset(m, 0, optlen, nxt0);
844 	}
845 #endif /* IPSEC */
846 
847 	if (!TAILQ_EMPTY(&ipv6_filters) &&
848 	    !((flags & IPV6_OUTARGS) &&
849 	    (ip6oa->ip6oa_flags & IP6OAF_INTCOPROC_ALLOWED)
850 #if NECP
851 	    && !necp_packet_should_skip_filters(m)
852 #endif // NECP
853 	    )) {
854 		struct ipfilter *filter;
855 		int seen = (inject_filter_ref == NULL);
856 		int fixscope = 0;
857 
858 		if (im6o != NULL && IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
859 			ippo->ippo_flags |= IPPOF_MCAST_OPTS;
860 			IM6O_LOCK(im6o);
861 			ippo->ippo_mcast_ifnet = im6o->im6o_multicast_ifp;
862 			ippo->ippo_mcast_ttl = im6o->im6o_multicast_hlim;
863 			ippo->ippo_mcast_loop = im6o->im6o_multicast_loop;
864 			IM6O_UNLOCK(im6o);
865 		}
866 
867 		/* Hack: embed the scope_id in the destination */
868 		if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst) &&
869 		    (ip6->ip6_dst.s6_addr16[1] == 0) && (ro != NULL)) {
870 			fixscope = 1;
871 			ip6->ip6_dst.s6_addr16[1] =
872 			    htons((uint16_t)ro->ro_dst.sin6_scope_id);
873 		}
874 
875 		ipf_ref();
876 		TAILQ_FOREACH(filter, &ipv6_filters, ipf_link) {
877 			/*
878 			 * Don't process packet twice if we've already seen it.
879 			 */
880 			if (seen == 0) {
881 				if ((struct ipfilter *)inject_filter_ref ==
882 				    filter) {
883 					seen = 1;
884 				}
885 			} else if (filter->ipf_filter.ipf_output != NULL) {
886 				errno_t result;
887 
888 				result = filter->ipf_filter.ipf_output(
889 					filter->ipf_filter.cookie,
890 					(mbuf_t *)&m, ippo);
891 				if (result == EJUSTRETURN) {
892 					ipf_unref();
893 					m = NULL;
894 					goto evaluateloop;
895 				}
896 				if (result != 0) {
897 					ipf_unref();
898 					goto bad;
899 				}
900 			}
901 		}
902 		ipf_unref();
903 
904 		ip6 = mtod(m, struct ip6_hdr *);
905 		/* Hack: cleanup embedded scope_id if we put it there */
906 		if (fixscope) {
907 			ip6->ip6_dst.s6_addr16[1] = 0;
908 		}
909 	}
910 
911 #if IPSEC
912 	if (ip6obf.needipsec) {
913 		uint8_t segleft_org;
914 
915 		/*
916 		 * pointers after IPsec headers are not valid any more.
917 		 * other pointers need a great care too.
918 		 * (IPsec routines should not mangle mbufs prior to AH/ESP)
919 		 */
920 		exthdrs.ip6e_dest2 = NULL;
921 
922 		if (exthdrs.ip6e_rthdr != NULL) {
923 			rh = mtod(exthdrs.ip6e_rthdr, struct ip6_rthdr *);
924 			segleft_org = rh->ip6r_segleft;
925 			rh->ip6r_segleft = 0;
926 		} else {
927 			rh = NULL;
928 			segleft_org = 0;
929 		}
930 
931 		ipsec_state.m = m;
932 		error = ipsec6_output_trans(&ipsec_state, nexthdrp, mprev,
933 		    sp, flags, &needipsectun);
934 		m = ipsec_state.m;
935 		if (error) {
936 			/* mbuf is already reclaimed in ipsec6_output_trans. */
937 			m = NULL;
938 			switch (error) {
939 			case EHOSTUNREACH:
940 			case ENETUNREACH:
941 			case EMSGSIZE:
942 			case ENOBUFS:
943 			case ENOMEM:
944 				break;
945 			default:
946 				printf("ip6_output (ipsec): error code %d\n",
947 				    error);
948 				OS_FALLTHROUGH;
949 			case ENOENT:
950 				/* don't show these error codes to the user */
951 				error = 0;
952 				break;
953 			}
954 			goto bad;
955 		}
956 		if (exthdrs.ip6e_rthdr != NULL) {
957 			/* ah6_output doesn't modify mbuf chain */
958 			rh->ip6r_segleft = segleft_org;
959 		}
960 	}
961 #endif /* IPSEC */
962 
963 	/* If there is a routing header, discard the packet. */
964 	if (exthdrs.ip6e_rthdr != NULL) {
965 		error = EINVAL;
966 		goto bad;
967 	}
968 
969 	/* Source address validation */
970 	if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src) &&
971 	    !(flags & IPV6_UNSPECSRC)) {
972 		error = EOPNOTSUPP;
973 		ip6stat.ip6s_badscope++;
974 		goto bad;
975 	}
976 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
977 		error = EOPNOTSUPP;
978 		ip6stat.ip6s_badscope++;
979 		goto bad;
980 	}
981 
982 	ip6stat.ip6s_localout++;
983 
984 	/*
985 	 * Route packet.
986 	 */
987 	if (ro == NULL) {
988 		ro = &ip6route;
989 		bzero((caddr_t)ro, sizeof(*ro));
990 	}
991 	ro_pmtu = ro;
992 	if (opt != NULL && opt->ip6po_rthdr) {
993 		ro = &opt->ip6po_route;
994 	}
995 	dst = SIN6(&ro->ro_dst);
996 
997 	if (ro->ro_rt != NULL) {
998 		RT_LOCK_ASSERT_NOTHELD(ro->ro_rt);
999 	}
1000 	/*
1001 	 * if specified, try to fill in the traffic class field.
1002 	 * do not override if a non-zero value is already set.
1003 	 * we check the diffserv field and the ecn field separately.
1004 	 */
1005 	if (opt != NULL && opt->ip6po_tclass >= 0) {
1006 		int mask = 0;
1007 
1008 		if ((ip6->ip6_flow & htonl(0xfc << 20)) == 0) {
1009 			mask |= 0xfc;
1010 		}
1011 		if ((ip6->ip6_flow & htonl(0x03 << 20)) == 0) {
1012 			mask |= 0x03;
1013 		}
1014 		if (mask != 0) {
1015 			ip6->ip6_flow |=
1016 			    htonl((opt->ip6po_tclass & mask) << 20);
1017 		}
1018 	}
1019 
1020 	if (((ntohl(ip6->ip6_flow & IPV6_FLOW_ECN_MASK) >> 20) & IPTOS_ECN_ECT1) == IPTOS_ECN_ECT1) {
1021 		m->m_pkthdr.pkt_ext_flags |= PKTF_EXT_L4S;
1022 	}
1023 
1024 	/* fill in or override the hop limit field, if necessary. */
1025 	if (opt && opt->ip6po_hlim != -1) {
1026 		ip6->ip6_hlim = opt->ip6po_hlim & 0xff;
1027 	} else if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
1028 		if (im6o != NULL) {
1029 			IM6O_LOCK(im6o);
1030 			ip6->ip6_hlim = im6o->im6o_multicast_hlim;
1031 			IM6O_UNLOCK(im6o);
1032 		} else {
1033 			ip6->ip6_hlim = (uint8_t)ip6_defmcasthlim;
1034 		}
1035 	}
1036 
1037 	/*
1038 	 * If there is a cached route, check that it is to the same
1039 	 * destination and is still up. If not, free it and try again.
1040 	 * Test rt_flags without holding rt_lock for performance reasons;
1041 	 * if the route is down it will hopefully be caught by the layer
1042 	 * below (since it uses this route as a hint) or during the
1043 	 * next transmit.
1044 	 */
1045 	if (ROUTE_UNUSABLE(ro) || dst->sin6_family != AF_INET6 ||
1046 	    !in6_are_addr_equal_scoped(&dst->sin6_addr, &ip6->ip6_dst, dst->sin6_scope_id, ip6_output_getdstifscope(m))) {
1047 		ROUTE_RELEASE(ro);
1048 	}
1049 
1050 	if (ro->ro_rt == NULL) {
1051 		bzero(dst, sizeof(*dst));
1052 		dst->sin6_family = AF_INET6;
1053 		dst->sin6_len = sizeof(struct sockaddr_in6);
1054 		dst->sin6_addr = ip6->ip6_dst;
1055 	}
1056 #if IPSEC
1057 	if (ip6obf.needipsec && needipsectun) {
1058 #if CONFIG_DTRACE
1059 		struct ifnet *trace_ifp = (ifpp_save != NULL) ? (*ifpp_save) : NULL;
1060 #endif /* CONFIG_DTRACE */
1061 		/*
1062 		 * All the extension headers will become inaccessible
1063 		 * (since they can be encrypted).
1064 		 * Don't panic, we need no more updates to extension headers
1065 		 * on inner IPv6 packet (since they are now encapsulated).
1066 		 *
1067 		 * IPv6 [ESP|AH] IPv6 [extension headers] payload
1068 		 */
1069 		bzero(&exthdrs, sizeof(exthdrs));
1070 		exthdrs.ip6e_ip6 = m;
1071 
1072 		ipsec_state.m = m;
1073 		route_copyout((struct route *)&ipsec_state.ro, (struct route *)ro,
1074 		    sizeof(struct route_in6));
1075 		ipsec_state.dst = SA(dst);
1076 
1077 		/* So that we can see packets inside the tunnel */
1078 		DTRACE_IP6(send, struct mbuf *, m, struct inpcb *, NULL,
1079 		    struct ip6_hdr *, ip6, struct ifnet *, trace_ifp,
1080 		    struct ip *, NULL, struct ip6_hdr *, ip6);
1081 
1082 		error = ipsec6_output_tunnel(&ipsec_state, sp, flags);
1083 		/* tunneled in IPv4? packet is gone */
1084 		if (ipsec_state.tunneled == 4) {
1085 			m = NULL;
1086 			goto evaluateloop;
1087 		}
1088 		m = ipsec_state.m;
1089 		ipsec_saved_route = ro;
1090 		ro = (struct route_in6 *)&ipsec_state.ro;
1091 		dst = SIN6(ipsec_state.dst);
1092 		if (error) {
1093 			/* mbuf is already reclaimed in ipsec6_output_tunnel. */
1094 			m = NULL;
1095 			switch (error) {
1096 			case EHOSTUNREACH:
1097 			case ENETUNREACH:
1098 			case EMSGSIZE:
1099 			case ENOBUFS:
1100 			case ENOMEM:
1101 				break;
1102 			default:
1103 				printf("ip6_output (ipsec): error code %d\n",
1104 				    error);
1105 				OS_FALLTHROUGH;
1106 			case ENOENT:
1107 				/* don't show these error codes to the user */
1108 				error = 0;
1109 				break;
1110 			}
1111 			goto bad;
1112 		}
1113 		/*
1114 		 * The packet has been encapsulated so the ifscope
1115 		 * is no longer valid since it does not apply to the
1116 		 * outer address: ignore the ifscope.
1117 		 */
1118 		if (flags & IPV6_OUTARGS) {
1119 			ip6oa->ip6oa_boundif = IFSCOPE_NONE;
1120 			ip6oa->ip6oa_flags &= ~IP6OAF_BOUND_IF;
1121 		}
1122 		if (opt != NULL && opt->ip6po_pktinfo != NULL) {
1123 			if (opt->ip6po_pktinfo->ipi6_ifindex != IFSCOPE_NONE) {
1124 				opt->ip6po_pktinfo->ipi6_ifindex = IFSCOPE_NONE;
1125 			}
1126 		}
1127 		exthdrs.ip6e_ip6 = m;
1128 	}
1129 #endif /* IPSEC */
1130 
1131 	/*
1132 	 * ifp should only be filled in for dummy net packets which will jump
1133 	 * to check_with_pf label.
1134 	 */
1135 	if (ifp != NULL) {
1136 		VERIFY(ip6obf.route_selected);
1137 	}
1138 
1139 	/* adjust pointer */
1140 	ip6 = mtod(m, struct ip6_hdr *);
1141 
1142 	if (ip6obf.select_srcif) {
1143 		bzero(&src_sa, sizeof(src_sa));
1144 		src_sa.sin6_family = AF_INET6;
1145 		src_sa.sin6_len = sizeof(src_sa);
1146 		src_sa.sin6_addr = ip6->ip6_src;
1147 		src_sa.sin6_scope_id = (!in6_embedded_scope && IN6_IS_SCOPE_EMBED(&ip6->ip6_src)) ? ip6_output_getsrcifscope(m) : IFSCOPE_NONE;
1148 	}
1149 	bzero(&dst_sa, sizeof(dst_sa));
1150 	dst_sa.sin6_family = AF_INET6;
1151 	dst_sa.sin6_len = sizeof(dst_sa);
1152 	dst_sa.sin6_addr = ip6->ip6_dst;
1153 	dst_sa.sin6_scope_id = (!in6_embedded_scope && IN6_IS_SCOPE_EMBED(&ip6->ip6_dst)) ? ip6_output_getdstifscope(m) : IFSCOPE_NONE;
1154 
1155 	/*
1156 	 * Only call in6_selectroute() on first iteration to avoid taking
1157 	 * multiple references on ifp and rt.
1158 	 *
1159 	 * in6_selectroute() might return an ifp with its reference held
1160 	 * even in the error case, so make sure to release its reference.
1161 	 * ip6oa may be NULL if IPV6_OUTARGS isn't set.
1162 	 */
1163 	if (!ip6obf.route_selected) {
1164 		error = in6_selectroute( ip6obf.select_srcif ? &src_sa : NULL,
1165 		    &dst_sa, opt, im6o, &src_ia, ro, &ifp, &rt, 0, ip6oa);
1166 
1167 		if (error != 0) {
1168 			switch (error) {
1169 			case EHOSTUNREACH:
1170 				ip6stat.ip6s_noroute++;
1171 				break;
1172 			case EADDRNOTAVAIL:
1173 			default:
1174 				break; /* XXX statistics? */
1175 			}
1176 			if (ifp != NULL) {
1177 				in6_ifstat_inc(ifp, ifs6_out_discard);
1178 			}
1179 			/* ifp (if non-NULL) will be released at the end */
1180 			goto bad;
1181 		}
1182 		ip6obf.route_selected = TRUE;
1183 	}
1184 	if (rt == NULL) {
1185 		/*
1186 		 * If in6_selectroute() does not return a route entry,
1187 		 * dst may not have been updated.
1188 		 */
1189 		*dst = dst_sa;  /* XXX */
1190 	}
1191 
1192 #if NECP
1193 	/* Catch-all to check if the interface is allowed */
1194 	if (!necp_packet_is_allowed_over_interface(m, ifp)) {
1195 		error = EHOSTUNREACH;
1196 		ip6stat.ip6s_necp_policy_drop++;
1197 		goto bad;
1198 	}
1199 #endif /* NECP */
1200 
1201 	/*
1202 	 * then rt (for unicast) and ifp must be non-NULL valid values.
1203 	 */
1204 	if (!(flags & IPV6_FORWARDING)) {
1205 		in6_ifstat_inc_na(ifp, ifs6_out_request);
1206 	}
1207 	if (rt != NULL) {
1208 		RT_LOCK(rt);
1209 		if (ia == NULL) {
1210 			ia = (struct in6_ifaddr *)(rt->rt_ifa);
1211 			if (ia != NULL) {
1212 				IFA_ADDREF(&ia->ia_ifa);
1213 			}
1214 		}
1215 		rt->rt_use++;
1216 		RT_UNLOCK(rt);
1217 	}
1218 
1219 	/*
1220 	 * The outgoing interface must be in the zone of source and
1221 	 * destination addresses (except local/loopback).  We should
1222 	 * use ia_ifp to support the case of sending packets to an
1223 	 * address of our own.
1224 	 */
1225 	if (ia != NULL && ia->ia_ifp) {
1226 		ifnet_reference(ia->ia_ifp);    /* for origifp */
1227 		if (origifp != NULL) {
1228 			ifnet_release(origifp);
1229 		}
1230 		origifp = ia->ia_ifp;
1231 	} else {
1232 		if (ifp != NULL) {
1233 			ifnet_reference(ifp);   /* for origifp */
1234 		}
1235 		if (origifp != NULL) {
1236 			ifnet_release(origifp);
1237 		}
1238 		origifp = ifp;
1239 	}
1240 
1241 	/* skip scope enforcements for local/loopback route */
1242 	if (rt == NULL || !(rt->rt_ifp->if_flags & IFF_LOOPBACK)) {
1243 		struct in6_addr src0, dst0;
1244 		u_int32_t zone;
1245 
1246 		src0 = ip6->ip6_src;
1247 		if (in6_setscope(&src0, origifp, &zone)) {
1248 			goto badscope;
1249 		}
1250 		bzero(&src_sa, sizeof(src_sa));
1251 		src_sa.sin6_family = AF_INET6;
1252 		src_sa.sin6_len = sizeof(src_sa);
1253 		src_sa.sin6_addr = ip6->ip6_src;
1254 		src_sa.sin6_scope_id = (!in6_embedded_scope && IN6_IS_SCOPE_EMBED(&src_sa.sin6_addr)) ? ip6_output_getsrcifscope(m) : IFSCOPE_NONE;
1255 		if ((sa6_recoverscope(&src_sa, TRUE) ||
1256 		    zone != src_sa.sin6_scope_id)) {
1257 			goto badscope;
1258 		}
1259 
1260 		dst0 = ip6->ip6_dst;
1261 		if ((in6_setscope(&dst0, origifp, &zone))) {
1262 			goto badscope;
1263 		}
1264 		/* re-initialize to be sure */
1265 		bzero(&dst_sa, sizeof(dst_sa));
1266 		dst_sa.sin6_family = AF_INET6;
1267 		dst_sa.sin6_len = sizeof(dst_sa);
1268 		dst_sa.sin6_addr = ip6->ip6_dst;
1269 		dst_sa.sin6_scope_id = (!in6_embedded_scope && IN6_IS_SCOPE_EMBED(&dst_sa.sin6_addr)) ?  ip6_output_getdstifscope(m) : IFSCOPE_NONE;
1270 		if ((sa6_recoverscope(&dst_sa, TRUE) ||
1271 		    zone != dst_sa.sin6_scope_id)) {
1272 			goto badscope;
1273 		}
1274 
1275 		/* scope check is done. */
1276 		goto routefound;
1277 
1278 badscope:
1279 		ip6stat.ip6s_badscope++;
1280 		in6_ifstat_inc(origifp, ifs6_out_discard);
1281 		if (error == 0) {
1282 			error = EHOSTUNREACH; /* XXX */
1283 		}
1284 		goto bad;
1285 	}
1286 
1287 routefound:
1288 	if (rt != NULL && !IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
1289 		if (opt != NULL && opt->ip6po_nextroute.ro_rt) {
1290 			/*
1291 			 * The nexthop is explicitly specified by the
1292 			 * application.  We assume the next hop is an IPv6
1293 			 * address.
1294 			 */
1295 			dst = SIN6(opt->ip6po_nexthop);
1296 		} else if ((rt->rt_flags & RTF_GATEWAY)) {
1297 			dst = SIN6(rt->rt_gateway);
1298 		}
1299 		/*
1300 		 * For packets destined to local/loopback, record the
1301 		 * source the source interface (which owns the source
1302 		 * address), as well as the output interface.  This is
1303 		 * needed to reconstruct the embedded zone for the
1304 		 * link-local address case in ip6_input().
1305 		 */
1306 		if (ia != NULL && (ifp->if_flags & IFF_LOOPBACK)) {
1307 			uint32_t srcidx;
1308 
1309 			if (src_ia != NULL) {
1310 				srcidx = src_ia->ia_ifp->if_index;
1311 			} else if (ro->ro_srcia != NULL) {
1312 				srcidx = ro->ro_srcia->ifa_ifp->if_index;
1313 			} else {
1314 				srcidx = 0;
1315 			}
1316 
1317 			ip6_setsrcifaddr_info(m, srcidx, NULL);
1318 			ip6_setdstifaddr_info(m, 0, ia);
1319 		}
1320 	}
1321 
1322 	if (!IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
1323 		m->m_flags &= ~(M_BCAST | M_MCAST); /* just in case */
1324 	} else {
1325 		struct  in6_multi *in6m;
1326 
1327 		m->m_flags = (m->m_flags & ~M_BCAST) | M_MCAST;
1328 		in6_ifstat_inc_na(ifp, ifs6_out_mcast);
1329 
1330 		/*
1331 		 * Confirm that the outgoing interface supports multicast.
1332 		 */
1333 		if (!(ifp->if_flags & IFF_MULTICAST)) {
1334 			ip6stat.ip6s_noroute++;
1335 			in6_ifstat_inc(ifp, ifs6_out_discard);
1336 			error = ENETUNREACH;
1337 			goto bad;
1338 		}
1339 		in6_multihead_lock_shared();
1340 		IN6_LOOKUP_MULTI(&ip6->ip6_dst, ifp, in6m);
1341 		in6_multihead_lock_done();
1342 		if (im6o != NULL) {
1343 			IM6O_LOCK(im6o);
1344 		}
1345 		if (in6m != NULL &&
1346 		    (im6o == NULL || im6o->im6o_multicast_loop)) {
1347 			if (im6o != NULL) {
1348 				IM6O_UNLOCK(im6o);
1349 			}
1350 			/*
1351 			 * If we belong to the destination multicast group
1352 			 * on the outgoing interface, and the caller did not
1353 			 * forbid loopback, loop back a copy.
1354 			 */
1355 			ip6_mloopback(NULL, ifp, m, dst, optlen, nxt0);
1356 		} else if (im6o != NULL) {
1357 			IM6O_UNLOCK(im6o);
1358 		}
1359 		if (in6m != NULL) {
1360 			IN6M_REMREF(in6m);
1361 		}
1362 		/*
1363 		 * Multicasts with a hoplimit of zero may be looped back,
1364 		 * above, but must not be transmitted on a network.
1365 		 * Also, multicasts addressed to the loopback interface
1366 		 * are not sent -- the above call to ip6_mloopback() will
1367 		 * loop back a copy if this host actually belongs to the
1368 		 * destination group on the loopback interface.
1369 		 */
1370 		if (ip6->ip6_hlim == 0 || (ifp->if_flags & IFF_LOOPBACK) ||
1371 		    IN6_IS_ADDR_MC_INTFACELOCAL(&ip6->ip6_dst)) {
1372 			/* remove m from the packetchain and continue looping */
1373 			if (m != NULL) {
1374 				m_freem(m);
1375 			}
1376 			m = NULL;
1377 			goto evaluateloop;
1378 		}
1379 	}
1380 
1381 	/*
1382 	 * Fill the outgoing inteface to tell the upper layer
1383 	 * to increment per-interface statistics.
1384 	 */
1385 	if (ifpp != NULL && *ifpp == NULL) {
1386 		ifnet_reference(ifp);   /* for caller */
1387 		*ifpp = ifp;
1388 	}
1389 
1390 	/* Determine path MTU. */
1391 	if ((error = ip6_getpmtu(ro_pmtu, ro, ifp, &finaldst, ifp->if_index, &mtu)) != 0) {
1392 		goto bad;
1393 	}
1394 
1395 	/*
1396 	 * The caller of this function may specify to use the minimum MTU
1397 	 * in some cases.
1398 	 * An advanced API option (IPV6_USE_MIN_MTU) can also override MTU
1399 	 * setting.  The logic is a bit complicated; by default, unicast
1400 	 * packets will follow path MTU while multicast packets will be sent at
1401 	 * the minimum MTU.  If IP6PO_MINMTU_ALL is specified, all packets
1402 	 * including unicast ones will be sent at the minimum MTU.  Multicast
1403 	 * packets will always be sent at the minimum MTU unless
1404 	 * IP6PO_MINMTU_DISABLE is explicitly specified.
1405 	 * See RFC 3542 for more details.
1406 	 */
1407 	if (mtu > IPV6_MMTU) {
1408 		if ((flags & IPV6_MINMTU)) {
1409 			mtu = IPV6_MMTU;
1410 		} else if (opt && opt->ip6po_minmtu == IP6PO_MINMTU_ALL) {
1411 			mtu = IPV6_MMTU;
1412 		} else if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) &&
1413 		    (opt == NULL ||
1414 		    opt->ip6po_minmtu != IP6PO_MINMTU_DISABLE)) {
1415 			mtu = IPV6_MMTU;
1416 		}
1417 	}
1418 
1419 	/*
1420 	 * clear embedded scope identifiers if necessary.
1421 	 * in6_clearscope will touch the addresses only when necessary.
1422 	 */
1423 	in6_clearscope(&ip6->ip6_src);
1424 	in6_clearscope(&ip6->ip6_dst);
1425 	/*
1426 	 * If the outgoing packet contains a hop-by-hop options header,
1427 	 * it must be examined and processed even by the source node.
1428 	 * (RFC 2460, section 4.)
1429 	 */
1430 	if (exthdrs.ip6e_hbh != NULL) {
1431 		struct ip6_hbh *hbh = mtod(exthdrs.ip6e_hbh, struct ip6_hbh *);
1432 		u_int32_t dummy; /* XXX unused */
1433 		uint32_t oplen = 0; /* for ip6_process_hopopts() */
1434 #if DIAGNOSTIC
1435 		if ((hbh->ip6h_len + 1) << 3 > exthdrs.ip6e_hbh->m_len) {
1436 			panic("ip6e_hbh is not continuous");
1437 		}
1438 #endif
1439 		/*
1440 		 * XXX: If we have to send an ICMPv6 error to the sender,
1441 		 * we need the M_LOOP flag since icmp6_error() expects
1442 		 * the IPv6 and the hop-by-hop options header are
1443 		 * continuous unless the flag is set.
1444 		 */
1445 		m->m_flags |= M_LOOP;
1446 		m->m_pkthdr.rcvif = ifp;
1447 		if (ip6_process_hopopts(m, (u_int8_t *)(hbh + 1),
1448 		    ((hbh->ip6h_len + 1) << 3) - sizeof(struct ip6_hbh),
1449 		    &dummy, &oplen) < 0) {
1450 			/*
1451 			 * m was already freed at this point. Set to NULL so it
1452 			 * is not re-freed at end of ip6_output_list.
1453 			 */
1454 			m = NULL;
1455 			error = EINVAL; /* better error? */
1456 			goto bad;
1457 		}
1458 		m->m_flags &= ~M_LOOP; /* XXX */
1459 		m->m_pkthdr.rcvif = NULL;
1460 	}
1461 
1462 #if DUMMYNET
1463 check_with_pf:
1464 #endif /* DUMMYNET */
1465 #if PF
1466 	if (PF_IS_ENABLED && !skip_pf) {
1467 #if DUMMYNET
1468 
1469 		/*
1470 		 * TODO: Need to save opt->ip6po_flags for reinjection
1471 		 * rdar://10434993
1472 		 */
1473 		args.fwa_oif = ifp;
1474 		args.fwa_oflags = flags;
1475 		if (flags & IPV6_OUTARGS) {
1476 			args.fwa_ip6oa = ip6oa;
1477 		}
1478 		args.fwa_ro6 = ro;
1479 		args.fwa_dst6 = dst;
1480 		args.fwa_ro6_pmtu = ro_pmtu;
1481 		args.fwa_origifp = origifp;
1482 		args.fwa_mtu = mtu;
1483 		args.fwa_unfragpartlen = unfragpartlen;
1484 		args.fwa_exthdrs = &exthdrs;
1485 		/* Invoke outbound packet filter */
1486 		error = pf_af_hook(ifp, NULL, &m, AF_INET6, FALSE, &args);
1487 #else /* !DUMMYNET */
1488 		error = pf_af_hook(ifp, NULL, &m, AF_INET6, FALSE, NULL);
1489 #endif /* !DUMMYNET */
1490 
1491 		if (error != 0 || m == NULL) {
1492 			if (m != NULL) {
1493 				panic("%s: unexpected packet %p",
1494 				    __func__, m);
1495 				/* NOTREACHED */
1496 			}
1497 			/* m was already freed by callee and is now NULL.  */
1498 			goto evaluateloop;
1499 		}
1500 		ip6 = mtod(m, struct ip6_hdr *);
1501 	}
1502 #endif /* PF */
1503 
1504 #ifdef IPSEC
1505 	/* clean ipsec history before fragmentation */
1506 	ipsec_delaux(m);
1507 #endif /* IPSEC */
1508 
1509 	if (ip6oa != NULL) {
1510 		u_int8_t dscp;
1511 
1512 		dscp = (ntohl(ip6->ip6_flow) & IP6FLOW_DSCP_MASK) >> IP6FLOW_DSCP_SHIFT;
1513 
1514 		error = set_packet_qos(m, ifp,
1515 		    ip6oa->ip6oa_flags & IP6OAF_QOSMARKING_ALLOWED ? TRUE : FALSE,
1516 		    ip6oa->ip6oa_sotc, ip6oa->ip6oa_netsvctype, &dscp);
1517 		if (error == 0) {
1518 			ip6->ip6_flow &= ~htonl(IP6FLOW_DSCP_MASK);
1519 			ip6->ip6_flow |= htonl((u_int32_t)dscp << IP6FLOW_DSCP_SHIFT);
1520 		} else {
1521 			printf("%s if_dscp_for_mbuf() error %d\n", __func__, error);
1522 			error = 0;
1523 		}
1524 	}
1525 	/*
1526 	 * Determine whether fragmentation is necessary. If so, m is passed
1527 	 * back as a chain of packets and original mbuf is freed. Otherwise, m
1528 	 * is unchanged.
1529 	 */
1530 	error = ip6_fragment_packet(&m, opt, ip6oa,
1531 	    &exthdrs, ifp, mtu, unfragpartlen, nxt0,
1532 	    optlen);
1533 
1534 	if (error) {
1535 		goto bad;
1536 	}
1537 
1538 /*
1539  * The evaluateloop label is where we decide whether to continue looping over
1540  * packets or call into nd code to send.
1541  */
1542 evaluateloop:
1543 
1544 	/*
1545 	 * m may be NULL when we jump to the evaluateloop label from PF or
1546 	 * other code that can drop packets.
1547 	 */
1548 	if (m != NULL) {
1549 		/*
1550 		 * If we already have a chain to send, tack m onto the end.
1551 		 * Otherwise make m the start and end of the to-be-sent chain.
1552 		 */
1553 		if (sendchain != NULL) {
1554 			sendchain_last->m_nextpkt = m;
1555 		} else {
1556 			sendchain = m;
1557 		}
1558 
1559 		/* Fragmentation may mean m is a chain. Find the last packet. */
1560 		while (m->m_nextpkt) {
1561 			m = m->m_nextpkt;
1562 		}
1563 		sendchain_last = m;
1564 		pktcnt++;
1565 	}
1566 
1567 	/* Fill in next m from inputchain as appropriate. */
1568 	m = inputchain;
1569 	if (m != NULL) {
1570 		/* Isolate m from rest of input chain. */
1571 		inputchain = m->m_nextpkt;
1572 		m->m_nextpkt = NULL;
1573 
1574 		/*
1575 		 * Clear exthdrs and ipsec_state so stale contents are not
1576 		 * reused. Note this also clears the exthdrs.merged flag.
1577 		 */
1578 		bzero(&exthdrs, sizeof(exthdrs));
1579 		bzero(&ipsec_state, sizeof(ipsec_state));
1580 
1581 		/* Continue looping. */
1582 		goto loopit;
1583 	}
1584 
1585 	/*
1586 	 * If we get here, there's no more mbufs in inputchain, so send the
1587 	 * sendchain if there is one.
1588 	 */
1589 	if (pktcnt > 0) {
1590 		error = nd6_output_list(ifp, origifp, sendchain, dst,
1591 		    ro->ro_rt, adv);
1592 		/*
1593 		 * Fall through to done label even in error case because
1594 		 * nd6_output_list frees packetchain in both success and
1595 		 * failure cases.
1596 		 */
1597 	}
1598 
1599 done:
1600 	if (ifpp_save != NULL && *ifpp_save != NULL) {
1601 		ifnet_release(*ifpp_save);
1602 		*ifpp_save = NULL;
1603 	}
1604 	ROUTE_RELEASE(&ip6route);
1605 #if IPSEC
1606 	ROUTE_RELEASE(&ipsec_state.ro);
1607 	if (sp != NULL) {
1608 		key_freesp(sp, KEY_SADB_UNLOCKED);
1609 	}
1610 #endif /* IPSEC */
1611 #if NECP
1612 	ROUTE_RELEASE(&necp_route);
1613 #endif /* NECP */
1614 #if DUMMYNET
1615 	ROUTE_RELEASE(&saved_route);
1616 	ROUTE_RELEASE(&saved_ro_pmtu);
1617 #endif /* DUMMYNET */
1618 
1619 	if (ia != NULL) {
1620 		IFA_REMREF(&ia->ia_ifa);
1621 	}
1622 	if (src_ia != NULL) {
1623 		IFA_REMREF(&src_ia->ia_ifa);
1624 	}
1625 	if (ifp != NULL) {
1626 		ifnet_release(ifp);
1627 	}
1628 	if (origifp != NULL) {
1629 		ifnet_release(origifp);
1630 	}
1631 	if (ip6_output_measure) {
1632 		net_perf_measure_time(&net_perf, &start_tv, packets_processed);
1633 		net_perf_histogram(&net_perf, packets_processed);
1634 	}
1635 	return error;
1636 
1637 freehdrs:
1638 	if (exthdrs.ip6e_hbh != NULL) {
1639 		if (exthdrs.merged) {
1640 			panic("Double free of ip6e_hbh");
1641 		}
1642 		m_freem(exthdrs.ip6e_hbh);
1643 	}
1644 	if (exthdrs.ip6e_dest1 != NULL) {
1645 		if (exthdrs.merged) {
1646 			panic("Double free of ip6e_dest1");
1647 		}
1648 		m_freem(exthdrs.ip6e_dest1);
1649 	}
1650 	if (exthdrs.ip6e_rthdr != NULL) {
1651 		if (exthdrs.merged) {
1652 			panic("Double free of ip6e_rthdr");
1653 		}
1654 		m_freem(exthdrs.ip6e_rthdr);
1655 	}
1656 	if (exthdrs.ip6e_dest2 != NULL) {
1657 		if (exthdrs.merged) {
1658 			panic("Double free of ip6e_dest2");
1659 		}
1660 		m_freem(exthdrs.ip6e_dest2);
1661 	}
1662 	/* FALLTHRU */
1663 bad:
1664 	if (inputchain != NULL) {
1665 		m_freem_list(inputchain);
1666 	}
1667 	if (sendchain != NULL) {
1668 		m_freem_list(sendchain);
1669 	}
1670 	if (m != NULL) {
1671 		m_freem(m);
1672 	}
1673 
1674 	goto done;
1675 
1676 #undef ipf_pktopts
1677 #undef exthdrs
1678 #undef ip6route
1679 #undef ipsec_state
1680 #undef saved_route
1681 #undef saved_ro_pmtu
1682 #undef args
1683 }
1684 
1685 /* ip6_fragment_packet
1686  *
1687  * The fragmentation logic is rather complex:
1688  * 1: normal case (dontfrag == 0)
1689  * 1-a:	send as is if tlen <= path mtu
1690  * 1-b:	fragment if tlen > path mtu
1691  *
1692  * 2: if user asks us not to fragment (dontfrag == 1)
1693  * 2-a:	send as is if tlen <= interface mtu
1694  * 2-b:	error if tlen > interface mtu
1695  */
1696 
1697 static int
ip6_fragment_packet(struct mbuf ** mptr,struct ip6_pktopts * opt,struct ip6_out_args * ip6oa,struct ip6_exthdrs * exthdrsp,struct ifnet * ifp,uint32_t mtu,uint32_t unfragpartlen,int nxt0,uint32_t optlen)1698 ip6_fragment_packet(struct mbuf **mptr, struct ip6_pktopts *opt,
1699     struct ip6_out_args *ip6oa, struct ip6_exthdrs *exthdrsp,
1700     struct ifnet *ifp, uint32_t mtu, uint32_t unfragpartlen,
1701     int nxt0, uint32_t optlen)
1702 {
1703 	VERIFY(NULL != mptr);
1704 	struct mbuf *m = *mptr;
1705 	int error = 0;
1706 	uint32_t tlen = m->m_pkthdr.len;
1707 	boolean_t dontfrag = (opt != NULL && (opt->ip6po_flags & IP6PO_DONTFRAG)) ||
1708 	    (ip6oa != NULL && (ip6oa->ip6oa_flags & IP6OAF_DONT_FRAG));
1709 
1710 	if (m->m_pkthdr.pkt_flags & PKTF_FORWARDED) {
1711 		dontfrag = TRUE;
1712 		/*
1713 		 * Discard partial sum information if this packet originated
1714 		 * from another interface; the packet would already have the
1715 		 * final checksum and we shouldn't recompute it.
1716 		 */
1717 		if ((m->m_pkthdr.csum_flags & (CSUM_DATA_VALID | CSUM_PARTIAL)) ==
1718 		    (CSUM_DATA_VALID | CSUM_PARTIAL)) {
1719 			m->m_pkthdr.csum_flags &= ~CSUM_TX_FLAGS;
1720 			m->m_pkthdr.csum_data = 0;
1721 		}
1722 	}
1723 
1724 	/* Access without acquiring nd_ifinfo lock for performance */
1725 	if (dontfrag && tlen > IN6_LINKMTU(ifp)) {      /* case 2-b */
1726 		/*
1727 		 * We do not notify the connection in the same outbound path
1728 		 * to avoid lock ordering issues.
1729 		 * The returned error should imply that the packet is too big
1730 		 * and the application should query the PMTU for a given destination.
1731 		 */
1732 		return EMSGSIZE;
1733 	}
1734 
1735 	/*
1736 	 * transmit packet without fragmentation
1737 	 */
1738 	if (dontfrag ||
1739 	    (tlen <= mtu || TSO_IPV6_OK(ifp, m) ||
1740 	    (ifp->if_hwassist & CSUM_FRAGMENT_IPV6))) {
1741 		/*
1742 		 * mppn not updated in this case because no new chain is formed
1743 		 * and inserted
1744 		 */
1745 		ip6_output_checksum(ifp, mtu, m, nxt0, tlen, optlen);
1746 	} else {
1747 		/*
1748 		 * time to fragment - cases 1-b is handled inside
1749 		 * ip6_do_fragmentation().
1750 		 * mppn is passed down to be updated to point at fragment chain.
1751 		 */
1752 		u_int8_t *lexthdrsp;
1753 
1754 		if (exthdrsp->ip6e_rthdr != NULL) {
1755 			lexthdrsp = mtod(exthdrsp->ip6e_rthdr, uint8_t *);
1756 		} else if (exthdrsp->ip6e_dest1 != NULL) {
1757 			lexthdrsp = mtod(exthdrsp->ip6e_dest1, uint8_t *);
1758 		} else if (exthdrsp->ip6e_hbh != NULL) {
1759 			lexthdrsp = mtod(exthdrsp->ip6e_hbh, uint8_t *);
1760 		} else {
1761 			lexthdrsp = NULL;
1762 		}
1763 		error = ip6_do_fragmentation(mptr, optlen, ifp,
1764 		    unfragpartlen, mtod(m, struct ip6_hdr *), lexthdrsp, mtu,
1765 		    nxt0, htonl(ip6_randomid()));
1766 	}
1767 
1768 	return error;
1769 }
1770 
1771 /*
1772  * ip6_do_fragmentation() is called by ip6_fragment_packet() after determining
1773  * the packet needs to be fragmented. on success, morig is freed and a chain
1774  * of fragments is linked into the packet chain where morig existed. Otherwise,
1775  * an errno is returned.
1776  * optlen:        total length of all extension headers (excludes the IPv6 header).
1777  * unfragpartlen: length of the per-fragment headers which consist of the IPv6
1778  *                header plus any extension headers that must be processed by nodes
1779  *                en route to the destination.
1780  * lexthdrsp:     pointer to the last extension header in the unfragmentable part
1781  *                or NULL.
1782  * nxt0:          upper-layer protocol number.
1783  * id:            Identification value to be used in the fragment header.
1784  */
1785 int
ip6_do_fragmentation(struct mbuf ** mptr,uint32_t optlen,struct ifnet * ifp,uint32_t unfragpartlen,struct ip6_hdr * ip6,uint8_t * lexthdrsp,uint32_t mtu,int nxt0,uint32_t id)1786 ip6_do_fragmentation(struct mbuf **mptr, uint32_t optlen, struct ifnet *ifp,
1787     uint32_t unfragpartlen, struct ip6_hdr *ip6, uint8_t *lexthdrsp,
1788     uint32_t mtu, int nxt0, uint32_t id)
1789 {
1790 	VERIFY(NULL != mptr);
1791 	int error = 0;
1792 
1793 	struct mbuf *morig = *mptr;
1794 	struct mbuf *first_mbufp = NULL;
1795 	struct mbuf *last_mbufp = NULL;
1796 
1797 	uint32_t tlen = morig->m_pkthdr.len;
1798 
1799 	/* try to fragment the packet. case 1-b */
1800 	if ((morig->m_pkthdr.csum_flags & CSUM_TSO_IPV6)) {
1801 		/* TSO and fragment aren't compatible */
1802 		in6_ifstat_inc(ifp, ifs6_out_fragfail);
1803 		return EMSGSIZE;
1804 	} else if (mtu < IPV6_MMTU) {
1805 		/* path MTU cannot be less than IPV6_MMTU */
1806 		in6_ifstat_inc(ifp, ifs6_out_fragfail);
1807 		return EMSGSIZE;
1808 	} else if (ip6->ip6_plen == 0) {
1809 		/* jumbo payload cannot be fragmented */
1810 		in6_ifstat_inc(ifp, ifs6_out_fragfail);
1811 		return EMSGSIZE;
1812 	} else {
1813 		uint32_t hlen, off, len;
1814 		struct mbuf **mnext = NULL;
1815 		struct ip6_frag *ip6f;
1816 		u_char nextproto;
1817 
1818 		/*
1819 		 * Too large for the destination or interface;
1820 		 * fragment if possible.
1821 		 * Must be able to put at least 8 bytes per fragment.
1822 		 */
1823 		hlen = unfragpartlen;
1824 		if (mtu > IPV6_MAXPACKET) {
1825 			mtu = IPV6_MAXPACKET;
1826 		}
1827 
1828 		len = (mtu - hlen - sizeof(struct ip6_frag)) & ~7;
1829 		if (len < 8) {
1830 			in6_ifstat_inc(ifp, ifs6_out_fragfail);
1831 			return EMSGSIZE;
1832 		}
1833 
1834 		/*
1835 		 * Change the next header field of the last header in the
1836 		 * unfragmentable part.
1837 		 */
1838 		if (lexthdrsp != NULL) {
1839 			nextproto = *lexthdrsp;
1840 			*lexthdrsp = IPPROTO_FRAGMENT;
1841 		} else {
1842 			nextproto = ip6->ip6_nxt;
1843 			ip6->ip6_nxt = IPPROTO_FRAGMENT;
1844 		}
1845 
1846 		if (morig->m_pkthdr.csum_flags & CSUM_DELAY_IPV6_DATA) {
1847 			in6_delayed_cksum_offset(morig, 0, optlen, nxt0);
1848 		}
1849 
1850 		/*
1851 		 * Loop through length of segment after first fragment,
1852 		 * make new header and copy data of each part and link onto
1853 		 * chain.
1854 		 */
1855 		for (off = hlen; off < tlen; off += len) {
1856 			struct ip6_hdr *new_mhip6;
1857 			struct mbuf *new_m;
1858 			struct mbuf *m_frgpart;
1859 
1860 			MGETHDR(new_m, M_DONTWAIT, MT_HEADER);  /* MAC-OK */
1861 			if (new_m == NULL) {
1862 				error = ENOBUFS;
1863 				ip6stat.ip6s_odropped++;
1864 				break;
1865 			}
1866 			new_m->m_pkthdr.rcvif = NULL;
1867 			new_m->m_flags = morig->m_flags & M_COPYFLAGS;
1868 
1869 			if (first_mbufp != NULL) {
1870 				/* Every pass through loop but first */
1871 				*mnext = new_m;
1872 				last_mbufp = new_m;
1873 			} else {
1874 				/* This is the first element of the fragment chain */
1875 				first_mbufp = new_m;
1876 				last_mbufp = new_m;
1877 			}
1878 			mnext = &new_m->m_nextpkt;
1879 
1880 			new_m->m_data += max_linkhdr;
1881 			new_mhip6 = mtod(new_m, struct ip6_hdr *);
1882 			*new_mhip6 = *ip6;
1883 			new_m->m_len = sizeof(*new_mhip6);
1884 
1885 			error = ip6_insertfraghdr(morig, new_m, hlen, &ip6f);
1886 			if (error) {
1887 				ip6stat.ip6s_odropped++;
1888 				break;
1889 			}
1890 
1891 			ip6f->ip6f_offlg = htons((u_short)((off - hlen) & ~7));
1892 			if (off + len >= tlen) {
1893 				len = tlen - off;
1894 			} else {
1895 				ip6f->ip6f_offlg |= IP6F_MORE_FRAG;
1896 			}
1897 			new_mhip6->ip6_plen = htons((u_short)(len + hlen +
1898 			    sizeof(*ip6f) - sizeof(struct ip6_hdr)));
1899 
1900 			if ((m_frgpart = m_copy(morig, off, len)) == NULL) {
1901 				error = ENOBUFS;
1902 				ip6stat.ip6s_odropped++;
1903 				break;
1904 			}
1905 			m_cat(new_m, m_frgpart);
1906 			new_m->m_pkthdr.len = len + hlen + sizeof(*ip6f);
1907 			new_m->m_pkthdr.rcvif = NULL;
1908 
1909 			M_COPY_CLASSIFIER(new_m, morig);
1910 			M_COPY_PFTAG(new_m, morig);
1911 			M_COPY_NECPTAG(new_m, morig);
1912 
1913 			ip6f->ip6f_reserved = 0;
1914 			ip6f->ip6f_ident = id;
1915 			ip6f->ip6f_nxt = nextproto;
1916 			ip6stat.ip6s_ofragments++;
1917 			in6_ifstat_inc(ifp, ifs6_out_fragcreat);
1918 		}
1919 
1920 		if (error) {
1921 			/* free all the fragments created */
1922 			if (first_mbufp != NULL) {
1923 				m_freem_list(first_mbufp);
1924 				first_mbufp = NULL;
1925 			}
1926 			last_mbufp = NULL;
1927 		} else {
1928 			/* successful fragmenting */
1929 			m_freem(morig);
1930 			*mptr = first_mbufp;
1931 			last_mbufp->m_nextpkt = NULL;
1932 			ip6stat.ip6s_fragmented++;
1933 			in6_ifstat_inc(ifp, ifs6_out_fragok);
1934 		}
1935 	}
1936 	return error;
1937 }
1938 
1939 static int
ip6_copyexthdr(struct mbuf ** mp,caddr_t hdr,int hlen)1940 ip6_copyexthdr(struct mbuf **mp, caddr_t hdr, int hlen)
1941 {
1942 	struct mbuf *m;
1943 
1944 	if (hlen > MCLBYTES) {
1945 		return ENOBUFS; /* XXX */
1946 	}
1947 	MGET(m, M_DONTWAIT, MT_DATA);
1948 	if (m == NULL) {
1949 		return ENOBUFS;
1950 	}
1951 
1952 	if (hlen > MLEN) {
1953 		MCLGET(m, M_DONTWAIT);
1954 		if (!(m->m_flags & M_EXT)) {
1955 			m_free(m);
1956 			return ENOBUFS;
1957 		}
1958 	}
1959 	m->m_len = hlen;
1960 	if (hdr != NULL) {
1961 		bcopy(hdr, mtod(m, caddr_t), hlen);
1962 	}
1963 
1964 	*mp = m;
1965 	return 0;
1966 }
1967 
1968 static void
ip6_out_cksum_stats(int proto,u_int32_t len)1969 ip6_out_cksum_stats(int proto, u_int32_t len)
1970 {
1971 	switch (proto) {
1972 	case IPPROTO_TCP:
1973 		tcp_out6_cksum_stats(len);
1974 		break;
1975 	case IPPROTO_UDP:
1976 		udp_out6_cksum_stats(len);
1977 		break;
1978 	default:
1979 		/* keep only TCP or UDP stats for now */
1980 		break;
1981 	}
1982 }
1983 
1984 /*
1985  * Process a delayed payload checksum calculation (outbound path.)
1986  *
1987  * hoff is the number of bytes beyond the mbuf data pointer which
1988  * points to the IPv6 header.  optlen is the number of bytes, if any,
1989  * between the end of IPv6 header and the beginning of the ULP payload
1990  * header, which represents the extension headers.  If optlen is less
1991  * than zero, this routine will bail when it detects extension headers.
1992  *
1993  * Returns a bitmask representing all the work done in software.
1994  */
1995 uint32_t
in6_finalize_cksum(struct mbuf * m,uint32_t hoff,int32_t optlen,int32_t nxt0,uint32_t csum_flags)1996 in6_finalize_cksum(struct mbuf *m, uint32_t hoff, int32_t optlen,
1997     int32_t nxt0, uint32_t csum_flags)
1998 {
1999 	unsigned char buf[sizeof(struct ip6_hdr)] __attribute__((aligned(8)));
2000 	struct ip6_hdr *ip6;
2001 	uint32_t offset, mlen, hlen, olen, sw_csum;
2002 	uint16_t csum, ulpoff, plen;
2003 	uint8_t nxt;
2004 
2005 	_CASSERT(sizeof(csum) == sizeof(uint16_t));
2006 	VERIFY(m->m_flags & M_PKTHDR);
2007 
2008 	sw_csum = (csum_flags & m->m_pkthdr.csum_flags);
2009 
2010 	if ((sw_csum &= CSUM_DELAY_IPV6_DATA) == 0) {
2011 		goto done;
2012 	}
2013 
2014 	mlen = m->m_pkthdr.len;                         /* total mbuf len */
2015 	hlen = sizeof(*ip6);                            /* IPv6 header len */
2016 
2017 	/* sanity check (need at least IPv6 header) */
2018 	if (mlen < (hoff + hlen)) {
2019 		panic("%s: mbuf %p pkt len (%u) < hoff+ip6_hdr "
2020 		    "(%u+%u)\n", __func__, m, mlen, hoff, hlen);
2021 		/* NOTREACHED */
2022 	}
2023 
2024 	/*
2025 	 * In case the IPv6 header is not contiguous, or not 32-bit
2026 	 * aligned, copy it to a local buffer.
2027 	 */
2028 	if ((hoff + hlen) > m->m_len ||
2029 	    !IP6_HDR_ALIGNED_P(mtod(m, caddr_t) + hoff)) {
2030 		m_copydata(m, hoff, hlen, (caddr_t)buf);
2031 		ip6 = (struct ip6_hdr *)(void *)buf;
2032 	} else {
2033 		ip6 = (struct ip6_hdr *)(void *)(m->m_data + hoff);
2034 	}
2035 
2036 	nxt = ip6->ip6_nxt;
2037 	plen = ntohs(ip6->ip6_plen);
2038 	if (plen != (mlen - (hoff + hlen))) {
2039 		plen = OSSwapInt16(plen);
2040 		if (plen != (mlen - (hoff + hlen))) {
2041 			/* Don't complain for jumbograms */
2042 			if (plen != 0 || nxt != IPPROTO_HOPOPTS) {
2043 				printf("%s: mbuf 0x%llx proto %d IPv6 "
2044 				    "plen %d (%x) [swapped %d (%x)] doesn't "
2045 				    "match actual packet length; %d is used "
2046 				    "instead\n", __func__,
2047 				    (uint64_t)VM_KERNEL_ADDRPERM(m), nxt,
2048 				    ip6->ip6_plen, ip6->ip6_plen, plen, plen,
2049 				    (mlen - (hoff + hlen)));
2050 			}
2051 			plen = (uint16_t)(mlen - (hoff + hlen));
2052 		}
2053 	}
2054 
2055 	if (optlen < 0) {
2056 		/* next header isn't TCP/UDP and we don't know optlen, bail */
2057 		if (nxt != IPPROTO_TCP && nxt != IPPROTO_UDP) {
2058 			sw_csum = 0;
2059 			goto done;
2060 		}
2061 		olen = 0;
2062 	} else {
2063 		/* caller supplied the original transport number; use it */
2064 		if (nxt0 >= 0) {
2065 			nxt = (uint8_t)nxt0;
2066 		}
2067 		olen = optlen;
2068 	}
2069 
2070 	offset = hoff + hlen + olen;                    /* ULP header */
2071 
2072 	/* sanity check */
2073 	if (mlen < offset) {
2074 		panic("%s: mbuf %p pkt len (%u) < hoff+ip6_hdr+ext_hdr "
2075 		    "(%u+%u+%u)\n", __func__, m, mlen, hoff, hlen, olen);
2076 		/* NOTREACHED */
2077 	}
2078 
2079 	/*
2080 	 * offset is added to the lower 16-bit value of csum_data,
2081 	 * which is expected to contain the ULP offset; therefore
2082 	 * CSUM_PARTIAL offset adjustment must be undone.
2083 	 */
2084 	if ((m->m_pkthdr.csum_flags & (CSUM_PARTIAL | CSUM_DATA_VALID)) ==
2085 	    (CSUM_PARTIAL | CSUM_DATA_VALID)) {
2086 		/*
2087 		 * Get back the original ULP offset (this will
2088 		 * undo the CSUM_PARTIAL logic in ip6_output.)
2089 		 */
2090 		m->m_pkthdr.csum_data = (m->m_pkthdr.csum_tx_stuff -
2091 		    m->m_pkthdr.csum_tx_start);
2092 	}
2093 
2094 	ulpoff = (m->m_pkthdr.csum_data & 0xffff);      /* ULP csum offset */
2095 
2096 	if (mlen < (ulpoff + sizeof(csum))) {
2097 		panic("%s: mbuf %p pkt len (%u) proto %d invalid ULP "
2098 		    "cksum offset (%u) cksum flags 0x%x\n", __func__,
2099 		    m, mlen, nxt, ulpoff, m->m_pkthdr.csum_flags);
2100 		/* NOTREACHED */
2101 	}
2102 
2103 	csum = inet6_cksum(m, 0, offset, plen - olen);
2104 
2105 	/* Update stats */
2106 	ip6_out_cksum_stats(nxt, plen - olen);
2107 
2108 	/* RFC1122 4.1.3.4 */
2109 	if (csum == 0 &&
2110 	    (m->m_pkthdr.csum_flags & (CSUM_UDPIPV6 | CSUM_ZERO_INVERT))) {
2111 		csum = 0xffff;
2112 	}
2113 
2114 	/* Insert the checksum in the ULP csum field */
2115 	offset += ulpoff;
2116 	if ((offset + sizeof(csum)) > m->m_len) {
2117 		m_copyback(m, offset, sizeof(csum), &csum);
2118 	} else if (IP6_HDR_ALIGNED_P(mtod(m, char *) + hoff)) {
2119 		*(uint16_t *)(void *)(mtod(m, char *) + offset) = csum;
2120 	} else {
2121 		bcopy(&csum, (mtod(m, char *) + offset), sizeof(csum));
2122 	}
2123 	m->m_pkthdr.csum_flags &= ~(CSUM_DELAY_IPV6_DATA | CSUM_DATA_VALID |
2124 	    CSUM_PARTIAL | CSUM_ZERO_INVERT);
2125 
2126 done:
2127 	return sw_csum;
2128 }
2129 
2130 /*
2131  * Insert jumbo payload option.
2132  */
2133 static int
ip6_insert_jumboopt(struct ip6_exthdrs * exthdrs,u_int32_t plen)2134 ip6_insert_jumboopt(struct ip6_exthdrs *exthdrs, u_int32_t plen)
2135 {
2136 	struct mbuf *mopt;
2137 	u_char *optbuf;
2138 	u_int32_t v;
2139 
2140 #define JUMBOOPTLEN     8       /* length of jumbo payload option and padding */
2141 
2142 	/*
2143 	 * If there is no hop-by-hop options header, allocate new one.
2144 	 * If there is one but it doesn't have enough space to store the
2145 	 * jumbo payload option, allocate a cluster to store the whole options.
2146 	 * Otherwise, use it to store the options.
2147 	 */
2148 	if (exthdrs->ip6e_hbh == NULL) {
2149 		MGET(mopt, M_DONTWAIT, MT_DATA);
2150 		if (mopt == NULL) {
2151 			return ENOBUFS;
2152 		}
2153 		mopt->m_len = JUMBOOPTLEN;
2154 		optbuf = mtod(mopt, u_char *);
2155 		optbuf[1] = 0;  /* = ((JUMBOOPTLEN) >> 3) - 1 */
2156 		exthdrs->ip6e_hbh = mopt;
2157 	} else {
2158 		struct ip6_hbh *hbh;
2159 
2160 		mopt = exthdrs->ip6e_hbh;
2161 		if (M_TRAILINGSPACE(mopt) < JUMBOOPTLEN) {
2162 			/*
2163 			 * XXX assumption:
2164 			 * - exthdrs->ip6e_hbh is not referenced from places
2165 			 *   other than exthdrs.
2166 			 * - exthdrs->ip6e_hbh is not an mbuf chain.
2167 			 */
2168 			u_int32_t oldoptlen = mopt->m_len;
2169 			struct mbuf *n;
2170 
2171 			/*
2172 			 * XXX: give up if the whole (new) hbh header does
2173 			 * not fit even in an mbuf cluster.
2174 			 */
2175 			if (oldoptlen + JUMBOOPTLEN > MCLBYTES) {
2176 				return ENOBUFS;
2177 			}
2178 
2179 			/*
2180 			 * As a consequence, we must always prepare a cluster
2181 			 * at this point.
2182 			 */
2183 			MGET(n, M_DONTWAIT, MT_DATA);
2184 			if (n != NULL) {
2185 				MCLGET(n, M_DONTWAIT);
2186 				if (!(n->m_flags & M_EXT)) {
2187 					m_freem(n);
2188 					n = NULL;
2189 				}
2190 			}
2191 			if (n == NULL) {
2192 				return ENOBUFS;
2193 			}
2194 			n->m_len = oldoptlen + JUMBOOPTLEN;
2195 			bcopy(mtod(mopt, caddr_t), mtod(n, caddr_t),
2196 			    oldoptlen);
2197 			optbuf = mtod(n, u_char *) + oldoptlen;
2198 			m_freem(mopt);
2199 			mopt = exthdrs->ip6e_hbh = n;
2200 		} else {
2201 			optbuf = mtod(mopt, u_char *) + mopt->m_len;
2202 			mopt->m_len += JUMBOOPTLEN;
2203 		}
2204 		optbuf[0] = IP6OPT_PADN;
2205 		optbuf[1] = 1;
2206 
2207 		/*
2208 		 * Adjust the header length according to the pad and
2209 		 * the jumbo payload option.
2210 		 */
2211 		hbh = mtod(mopt, struct ip6_hbh *);
2212 		hbh->ip6h_len += (JUMBOOPTLEN >> 3);
2213 	}
2214 
2215 	/* fill in the option. */
2216 	optbuf[2] = IP6OPT_JUMBO;
2217 	optbuf[3] = 4;
2218 	v = (u_int32_t)htonl(plen + JUMBOOPTLEN);
2219 	bcopy(&v, &optbuf[4], sizeof(u_int32_t));
2220 
2221 	/* finally, adjust the packet header length */
2222 	exthdrs->ip6e_ip6->m_pkthdr.len += JUMBOOPTLEN;
2223 
2224 	return 0;
2225 #undef JUMBOOPTLEN
2226 }
2227 
2228 /*
2229  * Insert fragment header and copy unfragmentable header portions.
2230  */
2231 static int
ip6_insertfraghdr(struct mbuf * m0,struct mbuf * m,int hlen,struct ip6_frag ** frghdrp)2232 ip6_insertfraghdr(struct mbuf *m0, struct mbuf *m, int hlen,
2233     struct ip6_frag **frghdrp)
2234 {
2235 	struct mbuf *n, *mlast;
2236 
2237 	if (hlen > sizeof(struct ip6_hdr)) {
2238 		n = m_copym(m0, sizeof(struct ip6_hdr),
2239 		    hlen - sizeof(struct ip6_hdr), M_DONTWAIT);
2240 		if (n == NULL) {
2241 			return ENOBUFS;
2242 		}
2243 		m->m_next = n;
2244 	} else {
2245 		n = m;
2246 	}
2247 
2248 	/* Search for the last mbuf of unfragmentable part. */
2249 	for (mlast = n; mlast->m_next; mlast = mlast->m_next) {
2250 		;
2251 	}
2252 
2253 	if (!(mlast->m_flags & M_EXT) &&
2254 	    M_TRAILINGSPACE(mlast) >= sizeof(struct ip6_frag)) {
2255 		/* use the trailing space of the last mbuf for the frag hdr */
2256 		*frghdrp = (struct ip6_frag *)(mtod(mlast, caddr_t) +
2257 		    mlast->m_len);
2258 		mlast->m_len += sizeof(struct ip6_frag);
2259 		m->m_pkthdr.len += sizeof(struct ip6_frag);
2260 	} else {
2261 		/* allocate a new mbuf for the fragment header */
2262 		struct mbuf *mfrg;
2263 
2264 		MGET(mfrg, M_DONTWAIT, MT_DATA);
2265 		if (mfrg == NULL) {
2266 			return ENOBUFS;
2267 		}
2268 		mfrg->m_len = sizeof(struct ip6_frag);
2269 		*frghdrp = mtod(mfrg, struct ip6_frag *);
2270 		mlast->m_next = mfrg;
2271 	}
2272 
2273 	return 0;
2274 }
2275 
2276 static int
ip6_getpmtu(struct route_in6 * ro_pmtu,struct route_in6 * ro,struct ifnet * ifp,struct in6_addr * dst,uint32_t dst_ifscope,u_int32_t * mtup)2277 ip6_getpmtu(struct route_in6 *ro_pmtu, struct route_in6 *ro,
2278     struct ifnet *ifp, struct in6_addr *dst, uint32_t dst_ifscope, u_int32_t *mtup)
2279 {
2280 	u_int32_t mtu = 0;
2281 	int error = 0;
2282 
2283 	if (ro_pmtu != ro) {
2284 		/* The first hop and the final destination may differ. */
2285 		struct sockaddr_in6 *sa6_dst = SIN6(&ro_pmtu->ro_dst);
2286 		if (ROUTE_UNUSABLE(ro_pmtu) ||
2287 		    !in6_are_addr_equal_scoped(&sa6_dst->sin6_addr, dst, sa6_dst->sin6_scope_id, dst_ifscope)) {
2288 			ROUTE_RELEASE(ro_pmtu);
2289 		}
2290 
2291 		if (ro_pmtu->ro_rt == NULL) {
2292 			bzero(sa6_dst, sizeof(*sa6_dst));
2293 			sa6_dst->sin6_family = AF_INET6;
2294 			sa6_dst->sin6_len = sizeof(struct sockaddr_in6);
2295 			sa6_dst->sin6_addr = *dst;
2296 
2297 			rtalloc_scoped((struct route *)ro_pmtu,
2298 			    ifp != NULL ? ifp->if_index : IFSCOPE_NONE);
2299 		}
2300 	}
2301 
2302 	if (ro_pmtu->ro_rt != NULL) {
2303 		u_int32_t ifmtu;
2304 
2305 		if (ifp == NULL) {
2306 			ifp = ro_pmtu->ro_rt->rt_ifp;
2307 		}
2308 		/* Access without acquiring nd_ifinfo lock for performance */
2309 		ifmtu = IN6_LINKMTU(ifp);
2310 
2311 		/*
2312 		 * Access rmx_mtu without holding the route entry lock,
2313 		 * for performance; this isn't something that changes
2314 		 * often, so optimize.
2315 		 */
2316 		mtu = ro_pmtu->ro_rt->rt_rmx.rmx_mtu;
2317 		if (mtu > ifmtu || mtu == 0) {
2318 			/*
2319 			 * The MTU on the route is larger than the MTU on
2320 			 * the interface!  This shouldn't happen, unless the
2321 			 * MTU of the interface has been changed after the
2322 			 * interface was brought up.  Change the MTU in the
2323 			 * route to match the interface MTU (as long as the
2324 			 * field isn't locked).
2325 			 *
2326 			 * if MTU on the route is 0, we need to fix the MTU.
2327 			 * this case happens with path MTU discovery timeouts.
2328 			 */
2329 			mtu = ifmtu;
2330 			if (!(ro_pmtu->ro_rt->rt_rmx.rmx_locks & RTV_MTU)) {
2331 				ro_pmtu->ro_rt->rt_rmx.rmx_mtu = mtu; /* XXX */
2332 			}
2333 		}
2334 	} else {
2335 		if (ifp) {
2336 			/* Don't hold nd_ifinfo lock for performance */
2337 			mtu = IN6_LINKMTU(ifp);
2338 		} else {
2339 			error = EHOSTUNREACH; /* XXX */
2340 		}
2341 	}
2342 
2343 	*mtup = mtu;
2344 	return error;
2345 }
2346 
2347 /*
2348  * IP6 socket option processing.
2349  */
2350 int
ip6_ctloutput(struct socket * so,struct sockopt * sopt)2351 ip6_ctloutput(struct socket *so, struct sockopt *sopt)
2352 {
2353 	int optdatalen, uproto;
2354 	void *optdata;
2355 	int privileged;
2356 	struct inpcb *in6p = sotoinpcb(so);
2357 	int error = 0, optval = 0;
2358 	int level, op = -1, optname = 0;
2359 	size_t optlen = 0;
2360 	struct proc *p;
2361 	lck_mtx_t *mutex_held = NULL;
2362 
2363 	VERIFY(sopt != NULL);
2364 
2365 	level = sopt->sopt_level;
2366 	op = sopt->sopt_dir;
2367 	optname = sopt->sopt_name;
2368 	optlen = sopt->sopt_valsize;
2369 	p = sopt->sopt_p;
2370 	uproto = (int)SOCK_PROTO(so);
2371 
2372 	privileged = (proc_suser(p) == 0);
2373 
2374 	if (level == IPPROTO_IPV6) {
2375 		boolean_t capture_exthdrstat_in = FALSE;
2376 		switch (op) {
2377 		case SOPT_SET:
2378 			mutex_held = socket_getlock(so, PR_F_WILLUNLOCK);
2379 			/*
2380 			 * Wait if we are in the middle of ip6_output
2381 			 * as we unlocked the socket there and don't
2382 			 * want to overwrite the IP options
2383 			 */
2384 			if (in6p->inp_sndinprog_cnt > 0) {
2385 				in6p->inp_sndingprog_waiters++;
2386 
2387 				while (in6p->inp_sndinprog_cnt > 0) {
2388 					msleep(&in6p->inp_sndinprog_cnt, mutex_held,
2389 					    PSOCK | PCATCH, "inp_sndinprog_cnt",
2390 					    NULL);
2391 				}
2392 				in6p->inp_sndingprog_waiters--;
2393 			}
2394 			switch (optname) {
2395 			case IPV6_2292PKTOPTIONS: {
2396 				struct mbuf *m;
2397 
2398 				error = soopt_getm(sopt, &m);
2399 				if (error != 0) {
2400 					break;
2401 				}
2402 				error = soopt_mcopyin(sopt, m);
2403 				if (error != 0) {
2404 					break;
2405 				}
2406 				error = ip6_pcbopts(&in6p->in6p_outputopts,
2407 				    m, so, sopt);
2408 				m_freem(m);
2409 				break;
2410 			}
2411 
2412 			/*
2413 			 * Use of some Hop-by-Hop options or some
2414 			 * Destination options, might require special
2415 			 * privilege.  That is, normal applications
2416 			 * (without special privilege) might be forbidden
2417 			 * from setting certain options in outgoing packets,
2418 			 * and might never see certain options in received
2419 			 * packets. [RFC 2292 Section 6]
2420 			 * KAME specific note:
2421 			 *  KAME prevents non-privileged users from sending or
2422 			 *  receiving ANY hbh/dst options in order to avoid
2423 			 *  overhead of parsing options in the kernel.
2424 			 */
2425 			case IPV6_RECVHOPOPTS:
2426 			case IPV6_RECVDSTOPTS:
2427 			case IPV6_RECVRTHDRDSTOPTS:
2428 				if (!privileged) {
2429 					break;
2430 				}
2431 				OS_FALLTHROUGH;
2432 			case IPV6_UNICAST_HOPS:
2433 			case IPV6_HOPLIMIT:
2434 			case IPV6_RECVPKTINFO:
2435 			case IPV6_RECVHOPLIMIT:
2436 			case IPV6_RECVRTHDR:
2437 			case IPV6_RECVPATHMTU:
2438 			case IPV6_RECVTCLASS:
2439 			case IPV6_V6ONLY:
2440 			case IPV6_AUTOFLOWLABEL:
2441 				if (optlen != sizeof(int)) {
2442 					error = EINVAL;
2443 					break;
2444 				}
2445 				error = sooptcopyin(sopt, &optval,
2446 				    sizeof(optval), sizeof(optval));
2447 				if (error) {
2448 					break;
2449 				}
2450 
2451 				switch (optname) {
2452 				case IPV6_UNICAST_HOPS:
2453 					if (optval < -1 || optval >= 256) {
2454 						error = EINVAL;
2455 					} else {
2456 						/* -1 = kernel default */
2457 						in6p->in6p_hops = (short)optval;
2458 						if (in6p->inp_vflag &
2459 						    INP_IPV4) {
2460 							in6p->inp_ip_ttl =
2461 							    (uint8_t)optval;
2462 						}
2463 					}
2464 					break;
2465 #define OPTSET(bit) do {                                                \
2466 	if (optval)                                                     \
2467 	        in6p->inp_flags |= (bit);                               \
2468 	else                                                            \
2469 	        in6p->inp_flags &= ~(bit);                              \
2470 } while (0)
2471 
2472 #define OPTSET2292(bit) do {                                            \
2473 	in6p->inp_flags |= IN6P_RFC2292;                                \
2474 	if (optval)                                                     \
2475 	        in6p->inp_flags |= (bit);                               \
2476 	else                                                            \
2477 	        in6p->inp_flags &= ~(bit);                              \
2478 } while (0)
2479 
2480 #define OPTBIT(bit) (in6p->inp_flags & (bit) ? 1 : 0)
2481 
2482 				case IPV6_RECVPKTINFO:
2483 					/* cannot mix with RFC2292 */
2484 					if (OPTBIT(IN6P_RFC2292)) {
2485 						error = EINVAL;
2486 						break;
2487 					}
2488 					OPTSET(IN6P_PKTINFO);
2489 					break;
2490 
2491 				case IPV6_HOPLIMIT: {
2492 					struct ip6_pktopts **optp;
2493 
2494 					/* cannot mix with RFC2292 */
2495 					if (OPTBIT(IN6P_RFC2292)) {
2496 						error = EINVAL;
2497 						break;
2498 					}
2499 					optp = &in6p->in6p_outputopts;
2500 					error = ip6_pcbopt(IPV6_HOPLIMIT,
2501 					    (u_char *)&optval, sizeof(optval),
2502 					    optp, uproto);
2503 					break;
2504 				}
2505 
2506 				case IPV6_RECVHOPLIMIT:
2507 					/* cannot mix with RFC2292 */
2508 					if (OPTBIT(IN6P_RFC2292)) {
2509 						error = EINVAL;
2510 						break;
2511 					}
2512 					OPTSET(IN6P_HOPLIMIT);
2513 					break;
2514 
2515 				case IPV6_RECVHOPOPTS:
2516 					/* cannot mix with RFC2292 */
2517 					if (OPTBIT(IN6P_RFC2292)) {
2518 						error = EINVAL;
2519 						break;
2520 					}
2521 					OPTSET(IN6P_HOPOPTS);
2522 					capture_exthdrstat_in = TRUE;
2523 					break;
2524 
2525 				case IPV6_RECVDSTOPTS:
2526 					/* cannot mix with RFC2292 */
2527 					if (OPTBIT(IN6P_RFC2292)) {
2528 						error = EINVAL;
2529 						break;
2530 					}
2531 					OPTSET(IN6P_DSTOPTS);
2532 					capture_exthdrstat_in = TRUE;
2533 					break;
2534 
2535 				case IPV6_RECVRTHDRDSTOPTS:
2536 					/* cannot mix with RFC2292 */
2537 					if (OPTBIT(IN6P_RFC2292)) {
2538 						error = EINVAL;
2539 						break;
2540 					}
2541 					OPTSET(IN6P_RTHDRDSTOPTS);
2542 					capture_exthdrstat_in = TRUE;
2543 					break;
2544 
2545 				case IPV6_RECVRTHDR:
2546 					/* cannot mix with RFC2292 */
2547 					if (OPTBIT(IN6P_RFC2292)) {
2548 						error = EINVAL;
2549 						break;
2550 					}
2551 					OPTSET(IN6P_RTHDR);
2552 					capture_exthdrstat_in = TRUE;
2553 					break;
2554 
2555 				case IPV6_RECVPATHMTU:
2556 					/*
2557 					 * We ignore this option for TCP
2558 					 * sockets.
2559 					 * (RFC3542 leaves this case
2560 					 * unspecified.)
2561 					 */
2562 					if (uproto != IPPROTO_TCP) {
2563 						OPTSET(IN6P_MTU);
2564 					}
2565 					break;
2566 
2567 				case IPV6_V6ONLY:
2568 					/*
2569 					 * make setsockopt(IPV6_V6ONLY)
2570 					 * available only prior to bind(2).
2571 					 * see ipng mailing list, Jun 22 2001.
2572 					 */
2573 					if (in6p->inp_lport ||
2574 					    !IN6_IS_ADDR_UNSPECIFIED(
2575 						    &in6p->in6p_laddr)) {
2576 						error = EINVAL;
2577 						break;
2578 					}
2579 					OPTSET(IN6P_IPV6_V6ONLY);
2580 					if (optval) {
2581 						in6p->inp_vflag &= ~INP_IPV4;
2582 					} else {
2583 						in6p->inp_vflag |= INP_IPV4;
2584 					}
2585 					break;
2586 
2587 				case IPV6_RECVTCLASS:
2588 					/* we can mix with RFC2292 */
2589 					OPTSET(IN6P_TCLASS);
2590 					break;
2591 
2592 				case IPV6_AUTOFLOWLABEL:
2593 					OPTSET(IN6P_AUTOFLOWLABEL);
2594 					break;
2595 				}
2596 				break;
2597 
2598 			case IPV6_TCLASS:
2599 			case IPV6_DONTFRAG:
2600 			case IPV6_USE_MIN_MTU:
2601 			case IPV6_PREFER_TEMPADDR: {
2602 				struct ip6_pktopts **optp;
2603 
2604 				if (optlen != sizeof(optval)) {
2605 					error = EINVAL;
2606 					break;
2607 				}
2608 				error = sooptcopyin(sopt, &optval,
2609 				    sizeof(optval), sizeof(optval));
2610 				if (error) {
2611 					break;
2612 				}
2613 
2614 				optp = &in6p->in6p_outputopts;
2615 				error = ip6_pcbopt(optname, (u_char *)&optval,
2616 				    sizeof(optval), optp, uproto);
2617 
2618 				if (optname == IPV6_TCLASS) {
2619 					// Add in the ECN flags
2620 					u_int8_t tos = (in6p->inp_ip_tos & ~IPTOS_ECN_MASK);
2621 					u_int8_t ecn = optval & IPTOS_ECN_MASK;
2622 					in6p->inp_ip_tos = tos | ecn;
2623 				}
2624 				break;
2625 			}
2626 
2627 			case IPV6_2292PKTINFO:
2628 			case IPV6_2292HOPLIMIT:
2629 			case IPV6_2292HOPOPTS:
2630 			case IPV6_2292DSTOPTS:
2631 			case IPV6_2292RTHDR:
2632 				/* RFC 2292 */
2633 				if (optlen != sizeof(int)) {
2634 					error = EINVAL;
2635 					break;
2636 				}
2637 				error = sooptcopyin(sopt, &optval,
2638 				    sizeof(optval), sizeof(optval));
2639 				if (error) {
2640 					break;
2641 				}
2642 				switch (optname) {
2643 				case IPV6_2292PKTINFO:
2644 					OPTSET2292(IN6P_PKTINFO);
2645 					break;
2646 				case IPV6_2292HOPLIMIT:
2647 					OPTSET2292(IN6P_HOPLIMIT);
2648 					break;
2649 				case IPV6_2292HOPOPTS:
2650 					/*
2651 					 * Check super-user privilege.
2652 					 * See comments for IPV6_RECVHOPOPTS.
2653 					 */
2654 					if (!privileged) {
2655 						return EPERM;
2656 					}
2657 					OPTSET2292(IN6P_HOPOPTS);
2658 					capture_exthdrstat_in = TRUE;
2659 					break;
2660 				case IPV6_2292DSTOPTS:
2661 					if (!privileged) {
2662 						return EPERM;
2663 					}
2664 					OPTSET2292(IN6P_DSTOPTS |
2665 					    IN6P_RTHDRDSTOPTS); /* XXX */
2666 					capture_exthdrstat_in = TRUE;
2667 					break;
2668 				case IPV6_2292RTHDR:
2669 					OPTSET2292(IN6P_RTHDR);
2670 					capture_exthdrstat_in = TRUE;
2671 					break;
2672 				}
2673 				break;
2674 
2675 			case IPV6_3542PKTINFO:
2676 			case IPV6_3542HOPOPTS:
2677 			case IPV6_3542RTHDR:
2678 			case IPV6_3542DSTOPTS:
2679 			case IPV6_RTHDRDSTOPTS:
2680 			case IPV6_3542NEXTHOP: {
2681 				struct ip6_pktopts **optp;
2682 				/* new advanced API (RFC3542) */
2683 				struct mbuf *m;
2684 
2685 				/* cannot mix with RFC2292 */
2686 				if (OPTBIT(IN6P_RFC2292)) {
2687 					error = EINVAL;
2688 					break;
2689 				}
2690 				error = soopt_getm(sopt, &m);
2691 				if (error != 0) {
2692 					break;
2693 				}
2694 				error = soopt_mcopyin(sopt, m);
2695 				if (error != 0) {
2696 					break;
2697 				}
2698 
2699 				optp = &in6p->in6p_outputopts;
2700 				error = ip6_pcbopt(optname, mtod(m, u_char *),
2701 				    m->m_len, optp, uproto);
2702 				m_freem(m);
2703 				break;
2704 			}
2705 #undef OPTSET
2706 			case IPV6_MULTICAST_IF:
2707 			case IPV6_MULTICAST_HOPS:
2708 			case IPV6_MULTICAST_LOOP:
2709 			case IPV6_JOIN_GROUP:
2710 			case IPV6_LEAVE_GROUP:
2711 			case IPV6_MSFILTER:
2712 			case MCAST_BLOCK_SOURCE:
2713 			case MCAST_UNBLOCK_SOURCE:
2714 			case MCAST_JOIN_GROUP:
2715 			case MCAST_LEAVE_GROUP:
2716 			case MCAST_JOIN_SOURCE_GROUP:
2717 			case MCAST_LEAVE_SOURCE_GROUP:
2718 				error = ip6_setmoptions(in6p, sopt);
2719 				break;
2720 
2721 			case IPV6_PORTRANGE:
2722 				error = sooptcopyin(sopt, &optval,
2723 				    sizeof(optval), sizeof(optval));
2724 				if (error) {
2725 					break;
2726 				}
2727 
2728 				switch (optval) {
2729 				case IPV6_PORTRANGE_DEFAULT:
2730 					in6p->inp_flags &= ~(INP_LOWPORT);
2731 					in6p->inp_flags &= ~(INP_HIGHPORT);
2732 					break;
2733 
2734 				case IPV6_PORTRANGE_HIGH:
2735 					in6p->inp_flags &= ~(INP_LOWPORT);
2736 					in6p->inp_flags |= INP_HIGHPORT;
2737 					break;
2738 
2739 				case IPV6_PORTRANGE_LOW:
2740 					in6p->inp_flags &= ~(INP_HIGHPORT);
2741 					in6p->inp_flags |= INP_LOWPORT;
2742 					break;
2743 
2744 				default:
2745 					error = EINVAL;
2746 					break;
2747 				}
2748 				break;
2749 #if IPSEC
2750 			case IPV6_IPSEC_POLICY: {
2751 				caddr_t req = NULL;
2752 				size_t len = 0;
2753 				struct mbuf *m;
2754 
2755 				if ((error = soopt_getm(sopt, &m)) != 0) {
2756 					break;
2757 				}
2758 				if ((error = soopt_mcopyin(sopt, m)) != 0) {
2759 					break;
2760 				}
2761 
2762 				req = mtod(m, caddr_t);
2763 				len = m->m_len;
2764 				error = ipsec6_set_policy(in6p, optname, req,
2765 				    len, privileged);
2766 				m_freem(m);
2767 				break;
2768 			}
2769 #endif /* IPSEC */
2770 			/*
2771 			 * IPv6 variant of IP_BOUND_IF; for details see
2772 			 * comments on IP_BOUND_IF in ip_ctloutput().
2773 			 */
2774 			case IPV6_BOUND_IF:
2775 				/* This option is settable only on IPv6 */
2776 				if (!(in6p->inp_vflag & INP_IPV6)) {
2777 					error = EINVAL;
2778 					break;
2779 				}
2780 
2781 				error = sooptcopyin(sopt, &optval,
2782 				    sizeof(optval), sizeof(optval));
2783 
2784 				if (error) {
2785 					break;
2786 				}
2787 
2788 				error = inp_bindif(in6p, optval, NULL);
2789 				break;
2790 
2791 			case IPV6_NO_IFT_CELLULAR:
2792 				/* This option is settable only for IPv6 */
2793 				if (!(in6p->inp_vflag & INP_IPV6)) {
2794 					error = EINVAL;
2795 					break;
2796 				}
2797 
2798 				error = sooptcopyin(sopt, &optval,
2799 				    sizeof(optval), sizeof(optval));
2800 
2801 				if (error) {
2802 					break;
2803 				}
2804 
2805 				/* once set, it cannot be unset */
2806 				if (!optval && INP_NO_CELLULAR(in6p)) {
2807 					error = EINVAL;
2808 					break;
2809 				}
2810 
2811 				error = so_set_restrictions(so,
2812 				    SO_RESTRICT_DENY_CELLULAR);
2813 				break;
2814 
2815 			case IPV6_OUT_IF:
2816 				/* This option is not settable */
2817 				error = EINVAL;
2818 				break;
2819 
2820 			default:
2821 				error = ENOPROTOOPT;
2822 				break;
2823 			}
2824 			if (capture_exthdrstat_in) {
2825 				if (uproto == IPPROTO_TCP) {
2826 					INC_ATOMIC_INT64_LIM(net_api_stats.nas_sock_inet6_stream_exthdr_in);
2827 				} else if (uproto == IPPROTO_UDP) {
2828 					INC_ATOMIC_INT64_LIM(net_api_stats.nas_sock_inet6_dgram_exthdr_in);
2829 				}
2830 			}
2831 			break;
2832 
2833 		case SOPT_GET:
2834 			switch (optname) {
2835 			case IPV6_2292PKTOPTIONS:
2836 				/*
2837 				 * RFC3542 (effectively) deprecated the
2838 				 * semantics of the 2292-style pktoptions.
2839 				 * Since it was not reliable in nature (i.e.,
2840 				 * applications had to expect the lack of some
2841 				 * information after all), it would make sense
2842 				 * to simplify this part by always returning
2843 				 * empty data.
2844 				 */
2845 				sopt->sopt_valsize = 0;
2846 				break;
2847 
2848 			case IPV6_RECVHOPOPTS:
2849 			case IPV6_RECVDSTOPTS:
2850 			case IPV6_RECVRTHDRDSTOPTS:
2851 			case IPV6_UNICAST_HOPS:
2852 			case IPV6_RECVPKTINFO:
2853 			case IPV6_RECVHOPLIMIT:
2854 			case IPV6_RECVRTHDR:
2855 			case IPV6_RECVPATHMTU:
2856 			case IPV6_V6ONLY:
2857 			case IPV6_PORTRANGE:
2858 			case IPV6_RECVTCLASS:
2859 			case IPV6_AUTOFLOWLABEL:
2860 				switch (optname) {
2861 				case IPV6_RECVHOPOPTS:
2862 					optval = OPTBIT(IN6P_HOPOPTS);
2863 					break;
2864 
2865 				case IPV6_RECVDSTOPTS:
2866 					optval = OPTBIT(IN6P_DSTOPTS);
2867 					break;
2868 
2869 				case IPV6_RECVRTHDRDSTOPTS:
2870 					optval = OPTBIT(IN6P_RTHDRDSTOPTS);
2871 					break;
2872 
2873 				case IPV6_UNICAST_HOPS:
2874 					optval = in6p->in6p_hops;
2875 					break;
2876 
2877 				case IPV6_RECVPKTINFO:
2878 					optval = OPTBIT(IN6P_PKTINFO);
2879 					break;
2880 
2881 				case IPV6_RECVHOPLIMIT:
2882 					optval = OPTBIT(IN6P_HOPLIMIT);
2883 					break;
2884 
2885 				case IPV6_RECVRTHDR:
2886 					optval = OPTBIT(IN6P_RTHDR);
2887 					break;
2888 
2889 				case IPV6_RECVPATHMTU:
2890 					optval = OPTBIT(IN6P_MTU);
2891 					break;
2892 
2893 				case IPV6_V6ONLY:
2894 					optval = OPTBIT(IN6P_IPV6_V6ONLY);
2895 					break;
2896 
2897 				case IPV6_PORTRANGE: {
2898 					int flags;
2899 					flags = in6p->inp_flags;
2900 					if (flags & INP_HIGHPORT) {
2901 						optval = IPV6_PORTRANGE_HIGH;
2902 					} else if (flags & INP_LOWPORT) {
2903 						optval = IPV6_PORTRANGE_LOW;
2904 					} else {
2905 						optval = 0;
2906 					}
2907 					break;
2908 				}
2909 				case IPV6_RECVTCLASS:
2910 					optval = OPTBIT(IN6P_TCLASS);
2911 					break;
2912 
2913 				case IPV6_AUTOFLOWLABEL:
2914 					optval = OPTBIT(IN6P_AUTOFLOWLABEL);
2915 					break;
2916 				}
2917 				if (error) {
2918 					break;
2919 				}
2920 				error = sooptcopyout(sopt, &optval,
2921 				    sizeof(optval));
2922 				break;
2923 
2924 			case IPV6_PATHMTU: {
2925 				u_int32_t pmtu = 0;
2926 				struct ip6_mtuinfo mtuinfo;
2927 				struct route_in6 sro;
2928 
2929 				bzero(&sro, sizeof(sro));
2930 
2931 				if (!(so->so_state & SS_ISCONNECTED)) {
2932 					return ENOTCONN;
2933 				}
2934 				/*
2935 				 * XXX: we dot not consider the case of source
2936 				 * routing, or optional information to specify
2937 				 * the outgoing interface.
2938 				 */
2939 				error = ip6_getpmtu(&sro, NULL, NULL,
2940 				    &in6p->in6p_faddr, in6p->inp_fifscope, &pmtu);
2941 				ROUTE_RELEASE(&sro);
2942 				if (error) {
2943 					break;
2944 				}
2945 				if (pmtu > IPV6_MAXPACKET) {
2946 					pmtu = IPV6_MAXPACKET;
2947 				}
2948 
2949 				bzero(&mtuinfo, sizeof(mtuinfo));
2950 				mtuinfo.ip6m_mtu = (u_int32_t)pmtu;
2951 				optdata = (void *)&mtuinfo;
2952 				optdatalen = sizeof(mtuinfo);
2953 				error = sooptcopyout(sopt, optdata,
2954 				    optdatalen);
2955 				break;
2956 			}
2957 
2958 			case IPV6_2292PKTINFO:
2959 			case IPV6_2292HOPLIMIT:
2960 			case IPV6_2292HOPOPTS:
2961 			case IPV6_2292RTHDR:
2962 			case IPV6_2292DSTOPTS:
2963 				switch (optname) {
2964 				case IPV6_2292PKTINFO:
2965 					optval = OPTBIT(IN6P_PKTINFO);
2966 					break;
2967 				case IPV6_2292HOPLIMIT:
2968 					optval = OPTBIT(IN6P_HOPLIMIT);
2969 					break;
2970 				case IPV6_2292HOPOPTS:
2971 					optval = OPTBIT(IN6P_HOPOPTS);
2972 					break;
2973 				case IPV6_2292RTHDR:
2974 					optval = OPTBIT(IN6P_RTHDR);
2975 					break;
2976 				case IPV6_2292DSTOPTS:
2977 					optval = OPTBIT(IN6P_DSTOPTS |
2978 					    IN6P_RTHDRDSTOPTS);
2979 					break;
2980 				}
2981 				error = sooptcopyout(sopt, &optval,
2982 				    sizeof(optval));
2983 				break;
2984 
2985 			case IPV6_PKTINFO:
2986 			case IPV6_HOPOPTS:
2987 			case IPV6_RTHDR:
2988 			case IPV6_DSTOPTS:
2989 			case IPV6_RTHDRDSTOPTS:
2990 			case IPV6_NEXTHOP:
2991 			case IPV6_TCLASS:
2992 			case IPV6_DONTFRAG:
2993 			case IPV6_USE_MIN_MTU:
2994 			case IPV6_PREFER_TEMPADDR:
2995 				error = ip6_getpcbopt(in6p->in6p_outputopts,
2996 				    optname, sopt);
2997 				break;
2998 
2999 			case IPV6_MULTICAST_IF:
3000 			case IPV6_MULTICAST_HOPS:
3001 			case IPV6_MULTICAST_LOOP:
3002 			case IPV6_MSFILTER:
3003 				error = ip6_getmoptions(in6p, sopt);
3004 				break;
3005 #if IPSEC
3006 			case IPV6_IPSEC_POLICY: {
3007 				error = 0; /* This option is no longer supported */
3008 				break;
3009 			}
3010 #endif /* IPSEC */
3011 			case IPV6_BOUND_IF:
3012 				if (in6p->inp_flags & INP_BOUND_IF) {
3013 					optval = in6p->inp_boundifp->if_index;
3014 				}
3015 				error = sooptcopyout(sopt, &optval,
3016 				    sizeof(optval));
3017 				break;
3018 
3019 			case IPV6_NO_IFT_CELLULAR:
3020 				optval = INP_NO_CELLULAR(in6p) ? 1 : 0;
3021 				error = sooptcopyout(sopt, &optval,
3022 				    sizeof(optval));
3023 				break;
3024 
3025 			case IPV6_OUT_IF:
3026 				optval = (in6p->in6p_last_outifp != NULL) ?
3027 				    in6p->in6p_last_outifp->if_index : 0;
3028 				error = sooptcopyout(sopt, &optval,
3029 				    sizeof(optval));
3030 				break;
3031 
3032 			default:
3033 				error = ENOPROTOOPT;
3034 				break;
3035 			}
3036 			break;
3037 		}
3038 	} else {
3039 		error = EINVAL;
3040 	}
3041 	return error;
3042 }
3043 
3044 int
ip6_raw_ctloutput(struct socket * so,struct sockopt * sopt)3045 ip6_raw_ctloutput(struct socket *so, struct sockopt *sopt)
3046 {
3047 	int error = 0, optval;
3048 	size_t optlen;
3049 	const int icmp6off = offsetof(struct icmp6_hdr, icmp6_cksum);
3050 	struct inpcb *in6p = sotoinpcb(so);
3051 	int level, op, optname;
3052 
3053 	level = sopt->sopt_level;
3054 	op = sopt->sopt_dir;
3055 	optname = sopt->sopt_name;
3056 	optlen = sopt->sopt_valsize;
3057 
3058 	if (level != IPPROTO_IPV6) {
3059 		return EINVAL;
3060 	}
3061 
3062 	switch (optname) {
3063 	case IPV6_CHECKSUM:
3064 		/*
3065 		 * For ICMPv6 sockets, no modification allowed for checksum
3066 		 * offset, permit "no change" values to help existing apps.
3067 		 *
3068 		 * RFC3542 says: "An attempt to set IPV6_CHECKSUM
3069 		 * for an ICMPv6 socket will fail."
3070 		 * The current behavior does not meet RFC3542.
3071 		 */
3072 		switch (op) {
3073 		case SOPT_SET:
3074 			if (optlen != sizeof(int)) {
3075 				error = EINVAL;
3076 				break;
3077 			}
3078 			error = sooptcopyin(sopt, &optval, sizeof(optval),
3079 			    sizeof(optval));
3080 			if (error) {
3081 				break;
3082 			}
3083 			if ((optval % 2) != 0) {
3084 				/* the API assumes even offset values */
3085 				error = EINVAL;
3086 			} else if (SOCK_PROTO(so) == IPPROTO_ICMPV6) {
3087 				if (optval != icmp6off) {
3088 					error = EINVAL;
3089 				}
3090 			} else {
3091 				in6p->in6p_cksum = optval;
3092 			}
3093 			break;
3094 
3095 		case SOPT_GET:
3096 			if (SOCK_PROTO(so) == IPPROTO_ICMPV6) {
3097 				optval = icmp6off;
3098 			} else {
3099 				optval = in6p->in6p_cksum;
3100 			}
3101 
3102 			error = sooptcopyout(sopt, &optval, sizeof(optval));
3103 			break;
3104 
3105 		default:
3106 			error = EINVAL;
3107 			break;
3108 		}
3109 		break;
3110 
3111 	default:
3112 		error = ENOPROTOOPT;
3113 		break;
3114 	}
3115 
3116 	return error;
3117 }
3118 
3119 /*
3120  * Set up IP6 options in pcb for insertion in output packets or
3121  * specifying behavior of outgoing packets.
3122  */
3123 static int
ip6_pcbopts(struct ip6_pktopts ** pktopt,struct mbuf * m,struct socket * so,struct sockopt * sopt)3124 ip6_pcbopts(struct ip6_pktopts **pktopt, struct mbuf *m, struct socket *so,
3125     struct sockopt *sopt)
3126 {
3127 #pragma unused(sopt)
3128 	struct ip6_pktopts *opt = *pktopt;
3129 	int error = 0;
3130 
3131 	/* turn off any old options. */
3132 	if (opt != NULL) {
3133 #if DIAGNOSTIC
3134 		if (opt->ip6po_pktinfo || opt->ip6po_nexthop ||
3135 		    opt->ip6po_hbh || opt->ip6po_dest1 || opt->ip6po_dest2 ||
3136 		    opt->ip6po_rhinfo.ip6po_rhi_rthdr) {
3137 			printf("%s: all specified options are cleared.\n",
3138 			    __func__);
3139 		}
3140 #endif
3141 		ip6_clearpktopts(opt, -1);
3142 	} else {
3143 		opt = kalloc_type(struct ip6_pktopts, Z_WAITOK | Z_NOFAIL);
3144 	}
3145 	*pktopt = NULL;
3146 
3147 	if (m == NULL || m->m_len == 0) {
3148 		/*
3149 		 * Only turning off any previous options, regardless of
3150 		 * whether the opt is just created or given.
3151 		 */
3152 		if (opt != NULL) {
3153 			kfree_type(struct ip6_pktopts, opt);
3154 		}
3155 		return 0;
3156 	}
3157 
3158 	/*  set options specified by user. */
3159 	if ((error = ip6_setpktopts(m, opt, NULL, SOCK_PROTO(so))) != 0) {
3160 		ip6_clearpktopts(opt, -1); /* XXX: discard all options */
3161 		kfree_type(struct ip6_pktopts, opt);
3162 		return error;
3163 	}
3164 	*pktopt = opt;
3165 	return 0;
3166 }
3167 
3168 /*
3169  * initialize ip6_pktopts.  beware that there are non-zero default values in
3170  * the struct.
3171  */
3172 void
ip6_initpktopts(struct ip6_pktopts * opt)3173 ip6_initpktopts(struct ip6_pktopts *opt)
3174 {
3175 	bzero(opt, sizeof(*opt));
3176 	opt->ip6po_hlim = -1;   /* -1 means default hop limit */
3177 	opt->ip6po_tclass = -1; /* -1 means default traffic class */
3178 	opt->ip6po_minmtu = IP6PO_MINMTU_MCASTONLY;
3179 	opt->ip6po_prefer_tempaddr = IP6PO_TEMPADDR_SYSTEM;
3180 }
3181 
3182 static int
ip6_pcbopt(int optname,u_char * buf,int len,struct ip6_pktopts ** pktopt,int uproto)3183 ip6_pcbopt(int optname, u_char *buf, int len, struct ip6_pktopts **pktopt,
3184     int uproto)
3185 {
3186 	struct ip6_pktopts *opt;
3187 
3188 	opt = *pktopt;
3189 	if (opt == NULL) {
3190 		opt = kalloc_type(struct ip6_pktopts, Z_WAITOK | Z_NOFAIL);
3191 		ip6_initpktopts(opt);
3192 		*pktopt = opt;
3193 	}
3194 
3195 	return ip6_setpktopt(optname, buf, len, opt, 1, 0, uproto);
3196 }
3197 
3198 static int
ip6_getpcbopt(struct ip6_pktopts * pktopt,int optname,struct sockopt * sopt)3199 ip6_getpcbopt(struct ip6_pktopts *pktopt, int optname, struct sockopt *sopt)
3200 {
3201 	void *optdata = NULL;
3202 	int optdatalen = 0;
3203 	struct ip6_ext *ip6e;
3204 	struct in6_pktinfo null_pktinfo;
3205 	int deftclass = 0, on;
3206 	int defminmtu = IP6PO_MINMTU_MCASTONLY;
3207 	int defpreftemp = IP6PO_TEMPADDR_SYSTEM;
3208 
3209 
3210 	switch (optname) {
3211 	case IPV6_PKTINFO:
3212 		if (pktopt && pktopt->ip6po_pktinfo) {
3213 			optdata = (void *)pktopt->ip6po_pktinfo;
3214 		} else {
3215 			/* XXX: we don't have to do this every time... */
3216 			bzero(&null_pktinfo, sizeof(null_pktinfo));
3217 			optdata = (void *)&null_pktinfo;
3218 		}
3219 		optdatalen = sizeof(struct in6_pktinfo);
3220 		break;
3221 
3222 	case IPV6_TCLASS:
3223 		if (pktopt && pktopt->ip6po_tclass >= 0) {
3224 			optdata = (void *)&pktopt->ip6po_tclass;
3225 		} else {
3226 			optdata = (void *)&deftclass;
3227 		}
3228 		optdatalen = sizeof(int);
3229 		break;
3230 
3231 	case IPV6_HOPOPTS:
3232 		if (pktopt && pktopt->ip6po_hbh) {
3233 			optdata = (void *)pktopt->ip6po_hbh;
3234 			ip6e = (struct ip6_ext *)pktopt->ip6po_hbh;
3235 			optdatalen = (ip6e->ip6e_len + 1) << 3;
3236 		}
3237 		break;
3238 
3239 	case IPV6_RTHDR:
3240 		if (pktopt && pktopt->ip6po_rthdr) {
3241 			optdata = (void *)pktopt->ip6po_rthdr;
3242 			ip6e = (struct ip6_ext *)pktopt->ip6po_rthdr;
3243 			optdatalen = (ip6e->ip6e_len + 1) << 3;
3244 		}
3245 		break;
3246 
3247 	case IPV6_RTHDRDSTOPTS:
3248 		if (pktopt && pktopt->ip6po_dest1) {
3249 			optdata = (void *)pktopt->ip6po_dest1;
3250 			ip6e = (struct ip6_ext *)pktopt->ip6po_dest1;
3251 			optdatalen = (ip6e->ip6e_len + 1) << 3;
3252 		}
3253 		break;
3254 
3255 	case IPV6_DSTOPTS:
3256 		if (pktopt && pktopt->ip6po_dest2) {
3257 			optdata = (void *)pktopt->ip6po_dest2;
3258 			ip6e = (struct ip6_ext *)pktopt->ip6po_dest2;
3259 			optdatalen = (ip6e->ip6e_len + 1) << 3;
3260 		}
3261 		break;
3262 
3263 	case IPV6_NEXTHOP:
3264 		if (pktopt && pktopt->ip6po_nexthop) {
3265 			optdata = (void *)pktopt->ip6po_nexthop;
3266 			optdatalen = pktopt->ip6po_nexthop->sa_len;
3267 		}
3268 		break;
3269 
3270 	case IPV6_USE_MIN_MTU:
3271 		if (pktopt) {
3272 			optdata = (void *)&pktopt->ip6po_minmtu;
3273 		} else {
3274 			optdata = (void *)&defminmtu;
3275 		}
3276 		optdatalen = sizeof(int);
3277 		break;
3278 
3279 	case IPV6_DONTFRAG:
3280 		if (pktopt && ((pktopt->ip6po_flags) & IP6PO_DONTFRAG)) {
3281 			on = 1;
3282 		} else {
3283 			on = 0;
3284 		}
3285 		optdata = (void *)&on;
3286 		optdatalen = sizeof(on);
3287 		break;
3288 
3289 	case IPV6_PREFER_TEMPADDR:
3290 		if (pktopt) {
3291 			optdata = (void *)&pktopt->ip6po_prefer_tempaddr;
3292 		} else {
3293 			optdata = (void *)&defpreftemp;
3294 		}
3295 		optdatalen = sizeof(int);
3296 		break;
3297 
3298 	default:                /* should not happen */
3299 #ifdef DIAGNOSTIC
3300 		panic("ip6_getpcbopt: unexpected option");
3301 #endif
3302 		return ENOPROTOOPT;
3303 	}
3304 
3305 	return sooptcopyout(sopt, optdata, optdatalen);
3306 }
3307 
3308 void
ip6_clearpktopts(struct ip6_pktopts * pktopt,int optname)3309 ip6_clearpktopts(struct ip6_pktopts *pktopt, int optname)
3310 {
3311 	if (pktopt == NULL) {
3312 		return;
3313 	}
3314 
3315 	if (optname == -1 || optname == IPV6_PKTINFO) {
3316 		if (pktopt->ip6po_pktinfo) {
3317 			kfree_type(struct in6_pktinfo, pktopt->ip6po_pktinfo);
3318 		}
3319 		pktopt->ip6po_pktinfo = NULL;
3320 	}
3321 	if (optname == -1 || optname == IPV6_HOPLIMIT) {
3322 		pktopt->ip6po_hlim = -1;
3323 	}
3324 	if (optname == -1 || optname == IPV6_TCLASS) {
3325 		pktopt->ip6po_tclass = -1;
3326 	}
3327 	if (optname == -1 || optname == IPV6_NEXTHOP) {
3328 		ROUTE_RELEASE(&pktopt->ip6po_nextroute);
3329 		if (pktopt->ip6po_nexthop) {
3330 			kfree_data_addr(pktopt->ip6po_nexthop);
3331 		}
3332 		pktopt->ip6po_nexthop = NULL;
3333 	}
3334 	if (optname == -1 || optname == IPV6_HOPOPTS) {
3335 		if (pktopt->ip6po_hbh) {
3336 			kfree_data_addr(pktopt->ip6po_hbh);
3337 		}
3338 		pktopt->ip6po_hbh = NULL;
3339 	}
3340 	if (optname == -1 || optname == IPV6_RTHDRDSTOPTS) {
3341 		if (pktopt->ip6po_dest1) {
3342 			kfree_data_addr(pktopt->ip6po_dest1);
3343 		}
3344 		pktopt->ip6po_dest1 = NULL;
3345 	}
3346 	if (optname == -1 || optname == IPV6_RTHDR) {
3347 		if (pktopt->ip6po_rhinfo.ip6po_rhi_rthdr) {
3348 			kfree_data_addr(pktopt->ip6po_rhinfo.ip6po_rhi_rthdr);
3349 		}
3350 		pktopt->ip6po_rhinfo.ip6po_rhi_rthdr = NULL;
3351 		ROUTE_RELEASE(&pktopt->ip6po_route);
3352 	}
3353 	if (optname == -1 || optname == IPV6_DSTOPTS) {
3354 		if (pktopt->ip6po_dest2) {
3355 			kfree_data_addr(pktopt->ip6po_dest2);
3356 		}
3357 		pktopt->ip6po_dest2 = NULL;
3358 	}
3359 }
3360 
3361 #define PKTOPT_EXTHDRCPY(type) do {                                 \
3362 	if (src->type) {                                                \
3363 	        int hlen =                                              \
3364 	            (((struct ip6_ext *)src->type)->ip6e_len + 1) << 3; \
3365 	        dst->type = kalloc_data(hlen, canwait);                 \
3366 	        if (dst->type == NULL && canwait == Z_NOWAIT)           \
3367 	            goto bad;                                           \
3368 	        bcopy(src->type, dst->type, hlen);                      \
3369 	}                                                               \
3370 } while (0)
3371 
3372 static int
copypktopts(struct ip6_pktopts * dst,struct ip6_pktopts * src,zalloc_flags_t canwait)3373 copypktopts(struct ip6_pktopts *dst, struct ip6_pktopts *src, zalloc_flags_t canwait)
3374 {
3375 	if (dst == NULL || src == NULL) {
3376 		printf("copypktopts: invalid argument\n");
3377 		return EINVAL;
3378 	}
3379 
3380 	dst->ip6po_hlim = src->ip6po_hlim;
3381 	dst->ip6po_tclass = src->ip6po_tclass;
3382 	dst->ip6po_flags = src->ip6po_flags;
3383 	if (src->ip6po_pktinfo) {
3384 		dst->ip6po_pktinfo = kalloc_type(struct in6_pktinfo, canwait);
3385 		if (dst->ip6po_pktinfo == NULL && canwait == Z_NOWAIT) {
3386 			goto bad;
3387 		}
3388 		*dst->ip6po_pktinfo = *src->ip6po_pktinfo;
3389 	}
3390 	if (src->ip6po_nexthop) {
3391 		dst->ip6po_nexthop = kalloc_data(src->ip6po_nexthop->sa_len, canwait);
3392 		if (dst->ip6po_nexthop == NULL && canwait == Z_NOWAIT) {
3393 			goto bad;
3394 		}
3395 		bcopy(src->ip6po_nexthop, dst->ip6po_nexthop,
3396 		    src->ip6po_nexthop->sa_len);
3397 	}
3398 	PKTOPT_EXTHDRCPY(ip6po_hbh);
3399 	PKTOPT_EXTHDRCPY(ip6po_dest1);
3400 	PKTOPT_EXTHDRCPY(ip6po_dest2);
3401 	PKTOPT_EXTHDRCPY(ip6po_rthdr); /* not copy the cached route */
3402 	return 0;
3403 
3404 bad:
3405 	ip6_clearpktopts(dst, -1);
3406 	return ENOBUFS;
3407 }
3408 #undef PKTOPT_EXTHDRCPY
3409 
3410 struct ip6_pktopts *
ip6_copypktopts(struct ip6_pktopts * src,zalloc_flags_t canwait)3411 ip6_copypktopts(struct ip6_pktopts *src, zalloc_flags_t canwait)
3412 {
3413 	int error;
3414 	struct ip6_pktopts *dst;
3415 
3416 	dst = kalloc_type(struct ip6_pktopts, canwait);
3417 	if (dst == NULL) {
3418 		return NULL;
3419 	}
3420 	ip6_initpktopts(dst);
3421 
3422 	if ((error = copypktopts(dst, src, canwait)) != 0) {
3423 		kfree_type(struct ip6_pktopts, dst);
3424 		return NULL;
3425 	}
3426 
3427 	return dst;
3428 }
3429 
3430 void
ip6_freepcbopts(struct ip6_pktopts * pktopt)3431 ip6_freepcbopts(struct ip6_pktopts *pktopt)
3432 {
3433 	if (pktopt == NULL) {
3434 		return;
3435 	}
3436 
3437 	ip6_clearpktopts(pktopt, -1);
3438 
3439 	kfree_type(struct ip6_pktopts, pktopt);
3440 }
3441 
3442 void
ip6_moptions_init(void)3443 ip6_moptions_init(void)
3444 {
3445 	PE_parse_boot_argn("ifa_debug", &im6o_debug, sizeof(im6o_debug));
3446 
3447 	vm_size_t im6o_size = (im6o_debug == 0) ? sizeof(struct ip6_moptions) :
3448 	    sizeof(struct ip6_moptions_dbg);
3449 
3450 	im6o_zone = zone_create(IM6O_ZONE_NAME, im6o_size, ZC_ZFREE_CLEARMEM);
3451 }
3452 
3453 void
im6o_addref(struct ip6_moptions * im6o,int locked)3454 im6o_addref(struct ip6_moptions *im6o, int locked)
3455 {
3456 	if (!locked) {
3457 		IM6O_LOCK(im6o);
3458 	} else {
3459 		IM6O_LOCK_ASSERT_HELD(im6o);
3460 	}
3461 
3462 	if (++im6o->im6o_refcnt == 0) {
3463 		panic("%s: im6o %p wraparound refcnt", __func__, im6o);
3464 		/* NOTREACHED */
3465 	} else if (im6o->im6o_trace != NULL) {
3466 		(*im6o->im6o_trace)(im6o, TRUE);
3467 	}
3468 
3469 	if (!locked) {
3470 		IM6O_UNLOCK(im6o);
3471 	}
3472 }
3473 
3474 void
im6o_remref(struct ip6_moptions * im6o)3475 im6o_remref(struct ip6_moptions *im6o)
3476 {
3477 	int i;
3478 
3479 	IM6O_LOCK(im6o);
3480 	if (im6o->im6o_refcnt == 0) {
3481 		panic("%s: im6o %p negative refcnt", __func__, im6o);
3482 		/* NOTREACHED */
3483 	} else if (im6o->im6o_trace != NULL) {
3484 		(*im6o->im6o_trace)(im6o, FALSE);
3485 	}
3486 
3487 	--im6o->im6o_refcnt;
3488 	if (im6o->im6o_refcnt > 0) {
3489 		IM6O_UNLOCK(im6o);
3490 		return;
3491 	}
3492 
3493 	for (i = 0; i < im6o->im6o_num_memberships; ++i) {
3494 		struct in6_mfilter *imf;
3495 
3496 		imf = im6o->im6o_mfilters ? &im6o->im6o_mfilters[i] : NULL;
3497 		if (imf != NULL) {
3498 			im6f_leave(imf);
3499 		}
3500 
3501 		(void) in6_mc_leave(im6o->im6o_membership[i], imf);
3502 
3503 		if (imf != NULL) {
3504 			im6f_purge(imf);
3505 		}
3506 
3507 		IN6M_REMREF(im6o->im6o_membership[i]);
3508 		im6o->im6o_membership[i] = NULL;
3509 	}
3510 	im6o->im6o_num_memberships = 0;
3511 	IM6O_UNLOCK(im6o);
3512 
3513 	kfree_type(struct in6_multi *, im6o->im6o_max_memberships, im6o->im6o_membership);
3514 	kfree_type(struct in6_mfilter, im6o->im6o_max_memberships, im6o->im6o_mfilters);
3515 	lck_mtx_destroy(&im6o->im6o_lock, &ifa_mtx_grp);
3516 
3517 	if (!(im6o->im6o_debug & IFD_ALLOC)) {
3518 		panic("%s: im6o %p cannot be freed", __func__, im6o);
3519 		/* NOTREACHED */
3520 	}
3521 	zfree(im6o_zone, im6o);
3522 }
3523 
3524 static void
im6o_trace(struct ip6_moptions * im6o,int refhold)3525 im6o_trace(struct ip6_moptions *im6o, int refhold)
3526 {
3527 	struct ip6_moptions_dbg *im6o_dbg = (struct ip6_moptions_dbg *)im6o;
3528 	ctrace_t *tr;
3529 	u_int32_t idx;
3530 	u_int16_t *cnt;
3531 
3532 	if (!(im6o->im6o_debug & IFD_DEBUG)) {
3533 		panic("%s: im6o %p has no debug structure", __func__, im6o);
3534 		/* NOTREACHED */
3535 	}
3536 	if (refhold) {
3537 		cnt = &im6o_dbg->im6o_refhold_cnt;
3538 		tr = im6o_dbg->im6o_refhold;
3539 	} else {
3540 		cnt = &im6o_dbg->im6o_refrele_cnt;
3541 		tr = im6o_dbg->im6o_refrele;
3542 	}
3543 
3544 	idx = atomic_add_16_ov(cnt, 1) % IM6O_TRACE_HIST_SIZE;
3545 	ctrace_record(&tr[idx]);
3546 }
3547 
3548 struct ip6_moptions *
ip6_allocmoptions(zalloc_flags_t how)3549 ip6_allocmoptions(zalloc_flags_t how)
3550 {
3551 	struct ip6_moptions *im6o;
3552 
3553 	im6o = zalloc_flags(im6o_zone, how | Z_ZERO);
3554 	if (im6o != NULL) {
3555 		lck_mtx_init(&im6o->im6o_lock, &ifa_mtx_grp, &ifa_mtx_attr);
3556 		im6o->im6o_debug |= IFD_ALLOC;
3557 		if (im6o_debug != 0) {
3558 			im6o->im6o_debug |= IFD_DEBUG;
3559 			im6o->im6o_trace = im6o_trace;
3560 		}
3561 		IM6O_ADDREF(im6o);
3562 	}
3563 
3564 	return im6o;
3565 }
3566 
3567 /*
3568  * Set IPv6 outgoing packet options based on advanced API.
3569  */
3570 int
ip6_setpktopts(struct mbuf * control,struct ip6_pktopts * opt,struct ip6_pktopts * stickyopt,int uproto)3571 ip6_setpktopts(struct mbuf *control, struct ip6_pktopts *opt,
3572     struct ip6_pktopts *stickyopt, int uproto)
3573 {
3574 	struct cmsghdr *cm = NULL;
3575 
3576 	if (control == NULL || opt == NULL) {
3577 		return EINVAL;
3578 	}
3579 
3580 	ip6_initpktopts(opt);
3581 	if (stickyopt) {
3582 		int error;
3583 
3584 		/*
3585 		 * If stickyopt is provided, make a local copy of the options
3586 		 * for this particular packet, then override them by ancillary
3587 		 * objects.
3588 		 * XXX: copypktopts() does not copy the cached route to a next
3589 		 * hop (if any).  This is not very good in terms of efficiency,
3590 		 * but we can allow this since this option should be rarely
3591 		 * used.
3592 		 */
3593 		if ((error = copypktopts(opt, stickyopt, Z_NOWAIT)) != 0) {
3594 			return error;
3595 		}
3596 	}
3597 
3598 	/*
3599 	 * XXX: Currently, we assume all the optional information is stored
3600 	 * in a single mbuf.
3601 	 */
3602 	if (control->m_next) {
3603 		return EINVAL;
3604 	}
3605 
3606 	if (control->m_len < CMSG_LEN(0)) {
3607 		return EINVAL;
3608 	}
3609 
3610 	for (cm = M_FIRST_CMSGHDR(control);
3611 	    is_cmsg_valid(control, cm);
3612 	    cm = M_NXT_CMSGHDR(control, cm)) {
3613 		int error;
3614 
3615 		if (cm->cmsg_level != IPPROTO_IPV6) {
3616 			continue;
3617 		}
3618 
3619 		error = ip6_setpktopt(cm->cmsg_type, CMSG_DATA(cm),
3620 		    cm->cmsg_len - CMSG_LEN(0), opt, 0, 1, uproto);
3621 		if (error) {
3622 			return error;
3623 		}
3624 	}
3625 
3626 	return 0;
3627 }
3628 /*
3629  * Set a particular packet option, as a sticky option or an ancillary data
3630  * item.  "len" can be 0 only when it's a sticky option.
3631  * We have 4 cases of combination of "sticky" and "cmsg":
3632  * "sticky=0, cmsg=0": impossible
3633  * "sticky=0, cmsg=1": RFC2292 or RFC3542 ancillary data
3634  * "sticky=1, cmsg=0": RFC3542 socket option
3635  * "sticky=1, cmsg=1": RFC2292 socket option
3636  */
3637 static int
ip6_setpktopt(int optname,u_char * buf,int len,struct ip6_pktopts * opt,int sticky,int cmsg,int uproto)3638 ip6_setpktopt(int optname, u_char *buf, int len, struct ip6_pktopts *opt,
3639     int sticky, int cmsg, int uproto)
3640 {
3641 	int minmtupolicy, preftemp;
3642 	int error;
3643 	boolean_t capture_exthdrstat_out = FALSE;
3644 
3645 	if (!sticky && !cmsg) {
3646 #ifdef DIAGNOSTIC
3647 		printf("ip6_setpktopt: impossible case\n");
3648 #endif
3649 		return EINVAL;
3650 	}
3651 
3652 	/*
3653 	 * Caller must have ensured that the buffer is at least
3654 	 * aligned on 32-bit boundary.
3655 	 */
3656 	VERIFY(IS_P2ALIGNED(buf, sizeof(u_int32_t)));
3657 
3658 	/*
3659 	 * IPV6_2292xxx is for backward compatibility to RFC2292, and should
3660 	 * not be specified in the context of RFC3542.  Conversely,
3661 	 * RFC3542 types should not be specified in the context of RFC2292.
3662 	 */
3663 	if (!cmsg) {
3664 		switch (optname) {
3665 		case IPV6_2292PKTINFO:
3666 		case IPV6_2292HOPLIMIT:
3667 		case IPV6_2292NEXTHOP:
3668 		case IPV6_2292HOPOPTS:
3669 		case IPV6_2292DSTOPTS:
3670 		case IPV6_2292RTHDR:
3671 		case IPV6_2292PKTOPTIONS:
3672 			return ENOPROTOOPT;
3673 		}
3674 	}
3675 	if (sticky && cmsg) {
3676 		switch (optname) {
3677 		case IPV6_PKTINFO:
3678 		case IPV6_HOPLIMIT:
3679 		case IPV6_NEXTHOP:
3680 		case IPV6_HOPOPTS:
3681 		case IPV6_DSTOPTS:
3682 		case IPV6_RTHDRDSTOPTS:
3683 		case IPV6_RTHDR:
3684 		case IPV6_USE_MIN_MTU:
3685 		case IPV6_DONTFRAG:
3686 		case IPV6_TCLASS:
3687 		case IPV6_PREFER_TEMPADDR: /* XXX: not an RFC3542 option */
3688 			return ENOPROTOOPT;
3689 		}
3690 	}
3691 
3692 	switch (optname) {
3693 	case IPV6_2292PKTINFO:
3694 	case IPV6_PKTINFO: {
3695 		struct ifnet *ifp = NULL;
3696 		struct in6_pktinfo *pktinfo;
3697 
3698 		if (len != sizeof(struct in6_pktinfo)) {
3699 			return EINVAL;
3700 		}
3701 
3702 		pktinfo = (struct in6_pktinfo *)(void *)buf;
3703 
3704 		/*
3705 		 * An application can clear any sticky IPV6_PKTINFO option by
3706 		 * doing a "regular" setsockopt with ipi6_addr being
3707 		 * in6addr_any and ipi6_ifindex being zero.
3708 		 * [RFC 3542, Section 6]
3709 		 */
3710 		if (optname == IPV6_PKTINFO && opt->ip6po_pktinfo &&
3711 		    pktinfo->ipi6_ifindex == 0 &&
3712 		    IN6_IS_ADDR_UNSPECIFIED(&pktinfo->ipi6_addr)) {
3713 			ip6_clearpktopts(opt, optname);
3714 			break;
3715 		}
3716 
3717 		if (uproto == IPPROTO_TCP && optname == IPV6_PKTINFO &&
3718 		    sticky && !IN6_IS_ADDR_UNSPECIFIED(&pktinfo->ipi6_addr)) {
3719 			return EINVAL;
3720 		}
3721 
3722 		/* validate the interface index if specified. */
3723 		ifnet_head_lock_shared();
3724 
3725 		if (pktinfo->ipi6_ifindex > if_index) {
3726 			ifnet_head_done();
3727 			return ENXIO;
3728 		}
3729 
3730 		if (pktinfo->ipi6_ifindex) {
3731 			ifp = ifindex2ifnet[pktinfo->ipi6_ifindex];
3732 			if (ifp == NULL) {
3733 				ifnet_head_done();
3734 				return ENXIO;
3735 			}
3736 		}
3737 
3738 		ifnet_head_done();
3739 
3740 		/*
3741 		 * We store the address anyway, and let in6_selectsrc()
3742 		 * validate the specified address.  This is because ipi6_addr
3743 		 * may not have enough information about its scope zone, and
3744 		 * we may need additional information (such as outgoing
3745 		 * interface or the scope zone of a destination address) to
3746 		 * disambiguate the scope.
3747 		 * XXX: the delay of the validation may confuse the
3748 		 * application when it is used as a sticky option.
3749 		 */
3750 		if (opt->ip6po_pktinfo == NULL) {
3751 			opt->ip6po_pktinfo = kalloc_type(struct in6_pktinfo, Z_NOWAIT);
3752 			if (opt->ip6po_pktinfo == NULL) {
3753 				return ENOBUFS;
3754 			}
3755 		}
3756 		bcopy(pktinfo, opt->ip6po_pktinfo, sizeof(*pktinfo));
3757 		break;
3758 	}
3759 
3760 	case IPV6_2292HOPLIMIT:
3761 	case IPV6_HOPLIMIT: {
3762 		int *hlimp;
3763 
3764 		/*
3765 		 * RFC 3542 deprecated the usage of sticky IPV6_HOPLIMIT
3766 		 * to simplify the ordering among hoplimit options.
3767 		 */
3768 		if (optname == IPV6_HOPLIMIT && sticky) {
3769 			return ENOPROTOOPT;
3770 		}
3771 
3772 		if (len != sizeof(int)) {
3773 			return EINVAL;
3774 		}
3775 		hlimp = (int *)(void *)buf;
3776 		if (*hlimp < -1 || *hlimp > IPV6_MAXHLIM) {
3777 			return EINVAL;
3778 		}
3779 
3780 		opt->ip6po_hlim = *hlimp;
3781 		break;
3782 	}
3783 
3784 	case IPV6_TCLASS: {
3785 		int tclass;
3786 
3787 		if (len != sizeof(int)) {
3788 			return EINVAL;
3789 		}
3790 		tclass = *(int *)(void *)buf;
3791 		if (tclass < -1 || tclass > 255) {
3792 			return EINVAL;
3793 		}
3794 
3795 		opt->ip6po_tclass = tclass;
3796 		break;
3797 	}
3798 
3799 	case IPV6_2292NEXTHOP:
3800 	case IPV6_NEXTHOP:
3801 		error = suser(kauth_cred_get(), 0);
3802 		if (error) {
3803 			return EACCES;
3804 		}
3805 
3806 		if (len == 0) { /* just remove the option */
3807 			ip6_clearpktopts(opt, IPV6_NEXTHOP);
3808 			break;
3809 		}
3810 
3811 		/* check if cmsg_len is large enough for sa_len */
3812 		if (len < sizeof(struct sockaddr) || len < *buf) {
3813 			return EINVAL;
3814 		}
3815 
3816 		switch (SA(buf)->sa_family) {
3817 		case AF_INET6: {
3818 			struct sockaddr_in6 *sa6 = SIN6(buf);
3819 
3820 			if (sa6->sin6_len != sizeof(struct sockaddr_in6)) {
3821 				return EINVAL;
3822 			}
3823 
3824 			if (IN6_IS_ADDR_UNSPECIFIED(&sa6->sin6_addr) ||
3825 			    IN6_IS_ADDR_MULTICAST(&sa6->sin6_addr)) {
3826 				return EINVAL;
3827 			}
3828 			if ((error = sa6_embedscope(sa6, ip6_use_defzone, IN6_NULL_IF_EMBEDDED_SCOPE(&sa6->sin6_scope_id)))
3829 			    != 0) {
3830 				return error;
3831 			}
3832 			break;
3833 		}
3834 		case AF_LINK:   /* should eventually be supported */
3835 		default:
3836 			return EAFNOSUPPORT;
3837 		}
3838 
3839 		/* turn off the previous option, then set the new option. */
3840 		ip6_clearpktopts(opt, IPV6_NEXTHOP);
3841 		opt->ip6po_nexthop = kalloc_data(*buf, Z_NOWAIT);
3842 		if (opt->ip6po_nexthop == NULL) {
3843 			return ENOBUFS;
3844 		}
3845 		bcopy(buf, opt->ip6po_nexthop, *buf);
3846 		break;
3847 
3848 	case IPV6_2292HOPOPTS:
3849 	case IPV6_HOPOPTS: {
3850 		struct ip6_hbh *hbh;
3851 		int hbhlen;
3852 
3853 		/*
3854 		 * XXX: We don't allow a non-privileged user to set ANY HbH
3855 		 * options, since per-option restriction has too much
3856 		 * overhead.
3857 		 */
3858 		error = suser(kauth_cred_get(), 0);
3859 		if (error) {
3860 			return EACCES;
3861 		}
3862 
3863 		if (len == 0) {
3864 			ip6_clearpktopts(opt, IPV6_HOPOPTS);
3865 			break;  /* just remove the option */
3866 		}
3867 
3868 		/* message length validation */
3869 		if (len < sizeof(struct ip6_hbh)) {
3870 			return EINVAL;
3871 		}
3872 		hbh = (struct ip6_hbh *)(void *)buf;
3873 		hbhlen = (hbh->ip6h_len + 1) << 3;
3874 		if (len != hbhlen) {
3875 			return EINVAL;
3876 		}
3877 
3878 		/* turn off the previous option, then set the new option. */
3879 		ip6_clearpktopts(opt, IPV6_HOPOPTS);
3880 		opt->ip6po_hbh = kalloc_data(hbhlen, Z_NOWAIT);
3881 		if (opt->ip6po_hbh == NULL) {
3882 			return ENOBUFS;
3883 		}
3884 		bcopy(hbh, opt->ip6po_hbh, hbhlen);
3885 		capture_exthdrstat_out = TRUE;
3886 		break;
3887 	}
3888 
3889 	case IPV6_2292DSTOPTS:
3890 	case IPV6_DSTOPTS:
3891 	case IPV6_RTHDRDSTOPTS: {
3892 		struct ip6_dest *dest, **newdest = NULL;
3893 		int destlen;
3894 
3895 		error = suser(kauth_cred_get(), 0);
3896 		if (error) {
3897 			return EACCES;
3898 		}
3899 
3900 		if (len == 0) {
3901 			ip6_clearpktopts(opt, optname);
3902 			break;  /* just remove the option */
3903 		}
3904 
3905 		/* message length validation */
3906 		if (len < sizeof(struct ip6_dest)) {
3907 			return EINVAL;
3908 		}
3909 		dest = (struct ip6_dest *)(void *)buf;
3910 		destlen = (dest->ip6d_len + 1) << 3;
3911 		if (len != destlen) {
3912 			return EINVAL;
3913 		}
3914 
3915 		/*
3916 		 * Determine the position that the destination options header
3917 		 * should be inserted; before or after the routing header.
3918 		 */
3919 		switch (optname) {
3920 		case IPV6_2292DSTOPTS:
3921 			/*
3922 			 * The old advacned API is ambiguous on this point.
3923 			 * Our approach is to determine the position based
3924 			 * according to the existence of a routing header.
3925 			 * Note, however, that this depends on the order of the
3926 			 * extension headers in the ancillary data; the 1st
3927 			 * part of the destination options header must appear
3928 			 * before the routing header in the ancillary data,
3929 			 * too.
3930 			 * RFC3542 solved the ambiguity by introducing
3931 			 * separate ancillary data or option types.
3932 			 */
3933 			if (opt->ip6po_rthdr == NULL) {
3934 				newdest = &opt->ip6po_dest1;
3935 			} else {
3936 				newdest = &opt->ip6po_dest2;
3937 			}
3938 			break;
3939 		case IPV6_RTHDRDSTOPTS:
3940 			newdest = &opt->ip6po_dest1;
3941 			break;
3942 		case IPV6_DSTOPTS:
3943 			newdest = &opt->ip6po_dest2;
3944 			break;
3945 		}
3946 
3947 		/* turn off the previous option, then set the new option. */
3948 		ip6_clearpktopts(opt, optname);
3949 		*newdest = kalloc_data(destlen, Z_NOWAIT);
3950 		if (*newdest == NULL) {
3951 			return ENOBUFS;
3952 		}
3953 		bcopy(dest, *newdest, destlen);
3954 		capture_exthdrstat_out = TRUE;
3955 		break;
3956 	}
3957 
3958 	case IPV6_2292RTHDR:
3959 	case IPV6_RTHDR: {
3960 		struct ip6_rthdr *rth;
3961 		int rthlen;
3962 
3963 		if (len == 0) {
3964 			ip6_clearpktopts(opt, IPV6_RTHDR);
3965 			break;  /* just remove the option */
3966 		}
3967 
3968 		/* message length validation */
3969 		if (len < sizeof(struct ip6_rthdr)) {
3970 			return EINVAL;
3971 		}
3972 		rth = (struct ip6_rthdr *)(void *)buf;
3973 		rthlen = (rth->ip6r_len + 1) << 3;
3974 		if (len != rthlen) {
3975 			return EINVAL;
3976 		}
3977 
3978 		switch (rth->ip6r_type) {
3979 		case IPV6_RTHDR_TYPE_0:
3980 			if (rth->ip6r_len == 0) { /* must contain one addr */
3981 				return EINVAL;
3982 			}
3983 			if (rth->ip6r_len % 2) { /* length must be even */
3984 				return EINVAL;
3985 			}
3986 			if (rth->ip6r_len / 2 != rth->ip6r_segleft) {
3987 				return EINVAL;
3988 			}
3989 			break;
3990 		default:
3991 			return EINVAL;        /* not supported */
3992 		}
3993 
3994 		/* turn off the previous option */
3995 		ip6_clearpktopts(opt, IPV6_RTHDR);
3996 		opt->ip6po_rthdr = kalloc_data(rthlen, Z_NOWAIT);
3997 		if (opt->ip6po_rthdr == NULL) {
3998 			return ENOBUFS;
3999 		}
4000 		bcopy(rth, opt->ip6po_rthdr, rthlen);
4001 		capture_exthdrstat_out = TRUE;
4002 		break;
4003 	}
4004 
4005 	case IPV6_USE_MIN_MTU:
4006 		if (len != sizeof(int)) {
4007 			return EINVAL;
4008 		}
4009 		minmtupolicy = *(int *)(void *)buf;
4010 		if (minmtupolicy != IP6PO_MINMTU_MCASTONLY &&
4011 		    minmtupolicy != IP6PO_MINMTU_DISABLE &&
4012 		    minmtupolicy != IP6PO_MINMTU_ALL) {
4013 			return EINVAL;
4014 		}
4015 		opt->ip6po_minmtu = minmtupolicy;
4016 		break;
4017 
4018 	case IPV6_DONTFRAG:
4019 		if (len != sizeof(int)) {
4020 			return EINVAL;
4021 		}
4022 
4023 		if (uproto == IPPROTO_TCP || *(int *)(void *)buf == 0) {
4024 			/*
4025 			 * we ignore this option for TCP sockets.
4026 			 * (RFC3542 leaves this case unspecified.)
4027 			 */
4028 			opt->ip6po_flags &= ~IP6PO_DONTFRAG;
4029 		} else {
4030 			opt->ip6po_flags |= IP6PO_DONTFRAG;
4031 		}
4032 		break;
4033 
4034 	case IPV6_PREFER_TEMPADDR:
4035 		if (len != sizeof(int)) {
4036 			return EINVAL;
4037 		}
4038 		preftemp = *(int *)(void *)buf;
4039 		if (preftemp != IP6PO_TEMPADDR_SYSTEM &&
4040 		    preftemp != IP6PO_TEMPADDR_NOTPREFER &&
4041 		    preftemp != IP6PO_TEMPADDR_PREFER) {
4042 			return EINVAL;
4043 		}
4044 		opt->ip6po_prefer_tempaddr = preftemp;
4045 		break;
4046 
4047 	default:
4048 		return ENOPROTOOPT;
4049 	} /* end of switch */
4050 
4051 	if (capture_exthdrstat_out) {
4052 		if (uproto == IPPROTO_TCP) {
4053 			INC_ATOMIC_INT64_LIM(net_api_stats.nas_sock_inet6_stream_exthdr_out);
4054 		} else if (uproto == IPPROTO_UDP) {
4055 			INC_ATOMIC_INT64_LIM(net_api_stats.nas_sock_inet6_dgram_exthdr_out);
4056 		}
4057 	}
4058 
4059 	return 0;
4060 }
4061 
4062 /*
4063  * Routine called from ip6_output() to loop back a copy of an IP6 multicast
4064  * packet to the input queue of a specified interface.  Note that this
4065  * calls the output routine of the loopback "driver", but with an interface
4066  * pointer that might NOT be &loif -- easier than replicating that code here.
4067  */
4068 void
ip6_mloopback(struct ifnet * srcifp,struct ifnet * origifp,struct mbuf * m,struct sockaddr_in6 * dst,uint32_t optlen,int32_t nxt0)4069 ip6_mloopback(struct ifnet *srcifp, struct ifnet *origifp, struct mbuf *m,
4070     struct sockaddr_in6 *dst, uint32_t optlen, int32_t nxt0)
4071 {
4072 	struct mbuf *copym;
4073 	struct ip6_hdr *ip6;
4074 	struct in6_addr src;
4075 
4076 	if (lo_ifp == NULL) {
4077 		return;
4078 	}
4079 
4080 	/*
4081 	 * Copy the packet header as it's needed for the checksum.
4082 	 * Make sure to deep-copy IPv6 header portion in case the data
4083 	 * is in an mbuf cluster, so that we can safely override the IPv6
4084 	 * header portion later.
4085 	 */
4086 	copym = m_copym_mode(m, 0, M_COPYALL, M_DONTWAIT, M_COPYM_COPY_HDR);
4087 	if (copym != NULL && ((copym->m_flags & M_EXT) ||
4088 	    copym->m_len < sizeof(struct ip6_hdr))) {
4089 		copym = m_pullup(copym, sizeof(struct ip6_hdr));
4090 	}
4091 
4092 	if (copym == NULL) {
4093 		return;
4094 	}
4095 
4096 	ip6 = mtod(copym, struct ip6_hdr *);
4097 	src = ip6->ip6_src;
4098 	/*
4099 	 * clear embedded scope identifiers if necessary.
4100 	 * in6_clearscope will touch the addresses only when necessary.
4101 	 */
4102 	in6_clearscope(&ip6->ip6_src);
4103 	in6_clearscope(&ip6->ip6_dst);
4104 
4105 	if (copym->m_pkthdr.csum_flags & CSUM_DELAY_IPV6_DATA) {
4106 		in6_delayed_cksum_offset(copym, 0, optlen, nxt0);
4107 	}
4108 
4109 	/*
4110 	 * Stuff the 'real' ifp into the pkthdr, to be used in matching
4111 	 * in ip6_input(); we need the loopback ifp/dl_tag passed as args
4112 	 * to make the loopback driver compliant with the data link
4113 	 * requirements.
4114 	 */
4115 	copym->m_pkthdr.rcvif = origifp;
4116 
4117 	/*
4118 	 * Also record the source interface (which owns the source address).
4119 	 * This is basically a stripped down version of ifa_foraddr6().
4120 	 */
4121 	if (srcifp == NULL) {
4122 		struct in6_ifaddr *ia;
4123 
4124 		lck_rw_lock_shared(&in6_ifaddr_rwlock);
4125 		TAILQ_FOREACH(ia, IN6ADDR_HASH(&src), ia6_hash) {
4126 			IFA_LOCK_SPIN(&ia->ia_ifa);
4127 			/* compare against src addr with embedded scope */
4128 			if (in6_are_addr_equal_scoped(&ia->ia_addr.sin6_addr, &src, ia->ia_addr.sin6_scope_id, ip6_output_getsrcifscope(m))) {
4129 				srcifp = ia->ia_ifp;
4130 				IFA_UNLOCK(&ia->ia_ifa);
4131 				break;
4132 			}
4133 			IFA_UNLOCK(&ia->ia_ifa);
4134 		}
4135 		lck_rw_done(&in6_ifaddr_rwlock);
4136 	}
4137 	if (srcifp != NULL) {
4138 		ip6_setsrcifaddr_info(copym, srcifp->if_index, NULL);
4139 	}
4140 	ip6_setdstifaddr_info(copym, origifp->if_index, NULL);
4141 
4142 	dlil_output(lo_ifp, PF_INET6, copym, NULL, SA(dst), 0, NULL);
4143 }
4144 
4145 /*
4146  * Chop IPv6 header off from the payload.
4147  */
4148 static int
ip6_splithdr(struct mbuf * m,struct ip6_exthdrs * exthdrs)4149 ip6_splithdr(struct mbuf *m, struct ip6_exthdrs *exthdrs)
4150 {
4151 	struct mbuf *mh;
4152 	struct ip6_hdr *ip6;
4153 
4154 	ip6 = mtod(m, struct ip6_hdr *);
4155 	if (m->m_len > sizeof(*ip6)) {
4156 		MGETHDR(mh, M_DONTWAIT, MT_HEADER);     /* MAC-OK */
4157 		if (mh == NULL) {
4158 			m_freem(m);
4159 			return ENOBUFS;
4160 		}
4161 		M_COPY_PKTHDR(mh, m);
4162 		MH_ALIGN(mh, sizeof(*ip6));
4163 		m->m_flags &= ~M_PKTHDR;
4164 		m->m_len -= sizeof(*ip6);
4165 		m->m_data += sizeof(*ip6);
4166 		mh->m_next = m;
4167 		m = mh;
4168 		m->m_len = sizeof(*ip6);
4169 		bcopy((caddr_t)ip6, mtod(m, caddr_t), sizeof(*ip6));
4170 	}
4171 	exthdrs->ip6e_ip6 = m;
4172 	return 0;
4173 }
4174 
4175 static void
ip6_output_checksum(struct ifnet * ifp,uint32_t mtu,struct mbuf * m,int nxt0,uint32_t tlen,uint32_t optlen)4176 ip6_output_checksum(struct ifnet *ifp, uint32_t mtu, struct mbuf *m,
4177     int nxt0, uint32_t tlen, uint32_t optlen)
4178 {
4179 	uint32_t sw_csum, hwcap = ifp->if_hwassist;
4180 	int tso = TSO_IPV6_OK(ifp, m);
4181 
4182 	if (!hwcksum_tx) {
4183 		/* do all in software; checksum offload is disabled */
4184 		sw_csum = CSUM_DELAY_IPV6_DATA & m->m_pkthdr.csum_flags;
4185 	} else {
4186 		/* do in software what the hardware cannot */
4187 		sw_csum = m->m_pkthdr.csum_flags &
4188 		    ~IF_HWASSIST_CSUM_FLAGS(hwcap);
4189 	}
4190 
4191 	if (optlen != 0) {
4192 		sw_csum |= (CSUM_DELAY_IPV6_DATA &
4193 		    m->m_pkthdr.csum_flags);
4194 	} else if (!(sw_csum & CSUM_DELAY_IPV6_DATA) &&
4195 	    (hwcap & CSUM_PARTIAL)) {
4196 		/*
4197 		 * Partial checksum offload, ere), if no extension headers,
4198 		 * and TCP only (no UDP support, as the hardware may not be
4199 		 * able to convert +0 to -0 (0xffff) per RFC1122 4.1.3.4.
4200 		 * unless the interface supports "invert zero" capability.)
4201 		 */
4202 		if (hwcksum_tx && !tso &&
4203 		    ((m->m_pkthdr.csum_flags & CSUM_TCPIPV6) ||
4204 		    ((hwcap & CSUM_ZERO_INVERT) &&
4205 		    (m->m_pkthdr.csum_flags & CSUM_ZERO_INVERT))) &&
4206 		    tlen <= mtu) {
4207 			uint16_t start = sizeof(struct ip6_hdr);
4208 			uint16_t ulpoff =
4209 			    m->m_pkthdr.csum_data & 0xffff;
4210 			m->m_pkthdr.csum_flags |=
4211 			    (CSUM_DATA_VALID | CSUM_PARTIAL);
4212 			m->m_pkthdr.csum_tx_stuff = (ulpoff + start);
4213 			m->m_pkthdr.csum_tx_start = start;
4214 			sw_csum = 0;
4215 		} else {
4216 			sw_csum |= (CSUM_DELAY_IPV6_DATA &
4217 			    m->m_pkthdr.csum_flags);
4218 		}
4219 	}
4220 
4221 	if (sw_csum & CSUM_DELAY_IPV6_DATA) {
4222 		in6_delayed_cksum_offset(m, 0, optlen, nxt0);
4223 		sw_csum &= ~CSUM_DELAY_IPV6_DATA;
4224 	}
4225 
4226 	if (hwcksum_tx) {
4227 		/*
4228 		 * Drop off bits that aren't supported by hardware;
4229 		 * also make sure to preserve non-checksum related bits.
4230 		 */
4231 		m->m_pkthdr.csum_flags =
4232 		    ((m->m_pkthdr.csum_flags &
4233 		    (IF_HWASSIST_CSUM_FLAGS(hwcap) | CSUM_DATA_VALID)) |
4234 		    (m->m_pkthdr.csum_flags & ~IF_HWASSIST_CSUM_MASK));
4235 	} else {
4236 		/* drop all bits; checksum offload is disabled */
4237 		m->m_pkthdr.csum_flags = 0;
4238 	}
4239 }
4240 
4241 /*
4242  * Compute IPv6 extension header length.
4243  */
4244 int
ip6_optlen(struct in6pcb * in6p)4245 ip6_optlen(struct in6pcb *in6p)
4246 {
4247 	int len;
4248 
4249 	if (!in6p->in6p_outputopts) {
4250 		return 0;
4251 	}
4252 
4253 	len = 0;
4254 #define elen(x)                                                         \
4255 	(((struct ip6_ext *)(x)) ?                                      \
4256 	(((struct ip6_ext *)(x))->ip6e_len + 1) << 3 : 0)
4257 
4258 	len += elen(in6p->in6p_outputopts->ip6po_hbh);
4259 	if (in6p->in6p_outputopts->ip6po_rthdr) {
4260 		/* dest1 is valid with rthdr only */
4261 		len += elen(in6p->in6p_outputopts->ip6po_dest1);
4262 	}
4263 	len += elen(in6p->in6p_outputopts->ip6po_rthdr);
4264 	len += elen(in6p->in6p_outputopts->ip6po_dest2);
4265 	return len;
4266 #undef elen
4267 }
4268 
4269 static int
4270 sysctl_reset_ip6_output_stats SYSCTL_HANDLER_ARGS
4271 {
4272 #pragma unused(arg1, arg2)
4273 	int error, i;
4274 
4275 	i = ip6_output_measure;
4276 	error = sysctl_handle_int(oidp, &i, 0, req);
4277 	if (error || req->newptr == USER_ADDR_NULL) {
4278 		goto done;
4279 	}
4280 	/* impose bounds */
4281 	if (i < 0 || i > 1) {
4282 		error = EINVAL;
4283 		goto done;
4284 	}
4285 	if (ip6_output_measure != i && i == 1) {
4286 		net_perf_initialize(&net_perf, ip6_output_measure_bins);
4287 	}
4288 	ip6_output_measure = i;
4289 done:
4290 	return error;
4291 }
4292 
4293 static int
4294 sysctl_ip6_output_measure_bins SYSCTL_HANDLER_ARGS
4295 {
4296 #pragma unused(arg1, arg2)
4297 	int error;
4298 	uint64_t i;
4299 
4300 	i = ip6_output_measure_bins;
4301 	error = sysctl_handle_quad(oidp, &i, 0, req);
4302 	if (error || req->newptr == USER_ADDR_NULL) {
4303 		goto done;
4304 	}
4305 	/* validate data */
4306 	if (!net_perf_validate_bins(i)) {
4307 		error = EINVAL;
4308 		goto done;
4309 	}
4310 	ip6_output_measure_bins = i;
4311 done:
4312 	return error;
4313 }
4314 
4315 static int
4316 sysctl_ip6_output_getperf SYSCTL_HANDLER_ARGS
4317 {
4318 #pragma unused(oidp, arg1, arg2)
4319 	if (req->oldptr == USER_ADDR_NULL) {
4320 		req->oldlen = (size_t)sizeof(struct ipstat);
4321 	}
4322 
4323 	return SYSCTL_OUT(req, &net_perf, MIN(sizeof(net_perf), req->oldlen));
4324 }
4325 
4326 void
ip6_output_setsrcifscope(struct mbuf * m,uint32_t src_idx,struct in6_ifaddr * ia6)4327 ip6_output_setsrcifscope(struct mbuf *m, uint32_t src_idx, struct in6_ifaddr *ia6)
4328 {
4329 	VERIFY(m->m_flags & M_PKTHDR);
4330 
4331 	m->m_pkthdr.pkt_ext_flags |= PKTF_EXT_OUTPUT_SCOPE;
4332 	if (ia6 != NULL) {
4333 		m->m_pkthdr.src_ifindex = ia6->ia_ifp->if_index;
4334 	} else {
4335 		m->m_pkthdr.src_ifindex = (uint16_t)src_idx;
4336 	}
4337 }
4338 
4339 void
ip6_output_setdstifscope(struct mbuf * m,uint32_t dst_idx,struct in6_ifaddr * ia6)4340 ip6_output_setdstifscope(struct mbuf *m, uint32_t dst_idx, struct in6_ifaddr *ia6)
4341 {
4342 	VERIFY(m->m_flags & M_PKTHDR);
4343 
4344 	m->m_pkthdr.pkt_ext_flags |= PKTF_EXT_OUTPUT_SCOPE;
4345 	if (ia6 != NULL) {
4346 		m->m_pkthdr.dst_ifindex = ia6->ia_ifp->if_index;
4347 	} else {
4348 		m->m_pkthdr.dst_ifindex = (uint16_t)dst_idx;
4349 	}
4350 }
4351 
4352 uint32_t
ip6_output_getsrcifscope(struct mbuf * m)4353 ip6_output_getsrcifscope(struct mbuf *m)
4354 {
4355 	VERIFY(m->m_flags & M_PKTHDR);
4356 	if (in6_embedded_scope_debug) {
4357 		VERIFY(m->m_pkthdr.pkt_ext_flags & PKTF_EXT_OUTPUT_SCOPE);
4358 		VERIFY((m->m_pkthdr.pkt_flags & PKTF_IFAINFO) == 0);
4359 	}
4360 
4361 	return m->m_pkthdr.src_ifindex;
4362 }
4363 
4364 uint32_t
ip6_output_getdstifscope(struct mbuf * m)4365 ip6_output_getdstifscope(struct mbuf *m)
4366 {
4367 	VERIFY(m->m_flags & M_PKTHDR);
4368 	if (in6_embedded_scope_debug) {
4369 		VERIFY(m->m_pkthdr.pkt_ext_flags & PKTF_EXT_OUTPUT_SCOPE);
4370 		VERIFY((m->m_pkthdr.pkt_flags & PKTF_IFAINFO) == 0);
4371 	}
4372 
4373 	return m->m_pkthdr.dst_ifindex;
4374 }
4375