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