xref: /xnu-8792.81.2/bsd/netinet/ip_output.c (revision 19c3b8c28c31cb8130e034cfb5df6bf9ba342d90)
1 /*
2  * Copyright (c) 2000-2021 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  * Copyright (c) 1982, 1986, 1988, 1990, 1993
30  *	The Regents of the University of California.  All rights reserved.
31  *
32  * Redistribution and use in source and binary forms, with or without
33  * modification, are permitted provided that the following conditions
34  * are met:
35  * 1. Redistributions of source code must retain the above copyright
36  *    notice, this list of conditions and the following disclaimer.
37  * 2. Redistributions in binary form must reproduce the above copyright
38  *    notice, this list of conditions and the following disclaimer in the
39  *    documentation and/or other materials provided with the distribution.
40  * 3. All advertising materials mentioning features or use of this software
41  *    must display the following acknowledgement:
42  *	This product includes software developed by the University of
43  *	California, Berkeley and its contributors.
44  * 4. Neither the name of the University nor the names of its contributors
45  *    may be used to endorse or promote products derived from this software
46  *    without specific prior written permission.
47  *
48  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58  * SUCH DAMAGE.
59  *
60  *	@(#)ip_output.c	8.3 (Berkeley) 1/21/94
61  */
62 /*
63  * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
64  * support for mandatory and extensible security protections.  This notice
65  * is included in support of clause 2.2 (b) of the Apple Public License,
66  * Version 2.0.
67  */
68 
69 #define _IP_VHL
70 
71 #include <sys/param.h>
72 #include <sys/systm.h>
73 #include <sys/kernel.h>
74 #include <sys/malloc.h>
75 #include <sys/mbuf.h>
76 #include <sys/protosw.h>
77 #include <sys/socket.h>
78 #include <sys/socketvar.h>
79 #include <kern/locks.h>
80 #include <sys/sysctl.h>
81 #include <sys/mcache.h>
82 #include <sys/kdebug.h>
83 
84 #include <machine/endian.h>
85 #include <pexpert/pexpert.h>
86 #include <mach/sdt.h>
87 
88 #include <libkern/OSAtomic.h>
89 #include <libkern/OSByteOrder.h>
90 
91 #include <net/if.h>
92 #include <net/if_dl.h>
93 #include <net/if_types.h>
94 #include <net/route.h>
95 #include <net/ntstat.h>
96 #include <net/net_osdep.h>
97 #include <net/dlil.h>
98 #include <net/net_perf.h>
99 
100 #include <netinet/in.h>
101 #include <netinet/in_systm.h>
102 #include <netinet/ip.h>
103 #include <netinet/in_pcb.h>
104 #include <netinet/in_var.h>
105 #include <netinet/ip_var.h>
106 #include <netinet/kpi_ipfilter_var.h>
107 #include <netinet/in_tclass.h>
108 #include <netinet/udp.h>
109 
110 #include <netinet6/nd6.h>
111 
112 #define DBG_LAYER_BEG           NETDBG_CODE(DBG_NETIP, 1)
113 #define DBG_LAYER_END           NETDBG_CODE(DBG_NETIP, 3)
114 #define DBG_FNC_IP_OUTPUT       NETDBG_CODE(DBG_NETIP, (1 << 8) | 1)
115 #define DBG_FNC_IPSEC4_OUTPUT   NETDBG_CODE(DBG_NETIP, (2 << 8) | 1)
116 
117 #if IPSEC
118 #include <netinet6/ipsec.h>
119 #include <netkey/key.h>
120 #if IPSEC_DEBUG
121 #include <netkey/key_debug.h>
122 #else
123 #define KEYDEBUG(lev, arg)
124 #endif
125 #endif /* IPSEC */
126 
127 #if NECP
128 #include <net/necp.h>
129 #endif /* NECP */
130 
131 
132 #if DUMMYNET
133 #include <netinet/ip_dummynet.h>
134 #endif
135 
136 #if PF
137 #include <net/pfvar.h>
138 #endif /* PF */
139 
140 
141 u_short ip_id;
142 
143 static int sysctl_reset_ip_output_stats SYSCTL_HANDLER_ARGS;
144 static int sysctl_ip_output_measure_bins SYSCTL_HANDLER_ARGS;
145 static int sysctl_ip_output_getperf SYSCTL_HANDLER_ARGS;
146 static void ip_out_cksum_stats(int, u_int32_t);
147 static struct mbuf *ip_insertoptions(struct mbuf *, struct mbuf *, int *);
148 static int ip_optcopy(struct ip *, struct ip *);
149 static int ip_pcbopts(int, struct mbuf **, struct mbuf *);
150 static void imo_trace(struct ip_moptions *, int);
151 static void ip_mloopback(struct ifnet *, struct ifnet *, struct mbuf *,
152     struct sockaddr_in *, int);
153 static struct ifaddr *in_selectsrcif(struct ip *, struct route *, unsigned int);
154 
155 extern struct ip_linklocal_stat ip_linklocal_stat;
156 
157 /* temporary: for testing */
158 #if IPSEC
159 extern int ipsec_bypass;
160 #endif
161 
162 static int ip_maxchainsent = 0;
163 SYSCTL_INT(_net_inet_ip, OID_AUTO, maxchainsent,
164     CTLFLAG_RW | CTLFLAG_LOCKED, &ip_maxchainsent, 0,
165     "use dlil_output_list");
166 #if DEBUG
167 static int forge_ce = 0;
168 SYSCTL_INT(_net_inet_ip, OID_AUTO, forge_ce,
169     CTLFLAG_RW | CTLFLAG_LOCKED, &forge_ce, 0,
170     "Forge ECN CE");
171 #endif /* DEBUG */
172 
173 static int ip_select_srcif_debug = 0;
174 SYSCTL_INT(_net_inet_ip, OID_AUTO, select_srcif_debug,
175     CTLFLAG_RW | CTLFLAG_LOCKED, &ip_select_srcif_debug, 0,
176     "log source interface selection debug info");
177 
178 static int ip_output_measure = 0;
179 SYSCTL_PROC(_net_inet_ip, OID_AUTO, output_perf,
180     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
181     &ip_output_measure, 0, sysctl_reset_ip_output_stats, "I",
182     "Do time measurement");
183 
184 static uint64_t ip_output_measure_bins = 0;
185 SYSCTL_PROC(_net_inet_ip, OID_AUTO, output_perf_bins,
186     CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED, &ip_output_measure_bins, 0,
187     sysctl_ip_output_measure_bins, "I",
188     "bins for chaining performance data histogram");
189 
190 static net_perf_t net_perf;
191 SYSCTL_PROC(_net_inet_ip, OID_AUTO, output_perf_data,
192     CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED,
193     0, 0, sysctl_ip_output_getperf, "S,net_perf",
194     "IP output performance data (struct net_perf, net/net_perf.h)");
195 
196 __private_extern__ int rfc6864 = 1;
197 SYSCTL_INT(_net_inet_ip, OID_AUTO, rfc6864, CTLFLAG_RW | CTLFLAG_LOCKED,
198     &rfc6864, 0, "updated ip id field behavior");
199 
200 #define IMO_TRACE_HIST_SIZE     32      /* size of trace history */
201 
202 /* For gdb */
203 __private_extern__ unsigned int imo_trace_hist_size = IMO_TRACE_HIST_SIZE;
204 
205 struct ip_moptions_dbg {
206 	struct ip_moptions      imo;                    /* ip_moptions */
207 	u_int16_t               imo_refhold_cnt;        /* # of IMO_ADDREF */
208 	u_int16_t               imo_refrele_cnt;        /* # of IMO_REMREF */
209 	/*
210 	 * Alloc and free callers.
211 	 */
212 	ctrace_t                imo_alloc;
213 	ctrace_t                imo_free;
214 	/*
215 	 * Circular lists of IMO_ADDREF and IMO_REMREF callers.
216 	 */
217 	ctrace_t                imo_refhold[IMO_TRACE_HIST_SIZE];
218 	ctrace_t                imo_refrele[IMO_TRACE_HIST_SIZE];
219 };
220 
221 #if DEBUG
222 static unsigned int imo_debug = 1;      /* debugging (enabled) */
223 #else
224 static unsigned int imo_debug;          /* debugging (disabled) */
225 #endif /* !DEBUG */
226 
227 static struct zone *imo_zone;           /* zone for ip_moptions */
228 #define IMO_ZONE_NAME           "ip_moptions"   /* zone name */
229 
230 #if PF
231 __attribute__((noinline))
232 static int
ip_output_pf_dn_hook(struct ifnet * ifp,struct mbuf ** mppn,struct mbuf ** mp,struct pf_rule * dn_pf_rule,struct route * ro,struct sockaddr_in * dst,int flags,struct ip_out_args * ipoa)233 ip_output_pf_dn_hook(struct ifnet *ifp, struct mbuf **mppn, struct mbuf **mp,
234     struct pf_rule *dn_pf_rule, struct route *ro, struct sockaddr_in *dst, int flags,
235     struct ip_out_args *ipoa)
236 {
237 	int rc;
238 	struct ip_fw_args args = {};
239 
240 	args.fwa_pf_rule = dn_pf_rule;
241 	args.fwa_oif = ifp;
242 	args.fwa_ro = ro;
243 	args.fwa_dst = dst;
244 	args.fwa_oflags = flags;
245 	if (flags & IP_OUTARGS) {
246 		args.fwa_ipoa = ipoa;
247 	}
248 	rc = pf_af_hook(ifp, mppn, mp, AF_INET, FALSE, &args);
249 
250 	return rc;
251 }
252 
253 #endif /* PF */
254 
255 
256 /*
257  * IP output.  The packet in mbuf chain m contains a skeletal IP
258  * header (with len, off, ttl, proto, tos, src, dst).
259  * The mbuf chain containing the packet will be freed.
260  * The mbuf opt, if present, will not be freed.
261  */
262 int
ip_output(struct mbuf * m0,struct mbuf * opt,struct route * ro,int flags,struct ip_moptions * imo,struct ip_out_args * ipoa)263 ip_output(struct mbuf *m0, struct mbuf *opt, struct route *ro, int flags,
264     struct ip_moptions *imo, struct ip_out_args *ipoa)
265 {
266 	return ip_output_list(m0, 0, opt, ro, flags, imo, ipoa);
267 }
268 
269 /*
270  * IP output.  The packet in mbuf chain m contains a skeletal IP
271  * header (with len, off, ttl, proto, tos, src, dst).
272  * The mbuf chain containing the packet will be freed.
273  * The mbuf opt, if present, will not be freed.
274  *
275  * Route ro MUST be non-NULL; if ro->ro_rt is valid, route lookup would be
276  * skipped and ro->ro_rt would be used.  Otherwise the result of route
277  * lookup is stored in ro->ro_rt.
278  *
279  * In the IP forwarding case, the packet will arrive with options already
280  * inserted, so must have a NULL opt pointer.
281  */
282 int
ip_output_list(struct mbuf * m0,int packetchain,struct mbuf * opt,struct route * ro,int flags,struct ip_moptions * imo,struct ip_out_args * ipoa)283 ip_output_list(struct mbuf *m0, int packetchain, struct mbuf *opt,
284     struct route *ro, int flags, struct ip_moptions *imo,
285     struct ip_out_args *ipoa)
286 {
287 	struct ip *ip;
288 	struct ifnet *ifp = NULL;               /* not refcnt'd */
289 	struct mbuf *m = m0, *prevnxt = NULL, **mppn = &prevnxt;
290 	int hlen = sizeof(struct ip);
291 	int len = 0, error = 0;
292 	struct sockaddr_in *dst = NULL;
293 	struct in_ifaddr *ia = NULL, *src_ia = NULL;
294 	struct in_addr pkt_dst;
295 	struct ipf_pktopts *ippo = NULL;
296 	ipfilter_t inject_filter_ref = NULL;
297 	struct mbuf *packetlist;
298 	uint32_t sw_csum, pktcnt = 0, scnt = 0, bytecnt = 0;
299 	uint32_t packets_processed = 0;
300 	unsigned int ifscope = IFSCOPE_NONE;
301 	struct flowadv *adv = NULL;
302 	struct timeval start_tv;
303 #if IPSEC
304 	struct socket *so = NULL;
305 	struct secpolicy *sp = NULL;
306 #endif /* IPSEC */
307 #if NECP
308 	necp_kernel_policy_result necp_result = 0;
309 	necp_kernel_policy_result_parameter necp_result_parameter;
310 	necp_kernel_policy_id necp_matched_policy_id = 0;
311 #endif /* NECP */
312 #if DUMMYNET
313 	struct m_tag *tag;
314 	struct ip_out_args saved_ipoa;
315 	struct sockaddr_in dst_buf;
316 #endif /* DUMMYNET */
317 	struct {
318 #if IPSEC
319 		struct ipsec_output_state ipsec_state;
320 #endif /* IPSEC */
321 #if NECP
322 		struct route necp_route;
323 #endif /* NECP */
324 #if DUMMYNET
325 		struct route saved_route;
326 #endif /* DUMMYNET */
327 		struct ipf_pktopts ipf_pktopts;
328 	} ipobz;
329 #define ipsec_state     ipobz.ipsec_state
330 #define necp_route      ipobz.necp_route
331 #define sro_fwd         ipobz.sro_fwd
332 #define saved_route     ipobz.saved_route
333 #define ipf_pktopts     ipobz.ipf_pktopts
334 	union {
335 		struct {
336 			boolean_t select_srcif : 1;     /* set once */
337 			boolean_t srcbound : 1;         /* set once */
338 			boolean_t nocell : 1;           /* set once */
339 			boolean_t isbroadcast : 1;
340 			boolean_t didfilter : 1;
341 			boolean_t noexpensive : 1;      /* set once */
342 			boolean_t noconstrained : 1;      /* set once */
343 			boolean_t awdl_unrestricted : 1;        /* set once */
344 		};
345 		uint32_t raw;
346 	} ipobf = { .raw = 0 };
347 
348 	int interface_mtu = 0;
349 	struct pf_rule *dn_pf_rule = NULL;
350 /*
351  * Here we check for restrictions when sending frames.
352  * N.B.: IPv4 over internal co-processor interfaces is not allowed.
353  */
354 #define IP_CHECK_RESTRICTIONS(_ifp, _ipobf)                             \
355 	(((_ipobf).nocell && IFNET_IS_CELLULAR(_ifp)) ||                \
356 	 ((_ipobf).noexpensive && IFNET_IS_EXPENSIVE(_ifp)) ||          \
357 	 ((_ipobf).noconstrained && IFNET_IS_CONSTRAINED(_ifp)) ||      \
358 	  (IFNET_IS_INTCOPROC(_ifp)) ||                                 \
359 	 (!(_ipobf).awdl_unrestricted && IFNET_IS_AWDL_RESTRICTED(_ifp)))
360 
361 	if (ip_output_measure) {
362 		net_perf_start_time(&net_perf, &start_tv);
363 	}
364 	KERNEL_DEBUG(DBG_FNC_IP_OUTPUT | DBG_FUNC_START, 0, 0, 0, 0, 0);
365 
366 	VERIFY(m0->m_flags & M_PKTHDR);
367 	packetlist = m0;
368 
369 	/* zero out {ipsec_state, args, sro_fwd, saved_route, ipf_pktops} */
370 	bzero(&ipobz, sizeof(ipobz));
371 	ippo = &ipf_pktopts;
372 
373 #if DUMMYNET
374 	if (SLIST_EMPTY(&m0->m_pkthdr.tags)) {
375 		goto ipfw_tags_done;
376 	}
377 
378 	/* Grab info from mtags prepended to the chain */
379 	if ((tag = m_tag_locate(m0, KERNEL_MODULE_TAG_ID,
380 	    KERNEL_TAG_TYPE_DUMMYNET, NULL)) != NULL) {
381 		struct dn_pkt_tag       *dn_tag;
382 
383 		dn_tag = (struct dn_pkt_tag *)(tag + 1);
384 		dn_pf_rule = dn_tag->dn_pf_rule;
385 		opt = NULL;
386 		saved_route = dn_tag->dn_ro;
387 		ro = &saved_route;
388 
389 		imo = NULL;
390 		bcopy(&dn_tag->dn_dst, &dst_buf, sizeof(dst_buf));
391 		dst = &dst_buf;
392 		ifp = dn_tag->dn_ifp;
393 		flags = dn_tag->dn_flags;
394 		if ((dn_tag->dn_flags & IP_OUTARGS)) {
395 			saved_ipoa = dn_tag->dn_ipoa;
396 			ipoa = &saved_ipoa;
397 		}
398 
399 		m_tag_delete(m0, tag);
400 	}
401 ipfw_tags_done:
402 #endif /* DUMMYNET */
403 
404 	m = m0;
405 	m->m_pkthdr.pkt_flags &= ~(PKTF_LOOP | PKTF_IFAINFO);
406 
407 #if IPSEC
408 	if (ipsec_bypass == 0 && !(flags & IP_NOIPSEC)) {
409 		/* If packet is bound to an interface, check bound policies */
410 		if ((flags & IP_OUTARGS) && (ipoa != NULL) &&
411 		    (ipoa->ipoa_flags & IPOAF_BOUND_IF) &&
412 		    ipoa->ipoa_boundif != IFSCOPE_NONE) {
413 			if (ipsec4_getpolicybyinterface(m, IPSEC_DIR_OUTBOUND,
414 			    &flags, ipoa, &sp) != 0) {
415 				goto bad;
416 			}
417 		}
418 	}
419 #endif /* IPSEC */
420 
421 	VERIFY(ro != NULL);
422 
423 	if (flags & IP_OUTARGS) {
424 		/*
425 		 * In the forwarding case, only the ifscope value is used,
426 		 * as source interface selection doesn't take place.
427 		 */
428 		if ((ipobf.select_srcif = (!(flags & IP_FORWARDING) &&
429 		    (ipoa->ipoa_flags & IPOAF_SELECT_SRCIF)))) {
430 			ipf_pktopts.ippo_flags |= IPPOF_SELECT_SRCIF;
431 		}
432 
433 		if ((ipoa->ipoa_flags & IPOAF_BOUND_IF) &&
434 		    ipoa->ipoa_boundif != IFSCOPE_NONE) {
435 			ifscope = ipoa->ipoa_boundif;
436 			ipf_pktopts.ippo_flags |=
437 			    (IPPOF_BOUND_IF | (ifscope << IPPOF_SHIFT_IFSCOPE));
438 		}
439 
440 		/* double negation needed for bool bit field */
441 		ipobf.srcbound = !!(ipoa->ipoa_flags & IPOAF_BOUND_SRCADDR);
442 		if (ipobf.srcbound) {
443 			ipf_pktopts.ippo_flags |= IPPOF_BOUND_SRCADDR;
444 		}
445 	} else {
446 		ipobf.select_srcif = FALSE;
447 		ipobf.srcbound = FALSE;
448 		ifscope = IFSCOPE_NONE;
449 		if (flags & IP_OUTARGS) {
450 			ipoa->ipoa_boundif = IFSCOPE_NONE;
451 			ipoa->ipoa_flags &= ~(IPOAF_SELECT_SRCIF |
452 			    IPOAF_BOUND_IF | IPOAF_BOUND_SRCADDR);
453 		}
454 	}
455 
456 	if (flags & IP_OUTARGS) {
457 		if (ipoa->ipoa_flags & IPOAF_NO_CELLULAR) {
458 			ipobf.nocell = TRUE;
459 			ipf_pktopts.ippo_flags |= IPPOF_NO_IFT_CELLULAR;
460 		}
461 		if (ipoa->ipoa_flags & IPOAF_NO_EXPENSIVE) {
462 			ipobf.noexpensive = TRUE;
463 			ipf_pktopts.ippo_flags |= IPPOF_NO_IFF_EXPENSIVE;
464 		}
465 		if (ipoa->ipoa_flags & IPOAF_NO_CONSTRAINED) {
466 			ipobf.noconstrained = TRUE;
467 			ipf_pktopts.ippo_flags |= IPPOF_NO_IFF_CONSTRAINED;
468 		}
469 		if (ipoa->ipoa_flags & IPOAF_AWDL_UNRESTRICTED) {
470 			ipobf.awdl_unrestricted = TRUE;
471 		}
472 		adv = &ipoa->ipoa_flowadv;
473 		adv->code = FADV_SUCCESS;
474 		ipoa->ipoa_flags &= ~IPOAF_RET_MASK;
475 	}
476 
477 #if IPSEC
478 	if (ipsec_bypass == 0 && !(flags & IP_NOIPSEC)) {
479 		so = ipsec_getsocket(m);
480 		if (so != NULL) {
481 			(void) ipsec_setsocket(m, NULL);
482 		}
483 	}
484 #endif /* IPSEC */
485 
486 #if DUMMYNET
487 	if (dn_pf_rule != NULL) {
488 		/* dummynet already saw us */
489 		ip = mtod(m, struct ip *);
490 		hlen = IP_VHL_HL(ip->ip_vhl) << 2;
491 		pkt_dst = ip->ip_dst;
492 		if (ro->ro_rt != NULL) {
493 			RT_LOCK_SPIN(ro->ro_rt);
494 			ia = (struct in_ifaddr *)ro->ro_rt->rt_ifa;
495 			if (ia) {
496 				/* Become a regular mutex */
497 				RT_CONVERT_LOCK(ro->ro_rt);
498 				IFA_ADDREF(&ia->ia_ifa);
499 			}
500 			RT_UNLOCK(ro->ro_rt);
501 		}
502 
503 		goto sendit;
504 	}
505 #endif /* DUMMYNET */
506 
507 loopit:
508 	packets_processed++;
509 	ipobf.isbroadcast = FALSE;
510 	ipobf.didfilter = FALSE;
511 
512 	VERIFY(m->m_flags & M_PKTHDR);
513 	/*
514 	 * No need to proccess packet twice if we've already seen it.
515 	 */
516 	if (!SLIST_EMPTY(&m->m_pkthdr.tags)) {
517 		inject_filter_ref = ipf_get_inject_filter(m);
518 	} else {
519 		inject_filter_ref = NULL;
520 	}
521 
522 	if (opt) {
523 		m = ip_insertoptions(m, opt, &len);
524 		hlen = len;
525 		/* Update the chain */
526 		if (m != m0) {
527 			if (m0 == packetlist) {
528 				packetlist = m;
529 			}
530 			m0 = m;
531 		}
532 	}
533 	ip = mtod(m, struct ip *);
534 
535 	pkt_dst = ip->ip_dst;
536 
537 	/*
538 	 * We must not send if the packet is destined to network zero.
539 	 * RFC1122 3.2.1.3 (a) and (b).
540 	 */
541 	if (IN_ZERONET(ntohl(pkt_dst.s_addr))) {
542 		error = EHOSTUNREACH;
543 		goto bad;
544 	}
545 
546 	/*
547 	 * Fill in IP header.
548 	 */
549 	if (!(flags & (IP_FORWARDING | IP_RAWOUTPUT))) {
550 		ip->ip_vhl = IP_MAKE_VHL(IPVERSION, hlen >> 2);
551 		ip->ip_off &= IP_DF;
552 		if (rfc6864 && IP_OFF_IS_ATOMIC(ip->ip_off)) {
553 			// Per RFC6864, value of ip_id is undefined for atomic ip packets
554 			ip->ip_id = 0;
555 		} else {
556 			ip->ip_id = ip_randomid((uint64_t)m);
557 		}
558 		OSAddAtomic(1, &ipstat.ips_localout);
559 	} else {
560 		hlen = IP_VHL_HL(ip->ip_vhl) << 2;
561 	}
562 
563 #if DEBUG
564 	/* For debugging, we let the stack forge congestion */
565 	if (forge_ce != 0 &&
566 	    ((ip->ip_tos & IPTOS_ECN_MASK) == IPTOS_ECN_ECT1 ||
567 	    (ip->ip_tos & IPTOS_ECN_MASK) == IPTOS_ECN_ECT0)) {
568 		ip->ip_tos = (ip->ip_tos & ~IPTOS_ECN_MASK) | IPTOS_ECN_CE;
569 		forge_ce--;
570 	}
571 #endif /* DEBUG */
572 
573 	if ((ip->ip_tos & IPTOS_ECN_MASK) == IPTOS_ECN_ECT1) {
574 		m->m_pkthdr.pkt_ext_flags |= PKTF_EXT_L4S;
575 	}
576 
577 	KERNEL_DEBUG(DBG_LAYER_BEG, ip->ip_dst.s_addr, ip->ip_src.s_addr,
578 	    ip->ip_p, ip->ip_off, ip->ip_len);
579 
580 	dst = SIN(&ro->ro_dst);
581 
582 	/*
583 	 * If there is a cached route,
584 	 * check that it is to the same destination
585 	 * and is still up.  If not, free it and try again.
586 	 * The address family should also be checked in case of sharing the
587 	 * cache with IPv6.
588 	 */
589 
590 	if (ro->ro_rt != NULL) {
591 		if (ROUTE_UNUSABLE(ro) && ip->ip_src.s_addr != INADDR_ANY &&
592 		    !(flags & (IP_ROUTETOIF | IP_FORWARDING))) {
593 			src_ia = ifa_foraddr(ip->ip_src.s_addr);
594 			if (src_ia == NULL) {
595 				error = EADDRNOTAVAIL;
596 				goto bad;
597 			}
598 			IFA_REMREF(&src_ia->ia_ifa);
599 			src_ia = NULL;
600 		}
601 		/*
602 		 * Test rt_flags without holding rt_lock for performance
603 		 * reasons; if the route is down it will hopefully be
604 		 * caught by the layer below (since it uses this route
605 		 * as a hint) or during the next transmit.
606 		 */
607 		if (ROUTE_UNUSABLE(ro) || dst->sin_family != AF_INET ||
608 		    dst->sin_addr.s_addr != pkt_dst.s_addr) {
609 			ROUTE_RELEASE(ro);
610 		}
611 
612 		/*
613 		 * If we're doing source interface selection, we may not
614 		 * want to use this route; only synch up the generation
615 		 * count otherwise.
616 		 */
617 		if (!ipobf.select_srcif && ro->ro_rt != NULL &&
618 		    RT_GENID_OUTOFSYNC(ro->ro_rt)) {
619 			RT_GENID_SYNC(ro->ro_rt);
620 		}
621 	}
622 	if (ro->ro_rt == NULL) {
623 		bzero(dst, sizeof(*dst));
624 		dst->sin_family = AF_INET;
625 		dst->sin_len = sizeof(*dst);
626 		dst->sin_addr = pkt_dst;
627 	}
628 	/*
629 	 * If routing to interface only,
630 	 * short circuit routing lookup.
631 	 */
632 	if (flags & IP_ROUTETOIF) {
633 		if (ia != NULL) {
634 			IFA_REMREF(&ia->ia_ifa);
635 		}
636 		if ((ia = ifatoia(ifa_ifwithdstaddr(sintosa(dst)))) == NULL) {
637 			ia = ifatoia(ifa_ifwithnet(sintosa(dst)));
638 			if (ia == NULL) {
639 				OSAddAtomic(1, &ipstat.ips_noroute);
640 				error = ENETUNREACH;
641 				/* XXX IPv6 APN fallback notification?? */
642 				goto bad;
643 			}
644 		}
645 		ifp = ia->ia_ifp;
646 		ip->ip_ttl = 1;
647 		ipobf.isbroadcast = in_broadcast(dst->sin_addr, ifp);
648 		/*
649 		 * For consistency with other cases below.  Loopback
650 		 * multicast case is handled separately by ip_mloopback().
651 		 */
652 		if ((ifp->if_flags & IFF_LOOPBACK) &&
653 		    !IN_MULTICAST(ntohl(pkt_dst.s_addr))) {
654 			m->m_pkthdr.rcvif = ifp;
655 			ip_setsrcifaddr_info(m, ifp->if_index, NULL);
656 			ip_setdstifaddr_info(m, ifp->if_index, NULL);
657 		}
658 	} else if (IN_MULTICAST(ntohl(pkt_dst.s_addr)) &&
659 	    imo != NULL && (ifp = imo->imo_multicast_ifp) != NULL) {
660 		/*
661 		 * Bypass the normal routing lookup for multicast
662 		 * packets if the interface is specified.
663 		 */
664 		ipobf.isbroadcast = FALSE;
665 		if (ia != NULL) {
666 			IFA_REMREF(&ia->ia_ifa);
667 		}
668 
669 		/* Macro takes reference on ia */
670 		IFP_TO_IA(ifp, ia);
671 	} else {
672 		struct ifaddr *ia0 = NULL;
673 		boolean_t cloneok = FALSE;
674 		/*
675 		 * Perform source interface selection; the source IP address
676 		 * must belong to one of the addresses of the interface used
677 		 * by the route.  For performance reasons, do this only if
678 		 * there is no route, or if the routing table has changed,
679 		 * or if we haven't done source interface selection on this
680 		 * route (for this PCB instance) before.
681 		 */
682 		if (ipobf.select_srcif &&
683 		    ip->ip_src.s_addr != INADDR_ANY && (ROUTE_UNUSABLE(ro) ||
684 		    !(ro->ro_flags & ROF_SRCIF_SELECTED))) {
685 			/* Find the source interface */
686 			ia0 = in_selectsrcif(ip, ro, ifscope);
687 
688 			/*
689 			 * If the source address belongs to a restricted
690 			 * interface and the caller forbids our using
691 			 * interfaces of such type, pretend that there is no
692 			 * route.
693 			 */
694 			if (ia0 != NULL &&
695 			    IP_CHECK_RESTRICTIONS(ia0->ifa_ifp, ipobf)) {
696 				IFA_REMREF(ia0);
697 				ia0 = NULL;
698 				error = EHOSTUNREACH;
699 				if (flags & IP_OUTARGS) {
700 					ipoa->ipoa_flags |= IPOAF_R_IFDENIED;
701 				}
702 				goto bad;
703 			}
704 
705 			/*
706 			 * If the source address is spoofed (in the case of
707 			 * IP_RAWOUTPUT on an unbounded socket), or if this
708 			 * is destined for local/loopback, just let it go out
709 			 * using the interface of the route.  Otherwise,
710 			 * there's no interface having such an address,
711 			 * so bail out.
712 			 */
713 			if (ia0 == NULL && (!(flags & IP_RAWOUTPUT) ||
714 			    ipobf.srcbound) && ifscope != lo_ifp->if_index) {
715 				error = EADDRNOTAVAIL;
716 				goto bad;
717 			}
718 
719 			/*
720 			 * If the caller didn't explicitly specify the scope,
721 			 * pick it up from the source interface.  If the cached
722 			 * route was wrong and was blown away as part of source
723 			 * interface selection, don't mask out RTF_PRCLONING
724 			 * since that route may have been allocated by the ULP,
725 			 * unless the IP header was created by the caller or
726 			 * the destination is IPv4 LLA.  The check for the
727 			 * latter is needed because IPv4 LLAs are never scoped
728 			 * in the current implementation, and we don't want to
729 			 * replace the resolved IPv4 LLA route with one whose
730 			 * gateway points to that of the default gateway on
731 			 * the primary interface of the system.
732 			 */
733 			if (ia0 != NULL) {
734 				if (ifscope == IFSCOPE_NONE) {
735 					ifscope = ia0->ifa_ifp->if_index;
736 				}
737 				cloneok = (!(flags & IP_RAWOUTPUT) &&
738 				    !(IN_LINKLOCAL(ntohl(ip->ip_dst.s_addr))));
739 			}
740 		}
741 
742 		/*
743 		 * If this is the case, we probably don't want to allocate
744 		 * a protocol-cloned route since we didn't get one from the
745 		 * ULP.  This lets TCP do its thing, while not burdening
746 		 * forwarding or ICMP with the overhead of cloning a route.
747 		 * Of course, we still want to do any cloning requested by
748 		 * the link layer, as this is probably required in all cases
749 		 * for correct operation (as it is for ARP).
750 		 */
751 		if (ro->ro_rt == NULL) {
752 			uint32_t ign = RTF_PRCLONING;
753 			/*
754 			 * We make an exception here: if the destination
755 			 * address is INADDR_BROADCAST, allocate a protocol-
756 			 * cloned host route so that we end up with a route
757 			 * marked with the RTF_BROADCAST flag.  Otherwise,
758 			 * we would end up referring to the default route,
759 			 * instead of creating a cloned host route entry.
760 			 * That would introduce inconsistencies between ULPs
761 			 * that allocate a route and those that don't.  The
762 			 * RTF_BROADCAST route is important since we'd want
763 			 * to send out undirected IP broadcast packets using
764 			 * link-level broadcast address. Another exception
765 			 * is for ULP-created routes that got blown away by
766 			 * source interface selection (see above).
767 			 *
768 			 * These exceptions will no longer be necessary when
769 			 * the RTF_PRCLONING scheme is no longer present.
770 			 */
771 			if (cloneok || dst->sin_addr.s_addr == INADDR_BROADCAST) {
772 				ign &= ~RTF_PRCLONING;
773 			}
774 
775 			/*
776 			 * Loosen the route lookup criteria if the ifscope
777 			 * corresponds to the loopback interface; this is
778 			 * needed to support Application Layer Gateways
779 			 * listening on loopback, in conjunction with packet
780 			 * filter redirection rules.  The final source IP
781 			 * address will be rewritten by the packet filter
782 			 * prior to the RFC1122 loopback check below.
783 			 */
784 			if (ifscope == lo_ifp->if_index) {
785 				rtalloc_ign(ro, ign);
786 			} else {
787 				rtalloc_scoped_ign(ro, ign, ifscope);
788 			}
789 
790 			/*
791 			 * If the route points to a cellular/expensive interface
792 			 * and the caller forbids our using interfaces of such type,
793 			 * pretend that there is no route.
794 			 */
795 			if (ro->ro_rt != NULL) {
796 				RT_LOCK_SPIN(ro->ro_rt);
797 				if (IP_CHECK_RESTRICTIONS(ro->ro_rt->rt_ifp,
798 				    ipobf)) {
799 					RT_UNLOCK(ro->ro_rt);
800 					ROUTE_RELEASE(ro);
801 					if (flags & IP_OUTARGS) {
802 						ipoa->ipoa_flags |=
803 						    IPOAF_R_IFDENIED;
804 					}
805 				} else {
806 					RT_UNLOCK(ro->ro_rt);
807 				}
808 			}
809 		}
810 
811 		if (ro->ro_rt == NULL) {
812 			OSAddAtomic(1, &ipstat.ips_noroute);
813 			error = EHOSTUNREACH;
814 			if (ia0 != NULL) {
815 				IFA_REMREF(ia0);
816 				ia0 = NULL;
817 			}
818 			goto bad;
819 		}
820 
821 		if (ia != NULL) {
822 			IFA_REMREF(&ia->ia_ifa);
823 		}
824 		RT_LOCK_SPIN(ro->ro_rt);
825 		ia = ifatoia(ro->ro_rt->rt_ifa);
826 		if (ia != NULL) {
827 			/* Become a regular mutex */
828 			RT_CONVERT_LOCK(ro->ro_rt);
829 			IFA_ADDREF(&ia->ia_ifa);
830 		}
831 		/*
832 		 * Note: ia_ifp may not be the same as rt_ifp; the latter
833 		 * is what we use for determining outbound i/f, mtu, etc.
834 		 */
835 		ifp = ro->ro_rt->rt_ifp;
836 		ro->ro_rt->rt_use++;
837 		if (ro->ro_rt->rt_flags & RTF_GATEWAY) {
838 			dst = SIN(ro->ro_rt->rt_gateway);
839 		}
840 		if (ro->ro_rt->rt_flags & RTF_HOST) {
841 			/* double negation needed for bool bit field */
842 			ipobf.isbroadcast =
843 			    !!(ro->ro_rt->rt_flags & RTF_BROADCAST);
844 		} else {
845 			/* Become a regular mutex */
846 			RT_CONVERT_LOCK(ro->ro_rt);
847 			ipobf.isbroadcast = in_broadcast(dst->sin_addr, ifp);
848 		}
849 		/*
850 		 * For consistency with IPv6, as well as to ensure that
851 		 * IP_RECVIF is set correctly for packets that are sent
852 		 * to one of the local addresses.  ia (rt_ifa) would have
853 		 * been fixed up by rt_setif for local routes.  This
854 		 * would make it appear as if the packet arrives on the
855 		 * interface which owns the local address.  Loopback
856 		 * multicast case is handled separately by ip_mloopback().
857 		 */
858 		if (ia != NULL && (ifp->if_flags & IFF_LOOPBACK) &&
859 		    !IN_MULTICAST(ntohl(pkt_dst.s_addr))) {
860 			uint16_t srcidx;
861 
862 			m->m_pkthdr.rcvif = ia->ia_ifa.ifa_ifp;
863 
864 			if (ia0 != NULL) {
865 				srcidx = ia0->ifa_ifp->if_index;
866 			} else if ((ro->ro_flags & ROF_SRCIF_SELECTED) &&
867 			    ro->ro_srcia != NULL) {
868 				srcidx = ro->ro_srcia->ifa_ifp->if_index;
869 			} else {
870 				srcidx = 0;
871 			}
872 
873 			ip_setsrcifaddr_info(m, srcidx, NULL);
874 			ip_setdstifaddr_info(m, 0, ia);
875 		}
876 		RT_UNLOCK(ro->ro_rt);
877 		if (ia0 != NULL) {
878 			IFA_REMREF(ia0);
879 			ia0 = NULL;
880 		}
881 	}
882 
883 	if (IN_MULTICAST(ntohl(pkt_dst.s_addr))) {
884 		struct ifnet *srcifp = NULL;
885 		struct in_multi *inm;
886 		u_int32_t vif = 0;
887 		u_int8_t ttl = IP_DEFAULT_MULTICAST_TTL;
888 		u_int8_t loop = IP_DEFAULT_MULTICAST_LOOP;
889 
890 		m->m_flags |= M_MCAST;
891 		/*
892 		 * IP destination address is multicast.  Make sure "dst"
893 		 * still points to the address in "ro".  (It may have been
894 		 * changed to point to a gateway address, above.)
895 		 */
896 		dst = SIN(&ro->ro_dst);
897 		/*
898 		 * See if the caller provided any multicast options
899 		 */
900 		if (imo != NULL) {
901 			IMO_LOCK(imo);
902 			vif = imo->imo_multicast_vif;
903 			ttl = imo->imo_multicast_ttl;
904 			loop = imo->imo_multicast_loop;
905 			if (!(flags & IP_RAWOUTPUT)) {
906 				ip->ip_ttl = ttl;
907 			}
908 			if (imo->imo_multicast_ifp != NULL) {
909 				ifp = imo->imo_multicast_ifp;
910 			}
911 			IMO_UNLOCK(imo);
912 		} else if (!(flags & IP_RAWOUTPUT)) {
913 			vif = -1;
914 			ip->ip_ttl = ttl;
915 		}
916 		/*
917 		 * Confirm that the outgoing interface supports multicast.
918 		 */
919 		if (imo == NULL || vif == -1) {
920 			if (!(ifp->if_flags & IFF_MULTICAST)) {
921 				OSAddAtomic(1, &ipstat.ips_noroute);
922 				error = ENETUNREACH;
923 				goto bad;
924 			}
925 		}
926 		/*
927 		 * If source address not specified yet, use address
928 		 * of outgoing interface.
929 		 */
930 		if (ip->ip_src.s_addr == INADDR_ANY) {
931 			struct in_ifaddr *ia1;
932 			lck_rw_lock_shared(&in_ifaddr_rwlock);
933 			TAILQ_FOREACH(ia1, &in_ifaddrhead, ia_link) {
934 				IFA_LOCK_SPIN(&ia1->ia_ifa);
935 				if (ia1->ia_ifp == ifp) {
936 					ip->ip_src = IA_SIN(ia1)->sin_addr;
937 					srcifp = ifp;
938 					IFA_UNLOCK(&ia1->ia_ifa);
939 					break;
940 				}
941 				IFA_UNLOCK(&ia1->ia_ifa);
942 			}
943 			lck_rw_done(&in_ifaddr_rwlock);
944 			if (ip->ip_src.s_addr == INADDR_ANY) {
945 				error = ENETUNREACH;
946 				goto bad;
947 			}
948 		}
949 
950 		in_multihead_lock_shared();
951 		IN_LOOKUP_MULTI(&pkt_dst, ifp, inm);
952 		in_multihead_lock_done();
953 		if (inm != NULL && (imo == NULL || loop)) {
954 			/*
955 			 * If we belong to the destination multicast group
956 			 * on the outgoing interface, and the caller did not
957 			 * forbid loopback, loop back a copy.
958 			 */
959 			if (!TAILQ_EMPTY(&ipv4_filters)
960 #if NECP
961 			    && !necp_packet_should_skip_filters(m)
962 #endif // NECP
963 			    ) {
964 				struct ipfilter *filter;
965 				int seen = (inject_filter_ref == NULL);
966 
967 				if (imo != NULL) {
968 					ipf_pktopts.ippo_flags |=
969 					    IPPOF_MCAST_OPTS;
970 					ipf_pktopts.ippo_mcast_ifnet = ifp;
971 					ipf_pktopts.ippo_mcast_ttl = ttl;
972 					ipf_pktopts.ippo_mcast_loop = loop;
973 				}
974 
975 				ipf_ref();
976 
977 				/*
978 				 * 4135317 - always pass network byte
979 				 * order to filter
980 				 */
981 #if BYTE_ORDER != BIG_ENDIAN
982 				HTONS(ip->ip_len);
983 				HTONS(ip->ip_off);
984 #endif
985 				TAILQ_FOREACH(filter, &ipv4_filters, ipf_link) {
986 					if (seen == 0) {
987 						if ((struct ipfilter *)
988 						    inject_filter_ref == filter) {
989 							seen = 1;
990 						}
991 					} else if (filter->ipf_filter.
992 					    ipf_output != NULL) {
993 						errno_t result;
994 						result = filter->ipf_filter.
995 						    ipf_output(filter->
996 						    ipf_filter.cookie,
997 						    (mbuf_t *)&m, ippo);
998 						if (result == EJUSTRETURN) {
999 							ipf_unref();
1000 							INM_REMREF(inm);
1001 							goto done;
1002 						}
1003 						if (result != 0) {
1004 							ipf_unref();
1005 							INM_REMREF(inm);
1006 							goto bad;
1007 						}
1008 					}
1009 				}
1010 
1011 				/* set back to host byte order */
1012 				ip = mtod(m, struct ip *);
1013 #if BYTE_ORDER != BIG_ENDIAN
1014 				NTOHS(ip->ip_len);
1015 				NTOHS(ip->ip_off);
1016 #endif
1017 				ipf_unref();
1018 				ipobf.didfilter = TRUE;
1019 			}
1020 			ip_mloopback(srcifp, ifp, m, dst, hlen);
1021 		}
1022 		if (inm != NULL) {
1023 			INM_REMREF(inm);
1024 		}
1025 		/*
1026 		 * Multicasts with a time-to-live of zero may be looped-
1027 		 * back, above, but must not be transmitted on a network.
1028 		 * Also, multicasts addressed to the loopback interface
1029 		 * are not sent -- the above call to ip_mloopback() will
1030 		 * loop back a copy if this host actually belongs to the
1031 		 * destination group on the loopback interface.
1032 		 */
1033 		if (ip->ip_ttl == 0 || ifp->if_flags & IFF_LOOPBACK) {
1034 			m_freem(m);
1035 			goto done;
1036 		}
1037 
1038 		goto sendit;
1039 	}
1040 	/*
1041 	 * If source address not specified yet, use address
1042 	 * of outgoing interface.
1043 	 */
1044 	if (ip->ip_src.s_addr == INADDR_ANY) {
1045 		IFA_LOCK_SPIN(&ia->ia_ifa);
1046 		ip->ip_src = IA_SIN(ia)->sin_addr;
1047 		IFA_UNLOCK(&ia->ia_ifa);
1048 	}
1049 
1050 	/*
1051 	 * Look for broadcast address and
1052 	 * and verify user is allowed to send
1053 	 * such a packet.
1054 	 */
1055 	if (ipobf.isbroadcast) {
1056 		if (!(ifp->if_flags & IFF_BROADCAST)) {
1057 			error = EADDRNOTAVAIL;
1058 			goto bad;
1059 		}
1060 		if (!(flags & IP_ALLOWBROADCAST)) {
1061 			error = EACCES;
1062 			goto bad;
1063 		}
1064 		/* don't allow broadcast messages to be fragmented */
1065 		if ((u_short)ip->ip_len > ifp->if_mtu) {
1066 			error = EMSGSIZE;
1067 			goto bad;
1068 		}
1069 		m->m_flags |= M_BCAST;
1070 	} else {
1071 		m->m_flags &= ~M_BCAST;
1072 	}
1073 
1074 sendit:
1075 #if PF
1076 	/* Invoke outbound packet filter */
1077 	if (PF_IS_ENABLED) {
1078 		int rc;
1079 
1080 		m0 = m; /* Save for later */
1081 #if DUMMYNET
1082 		rc = ip_output_pf_dn_hook(ifp, mppn, &m, dn_pf_rule, ro, dst, flags, ipoa);
1083 #else /* DUMMYNET */
1084 		rc = pf_af_hook(ifp, mppn, &m, AF_INET, FALSE, NULL);
1085 #endif /* DUMMYNET */
1086 		if (rc != 0 || m == NULL) {
1087 			/* Move to the next packet */
1088 			m = *mppn;
1089 
1090 			/* Skip ahead if first packet in list got dropped */
1091 			if (packetlist == m0) {
1092 				packetlist = m;
1093 			}
1094 
1095 			if (m != NULL) {
1096 				m0 = m;
1097 				/* Next packet in the chain */
1098 				goto loopit;
1099 			} else if (packetlist != NULL) {
1100 				/* No more packet; send down the chain */
1101 				goto sendchain;
1102 			}
1103 			/* Nothing left; we're done */
1104 			goto done;
1105 		}
1106 		m0 = m;
1107 		ip = mtod(m, struct ip *);
1108 		pkt_dst = ip->ip_dst;
1109 		hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1110 	}
1111 #endif /* PF */
1112 	/*
1113 	 * Force IP TTL to 255 following draft-ietf-zeroconf-ipv4-linklocal.txt
1114 	 */
1115 	if (IN_LINKLOCAL(ntohl(ip->ip_src.s_addr)) ||
1116 	    IN_LINKLOCAL(ntohl(ip->ip_dst.s_addr))) {
1117 		ip_linklocal_stat.iplls_out_total++;
1118 		if (ip->ip_ttl != MAXTTL) {
1119 			ip_linklocal_stat.iplls_out_badttl++;
1120 			ip->ip_ttl = MAXTTL;
1121 		}
1122 	}
1123 
1124 	if (!ipobf.didfilter &&
1125 	    !TAILQ_EMPTY(&ipv4_filters)
1126 #if NECP
1127 	    && !necp_packet_should_skip_filters(m)
1128 #endif // NECP
1129 	    ) {
1130 		struct ipfilter *filter;
1131 		int seen = (inject_filter_ref == NULL);
1132 		ipf_pktopts.ippo_flags &= ~IPPOF_MCAST_OPTS;
1133 
1134 		/*
1135 		 * Check that a TSO frame isn't passed to a filter.
1136 		 * This could happen if a filter is inserted while
1137 		 * TCP is sending the TSO packet.
1138 		 */
1139 		if (m->m_pkthdr.csum_flags & CSUM_TSO_IPV4) {
1140 			error = EMSGSIZE;
1141 			goto bad;
1142 		}
1143 
1144 		ipf_ref();
1145 
1146 		/* 4135317 - always pass network byte order to filter */
1147 #if BYTE_ORDER != BIG_ENDIAN
1148 		HTONS(ip->ip_len);
1149 		HTONS(ip->ip_off);
1150 #endif
1151 		TAILQ_FOREACH(filter, &ipv4_filters, ipf_link) {
1152 			if (seen == 0) {
1153 				if ((struct ipfilter *)inject_filter_ref ==
1154 				    filter) {
1155 					seen = 1;
1156 				}
1157 			} else if (filter->ipf_filter.ipf_output) {
1158 				errno_t result;
1159 				result = filter->ipf_filter.
1160 				    ipf_output(filter->ipf_filter.cookie,
1161 				    (mbuf_t *)&m, ippo);
1162 				if (result == EJUSTRETURN) {
1163 					ipf_unref();
1164 					goto done;
1165 				}
1166 				if (result != 0) {
1167 					ipf_unref();
1168 					goto bad;
1169 				}
1170 			}
1171 		}
1172 		/* set back to host byte order */
1173 		ip = mtod(m, struct ip *);
1174 #if BYTE_ORDER != BIG_ENDIAN
1175 		NTOHS(ip->ip_len);
1176 		NTOHS(ip->ip_off);
1177 #endif
1178 		ipf_unref();
1179 	}
1180 
1181 #if NECP
1182 	/* Process Network Extension Policy. Will Pass, Drop, or Rebind packet. */
1183 	necp_matched_policy_id = necp_ip_output_find_policy_match(m,
1184 	    flags, (flags & IP_OUTARGS) ? ipoa : NULL, ro ? ro->ro_rt : NULL, &necp_result, &necp_result_parameter);
1185 	if (necp_matched_policy_id) {
1186 		necp_mark_packet_from_ip(m, necp_matched_policy_id);
1187 		switch (necp_result) {
1188 		case NECP_KERNEL_POLICY_RESULT_PASS:
1189 			if (necp_result_parameter.pass_flags & NECP_KERNEL_POLICY_PASS_NO_SKIP_IPSEC) {
1190 				break;
1191 			}
1192 			/* Check if the interface is allowed */
1193 			if (!necp_packet_is_allowed_over_interface(m, ifp)) {
1194 				error = EHOSTUNREACH;
1195 				OSAddAtomic(1, &ipstat.ips_necp_policy_drop);
1196 				goto bad;
1197 			}
1198 			goto skip_ipsec;
1199 		case NECP_KERNEL_POLICY_RESULT_DROP:
1200 		case NECP_KERNEL_POLICY_RESULT_SOCKET_DIVERT:
1201 			/* Flow divert packets should be blocked at the IP layer */
1202 			error = EHOSTUNREACH;
1203 			OSAddAtomic(1, &ipstat.ips_necp_policy_drop);
1204 			goto bad;
1205 		case NECP_KERNEL_POLICY_RESULT_IP_TUNNEL: {
1206 			/* Verify that the packet is being routed to the tunnel */
1207 			struct ifnet *policy_ifp = necp_get_ifnet_from_result_parameter(&necp_result_parameter);
1208 			if (policy_ifp == ifp) {
1209 				/* Check if the interface is allowed */
1210 				if (!necp_packet_is_allowed_over_interface(m, ifp)) {
1211 					error = EHOSTUNREACH;
1212 					OSAddAtomic(1, &ipstat.ips_necp_policy_drop);
1213 					goto bad;
1214 				}
1215 				goto skip_ipsec;
1216 			} else {
1217 				if (necp_packet_can_rebind_to_ifnet(m, policy_ifp, &necp_route, AF_INET)) {
1218 					/* Check if the interface is allowed */
1219 					if (!necp_packet_is_allowed_over_interface(m, policy_ifp)) {
1220 						error = EHOSTUNREACH;
1221 						OSAddAtomic(1, &ipstat.ips_necp_policy_drop);
1222 						goto bad;
1223 					}
1224 
1225 					/*
1226 					 * Update the QOS marking policy if
1227 					 * 1. up layer asks it to do so
1228 					 * 2. net_qos_policy_restricted is not set
1229 					 * 3. qos_marking_gencount doesn't match necp_kernel_socket_policies_gencount (checked in necp_lookup_current_qos_marking)
1230 					 */
1231 					if (ipoa != NULL &&
1232 					    (ipoa->ipoa_flags & IPOAF_REDO_QOSMARKING_POLICY) &&
1233 					    net_qos_policy_restricted != 0) {
1234 						bool qos_marking = (ipoa->ipoa_flags & IPOAF_QOSMARKING_ALLOWED) ? TRUE : FALSE;
1235 						qos_marking = necp_lookup_current_qos_marking(&ipoa->qos_marking_gencount, NULL, policy_ifp, necp_result_parameter.route_rule_id, qos_marking);
1236 						if (qos_marking) {
1237 							ipoa->ipoa_flags |= IPOAF_QOSMARKING_ALLOWED;
1238 						} else {
1239 							ipoa->ipoa_flags &= ~IPOAF_QOSMARKING_ALLOWED;
1240 						}
1241 					}
1242 
1243 					/* Set ifp to the tunnel interface, since it is compatible with the packet */
1244 					ifp = policy_ifp;
1245 					ro = &necp_route;
1246 					goto skip_ipsec;
1247 				} else {
1248 					error = ENETUNREACH;
1249 					OSAddAtomic(1, &ipstat.ips_necp_policy_drop);
1250 					goto bad;
1251 				}
1252 			}
1253 		}
1254 		default:
1255 			break;
1256 		}
1257 	}
1258 	/* Catch-all to check if the interface is allowed */
1259 	if (!necp_packet_is_allowed_over_interface(m, ifp)) {
1260 		error = EHOSTUNREACH;
1261 		OSAddAtomic(1, &ipstat.ips_necp_policy_drop);
1262 		goto bad;
1263 	}
1264 #endif /* NECP */
1265 
1266 #if IPSEC
1267 	if (ipsec_bypass != 0 || (flags & IP_NOIPSEC)) {
1268 		goto skip_ipsec;
1269 	}
1270 
1271 	KERNEL_DEBUG(DBG_FNC_IPSEC4_OUTPUT | DBG_FUNC_START, 0, 0, 0, 0, 0);
1272 
1273 	if (sp == NULL) {
1274 		/* get SP for this packet */
1275 		if (so != NULL) {
1276 			sp = ipsec4_getpolicybysock(m, IPSEC_DIR_OUTBOUND,
1277 			    so, &error);
1278 		} else {
1279 			sp = ipsec4_getpolicybyaddr(m, IPSEC_DIR_OUTBOUND,
1280 			    flags, &error);
1281 		}
1282 		if (sp == NULL) {
1283 			IPSEC_STAT_INCREMENT(ipsecstat.out_inval);
1284 			KERNEL_DEBUG(DBG_FNC_IPSEC4_OUTPUT | DBG_FUNC_END,
1285 			    0, 0, 0, 0, 0);
1286 			goto bad;
1287 		}
1288 	}
1289 
1290 	error = 0;
1291 
1292 	/* check policy */
1293 	switch (sp->policy) {
1294 	case IPSEC_POLICY_DISCARD:
1295 	case IPSEC_POLICY_GENERATE:
1296 		/*
1297 		 * This packet is just discarded.
1298 		 */
1299 		IPSEC_STAT_INCREMENT(ipsecstat.out_polvio);
1300 		KERNEL_DEBUG(DBG_FNC_IPSEC4_OUTPUT | DBG_FUNC_END,
1301 		    1, 0, 0, 0, 0);
1302 		goto bad;
1303 
1304 	case IPSEC_POLICY_BYPASS:
1305 	case IPSEC_POLICY_NONE:
1306 		/* no need to do IPsec. */
1307 		KERNEL_DEBUG(DBG_FNC_IPSEC4_OUTPUT | DBG_FUNC_END,
1308 		    2, 0, 0, 0, 0);
1309 		goto skip_ipsec;
1310 
1311 	case IPSEC_POLICY_IPSEC:
1312 		if (sp->req == NULL) {
1313 			/* acquire a policy */
1314 			error = key_spdacquire(sp);
1315 			KERNEL_DEBUG(DBG_FNC_IPSEC4_OUTPUT | DBG_FUNC_END,
1316 			    3, 0, 0, 0, 0);
1317 			goto bad;
1318 		}
1319 		if (sp->ipsec_if) {
1320 			/* Verify the redirect to ipsec interface */
1321 			if (sp->ipsec_if == ifp) {
1322 				goto skip_ipsec;
1323 			}
1324 			goto bad;
1325 		}
1326 		break;
1327 
1328 	case IPSEC_POLICY_ENTRUST:
1329 	default:
1330 		printf("ip_output: Invalid policy found. %d\n", sp->policy);
1331 	}
1332 	{
1333 		ipsec_state.m = m;
1334 		if (flags & IP_ROUTETOIF) {
1335 			bzero(&ipsec_state.ro, sizeof(ipsec_state.ro));
1336 		} else {
1337 			route_copyout((struct route *)&ipsec_state.ro, ro, sizeof(struct route));
1338 		}
1339 		ipsec_state.dst = SA(dst);
1340 
1341 		ip->ip_sum = 0;
1342 
1343 		/*
1344 		 * XXX
1345 		 * delayed checksums are not currently compatible with IPsec
1346 		 */
1347 		if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
1348 			in_delayed_cksum(m);
1349 		}
1350 
1351 #if BYTE_ORDER != BIG_ENDIAN
1352 		HTONS(ip->ip_len);
1353 		HTONS(ip->ip_off);
1354 #endif
1355 
1356 		DTRACE_IP6(send, struct mbuf *, m, struct inpcb *, NULL,
1357 		    struct ip *, ip, struct ifnet *, ifp,
1358 		    struct ip *, ip, struct ip6_hdr *, NULL);
1359 
1360 		error = ipsec4_output(&ipsec_state, sp, flags);
1361 		if (ipsec_state.tunneled == 6) {
1362 			m0 = m = NULL;
1363 			error = 0;
1364 			goto bad;
1365 		}
1366 
1367 		m0 = m = ipsec_state.m;
1368 
1369 #if DUMMYNET
1370 		/*
1371 		 * If we're about to use the route in ipsec_state
1372 		 * and this came from dummynet, cleaup now.
1373 		 */
1374 		if (ro == &saved_route &&
1375 		    (!(flags & IP_ROUTETOIF) || ipsec_state.tunneled)) {
1376 			ROUTE_RELEASE(ro);
1377 		}
1378 #endif /* DUMMYNET */
1379 
1380 		if (flags & IP_ROUTETOIF) {
1381 			/*
1382 			 * if we have tunnel mode SA, we may need to ignore
1383 			 * IP_ROUTETOIF.
1384 			 */
1385 			if (ipsec_state.tunneled) {
1386 				flags &= ~IP_ROUTETOIF;
1387 				ro = (struct route *)&ipsec_state.ro;
1388 			}
1389 		} else {
1390 			ro = (struct route *)&ipsec_state.ro;
1391 		}
1392 		dst = SIN(ipsec_state.dst);
1393 		if (error) {
1394 			/* mbuf is already reclaimed in ipsec4_output. */
1395 			m0 = NULL;
1396 			switch (error) {
1397 			case EHOSTUNREACH:
1398 			case ENETUNREACH:
1399 			case EMSGSIZE:
1400 			case ENOBUFS:
1401 			case ENOMEM:
1402 				break;
1403 			default:
1404 				printf("ip4_output (ipsec): error code %d\n", error);
1405 				OS_FALLTHROUGH;
1406 			case ENOENT:
1407 				/* don't show these error codes to the user */
1408 				error = 0;
1409 				break;
1410 			}
1411 			KERNEL_DEBUG(DBG_FNC_IPSEC4_OUTPUT | DBG_FUNC_END,
1412 			    4, 0, 0, 0, 0);
1413 			goto bad;
1414 		}
1415 	}
1416 
1417 	/* be sure to update variables that are affected by ipsec4_output() */
1418 	ip = mtod(m, struct ip *);
1419 
1420 #ifdef _IP_VHL
1421 	hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1422 #else /* !_IP_VHL */
1423 	hlen = ip->ip_hl << 2;
1424 #endif /* !_IP_VHL */
1425 	/* Check that there wasn't a route change and src is still valid */
1426 	if (ROUTE_UNUSABLE(ro)) {
1427 		ROUTE_RELEASE(ro);
1428 		VERIFY(src_ia == NULL);
1429 		if (ip->ip_src.s_addr != INADDR_ANY &&
1430 		    !(flags & (IP_ROUTETOIF | IP_FORWARDING)) &&
1431 		    (src_ia = ifa_foraddr(ip->ip_src.s_addr)) == NULL) {
1432 			error = EADDRNOTAVAIL;
1433 			KERNEL_DEBUG(DBG_FNC_IPSEC4_OUTPUT | DBG_FUNC_END,
1434 			    5, 0, 0, 0, 0);
1435 			goto bad;
1436 		}
1437 		if (src_ia != NULL) {
1438 			IFA_REMREF(&src_ia->ia_ifa);
1439 			src_ia = NULL;
1440 		}
1441 	}
1442 
1443 	if (ro->ro_rt == NULL) {
1444 		if (!(flags & IP_ROUTETOIF)) {
1445 			printf("%s: can't update route after "
1446 			    "IPsec processing\n", __func__);
1447 			error = EHOSTUNREACH;   /* XXX */
1448 			KERNEL_DEBUG(DBG_FNC_IPSEC4_OUTPUT | DBG_FUNC_END,
1449 			    6, 0, 0, 0, 0);
1450 			goto bad;
1451 		}
1452 	} else {
1453 		if (ia != NULL) {
1454 			IFA_REMREF(&ia->ia_ifa);
1455 		}
1456 		RT_LOCK_SPIN(ro->ro_rt);
1457 		ia = ifatoia(ro->ro_rt->rt_ifa);
1458 		if (ia != NULL) {
1459 			/* Become a regular mutex */
1460 			RT_CONVERT_LOCK(ro->ro_rt);
1461 			IFA_ADDREF(&ia->ia_ifa);
1462 		}
1463 		ifp = ro->ro_rt->rt_ifp;
1464 		RT_UNLOCK(ro->ro_rt);
1465 	}
1466 
1467 	/* make it flipped, again. */
1468 #if BYTE_ORDER != BIG_ENDIAN
1469 	NTOHS(ip->ip_len);
1470 	NTOHS(ip->ip_off);
1471 #endif
1472 	KERNEL_DEBUG(DBG_FNC_IPSEC4_OUTPUT | DBG_FUNC_END,
1473 	    7, 0xff, 0xff, 0xff, 0xff);
1474 
1475 	/* Pass to filters again */
1476 	if (!TAILQ_EMPTY(&ipv4_filters)
1477 #if NECP
1478 	    && !necp_packet_should_skip_filters(m)
1479 #endif // NECP
1480 	    ) {
1481 		struct ipfilter *filter;
1482 
1483 		ipf_pktopts.ippo_flags &= ~IPPOF_MCAST_OPTS;
1484 
1485 		/*
1486 		 * Check that a TSO frame isn't passed to a filter.
1487 		 * This could happen if a filter is inserted while
1488 		 * TCP is sending the TSO packet.
1489 		 */
1490 		if (m->m_pkthdr.csum_flags & CSUM_TSO_IPV4) {
1491 			error = EMSGSIZE;
1492 			goto bad;
1493 		}
1494 
1495 		ipf_ref();
1496 
1497 		/* 4135317 - always pass network byte order to filter */
1498 #if BYTE_ORDER != BIG_ENDIAN
1499 		HTONS(ip->ip_len);
1500 		HTONS(ip->ip_off);
1501 #endif
1502 		TAILQ_FOREACH(filter, &ipv4_filters, ipf_link) {
1503 			if (filter->ipf_filter.ipf_output) {
1504 				errno_t result;
1505 				result = filter->ipf_filter.
1506 				    ipf_output(filter->ipf_filter.cookie,
1507 				    (mbuf_t *)&m, ippo);
1508 				if (result == EJUSTRETURN) {
1509 					ipf_unref();
1510 					goto done;
1511 				}
1512 				if (result != 0) {
1513 					ipf_unref();
1514 					goto bad;
1515 				}
1516 			}
1517 		}
1518 		/* set back to host byte order */
1519 		ip = mtod(m, struct ip *);
1520 #if BYTE_ORDER != BIG_ENDIAN
1521 		NTOHS(ip->ip_len);
1522 		NTOHS(ip->ip_off);
1523 #endif
1524 		ipf_unref();
1525 	}
1526 skip_ipsec:
1527 #endif /* IPSEC */
1528 
1529 
1530 	/* 127/8 must not appear on wire - RFC1122 */
1531 	if (!(ifp->if_flags & IFF_LOOPBACK) &&
1532 	    ((ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
1533 	    (ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)) {
1534 		OSAddAtomic(1, &ipstat.ips_badaddr);
1535 		error = EADDRNOTAVAIL;
1536 		goto bad;
1537 	}
1538 
1539 	if (ipoa != NULL) {
1540 		u_int8_t dscp = ip->ip_tos >> IPTOS_DSCP_SHIFT;
1541 
1542 		error = set_packet_qos(m, ifp,
1543 		    ipoa->ipoa_flags & IPOAF_QOSMARKING_ALLOWED ? TRUE : FALSE,
1544 		    ipoa->ipoa_sotc, ipoa->ipoa_netsvctype, &dscp);
1545 		if (error == 0) {
1546 			ip->ip_tos &= IPTOS_ECN_MASK;
1547 			ip->ip_tos |= dscp << IPTOS_DSCP_SHIFT;
1548 		} else {
1549 			printf("%s if_dscp_for_mbuf() error %d\n", __func__, error);
1550 			error = 0;
1551 		}
1552 	}
1553 
1554 	ip_output_checksum(ifp, m, (IP_VHL_HL(ip->ip_vhl) << 2),
1555 	    ip->ip_len, &sw_csum);
1556 
1557 	interface_mtu = ifp->if_mtu;
1558 
1559 	if (INTF_ADJUST_MTU_FOR_CLAT46(ifp)) {
1560 		interface_mtu = IN6_LINKMTU(ifp);
1561 		/* Further adjust the size for CLAT46 expansion */
1562 		interface_mtu -= CLAT46_HDR_EXPANSION_OVERHD;
1563 	}
1564 
1565 	/*
1566 	 * If small enough for interface, or the interface will take
1567 	 * care of the fragmentation for us, can just send directly.
1568 	 */
1569 	if ((u_short)ip->ip_len <= interface_mtu || TSO_IPV4_OK(ifp, m) ||
1570 	    (!(ip->ip_off & IP_DF) && (ifp->if_hwassist & CSUM_FRAGMENT))) {
1571 #if BYTE_ORDER != BIG_ENDIAN
1572 		HTONS(ip->ip_len);
1573 		HTONS(ip->ip_off);
1574 #endif
1575 
1576 		ip->ip_sum = 0;
1577 		if (sw_csum & CSUM_DELAY_IP) {
1578 			ip->ip_sum = ip_cksum_hdr_out(m, hlen);
1579 			sw_csum &= ~CSUM_DELAY_IP;
1580 			m->m_pkthdr.csum_flags &= ~CSUM_DELAY_IP;
1581 		}
1582 
1583 #if IPSEC
1584 		/* clean ipsec history once it goes out of the node */
1585 		if (ipsec_bypass == 0 && !(flags & IP_NOIPSEC)) {
1586 			ipsec_delaux(m);
1587 		}
1588 #endif /* IPSEC */
1589 		if ((m->m_pkthdr.csum_flags & CSUM_TSO_IPV4) &&
1590 		    (m->m_pkthdr.tso_segsz > 0)) {
1591 			scnt += m->m_pkthdr.len / m->m_pkthdr.tso_segsz;
1592 		} else {
1593 			scnt++;
1594 		}
1595 
1596 		if (packetchain == 0) {
1597 			if (ro->ro_rt != NULL && nstat_collect) {
1598 				nstat_route_tx(ro->ro_rt, scnt,
1599 				    m->m_pkthdr.len, 0);
1600 			}
1601 
1602 			error = dlil_output(ifp, PF_INET, m, ro->ro_rt,
1603 			    SA(dst), 0, adv);
1604 			if (dlil_verbose && error) {
1605 				printf("dlil_output error on interface %s: %d\n",
1606 				    ifp->if_xname, error);
1607 			}
1608 			scnt = 0;
1609 			goto done;
1610 		} else {
1611 			/*
1612 			 * packet chaining allows us to reuse the
1613 			 * route for all packets
1614 			 */
1615 			bytecnt += m->m_pkthdr.len;
1616 			mppn = &m->m_nextpkt;
1617 			m = m->m_nextpkt;
1618 			if (m == NULL) {
1619 #if PF
1620 sendchain:
1621 #endif /* PF */
1622 				if (pktcnt > ip_maxchainsent) {
1623 					ip_maxchainsent = pktcnt;
1624 				}
1625 				if (ro->ro_rt != NULL && nstat_collect) {
1626 					nstat_route_tx(ro->ro_rt, scnt,
1627 					    bytecnt, 0);
1628 				}
1629 
1630 				error = dlil_output(ifp, PF_INET, packetlist,
1631 				    ro->ro_rt, SA(dst), 0, adv);
1632 				if (dlil_verbose && error) {
1633 					printf("dlil_output error on interface %s: %d\n",
1634 					    ifp->if_xname, error);
1635 				}
1636 				pktcnt = 0;
1637 				scnt = 0;
1638 				bytecnt = 0;
1639 				goto done;
1640 			}
1641 			m0 = m;
1642 			pktcnt++;
1643 			goto loopit;
1644 		}
1645 	}
1646 
1647 	VERIFY(interface_mtu != 0);
1648 	/*
1649 	 * Too large for interface; fragment if possible.
1650 	 * Must be able to put at least 8 bytes per fragment.
1651 	 * Balk when DF bit is set or the interface didn't support TSO.
1652 	 */
1653 	if ((ip->ip_off & IP_DF) || pktcnt > 0 ||
1654 	    (m->m_pkthdr.csum_flags & CSUM_TSO_IPV4)) {
1655 		error = EMSGSIZE;
1656 		/*
1657 		 * This case can happen if the user changed the MTU
1658 		 * of an interface after enabling IP on it.  Because
1659 		 * most netifs don't keep track of routes pointing to
1660 		 * them, there is no way for one to update all its
1661 		 * routes when the MTU is changed.
1662 		 */
1663 		if (ro->ro_rt) {
1664 			RT_LOCK_SPIN(ro->ro_rt);
1665 			if ((ro->ro_rt->rt_flags & (RTF_UP | RTF_HOST)) &&
1666 			    !(ro->ro_rt->rt_rmx.rmx_locks & RTV_MTU) &&
1667 			    (ro->ro_rt->rt_rmx.rmx_mtu > interface_mtu)) {
1668 				ro->ro_rt->rt_rmx.rmx_mtu = interface_mtu;
1669 			}
1670 			RT_UNLOCK(ro->ro_rt);
1671 		}
1672 		if (pktcnt > 0) {
1673 			m0 = packetlist;
1674 		}
1675 		OSAddAtomic(1, &ipstat.ips_cantfrag);
1676 		goto bad;
1677 	}
1678 
1679 	/*
1680 	 * XXX Only TCP seems to be passing a list of packets here.
1681 	 * The following issue is limited to UDP datagrams with 0 checksum.
1682 	 * For now limit it to the case when single packet is passed down.
1683 	 */
1684 	if (packetchain == 0 && IS_INTF_CLAT46(ifp)) {
1685 		/*
1686 		 * If it is a UDP packet that has checksum set to 0
1687 		 * and is also not being offloaded, compute a full checksum
1688 		 * and update the UDP checksum.
1689 		 */
1690 		if (ip->ip_p == IPPROTO_UDP &&
1691 		    !(m->m_pkthdr.csum_flags & (CSUM_UDP | CSUM_PARTIAL))) {
1692 			struct udphdr *uh = NULL;
1693 
1694 			if (m->m_len < hlen + sizeof(struct udphdr)) {
1695 				m = m_pullup(m, hlen + sizeof(struct udphdr));
1696 				if (m == NULL) {
1697 					error = ENOBUFS;
1698 					m0 = m;
1699 					goto bad;
1700 				}
1701 				m0 = m;
1702 				ip = mtod(m, struct ip *);
1703 			}
1704 			/*
1705 			 * Get UDP header and if checksum is 0, then compute the full
1706 			 * checksum.
1707 			 */
1708 			uh = (struct udphdr *)(void *)((caddr_t)ip + hlen);
1709 			if (uh->uh_sum == 0) {
1710 				uh->uh_sum = inet_cksum(m, IPPROTO_UDP, hlen,
1711 				    ip->ip_len - hlen);
1712 				if (uh->uh_sum == 0) {
1713 					uh->uh_sum = 0xffff;
1714 				}
1715 			}
1716 		}
1717 	}
1718 
1719 	error = ip_fragment(m, ifp, interface_mtu, sw_csum);
1720 	if (error != 0) {
1721 		m0 = m = NULL;
1722 		goto bad;
1723 	}
1724 
1725 	KERNEL_DEBUG(DBG_LAYER_END, ip->ip_dst.s_addr,
1726 	    ip->ip_src.s_addr, ip->ip_p, ip->ip_off, ip->ip_len);
1727 
1728 	for (m = m0; m; m = m0) {
1729 		m0 = m->m_nextpkt;
1730 		m->m_nextpkt = 0;
1731 #if IPSEC
1732 		/* clean ipsec history once it goes out of the node */
1733 		if (ipsec_bypass == 0 && !(flags & IP_NOIPSEC)) {
1734 			ipsec_delaux(m);
1735 		}
1736 #endif /* IPSEC */
1737 		if (error == 0) {
1738 			if ((packetchain != 0) && (pktcnt > 0)) {
1739 				panic("%s: mix of packet in packetlist is "
1740 				    "wrong=%p", __func__, packetlist);
1741 				/* NOTREACHED */
1742 			}
1743 			if (ro->ro_rt != NULL && nstat_collect) {
1744 				nstat_route_tx(ro->ro_rt, 1,
1745 				    m->m_pkthdr.len, 0);
1746 			}
1747 			error = dlil_output(ifp, PF_INET, m, ro->ro_rt,
1748 			    SA(dst), 0, adv);
1749 			if (dlil_verbose && error) {
1750 				printf("dlil_output error on interface %s: %d\n",
1751 				    ifp->if_xname, error);
1752 			}
1753 		} else {
1754 			m_freem(m);
1755 		}
1756 	}
1757 
1758 	if (error == 0) {
1759 		OSAddAtomic(1, &ipstat.ips_fragmented);
1760 	}
1761 
1762 done:
1763 	if (ia != NULL) {
1764 		IFA_REMREF(&ia->ia_ifa);
1765 		ia = NULL;
1766 	}
1767 #if IPSEC
1768 	ROUTE_RELEASE(&ipsec_state.ro);
1769 	if (sp != NULL) {
1770 		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1771 		    printf("DP ip_output call free SP:%x\n", sp));
1772 		key_freesp(sp, KEY_SADB_UNLOCKED);
1773 	}
1774 #endif /* IPSEC */
1775 #if NECP
1776 	ROUTE_RELEASE(&necp_route);
1777 #endif /* NECP */
1778 #if DUMMYNET
1779 	ROUTE_RELEASE(&saved_route);
1780 #endif /* DUMMYNET */
1781 
1782 	KERNEL_DEBUG(DBG_FNC_IP_OUTPUT | DBG_FUNC_END, error, 0, 0, 0, 0);
1783 	if (ip_output_measure) {
1784 		net_perf_measure_time(&net_perf, &start_tv, packets_processed);
1785 		net_perf_histogram(&net_perf, packets_processed);
1786 	}
1787 	return error;
1788 bad:
1789 	if (pktcnt > 0) {
1790 		m0 = packetlist;
1791 	}
1792 	m_freem_list(m0);
1793 	goto done;
1794 
1795 #undef ipsec_state
1796 #undef args
1797 #undef sro_fwd
1798 #undef saved_route
1799 #undef ipf_pktopts
1800 #undef IP_CHECK_RESTRICTIONS
1801 }
1802 
1803 int
ip_fragment(struct mbuf * m,struct ifnet * ifp,uint32_t mtu,int sw_csum)1804 ip_fragment(struct mbuf *m, struct ifnet *ifp, uint32_t mtu, int sw_csum)
1805 {
1806 	struct ip *ip, *mhip;
1807 	int len, hlen, mhlen, firstlen, off, error = 0;
1808 	struct mbuf **mnext = &m->m_nextpkt, *m0;
1809 	int nfrags = 1;
1810 
1811 	ip = mtod(m, struct ip *);
1812 #ifdef _IP_VHL
1813 	hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1814 #else /* !_IP_VHL */
1815 	hlen = ip->ip_hl << 2;
1816 #endif /* !_IP_VHL */
1817 
1818 	/*
1819 	 * We need to adjust the fragment sizes to account
1820 	 * for IPv6 fragment header if it needs to be translated
1821 	 * from IPv4 to IPv6.
1822 	 */
1823 	if (IS_INTF_CLAT46(ifp)) {
1824 		mtu -= sizeof(struct ip6_frag);
1825 	}
1826 
1827 	firstlen = len = (mtu - hlen) & ~7;
1828 	if (len < 8) {
1829 		m_freem(m);
1830 		return EMSGSIZE;
1831 	}
1832 
1833 	/*
1834 	 * if the interface will not calculate checksums on
1835 	 * fragmented packets, then do it here.
1836 	 */
1837 	if ((m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) &&
1838 	    !(ifp->if_hwassist & CSUM_IP_FRAGS)) {
1839 		in_delayed_cksum(m);
1840 	}
1841 
1842 	/*
1843 	 * Loop through length of segment after first fragment,
1844 	 * make new header and copy data of each part and link onto chain.
1845 	 */
1846 	m0 = m;
1847 	mhlen = sizeof(struct ip);
1848 	for (off = hlen + len; off < (u_short)ip->ip_len; off += len) {
1849 		MGETHDR(m, M_DONTWAIT, MT_HEADER);      /* MAC-OK */
1850 		if (m == NULL) {
1851 			error = ENOBUFS;
1852 			OSAddAtomic(1, &ipstat.ips_odropped);
1853 			goto sendorfree;
1854 		}
1855 		m->m_flags |= (m0->m_flags & M_MCAST) | M_FRAG;
1856 		m->m_data += max_linkhdr;
1857 		mhip = mtod(m, struct ip *);
1858 		*mhip = *ip;
1859 		if (hlen > sizeof(struct ip)) {
1860 			mhlen = ip_optcopy(ip, mhip) + sizeof(struct ip);
1861 			mhip->ip_vhl = IP_MAKE_VHL(IPVERSION, mhlen >> 2);
1862 		}
1863 		m->m_len = mhlen;
1864 		mhip->ip_off = (u_short)(((off - hlen) >> 3) + (ip->ip_off & ~IP_MF));
1865 		if (ip->ip_off & IP_MF) {
1866 			mhip->ip_off |= IP_MF;
1867 		}
1868 		if (off + len >= (u_short)ip->ip_len) {
1869 			len = (u_short)ip->ip_len - off;
1870 		} else {
1871 			mhip->ip_off |= IP_MF;
1872 		}
1873 		mhip->ip_len = htons((u_short)(len + mhlen));
1874 		m->m_next = m_copy(m0, off, len);
1875 		if (m->m_next == NULL) {
1876 			(void) m_free(m);
1877 			error = ENOBUFS;        /* ??? */
1878 			OSAddAtomic(1, &ipstat.ips_odropped);
1879 			goto sendorfree;
1880 		}
1881 		m->m_pkthdr.len = mhlen + len;
1882 		m->m_pkthdr.rcvif = NULL;
1883 		m->m_pkthdr.csum_flags = m0->m_pkthdr.csum_flags;
1884 
1885 		M_COPY_CLASSIFIER(m, m0);
1886 		M_COPY_PFTAG(m, m0);
1887 		M_COPY_NECPTAG(m, m0);
1888 
1889 #if BYTE_ORDER != BIG_ENDIAN
1890 		HTONS(mhip->ip_off);
1891 #endif
1892 
1893 		mhip->ip_sum = 0;
1894 		if (sw_csum & CSUM_DELAY_IP) {
1895 			mhip->ip_sum = ip_cksum_hdr_out(m, mhlen);
1896 			m->m_pkthdr.csum_flags &= ~CSUM_DELAY_IP;
1897 		}
1898 		*mnext = m;
1899 		mnext = &m->m_nextpkt;
1900 		nfrags++;
1901 	}
1902 	OSAddAtomic(nfrags, &ipstat.ips_ofragments);
1903 
1904 	/* set first/last markers for fragment chain */
1905 	m->m_flags |= M_LASTFRAG;
1906 	m0->m_flags |= M_FIRSTFRAG | M_FRAG;
1907 	m0->m_pkthdr.csum_data = nfrags;
1908 
1909 	/*
1910 	 * Update first fragment by trimming what's been copied out
1911 	 * and updating header, then send each fragment (in order).
1912 	 */
1913 	m = m0;
1914 	m_adj(m, hlen + firstlen - (u_short)ip->ip_len);
1915 	m->m_pkthdr.len = hlen + firstlen;
1916 	ip->ip_len = htons((u_short)m->m_pkthdr.len);
1917 	ip->ip_off |= IP_MF;
1918 
1919 #if BYTE_ORDER != BIG_ENDIAN
1920 	HTONS(ip->ip_off);
1921 #endif
1922 
1923 	ip->ip_sum = 0;
1924 	if (sw_csum & CSUM_DELAY_IP) {
1925 		ip->ip_sum = ip_cksum_hdr_out(m, hlen);
1926 		m->m_pkthdr.csum_flags &= ~CSUM_DELAY_IP;
1927 	}
1928 sendorfree:
1929 	if (error) {
1930 		m_freem_list(m0);
1931 	}
1932 
1933 	return error;
1934 }
1935 
1936 static void
ip_out_cksum_stats(int proto,u_int32_t len)1937 ip_out_cksum_stats(int proto, u_int32_t len)
1938 {
1939 	switch (proto) {
1940 	case IPPROTO_TCP:
1941 		tcp_out_cksum_stats(len);
1942 		break;
1943 	case IPPROTO_UDP:
1944 		udp_out_cksum_stats(len);
1945 		break;
1946 	default:
1947 		/* keep only TCP or UDP stats for now */
1948 		break;
1949 	}
1950 }
1951 
1952 /*
1953  * Process a delayed payload checksum calculation (outbound path.)
1954  *
1955  * hoff is the number of bytes beyond the mbuf data pointer which
1956  * points to the IP header.
1957  *
1958  * Returns a bitmask representing all the work done in software.
1959  */
1960 uint32_t
in_finalize_cksum(struct mbuf * m,uint32_t hoff,uint32_t csum_flags)1961 in_finalize_cksum(struct mbuf *m, uint32_t hoff, uint32_t csum_flags)
1962 {
1963 	unsigned char buf[15 << 2] __attribute__((aligned(8)));
1964 	struct ip *ip;
1965 	uint32_t offset, _hlen, mlen, hlen, len, sw_csum;
1966 	uint16_t csum, ip_len;
1967 
1968 	_CASSERT(sizeof(csum) == sizeof(uint16_t));
1969 	VERIFY(m->m_flags & M_PKTHDR);
1970 
1971 	sw_csum = (csum_flags & m->m_pkthdr.csum_flags);
1972 
1973 	if ((sw_csum &= (CSUM_DELAY_IP | CSUM_DELAY_DATA)) == 0) {
1974 		goto done;
1975 	}
1976 
1977 	mlen = m->m_pkthdr.len;                         /* total mbuf len */
1978 
1979 	/* sanity check (need at least simple IP header) */
1980 	if (mlen < (hoff + sizeof(*ip))) {
1981 		panic("%s: mbuf %p pkt len (%u) < hoff+ip_hdr "
1982 		    "(%u+%u)\n", __func__, m, mlen, hoff,
1983 		    (uint32_t)sizeof(*ip));
1984 		/* NOTREACHED */
1985 	}
1986 
1987 	/*
1988 	 * In case the IP header is not contiguous, or not 32-bit aligned,
1989 	 * or if we're computing the IP header checksum, copy it to a local
1990 	 * buffer.  Copy only the simple IP header here (IP options case
1991 	 * is handled below.)
1992 	 */
1993 	if ((sw_csum & CSUM_DELAY_IP) || (hoff + sizeof(*ip)) > m->m_len ||
1994 	    !IP_HDR_ALIGNED_P(mtod(m, caddr_t) + hoff)) {
1995 		m_copydata(m, hoff, sizeof(*ip), (caddr_t)buf);
1996 		ip = (struct ip *)(void *)buf;
1997 		_hlen = sizeof(*ip);
1998 	} else {
1999 		ip = (struct ip *)(void *)(m->m_data + hoff);
2000 		_hlen = 0;
2001 	}
2002 
2003 	hlen = IP_VHL_HL(ip->ip_vhl) << 2;              /* IP header len */
2004 
2005 	/* sanity check */
2006 	if (mlen < (hoff + hlen)) {
2007 		panic("%s: mbuf %p pkt too short (%d) for IP header (%u), "
2008 		    "hoff %u", __func__, m, mlen, hlen, hoff);
2009 		/* NOTREACHED */
2010 	}
2011 
2012 	/*
2013 	 * We could be in the context of an IP or interface filter; in the
2014 	 * former case, ip_len would be in host (correct) order while for
2015 	 * the latter it would be in network order.  Because of this, we
2016 	 * attempt to interpret the length field by comparing it against
2017 	 * the actual packet length.  If the comparison fails, byte swap
2018 	 * the length and check again.  If it still fails, use the actual
2019 	 * packet length.  This also covers the trailing bytes case.
2020 	 */
2021 	ip_len = ip->ip_len;
2022 	if (ip_len != (mlen - hoff)) {
2023 		ip_len = OSSwapInt16(ip_len);
2024 		if (ip_len != (mlen - hoff)) {
2025 			printf("%s: mbuf 0x%llx proto %d IP len %d (%x) "
2026 			    "[swapped %d (%x)] doesn't match actual packet "
2027 			    "length; %d is used instead\n", __func__,
2028 			    (uint64_t)VM_KERNEL_ADDRPERM(m), ip->ip_p,
2029 			    ip->ip_len, ip->ip_len, ip_len, ip_len,
2030 			    (mlen - hoff));
2031 			if (mlen - hoff > UINT16_MAX) {
2032 				panic("%s: mlen %u - hoff %u > 65535",
2033 				    __func__, mlen, hoff);
2034 			}
2035 			ip_len = (uint16_t)(mlen - hoff);
2036 		}
2037 	}
2038 
2039 	len = ip_len - hlen;                            /* csum span */
2040 
2041 	if (sw_csum & CSUM_DELAY_DATA) {
2042 		uint16_t ulpoff;
2043 
2044 		/*
2045 		 * offset is added to the lower 16-bit value of csum_data,
2046 		 * which is expected to contain the ULP offset; therefore
2047 		 * CSUM_PARTIAL offset adjustment must be undone.
2048 		 */
2049 		if ((m->m_pkthdr.csum_flags & (CSUM_PARTIAL | CSUM_DATA_VALID)) ==
2050 		    (CSUM_PARTIAL | CSUM_DATA_VALID)) {
2051 			/*
2052 			 * Get back the original ULP offset (this will
2053 			 * undo the CSUM_PARTIAL logic in ip_output.)
2054 			 */
2055 			m->m_pkthdr.csum_data = (m->m_pkthdr.csum_tx_stuff -
2056 			    m->m_pkthdr.csum_tx_start);
2057 		}
2058 
2059 		ulpoff = (m->m_pkthdr.csum_data & 0xffff); /* ULP csum offset */
2060 		offset = hoff + hlen;                   /* ULP header */
2061 
2062 		if (mlen < (ulpoff + sizeof(csum))) {
2063 			panic("%s: mbuf %p pkt len (%u) proto %d invalid ULP "
2064 			    "cksum offset (%u) cksum flags 0x%x\n", __func__,
2065 			    m, mlen, ip->ip_p, ulpoff, m->m_pkthdr.csum_flags);
2066 			/* NOTREACHED */
2067 		}
2068 
2069 		csum = inet_cksum(m, 0, offset, len);
2070 
2071 		/* Update stats */
2072 		ip_out_cksum_stats(ip->ip_p, len);
2073 
2074 		/* RFC1122 4.1.3.4 */
2075 		if (csum == 0 &&
2076 		    (m->m_pkthdr.csum_flags & (CSUM_UDP | CSUM_ZERO_INVERT))) {
2077 			csum = 0xffff;
2078 		}
2079 
2080 		/* Insert the checksum in the ULP csum field */
2081 		offset += ulpoff;
2082 		if (offset + sizeof(csum) > m->m_len) {
2083 			m_copyback(m, offset, sizeof(csum), &csum);
2084 		} else if (IP_HDR_ALIGNED_P(mtod(m, char *) + hoff)) {
2085 			*(uint16_t *)(void *)(mtod(m, char *) + offset) = csum;
2086 		} else {
2087 			bcopy(&csum, (mtod(m, char *) + offset), sizeof(csum));
2088 		}
2089 		m->m_pkthdr.csum_flags &= ~(CSUM_DELAY_DATA | CSUM_DATA_VALID |
2090 		    CSUM_PARTIAL | CSUM_ZERO_INVERT);
2091 	}
2092 
2093 	if (sw_csum & CSUM_DELAY_IP) {
2094 		/* IP header must be in the local buffer */
2095 		VERIFY(_hlen == sizeof(*ip));
2096 		if (_hlen != hlen) {
2097 			VERIFY(hlen <= sizeof(buf));
2098 			m_copydata(m, hoff, hlen, (caddr_t)buf);
2099 			ip = (struct ip *)(void *)buf;
2100 			_hlen = hlen;
2101 		}
2102 
2103 		/*
2104 		 * Compute the IP header checksum as if the IP length
2105 		 * is the length which we believe is "correct"; see
2106 		 * how ip_len gets calculated above.  Note that this
2107 		 * is done on the local copy and not on the real one.
2108 		 */
2109 		ip->ip_len = htons(ip_len);
2110 		ip->ip_sum = 0;
2111 		csum = in_cksum_hdr_opt(ip);
2112 
2113 		/* Update stats */
2114 		ipstat.ips_snd_swcsum++;
2115 		ipstat.ips_snd_swcsum_bytes += hlen;
2116 
2117 		/*
2118 		 * Insert only the checksum in the existing IP header
2119 		 * csum field; all other fields are left unchanged.
2120 		 */
2121 		offset = hoff + offsetof(struct ip, ip_sum);
2122 		if (offset + sizeof(csum) > m->m_len) {
2123 			m_copyback(m, offset, sizeof(csum), &csum);
2124 		} else if (IP_HDR_ALIGNED_P(mtod(m, char *) + hoff)) {
2125 			*(uint16_t *)(void *)(mtod(m, char *) + offset) = csum;
2126 		} else {
2127 			bcopy(&csum, (mtod(m, char *) + offset), sizeof(csum));
2128 		}
2129 		m->m_pkthdr.csum_flags &= ~CSUM_DELAY_IP;
2130 	}
2131 
2132 done:
2133 	return sw_csum;
2134 }
2135 
2136 /*
2137  * Insert IP options into preformed packet.
2138  * Adjust IP destination as required for IP source routing,
2139  * as indicated by a non-zero in_addr at the start of the options.
2140  *
2141  * XXX This routine assumes that the packet has no options in place.
2142  */
2143 static struct mbuf *
ip_insertoptions(struct mbuf * m,struct mbuf * opt,int * phlen)2144 ip_insertoptions(struct mbuf *m, struct mbuf *opt, int *phlen)
2145 {
2146 	struct ipoption *p = mtod(opt, struct ipoption *);
2147 	struct mbuf *n;
2148 	struct ip *ip = mtod(m, struct ip *);
2149 	unsigned optlen;
2150 
2151 	optlen = opt->m_len - sizeof(p->ipopt_dst);
2152 	if (optlen + (u_short)ip->ip_len > IP_MAXPACKET) {
2153 		return m;             /* XXX should fail */
2154 	}
2155 	if (p->ipopt_dst.s_addr) {
2156 		ip->ip_dst = p->ipopt_dst;
2157 	}
2158 	if (m->m_flags & M_EXT || m->m_data - optlen < m->m_pktdat) {
2159 		MGETHDR(n, M_DONTWAIT, MT_HEADER);      /* MAC-OK */
2160 		if (n == NULL) {
2161 			return m;
2162 		}
2163 		n->m_pkthdr.rcvif = 0;
2164 		n->m_pkthdr.len = m->m_pkthdr.len + optlen;
2165 		m->m_len -= sizeof(struct ip);
2166 		m->m_data += sizeof(struct ip);
2167 		n->m_next = m;
2168 		m = n;
2169 		m->m_len = optlen + sizeof(struct ip);
2170 		m->m_data += max_linkhdr;
2171 		(void) memcpy(mtod(m, void *), ip, sizeof(struct ip));
2172 	} else {
2173 		m->m_data -= optlen;
2174 		m->m_len += optlen;
2175 		m->m_pkthdr.len += optlen;
2176 		ovbcopy((caddr_t)ip, mtod(m, caddr_t), sizeof(struct ip));
2177 	}
2178 	ip = mtod(m, struct ip *);
2179 	bcopy(p->ipopt_list, ip + 1, optlen);
2180 	*phlen = sizeof(struct ip) + optlen;
2181 	ip->ip_vhl = IP_MAKE_VHL(IPVERSION, *phlen >> 2);
2182 	ip->ip_len += optlen;
2183 	return m;
2184 }
2185 
2186 /*
2187  * Copy options from ip to jp,
2188  * omitting those not copied during fragmentation.
2189  */
2190 static int
ip_optcopy(struct ip * ip,struct ip * jp)2191 ip_optcopy(struct ip *ip, struct ip *jp)
2192 {
2193 	u_char *cp, *dp;
2194 	int opt, optlen, cnt;
2195 
2196 	cp = (u_char *)(ip + 1);
2197 	dp = (u_char *)(jp + 1);
2198 	cnt = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
2199 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
2200 		opt = cp[0];
2201 		if (opt == IPOPT_EOL) {
2202 			break;
2203 		}
2204 		if (opt == IPOPT_NOP) {
2205 			/* Preserve for IP mcast tunnel's LSRR alignment. */
2206 			*dp++ = IPOPT_NOP;
2207 			optlen = 1;
2208 			continue;
2209 		}
2210 #if DIAGNOSTIC
2211 		if (cnt < IPOPT_OLEN + sizeof(*cp)) {
2212 			panic("malformed IPv4 option passed to ip_optcopy");
2213 			/* NOTREACHED */
2214 		}
2215 #endif
2216 		optlen = cp[IPOPT_OLEN];
2217 #if DIAGNOSTIC
2218 		if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt) {
2219 			panic("malformed IPv4 option passed to ip_optcopy");
2220 			/* NOTREACHED */
2221 		}
2222 #endif
2223 		/* bogus lengths should have been caught by ip_dooptions */
2224 		if (optlen > cnt) {
2225 			optlen = cnt;
2226 		}
2227 		if (IPOPT_COPIED(opt)) {
2228 			bcopy(cp, dp, optlen);
2229 			dp += optlen;
2230 		}
2231 	}
2232 	for (optlen = (int)(dp - (u_char *)(jp + 1)); optlen & 0x3; optlen++) {
2233 		*dp++ = IPOPT_EOL;
2234 	}
2235 	return optlen;
2236 }
2237 
2238 /*
2239  * IP socket option processing.
2240  */
2241 int
ip_ctloutput(struct socket * so,struct sockopt * sopt)2242 ip_ctloutput(struct socket *so, struct sockopt *sopt)
2243 {
2244 	struct  inpcb *inp = sotoinpcb(so);
2245 	int     error, optval;
2246 	lck_mtx_t *mutex_held = NULL;
2247 
2248 	error = optval = 0;
2249 	if (sopt->sopt_level != IPPROTO_IP) {
2250 		return EINVAL;
2251 	}
2252 
2253 	switch (sopt->sopt_dir) {
2254 	case SOPT_SET:
2255 		mutex_held = socket_getlock(so, PR_F_WILLUNLOCK);
2256 		/*
2257 		 *  Wait if we are in the middle of ip_output
2258 		 *  as we unlocked the socket there and don't
2259 		 *  want to overwrite the IP options
2260 		 */
2261 		if (inp->inp_sndinprog_cnt > 0) {
2262 			inp->inp_sndingprog_waiters++;
2263 
2264 			while (inp->inp_sndinprog_cnt > 0) {
2265 				msleep(&inp->inp_sndinprog_cnt, mutex_held,
2266 				    PSOCK | PCATCH, "inp_sndinprog_cnt", NULL);
2267 			}
2268 			inp->inp_sndingprog_waiters--;
2269 		}
2270 		switch (sopt->sopt_name) {
2271 #ifdef notyet
2272 		case IP_RETOPTS:
2273 #endif
2274 		case IP_OPTIONS: {
2275 			struct mbuf *m;
2276 
2277 			if (sopt->sopt_valsize > MLEN) {
2278 				error = EMSGSIZE;
2279 				break;
2280 			}
2281 			MGET(m, sopt->sopt_p != kernproc ? M_WAIT : M_DONTWAIT,
2282 			    MT_HEADER);
2283 			if (m == NULL) {
2284 				error = ENOBUFS;
2285 				break;
2286 			}
2287 			m->m_len = (int32_t)sopt->sopt_valsize;
2288 			error = sooptcopyin(sopt, mtod(m, char *),
2289 			    m->m_len, m->m_len);
2290 			if (error) {
2291 				m_freem(m);
2292 				break;
2293 			}
2294 
2295 			return ip_pcbopts(sopt->sopt_name,
2296 			           &inp->inp_options, m);
2297 		}
2298 
2299 		case IP_TOS:
2300 		case IP_TTL:
2301 		case IP_RECVOPTS:
2302 		case IP_RECVRETOPTS:
2303 		case IP_RECVDSTADDR:
2304 		case IP_RECVIF:
2305 		case IP_RECVTTL:
2306 		case IP_RECVPKTINFO:
2307 		case IP_RECVTOS:
2308 		case IP_DONTFRAG:
2309 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2310 			    sizeof(optval));
2311 			if (error) {
2312 				break;
2313 			}
2314 
2315 			switch (sopt->sopt_name) {
2316 			case IP_TOS:
2317 				if (optval > UINT8_MAX) {
2318 					error = EINVAL;
2319 					break;
2320 				}
2321 				inp->inp_ip_tos = (uint8_t)optval;
2322 				break;
2323 
2324 			case IP_TTL:
2325 				if (optval > UINT8_MAX) {
2326 					error = EINVAL;
2327 					break;
2328 				}
2329 				inp->inp_ip_ttl = (uint8_t)optval;
2330 				break;
2331 #define OPTSET(bit) do {                                                \
2332 	if (optval) {                                                   \
2333 	    inp->inp_flags |= bit;                                      \
2334 	} else {                                                        \
2335 	    inp->inp_flags &= ~bit;                                     \
2336 	}                                                               \
2337 } while (0)
2338 
2339 #define OPTSET2(bit) do {                                               \
2340 	if (optval) {                                                   \
2341 	    inp->inp_flags2 |= bit;                                     \
2342 	} else {                                                        \
2343 	    inp->inp_flags2 &= ~bit;                                    \
2344 	}                                                               \
2345 } while (0)
2346 
2347 			case IP_RECVOPTS:
2348 				OPTSET(INP_RECVOPTS);
2349 				break;
2350 
2351 			case IP_RECVRETOPTS:
2352 				OPTSET(INP_RECVRETOPTS);
2353 				break;
2354 
2355 			case IP_RECVDSTADDR:
2356 				OPTSET(INP_RECVDSTADDR);
2357 				break;
2358 
2359 			case IP_RECVIF:
2360 				OPTSET(INP_RECVIF);
2361 				break;
2362 
2363 			case IP_RECVTTL:
2364 				OPTSET(INP_RECVTTL);
2365 				break;
2366 
2367 			case IP_RECVPKTINFO:
2368 				OPTSET(INP_PKTINFO);
2369 				break;
2370 
2371 			case IP_RECVTOS:
2372 				OPTSET(INP_RECVTOS);
2373 				break;
2374 
2375 			case IP_DONTFRAG:
2376 				/* This option is settable only for IPv4 */
2377 				if (!(inp->inp_vflag & INP_IPV4)) {
2378 					error = EINVAL;
2379 					break;
2380 				}
2381 				OPTSET2(INP2_DONTFRAG);
2382 				break;
2383 #undef OPTSET
2384 #undef OPTSET2
2385 			}
2386 			break;
2387 		/*
2388 		 * Multicast socket options are processed by the in_mcast
2389 		 * module.
2390 		 */
2391 		case IP_MULTICAST_IF:
2392 		case IP_MULTICAST_IFINDEX:
2393 		case IP_MULTICAST_VIF:
2394 		case IP_MULTICAST_TTL:
2395 		case IP_MULTICAST_LOOP:
2396 		case IP_ADD_MEMBERSHIP:
2397 		case IP_DROP_MEMBERSHIP:
2398 		case IP_ADD_SOURCE_MEMBERSHIP:
2399 		case IP_DROP_SOURCE_MEMBERSHIP:
2400 		case IP_BLOCK_SOURCE:
2401 		case IP_UNBLOCK_SOURCE:
2402 		case IP_MSFILTER:
2403 		case MCAST_JOIN_GROUP:
2404 		case MCAST_LEAVE_GROUP:
2405 		case MCAST_JOIN_SOURCE_GROUP:
2406 		case MCAST_LEAVE_SOURCE_GROUP:
2407 		case MCAST_BLOCK_SOURCE:
2408 		case MCAST_UNBLOCK_SOURCE:
2409 			error = inp_setmoptions(inp, sopt);
2410 			break;
2411 
2412 		case IP_PORTRANGE:
2413 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2414 			    sizeof(optval));
2415 			if (error) {
2416 				break;
2417 			}
2418 
2419 			switch (optval) {
2420 			case IP_PORTRANGE_DEFAULT:
2421 				inp->inp_flags &= ~(INP_LOWPORT);
2422 				inp->inp_flags &= ~(INP_HIGHPORT);
2423 				break;
2424 
2425 			case IP_PORTRANGE_HIGH:
2426 				inp->inp_flags &= ~(INP_LOWPORT);
2427 				inp->inp_flags |= INP_HIGHPORT;
2428 				break;
2429 
2430 			case IP_PORTRANGE_LOW:
2431 				inp->inp_flags &= ~(INP_HIGHPORT);
2432 				inp->inp_flags |= INP_LOWPORT;
2433 				break;
2434 
2435 			default:
2436 				error = EINVAL;
2437 				break;
2438 			}
2439 			break;
2440 
2441 #if IPSEC
2442 		case IP_IPSEC_POLICY: {
2443 			caddr_t req = NULL;
2444 			size_t len = 0;
2445 			int priv;
2446 			struct mbuf *m;
2447 			int optname;
2448 
2449 			if ((error = soopt_getm(sopt, &m)) != 0) { /* XXX */
2450 				break;
2451 			}
2452 			if ((error = soopt_mcopyin(sopt, m)) != 0) { /* XXX */
2453 				break;
2454 			}
2455 			priv = (proc_suser(sopt->sopt_p) == 0);
2456 			if (m) {
2457 				req = mtod(m, caddr_t);
2458 				len = m->m_len;
2459 			}
2460 			optname = sopt->sopt_name;
2461 			error = ipsec4_set_policy(inp, optname, req, len, priv);
2462 			m_freem(m);
2463 			break;
2464 		}
2465 #endif /* IPSEC */
2466 
2467 #if TRAFFIC_MGT
2468 		case IP_TRAFFIC_MGT_BACKGROUND: {
2469 			unsigned background = 0;
2470 
2471 			error = sooptcopyin(sopt, &background,
2472 			    sizeof(background), sizeof(background));
2473 			if (error) {
2474 				break;
2475 			}
2476 
2477 			if (background) {
2478 				socket_set_traffic_mgt_flags_locked(so,
2479 				    TRAFFIC_MGT_SO_BACKGROUND);
2480 			} else {
2481 				socket_clear_traffic_mgt_flags_locked(so,
2482 				    TRAFFIC_MGT_SO_BACKGROUND);
2483 			}
2484 
2485 			break;
2486 		}
2487 #endif /* TRAFFIC_MGT */
2488 
2489 		/*
2490 		 * On a multihomed system, scoped routing can be used to
2491 		 * restrict the source interface used for sending packets.
2492 		 * The socket option IP_BOUND_IF binds a particular AF_INET
2493 		 * socket to an interface such that data sent on the socket
2494 		 * is restricted to that interface.  This is unlike the
2495 		 * SO_DONTROUTE option where the routing table is bypassed;
2496 		 * therefore it allows for a greater flexibility and control
2497 		 * over the system behavior, and does not place any restriction
2498 		 * on the destination address type (e.g.  unicast, multicast,
2499 		 * or broadcast if applicable) or whether or not the host is
2500 		 * directly reachable.  Note that in the multicast transmit
2501 		 * case, IP_MULTICAST_{IF,IFINDEX} takes precedence over
2502 		 * IP_BOUND_IF, since the former practically bypasses the
2503 		 * routing table; in this case, IP_BOUND_IF sets the default
2504 		 * interface used for sending multicast packets in the absence
2505 		 * of an explicit multicast transmit interface.
2506 		 */
2507 		case IP_BOUND_IF:
2508 			/* This option is settable only for IPv4 */
2509 			if (!(inp->inp_vflag & INP_IPV4)) {
2510 				error = EINVAL;
2511 				break;
2512 			}
2513 
2514 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2515 			    sizeof(optval));
2516 
2517 			if (error) {
2518 				break;
2519 			}
2520 
2521 			error = inp_bindif(inp, optval, NULL);
2522 			break;
2523 
2524 		case IP_NO_IFT_CELLULAR:
2525 			/* This option is settable only for IPv4 */
2526 			if (!(inp->inp_vflag & INP_IPV4)) {
2527 				error = EINVAL;
2528 				break;
2529 			}
2530 
2531 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2532 			    sizeof(optval));
2533 
2534 			if (error) {
2535 				break;
2536 			}
2537 
2538 			/* once set, it cannot be unset */
2539 			if (!optval && INP_NO_CELLULAR(inp)) {
2540 				error = EINVAL;
2541 				break;
2542 			}
2543 
2544 			error = so_set_restrictions(so,
2545 			    SO_RESTRICT_DENY_CELLULAR);
2546 			break;
2547 
2548 		case IP_OUT_IF:
2549 			/* This option is not settable */
2550 			error = EINVAL;
2551 			break;
2552 
2553 		default:
2554 			error = ENOPROTOOPT;
2555 			break;
2556 		}
2557 		break;
2558 
2559 	case SOPT_GET:
2560 		switch (sopt->sopt_name) {
2561 		case IP_OPTIONS:
2562 		case IP_RETOPTS:
2563 			if (inp->inp_options) {
2564 				error = sooptcopyout(sopt,
2565 				    mtod(inp->inp_options, char *),
2566 				    inp->inp_options->m_len);
2567 			} else {
2568 				sopt->sopt_valsize = 0;
2569 			}
2570 			break;
2571 
2572 		case IP_TOS:
2573 		case IP_TTL:
2574 		case IP_RECVOPTS:
2575 		case IP_RECVRETOPTS:
2576 		case IP_RECVDSTADDR:
2577 		case IP_RECVIF:
2578 		case IP_RECVTTL:
2579 		case IP_PORTRANGE:
2580 		case IP_RECVPKTINFO:
2581 		case IP_RECVTOS:
2582 		case IP_DONTFRAG:
2583 			switch (sopt->sopt_name) {
2584 			case IP_TOS:
2585 				optval = inp->inp_ip_tos;
2586 				break;
2587 
2588 			case IP_TTL:
2589 				optval = inp->inp_ip_ttl;
2590 				break;
2591 
2592 #define OPTBIT(bit)     (inp->inp_flags & bit ? 1 : 0)
2593 #define OPTBIT2(bit)    (inp->inp_flags2 & bit ? 1 : 0)
2594 			case IP_RECVOPTS:
2595 				optval = OPTBIT(INP_RECVOPTS);
2596 				break;
2597 
2598 			case IP_RECVRETOPTS:
2599 				optval = OPTBIT(INP_RECVRETOPTS);
2600 				break;
2601 
2602 			case IP_RECVDSTADDR:
2603 				optval = OPTBIT(INP_RECVDSTADDR);
2604 				break;
2605 
2606 			case IP_RECVIF:
2607 				optval = OPTBIT(INP_RECVIF);
2608 				break;
2609 
2610 			case IP_RECVTTL:
2611 				optval = OPTBIT(INP_RECVTTL);
2612 				break;
2613 
2614 			case IP_PORTRANGE:
2615 				if (inp->inp_flags & INP_HIGHPORT) {
2616 					optval = IP_PORTRANGE_HIGH;
2617 				} else if (inp->inp_flags & INP_LOWPORT) {
2618 					optval = IP_PORTRANGE_LOW;
2619 				} else {
2620 					optval = 0;
2621 				}
2622 				break;
2623 
2624 			case IP_RECVPKTINFO:
2625 				optval = OPTBIT(INP_PKTINFO);
2626 				break;
2627 
2628 			case IP_RECVTOS:
2629 				optval = OPTBIT(INP_RECVTOS);
2630 				break;
2631 			case IP_DONTFRAG:
2632 				optval = OPTBIT2(INP2_DONTFRAG);
2633 				break;
2634 			}
2635 			error = sooptcopyout(sopt, &optval, sizeof(optval));
2636 			break;
2637 
2638 		case IP_MULTICAST_IF:
2639 		case IP_MULTICAST_IFINDEX:
2640 		case IP_MULTICAST_VIF:
2641 		case IP_MULTICAST_TTL:
2642 		case IP_MULTICAST_LOOP:
2643 		case IP_MSFILTER:
2644 			error = inp_getmoptions(inp, sopt);
2645 			break;
2646 
2647 #if IPSEC
2648 		case IP_IPSEC_POLICY: {
2649 			error = 0; /* This option is no longer supported */
2650 			break;
2651 		}
2652 #endif /* IPSEC */
2653 
2654 #if TRAFFIC_MGT
2655 		case IP_TRAFFIC_MGT_BACKGROUND: {
2656 			unsigned background = (so->so_flags1 &
2657 			    SOF1_TRAFFIC_MGT_SO_BACKGROUND) ? 1 : 0;
2658 			return sooptcopyout(sopt, &background,
2659 			           sizeof(background));
2660 		}
2661 #endif /* TRAFFIC_MGT */
2662 
2663 		case IP_BOUND_IF:
2664 			if (inp->inp_flags & INP_BOUND_IF) {
2665 				optval = inp->inp_boundifp->if_index;
2666 			}
2667 			error = sooptcopyout(sopt, &optval, sizeof(optval));
2668 			break;
2669 
2670 		case IP_NO_IFT_CELLULAR:
2671 			optval = INP_NO_CELLULAR(inp) ? 1 : 0;
2672 			error = sooptcopyout(sopt, &optval, sizeof(optval));
2673 			break;
2674 
2675 		case IP_OUT_IF:
2676 			optval = (inp->inp_last_outifp != NULL) ?
2677 			    inp->inp_last_outifp->if_index : 0;
2678 			error = sooptcopyout(sopt, &optval, sizeof(optval));
2679 			break;
2680 
2681 		default:
2682 			error = ENOPROTOOPT;
2683 			break;
2684 		}
2685 		break;
2686 	}
2687 	return error;
2688 }
2689 
2690 /*
2691  * Set up IP options in pcb for insertion in output packets.
2692  * Store in mbuf with pointer in pcbopt, adding pseudo-option
2693  * with destination address if source routed.
2694  */
2695 static int
ip_pcbopts(int optname,struct mbuf ** pcbopt,struct mbuf * m)2696 ip_pcbopts(int optname, struct mbuf **pcbopt, struct mbuf *m)
2697 {
2698 #pragma unused(optname)
2699 	int cnt, optlen;
2700 	u_char *cp;
2701 	u_char opt;
2702 
2703 	/* turn off any old options */
2704 	if (*pcbopt) {
2705 		(void) m_free(*pcbopt);
2706 	}
2707 	*pcbopt = 0;
2708 	if (m == (struct mbuf *)0 || m->m_len == 0) {
2709 		/*
2710 		 * Only turning off any previous options.
2711 		 */
2712 		if (m) {
2713 			(void) m_free(m);
2714 		}
2715 		return 0;
2716 	}
2717 
2718 	if (m->m_len % sizeof(int32_t)) {
2719 		goto bad;
2720 	}
2721 
2722 	/*
2723 	 * IP first-hop destination address will be stored before
2724 	 * actual options; move other options back
2725 	 * and clear it when none present.
2726 	 */
2727 	if (m->m_data + m->m_len + sizeof(struct in_addr) >= &m->m_dat[MLEN]) {
2728 		goto bad;
2729 	}
2730 	cnt = m->m_len;
2731 	m->m_len += sizeof(struct in_addr);
2732 	cp = mtod(m, u_char *) + sizeof(struct in_addr);
2733 	ovbcopy(mtod(m, caddr_t), (caddr_t)cp, (unsigned)cnt);
2734 	bzero(mtod(m, caddr_t), sizeof(struct in_addr));
2735 
2736 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
2737 		opt = cp[IPOPT_OPTVAL];
2738 		if (opt == IPOPT_EOL) {
2739 			break;
2740 		}
2741 		if (opt == IPOPT_NOP) {
2742 			optlen = 1;
2743 		} else {
2744 			if (cnt < IPOPT_OLEN + sizeof(*cp)) {
2745 				goto bad;
2746 			}
2747 			optlen = cp[IPOPT_OLEN];
2748 			if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt) {
2749 				goto bad;
2750 			}
2751 		}
2752 		switch (opt) {
2753 		default:
2754 			break;
2755 
2756 		case IPOPT_LSRR:
2757 		case IPOPT_SSRR:
2758 			/*
2759 			 * user process specifies route as:
2760 			 *	->A->B->C->D
2761 			 * D must be our final destination (but we can't
2762 			 * check that since we may not have connected yet).
2763 			 * A is first hop destination, which doesn't appear in
2764 			 * actual IP option, but is stored before the options.
2765 			 */
2766 			if (optlen < IPOPT_MINOFF - 1 + sizeof(struct in_addr)) {
2767 				goto bad;
2768 			}
2769 			if (optlen > UINT8_MAX) {
2770 				goto bad;
2771 			}
2772 			m->m_len -= sizeof(struct in_addr);
2773 			cnt -= sizeof(struct in_addr);
2774 			optlen -= sizeof(struct in_addr);
2775 			cp[IPOPT_OLEN] = (uint8_t)optlen;
2776 			/*
2777 			 * Move first hop before start of options.
2778 			 */
2779 			bcopy((caddr_t)&cp[IPOPT_OFFSET + 1], mtod(m, caddr_t),
2780 			    sizeof(struct in_addr));
2781 			/*
2782 			 * Then copy rest of options back
2783 			 * to close up the deleted entry.
2784 			 */
2785 			ovbcopy((caddr_t)(&cp[IPOPT_OFFSET + 1] +
2786 			    sizeof(struct in_addr)),
2787 			    (caddr_t)&cp[IPOPT_OFFSET + 1],
2788 			    (unsigned)cnt - (IPOPT_MINOFF - 1));
2789 			break;
2790 		}
2791 	}
2792 	if (m->m_len > MAX_IPOPTLEN + sizeof(struct in_addr)) {
2793 		goto bad;
2794 	}
2795 	*pcbopt = m;
2796 	return 0;
2797 
2798 bad:
2799 	(void) m_free(m);
2800 	return EINVAL;
2801 }
2802 
2803 void
ip_moptions_init(void)2804 ip_moptions_init(void)
2805 {
2806 	PE_parse_boot_argn("ifa_debug", &imo_debug, sizeof(imo_debug));
2807 
2808 	vm_size_t imo_size = (imo_debug == 0) ? sizeof(struct ip_moptions) :
2809 	    sizeof(struct ip_moptions_dbg);
2810 
2811 	imo_zone = zone_create(IMO_ZONE_NAME, imo_size, ZC_ZFREE_CLEARMEM);
2812 }
2813 
2814 void
imo_addref(struct ip_moptions * imo,int locked)2815 imo_addref(struct ip_moptions *imo, int locked)
2816 {
2817 	if (!locked) {
2818 		IMO_LOCK(imo);
2819 	} else {
2820 		IMO_LOCK_ASSERT_HELD(imo);
2821 	}
2822 
2823 	if (++imo->imo_refcnt == 0) {
2824 		panic("%s: imo %p wraparound refcnt", __func__, imo);
2825 		/* NOTREACHED */
2826 	} else if (imo->imo_trace != NULL) {
2827 		(*imo->imo_trace)(imo, TRUE);
2828 	}
2829 
2830 	if (!locked) {
2831 		IMO_UNLOCK(imo);
2832 	}
2833 }
2834 
2835 void
imo_remref(struct ip_moptions * imo)2836 imo_remref(struct ip_moptions *imo)
2837 {
2838 	int i;
2839 
2840 	IMO_LOCK(imo);
2841 	if (imo->imo_refcnt == 0) {
2842 		panic("%s: imo %p negative refcnt", __func__, imo);
2843 		/* NOTREACHED */
2844 	} else if (imo->imo_trace != NULL) {
2845 		(*imo->imo_trace)(imo, FALSE);
2846 	}
2847 
2848 	--imo->imo_refcnt;
2849 	if (imo->imo_refcnt > 0) {
2850 		IMO_UNLOCK(imo);
2851 		return;
2852 	}
2853 
2854 	for (i = 0; i < imo->imo_num_memberships; ++i) {
2855 		struct in_mfilter *imf;
2856 
2857 		imf = imo->imo_mfilters ? &imo->imo_mfilters[i] : NULL;
2858 		if (imf != NULL) {
2859 			imf_leave(imf);
2860 		}
2861 
2862 		(void) in_leavegroup(imo->imo_membership[i], imf);
2863 
2864 		if (imf != NULL) {
2865 			imf_purge(imf);
2866 		}
2867 
2868 		INM_REMREF(imo->imo_membership[i]);
2869 		imo->imo_membership[i] = NULL;
2870 	}
2871 	imo->imo_num_memberships = 0;
2872 	IMO_UNLOCK(imo);
2873 
2874 	kfree_type(struct in_multi *, imo->imo_max_memberships, imo->imo_membership);
2875 	kfree_type(struct in_mfilter, imo->imo_max_memberships, imo->imo_mfilters);
2876 	lck_mtx_destroy(&imo->imo_lock, &ifa_mtx_grp);
2877 
2878 	if (!(imo->imo_debug & IFD_ALLOC)) {
2879 		panic("%s: imo %p cannot be freed", __func__, imo);
2880 		/* NOTREACHED */
2881 	}
2882 	zfree(imo_zone, imo);
2883 }
2884 
2885 static void
imo_trace(struct ip_moptions * imo,int refhold)2886 imo_trace(struct ip_moptions *imo, int refhold)
2887 {
2888 	struct ip_moptions_dbg *imo_dbg = (struct ip_moptions_dbg *)imo;
2889 	ctrace_t *tr;
2890 	u_int32_t idx;
2891 	u_int16_t *cnt;
2892 
2893 	if (!(imo->imo_debug & IFD_DEBUG)) {
2894 		panic("%s: imo %p has no debug structure", __func__, imo);
2895 		/* NOTREACHED */
2896 	}
2897 	if (refhold) {
2898 		cnt = &imo_dbg->imo_refhold_cnt;
2899 		tr = imo_dbg->imo_refhold;
2900 	} else {
2901 		cnt = &imo_dbg->imo_refrele_cnt;
2902 		tr = imo_dbg->imo_refrele;
2903 	}
2904 
2905 	idx = atomic_add_16_ov(cnt, 1) % IMO_TRACE_HIST_SIZE;
2906 	ctrace_record(&tr[idx]);
2907 }
2908 
2909 struct ip_moptions *
ip_allocmoptions(zalloc_flags_t how)2910 ip_allocmoptions(zalloc_flags_t how)
2911 {
2912 	struct ip_moptions *imo;
2913 
2914 	imo = zalloc_flags(imo_zone, how | Z_ZERO);
2915 	if (imo != NULL) {
2916 		lck_mtx_init(&imo->imo_lock, &ifa_mtx_grp, &ifa_mtx_attr);
2917 		imo->imo_debug |= IFD_ALLOC;
2918 		if (imo_debug != 0) {
2919 			imo->imo_debug |= IFD_DEBUG;
2920 			imo->imo_trace = imo_trace;
2921 		}
2922 		IMO_ADDREF(imo);
2923 	}
2924 
2925 	return imo;
2926 }
2927 
2928 /*
2929  * Routine called from ip_output() to loop back a copy of an IP multicast
2930  * packet to the input queue of a specified interface.  Note that this
2931  * calls the output routine of the loopback "driver", but with an interface
2932  * pointer that might NOT be a loopback interface -- evil, but easier than
2933  * replicating that code here.
2934  */
2935 static void
ip_mloopback(struct ifnet * srcifp,struct ifnet * origifp,struct mbuf * m,struct sockaddr_in * dst,int hlen)2936 ip_mloopback(struct ifnet *srcifp, struct ifnet *origifp, struct mbuf *m,
2937     struct sockaddr_in *dst, int hlen)
2938 {
2939 	struct mbuf *copym;
2940 	struct ip *ip;
2941 
2942 	if (lo_ifp == NULL) {
2943 		return;
2944 	}
2945 
2946 	/*
2947 	 * Copy the packet header as it's needed for the checksum
2948 	 * Make sure to deep-copy IP header portion in case the data
2949 	 * is in an mbuf cluster, so that we can safely override the IP
2950 	 * header portion later.
2951 	 */
2952 	copym = m_copym_mode(m, 0, M_COPYALL, M_DONTWAIT, M_COPYM_COPY_HDR);
2953 	if (copym != NULL && ((copym->m_flags & M_EXT) || copym->m_len < hlen)) {
2954 		copym = m_pullup(copym, hlen);
2955 	}
2956 
2957 	if (copym == NULL) {
2958 		return;
2959 	}
2960 
2961 	/*
2962 	 * We don't bother to fragment if the IP length is greater
2963 	 * than the interface's MTU.  Can this possibly matter?
2964 	 */
2965 	ip = mtod(copym, struct ip *);
2966 #if BYTE_ORDER != BIG_ENDIAN
2967 	HTONS(ip->ip_len);
2968 	HTONS(ip->ip_off);
2969 #endif
2970 	ip->ip_sum = 0;
2971 	ip->ip_sum = ip_cksum_hdr_out(copym, hlen);
2972 
2973 	/*
2974 	 * Mark checksum as valid unless receive checksum offload is
2975 	 * disabled; if so, compute checksum in software.  If the
2976 	 * interface itself is lo0, this will be overridden by if_loop.
2977 	 */
2978 	if (hwcksum_rx) {
2979 		copym->m_pkthdr.csum_flags &= ~(CSUM_PARTIAL | CSUM_ZERO_INVERT);
2980 		copym->m_pkthdr.csum_flags |=
2981 		    CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
2982 		copym->m_pkthdr.csum_data = 0xffff;
2983 	} else if (copym->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2984 #if BYTE_ORDER != BIG_ENDIAN
2985 		NTOHS(ip->ip_len);
2986 #endif
2987 		in_delayed_cksum(copym);
2988 #if BYTE_ORDER != BIG_ENDIAN
2989 		HTONS(ip->ip_len);
2990 #endif
2991 	}
2992 
2993 	/*
2994 	 * Stuff the 'real' ifp into the pkthdr, to be used in matching
2995 	 * in ip_input(); we need the loopback ifp/dl_tag passed as args
2996 	 * to make the loopback driver compliant with the data link
2997 	 * requirements.
2998 	 */
2999 	copym->m_pkthdr.rcvif = origifp;
3000 
3001 	/*
3002 	 * Also record the source interface (which owns the source address).
3003 	 * This is basically a stripped down version of ifa_foraddr().
3004 	 */
3005 	if (srcifp == NULL) {
3006 		struct in_ifaddr *ia;
3007 
3008 		lck_rw_lock_shared(&in_ifaddr_rwlock);
3009 		TAILQ_FOREACH(ia, INADDR_HASH(ip->ip_src.s_addr), ia_hash) {
3010 			IFA_LOCK_SPIN(&ia->ia_ifa);
3011 			if (IA_SIN(ia)->sin_addr.s_addr == ip->ip_src.s_addr) {
3012 				srcifp = ia->ia_ifp;
3013 				IFA_UNLOCK(&ia->ia_ifa);
3014 				break;
3015 			}
3016 			IFA_UNLOCK(&ia->ia_ifa);
3017 		}
3018 		lck_rw_done(&in_ifaddr_rwlock);
3019 	}
3020 	if (srcifp != NULL) {
3021 		ip_setsrcifaddr_info(copym, srcifp->if_index, NULL);
3022 	}
3023 	ip_setdstifaddr_info(copym, origifp->if_index, NULL);
3024 
3025 	dlil_output(lo_ifp, PF_INET, copym, NULL, SA(dst), 0, NULL);
3026 }
3027 
3028 /*
3029  * Given a source IP address (and route, if available), determine the best
3030  * interface to send the packet from.  Checking for (and updating) the
3031  * ROF_SRCIF_SELECTED flag in the pcb-supplied route placeholder is done
3032  * without any locks based on the assumption that ip_output() is single-
3033  * threaded per-pcb, i.e. for any given pcb there can only be one thread
3034  * performing output at the IP layer.
3035  *
3036  * This routine is analogous to in6_selectroute() for IPv6.
3037  */
3038 static struct ifaddr *
in_selectsrcif(struct ip * ip,struct route * ro,unsigned int ifscope)3039 in_selectsrcif(struct ip *ip, struct route *ro, unsigned int ifscope)
3040 {
3041 	struct ifaddr *ifa = NULL;
3042 	struct in_addr src = ip->ip_src;
3043 	struct in_addr dst = ip->ip_dst;
3044 	struct ifnet *rt_ifp;
3045 	char s_src[MAX_IPv4_STR_LEN], s_dst[MAX_IPv4_STR_LEN];
3046 
3047 	VERIFY(src.s_addr != INADDR_ANY);
3048 
3049 	if (ip_select_srcif_debug) {
3050 		(void) inet_ntop(AF_INET, &src.s_addr, s_src, sizeof(s_src));
3051 		(void) inet_ntop(AF_INET, &dst.s_addr, s_dst, sizeof(s_dst));
3052 	}
3053 
3054 	if (ro->ro_rt != NULL) {
3055 		RT_LOCK(ro->ro_rt);
3056 	}
3057 
3058 	rt_ifp = (ro->ro_rt != NULL) ? ro->ro_rt->rt_ifp : NULL;
3059 
3060 	/*
3061 	 * Given the source IP address, find a suitable source interface
3062 	 * to use for transmission; if the caller has specified a scope,
3063 	 * optimize the search by looking at the addresses only for that
3064 	 * interface.  This is still suboptimal, however, as we need to
3065 	 * traverse the per-interface list.
3066 	 */
3067 	if (ifscope != IFSCOPE_NONE || ro->ro_rt != NULL) {
3068 		unsigned int scope = ifscope;
3069 
3070 		/*
3071 		 * If no scope is specified and the route is stale (pointing
3072 		 * to a defunct interface) use the current primary interface;
3073 		 * this happens when switching between interfaces configured
3074 		 * with the same IP address.  Otherwise pick up the scope
3075 		 * information from the route; the ULP may have looked up a
3076 		 * correct route and we just need to verify it here and mark
3077 		 * it with the ROF_SRCIF_SELECTED flag below.
3078 		 */
3079 		if (scope == IFSCOPE_NONE) {
3080 			scope = rt_ifp->if_index;
3081 			if (scope != get_primary_ifscope(AF_INET) &&
3082 			    ROUTE_UNUSABLE(ro)) {
3083 				scope = get_primary_ifscope(AF_INET);
3084 			}
3085 		}
3086 
3087 		ifa = (struct ifaddr *)ifa_foraddr_scoped(src.s_addr, scope);
3088 
3089 		if (ifa == NULL && ip->ip_p != IPPROTO_UDP &&
3090 		    ip->ip_p != IPPROTO_TCP && ipforwarding) {
3091 			/*
3092 			 * If forwarding is enabled, and if the packet isn't
3093 			 * TCP or UDP, check if the source address belongs
3094 			 * to one of our own interfaces; if so, demote the
3095 			 * interface scope and do a route lookup right below.
3096 			 */
3097 			ifa = (struct ifaddr *)ifa_foraddr(src.s_addr);
3098 			if (ifa != NULL) {
3099 				IFA_REMREF(ifa);
3100 				ifa = NULL;
3101 				ifscope = IFSCOPE_NONE;
3102 			}
3103 		}
3104 
3105 		if (ip_select_srcif_debug && ifa != NULL) {
3106 			if (ro->ro_rt != NULL) {
3107 				printf("%s->%s ifscope %d->%d ifa_if %s "
3108 				    "ro_if %s\n", s_src, s_dst, ifscope,
3109 				    scope, if_name(ifa->ifa_ifp),
3110 				    if_name(rt_ifp));
3111 			} else {
3112 				printf("%s->%s ifscope %d->%d ifa_if %s\n",
3113 				    s_src, s_dst, ifscope, scope,
3114 				    if_name(ifa->ifa_ifp));
3115 			}
3116 		}
3117 	}
3118 
3119 	/*
3120 	 * Slow path; search for an interface having the corresponding source
3121 	 * IP address if the scope was not specified by the caller, and:
3122 	 *
3123 	 *   1) There currently isn't any route, or,
3124 	 *   2) The interface used by the route does not own that source
3125 	 *	IP address; in this case, the route will get blown away
3126 	 *	and we'll do a more specific scoped search using the newly
3127 	 *	found interface.
3128 	 */
3129 	if (ifa == NULL && ifscope == IFSCOPE_NONE) {
3130 		ifa = (struct ifaddr *)ifa_foraddr(src.s_addr);
3131 
3132 		/*
3133 		 * If we have the IP address, but not the route, we don't
3134 		 * really know whether or not it belongs to the correct
3135 		 * interface (it could be shared across multiple interfaces.)
3136 		 * The only way to find out is to do a route lookup.
3137 		 */
3138 		if (ifa != NULL && ro->ro_rt == NULL) {
3139 			struct rtentry *rt;
3140 			struct sockaddr_in sin;
3141 			struct ifaddr *oifa = NULL;
3142 
3143 			bzero(&sin, sizeof(sin));
3144 			sin.sin_family = AF_INET;
3145 			sin.sin_len = sizeof(sin);
3146 			sin.sin_addr = dst;
3147 
3148 			lck_mtx_lock(rnh_lock);
3149 			if ((rt = rt_lookup(TRUE, SA(&sin), NULL,
3150 			    rt_tables[AF_INET], IFSCOPE_NONE)) != NULL) {
3151 				RT_LOCK(rt);
3152 				/*
3153 				 * If the route uses a different interface,
3154 				 * use that one instead.  The IP address of
3155 				 * the ifaddr that we pick up here is not
3156 				 * relevant.
3157 				 */
3158 				if (ifa->ifa_ifp != rt->rt_ifp) {
3159 					oifa = ifa;
3160 					ifa = rt->rt_ifa;
3161 					IFA_ADDREF(ifa);
3162 					RT_UNLOCK(rt);
3163 				} else {
3164 					RT_UNLOCK(rt);
3165 				}
3166 				rtfree_locked(rt);
3167 			}
3168 			lck_mtx_unlock(rnh_lock);
3169 
3170 			if (oifa != NULL) {
3171 				struct ifaddr *iifa;
3172 
3173 				/*
3174 				 * See if the interface pointed to by the
3175 				 * route is configured with the source IP
3176 				 * address of the packet.
3177 				 */
3178 				iifa = (struct ifaddr *)ifa_foraddr_scoped(
3179 					src.s_addr, ifa->ifa_ifp->if_index);
3180 
3181 				if (iifa != NULL) {
3182 					/*
3183 					 * Found it; drop the original one
3184 					 * as well as the route interface
3185 					 * address, and use this instead.
3186 					 */
3187 					IFA_REMREF(oifa);
3188 					IFA_REMREF(ifa);
3189 					ifa = iifa;
3190 				} else if (!ipforwarding ||
3191 				    (rt->rt_flags & RTF_GATEWAY)) {
3192 					/*
3193 					 * This interface doesn't have that
3194 					 * source IP address; drop the route
3195 					 * interface address and just use the
3196 					 * original one, and let the caller
3197 					 * do a scoped route lookup.
3198 					 */
3199 					IFA_REMREF(ifa);
3200 					ifa = oifa;
3201 				} else {
3202 					/*
3203 					 * Forwarding is enabled and the source
3204 					 * address belongs to one of our own
3205 					 * interfaces which isn't the outgoing
3206 					 * interface, and we have a route, and
3207 					 * the destination is on a network that
3208 					 * is directly attached (onlink); drop
3209 					 * the original one and use the route
3210 					 * interface address instead.
3211 					 */
3212 					IFA_REMREF(oifa);
3213 				}
3214 			}
3215 		} else if (ifa != NULL && ro->ro_rt != NULL &&
3216 		    !(ro->ro_rt->rt_flags & RTF_GATEWAY) &&
3217 		    ifa->ifa_ifp != ro->ro_rt->rt_ifp && ipforwarding) {
3218 			/*
3219 			 * Forwarding is enabled and the source address belongs
3220 			 * to one of our own interfaces which isn't the same
3221 			 * as the interface used by the known route; drop the
3222 			 * original one and use the route interface address.
3223 			 */
3224 			IFA_REMREF(ifa);
3225 			ifa = ro->ro_rt->rt_ifa;
3226 			IFA_ADDREF(ifa);
3227 		}
3228 
3229 		if (ip_select_srcif_debug && ifa != NULL) {
3230 			printf("%s->%s ifscope %d ifa_if %s\n",
3231 			    s_src, s_dst, ifscope, if_name(ifa->ifa_ifp));
3232 		}
3233 	}
3234 
3235 	if (ro->ro_rt != NULL) {
3236 		RT_LOCK_ASSERT_HELD(ro->ro_rt);
3237 	}
3238 	/*
3239 	 * If there is a non-loopback route with the wrong interface, or if
3240 	 * there is no interface configured with such an address, blow it
3241 	 * away.  Except for local/loopback, we look for one with a matching
3242 	 * interface scope/index.
3243 	 */
3244 	if (ro->ro_rt != NULL &&
3245 	    (ifa == NULL || (ifa->ifa_ifp != rt_ifp && rt_ifp != lo_ifp) ||
3246 	    !(ro->ro_rt->rt_flags & RTF_UP))) {
3247 		if (ip_select_srcif_debug) {
3248 			if (ifa != NULL) {
3249 				printf("%s->%s ifscope %d ro_if %s != "
3250 				    "ifa_if %s (cached route cleared)\n",
3251 				    s_src, s_dst, ifscope, if_name(rt_ifp),
3252 				    if_name(ifa->ifa_ifp));
3253 			} else {
3254 				printf("%s->%s ifscope %d ro_if %s "
3255 				    "(no ifa_if found)\n",
3256 				    s_src, s_dst, ifscope, if_name(rt_ifp));
3257 			}
3258 		}
3259 
3260 		RT_UNLOCK(ro->ro_rt);
3261 		ROUTE_RELEASE(ro);
3262 
3263 		/*
3264 		 * If the destination is IPv4 LLA and the route's interface
3265 		 * doesn't match the source interface, then the source IP
3266 		 * address is wrong; it most likely belongs to the primary
3267 		 * interface associated with the IPv4 LL subnet.  Drop the
3268 		 * packet rather than letting it go out and return an error
3269 		 * to the ULP.  This actually applies not only to IPv4 LL
3270 		 * but other shared subnets; for now we explicitly test only
3271 		 * for the former case and save the latter for future.
3272 		 */
3273 		if (IN_LINKLOCAL(ntohl(dst.s_addr)) &&
3274 		    !IN_LINKLOCAL(ntohl(src.s_addr)) && ifa != NULL) {
3275 			IFA_REMREF(ifa);
3276 			ifa = NULL;
3277 		}
3278 	}
3279 
3280 	if (ip_select_srcif_debug && ifa == NULL) {
3281 		printf("%s->%s ifscope %d (neither ro_if/ifa_if found)\n",
3282 		    s_src, s_dst, ifscope);
3283 	}
3284 
3285 	/*
3286 	 * If there is a route, mark it accordingly.  If there isn't one,
3287 	 * we'll get here again during the next transmit (possibly with a
3288 	 * route) and the flag will get set at that point.  For IPv4 LLA
3289 	 * destination, mark it only if the route has been fully resolved;
3290 	 * otherwise we want to come back here again when the route points
3291 	 * to the interface over which the ARP reply arrives on.
3292 	 */
3293 	if (ro->ro_rt != NULL && (!IN_LINKLOCAL(ntohl(dst.s_addr)) ||
3294 	    (ro->ro_rt->rt_gateway->sa_family == AF_LINK &&
3295 	    SDL(ro->ro_rt->rt_gateway)->sdl_alen != 0))) {
3296 		if (ifa != NULL) {
3297 			IFA_ADDREF(ifa);        /* for route */
3298 		}
3299 		if (ro->ro_srcia != NULL) {
3300 			IFA_REMREF(ro->ro_srcia);
3301 		}
3302 		ro->ro_srcia = ifa;
3303 		ro->ro_flags |= ROF_SRCIF_SELECTED;
3304 		RT_GENID_SYNC(ro->ro_rt);
3305 	}
3306 
3307 	if (ro->ro_rt != NULL) {
3308 		RT_UNLOCK(ro->ro_rt);
3309 	}
3310 
3311 	return ifa;
3312 }
3313 
3314 /*
3315  * @brief	Given outgoing interface it determines what checksum needs
3316  *      to be computed in software and what needs to be offloaded to the
3317  *      interface.
3318  *
3319  * @param	ifp Pointer to the outgoing interface
3320  * @param	m Pointer to the packet
3321  * @param	hlen IP header length
3322  * @param	ip_len Total packet size i.e. headers + data payload
3323  * @param	sw_csum Pointer to a software checksum flag set
3324  *
3325  * @return	void
3326  */
3327 void
ip_output_checksum(struct ifnet * ifp,struct mbuf * m,int hlen,int ip_len,uint32_t * sw_csum)3328 ip_output_checksum(struct ifnet *ifp, struct mbuf *m, int hlen, int ip_len,
3329     uint32_t *sw_csum)
3330 {
3331 	int tso = TSO_IPV4_OK(ifp, m);
3332 	uint32_t hwcap = ifp->if_hwassist;
3333 
3334 	m->m_pkthdr.csum_flags |= CSUM_IP;
3335 
3336 	if (!hwcksum_tx) {
3337 		/* do all in software; hardware checksum offload is disabled */
3338 		*sw_csum = (CSUM_DELAY_DATA | CSUM_DELAY_IP) &
3339 		    m->m_pkthdr.csum_flags;
3340 	} else {
3341 		/* do in software what the hardware cannot */
3342 		*sw_csum = m->m_pkthdr.csum_flags &
3343 		    ~IF_HWASSIST_CSUM_FLAGS(hwcap);
3344 	}
3345 
3346 	if (hlen != sizeof(struct ip)) {
3347 		*sw_csum |= ((CSUM_DELAY_DATA | CSUM_DELAY_IP) &
3348 		    m->m_pkthdr.csum_flags);
3349 	} else if (!(*sw_csum & CSUM_DELAY_DATA) && (hwcap & CSUM_PARTIAL)) {
3350 		int interface_mtu = ifp->if_mtu;
3351 
3352 		if (INTF_ADJUST_MTU_FOR_CLAT46(ifp)) {
3353 			interface_mtu = IN6_LINKMTU(ifp);
3354 			/* Further adjust the size for CLAT46 expansion */
3355 			interface_mtu -= CLAT46_HDR_EXPANSION_OVERHD;
3356 		}
3357 
3358 		/*
3359 		 * Partial checksum offload, if non-IP fragment, and TCP only
3360 		 * (no UDP support, as the hardware may not be able to convert
3361 		 * +0 to -0 (0xffff) per RFC1122 4.1.3.4. unless the interface
3362 		 * supports "invert zero" capability.)
3363 		 */
3364 		if (hwcksum_tx && !tso &&
3365 		    ((m->m_pkthdr.csum_flags & CSUM_TCP) ||
3366 		    ((hwcap & CSUM_ZERO_INVERT) &&
3367 		    (m->m_pkthdr.csum_flags & CSUM_ZERO_INVERT))) &&
3368 		    ip_len <= interface_mtu) {
3369 			uint16_t start = sizeof(struct ip);
3370 			uint16_t ulpoff = m->m_pkthdr.csum_data & 0xffff;
3371 			m->m_pkthdr.csum_flags |=
3372 			    (CSUM_DATA_VALID | CSUM_PARTIAL);
3373 			m->m_pkthdr.csum_tx_stuff = (ulpoff + start);
3374 			m->m_pkthdr.csum_tx_start = start;
3375 			/* do IP hdr chksum in software */
3376 			*sw_csum = CSUM_DELAY_IP;
3377 		} else {
3378 			*sw_csum |= (CSUM_DELAY_DATA & m->m_pkthdr.csum_flags);
3379 		}
3380 	}
3381 
3382 	if (*sw_csum & CSUM_DELAY_DATA) {
3383 		in_delayed_cksum(m);
3384 		*sw_csum &= ~CSUM_DELAY_DATA;
3385 	}
3386 
3387 	if (hwcksum_tx) {
3388 		/*
3389 		 * Drop off bits that aren't supported by hardware;
3390 		 * also make sure to preserve non-checksum related bits.
3391 		 */
3392 		m->m_pkthdr.csum_flags =
3393 		    ((m->m_pkthdr.csum_flags &
3394 		    (IF_HWASSIST_CSUM_FLAGS(hwcap) | CSUM_DATA_VALID)) |
3395 		    (m->m_pkthdr.csum_flags & ~IF_HWASSIST_CSUM_MASK));
3396 	} else {
3397 		/* drop all bits; hardware checksum offload is disabled */
3398 		m->m_pkthdr.csum_flags = 0;
3399 	}
3400 }
3401 
3402 /*
3403  * GRE protocol output for PPP/PPTP
3404  */
3405 int
ip_gre_output(struct mbuf * m)3406 ip_gre_output(struct mbuf *m)
3407 {
3408 	struct route ro;
3409 	int error;
3410 
3411 	bzero(&ro, sizeof(ro));
3412 
3413 	error = ip_output(m, NULL, &ro, 0, NULL, NULL);
3414 
3415 	ROUTE_RELEASE(&ro);
3416 
3417 	return error;
3418 }
3419 
3420 static int
3421 sysctl_reset_ip_output_stats SYSCTL_HANDLER_ARGS
3422 {
3423 #pragma unused(arg1, arg2)
3424 	int error, i;
3425 
3426 	i = ip_output_measure;
3427 	error = sysctl_handle_int(oidp, &i, 0, req);
3428 	if (error || req->newptr == USER_ADDR_NULL) {
3429 		goto done;
3430 	}
3431 	/* impose bounds */
3432 	if (i < 0 || i > 1) {
3433 		error = EINVAL;
3434 		goto done;
3435 	}
3436 	if (ip_output_measure != i && i == 1) {
3437 		net_perf_initialize(&net_perf, ip_output_measure_bins);
3438 	}
3439 	ip_output_measure = i;
3440 done:
3441 	return error;
3442 }
3443 
3444 static int
3445 sysctl_ip_output_measure_bins SYSCTL_HANDLER_ARGS
3446 {
3447 #pragma unused(arg1, arg2)
3448 	int error;
3449 	uint64_t i;
3450 
3451 	i = ip_output_measure_bins;
3452 	error = sysctl_handle_quad(oidp, &i, 0, req);
3453 	if (error || req->newptr == USER_ADDR_NULL) {
3454 		goto done;
3455 	}
3456 	/* validate data */
3457 	if (!net_perf_validate_bins(i)) {
3458 		error = EINVAL;
3459 		goto done;
3460 	}
3461 	ip_output_measure_bins = i;
3462 done:
3463 	return error;
3464 }
3465 
3466 static int
3467 sysctl_ip_output_getperf SYSCTL_HANDLER_ARGS
3468 {
3469 #pragma unused(oidp, arg1, arg2)
3470 	if (req->oldptr == USER_ADDR_NULL) {
3471 		req->oldlen = (size_t)sizeof(struct ipstat);
3472 	}
3473 
3474 	return SYSCTL_OUT(req, &net_perf, MIN(sizeof(net_perf), req->oldlen));
3475 }
3476