xref: /xnu-12377.41.6/bsd/netinet/udp_usrreq.c (revision bbb1b6f9e71b8cdde6e5cd6f4841f207dee3d828)
1 /*
2  * Copyright (c) 2000-2024 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, 1995
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  *	@(#)udp_usrreq.c	8.6 (Berkeley) 5/23/95
61  */
62 
63 #include <sys/param.h>
64 #include <sys/systm.h>
65 #include <sys/kernel.h>
66 #include <sys/malloc.h>
67 #include <sys/mbuf.h>
68 #include <sys/domain.h>
69 #include <sys/protosw.h>
70 #include <sys/socket.h>
71 #include <sys/socketvar.h>
72 #include <sys/sysctl.h>
73 #include <sys/syslog.h>
74 #include <sys/mcache.h>
75 #include <net/ntstat.h>
76 
77 #include <kern/uipc_socket.h>
78 #include <kern/zalloc.h>
79 #include <mach/boolean.h>
80 #include <pexpert/pexpert.h>
81 
82 #include <net/if.h>
83 #include <net/if_types.h>
84 #include <net/route.h>
85 #include <net/dlil.h>
86 #include <net/droptap.h>
87 #include <net/net_api_stats.h>
88 
89 #include <netinet/in.h>
90 #include <netinet/in_systm.h>
91 #include <netinet/in_tclass.h>
92 #include <netinet/ip.h>
93 #include <netinet/ip6.h>
94 #include <netinet/in_pcb.h>
95 #include <netinet/in_var.h>
96 #include <netinet/ip_var.h>
97 #include <netinet6/in6_pcb.h>
98 #include <netinet6/ip6_var.h>
99 #include <netinet6/udp6_var.h>
100 #include <netinet/ip_icmp.h>
101 #include <netinet/icmp_var.h>
102 #include <netinet/udp.h>
103 #include <netinet/udp_var.h>
104 #include <netinet/udp_log.h>
105 #include <sys/kdebug.h>
106 
107 #if IPSEC
108 #include <netinet6/ipsec.h>
109 #include <netinet6/esp.h>
110 #include <netkey/key.h>
111 extern int ipsec_bypass;
112 extern int esp_udp_encap_port;
113 #endif /* IPSEC */
114 
115 #if NECP
116 #include <net/necp.h>
117 #endif /* NECP */
118 
119 #if FLOW_DIVERT
120 #include <netinet/flow_divert.h>
121 #endif /* FLOW_DIVERT */
122 
123 #if CONTENT_FILTER
124 #include <net/content_filter.h>
125 #endif /* CONTENT_FILTER */
126 
127 #if SKYWALK
128 #include <skywalk/core/skywalk_var.h>
129 #endif /* SKYWALK */
130 
131 #include <net/sockaddr_utils.h>
132 
133 #define DBG_LAYER_IN_BEG        NETDBG_CODE(DBG_NETUDP, 0)
134 #define DBG_LAYER_IN_END        NETDBG_CODE(DBG_NETUDP, 2)
135 #define DBG_LAYER_OUT_BEG       NETDBG_CODE(DBG_NETUDP, 1)
136 #define DBG_LAYER_OUT_END       NETDBG_CODE(DBG_NETUDP, 3)
137 #define DBG_FNC_UDP_INPUT       NETDBG_CODE(DBG_NETUDP, (5 << 8))
138 #define DBG_FNC_UDP_OUTPUT      NETDBG_CODE(DBG_NETUDP, (6 << 8) | 1)
139 
140 /*
141  * UDP protocol implementation.
142  * Per RFC 768, August, 1980.
143  */
144 #ifndef COMPAT_42
145 static int udpcksum = 1;
146 #else
147 static int udpcksum = 0;                /* XXX */
148 #endif
149 SYSCTL_INT(_net_inet_udp, UDPCTL_CHECKSUM, checksum,
150     CTLFLAG_RW | CTLFLAG_LOCKED, &udpcksum, 0, "");
151 
152 int udp_log_in_vain = 0;
153 SYSCTL_INT(_net_inet_udp, OID_AUTO, log_in_vain, CTLFLAG_RW | CTLFLAG_LOCKED,
154     &udp_log_in_vain, 0, "Log all incoming UDP packets");
155 
156 static int blackhole = 0;
157 SYSCTL_INT(_net_inet_udp, OID_AUTO, blackhole, CTLFLAG_RW | CTLFLAG_LOCKED,
158     &blackhole, 0, "Do not send port unreachables for refused connects");
159 
160 static KALLOC_TYPE_DEFINE(inpcbzone, struct inpcb, NET_KT_DEFAULT);
161 
162 struct inpcbhead udb;           /* from udp_var.h */
163 #define udb6    udb  /* for KAME src sync over BSD*'s */
164 struct inpcbinfo udbinfo;
165 
166 #ifndef UDBHASHSIZE
167 #define UDBHASHSIZE 16
168 #endif
169 
170 /* Garbage collection performed during most recent udp_gc() run */
171 static boolean_t udp_gc_done = FALSE;
172 
173 #define log_in_vain_log(a) { log a; }
174 
175 static int udp_getstat SYSCTL_HANDLER_ARGS;
176 struct  udpstat udpstat;        /* from udp_var.h */
177 SYSCTL_PROC(_net_inet_udp, UDPCTL_STATS, stats,
178     CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED,
179     0, 0, udp_getstat, "S,udpstat",
180     "UDP statistics (struct udpstat, netinet/udp_var.h)");
181 
182 SYSCTL_UINT(_net_inet_udp, OID_AUTO, pcbcount,
183     CTLFLAG_RD | CTLFLAG_LOCKED, &udbinfo.ipi_count, 0,
184     "Number of active PCBs");
185 
186 __private_extern__ int udp_use_randomport = 1;
187 SYSCTL_INT(_net_inet_udp, OID_AUTO, randomize_ports,
188     CTLFLAG_RW | CTLFLAG_LOCKED, &udp_use_randomport, 0,
189     "Randomize UDP port numbers");
190 
191 struct udp_in6 {
192 	struct sockaddr_in6     uin6_sin;
193 	u_char                  uin6_init_done : 1;
194 };
195 struct udp_ip6 {
196 	struct ip6_hdr          uip6_ip6;
197 	u_char                  uip6_init_done : 1;
198 };
199 
200 static int udp_abort(struct socket *);
201 static int udp_attach(struct socket *, int, struct proc *);
202 static int udp_bind(struct socket *, struct sockaddr *, struct proc *);
203 static int udp_connect(struct socket *, struct sockaddr *, struct proc *);
204 static int udp_connectx(struct socket *, struct sockaddr *,
205     struct sockaddr *, struct proc *, uint32_t, sae_associd_t,
206     sae_connid_t *, uint32_t, void *, uint32_t, struct uio *, user_ssize_t *);
207 static int udp_detach(struct socket *);
208 static int udp_disconnect(struct socket *);
209 static int udp_disconnectx(struct socket *, sae_associd_t, sae_connid_t);
210 static int udp_send(struct socket *, int, struct mbuf *, struct sockaddr *,
211     struct mbuf *, struct proc *);
212 static void udp_append(struct inpcb *, struct ip *, struct mbuf *, int,
213     struct sockaddr_in *, struct udp_in6 *, struct udp_ip6 *, struct ifnet *);
214 static int udp_input_checksum(struct mbuf *, struct udphdr *, int, int);
215 static int udp_output(struct inpcb *, struct mbuf *, struct sockaddr *,
216     struct mbuf *, struct proc *);
217 static void ip_2_ip6_hdr(struct ip6_hdr *ip6, struct ip *ip);
218 static void udp_gc(struct inpcbinfo *);
219 static int udp_defunct(struct socket *);
220 
221 struct pr_usrreqs udp_usrreqs = {
222 	.pru_abort =            udp_abort,
223 	.pru_attach =           udp_attach,
224 	.pru_bind =             udp_bind,
225 	.pru_connect =          udp_connect,
226 	.pru_connectx =         udp_connectx,
227 	.pru_control =          in_control,
228 	.pru_detach =           udp_detach,
229 	.pru_disconnect =       udp_disconnect,
230 	.pru_disconnectx =      udp_disconnectx,
231 	.pru_peeraddr =         in_getpeeraddr,
232 	.pru_send =             udp_send,
233 	.pru_shutdown =         udp_shutdown,
234 	.pru_sockaddr =         in_getsockaddr,
235 	.pru_sosend =           sosend,
236 	.pru_soreceive =        soreceive,
237 	.pru_defunct =          udp_defunct,
238 };
239 
240 struct mem_acct *udp_memacct;
241 
242 static LCK_ATTR_DECLARE(udp_port_unreach_rlc_attr, 0, 0);
243 static LCK_GRP_DECLARE(udp_port_unreach_rlc_mtx_grp, "udp_port_unreach_rlc");
244 static LCK_MTX_DECLARE_ATTR(udp_port_unreach_rlc_mtx_data, &udp_port_unreach_rlc_mtx_grp, &udp_port_unreach_rlc_attr);
245 static lck_mtx_t  * const udp_port_unreach_rlc_mtx = &udp_port_unreach_rlc_mtx_data;
246 
247 struct in_endpoints     udp_port_unreach_rlc_state;
248 uint32_t                udp_port_unreach_rlc_ts;
249 static uint32_t         udp_port_unreach_rlc_cnt = 0;
250 
251 static int udp_port_unreach_rlc_enable = 1;
252 SYSCTL_INT(_net_inet_udp, OID_AUTO, port_unreach_rlc_enable, CTLFLAG_RW | CTLFLAG_LOCKED,
253     &udp_port_unreach_rlc_enable, 1, "Enable ICMP port unreachable run-length-compression");
254 
255 static int udp_port_unreach_rlc_bucket_ms = 100;
256 SYSCTL_INT(_net_inet_udp, OID_AUTO, port_unreach_rlc_bucket_ms, CTLFLAG_RW | CTLFLAG_LOCKED,
257     &udp_port_unreach_rlc_bucket_ms, 100, "Duration of RLC bucket in milliseconds for the ICMP port unreachable run-length-compression");
258 
259 static int udp_port_unreach_rlc_use_ts = 1;
260 SYSCTL_INT(_net_inet_udp, OID_AUTO, port_unreach_rlc_use_ts, CTLFLAG_RW | CTLFLAG_LOCKED,
261     &udp_port_unreach_rlc_use_ts, 0, "Include timestamp in ICMP port unreachable run-length-compression");
262 
263 static int udp_port_unreach_rlc_verbose = 0;
264 SYSCTL_INT(_net_inet_udp, OID_AUTO, port_unreach_rlc_verbose, CTLFLAG_RW | CTLFLAG_LOCKED,
265     &udp_port_unreach_rlc_verbose, 0, "Verbose output: 0: no output; 1: log whenever the ICMP port unreachable RLC buffer changes");
266 
267 static bool
268 udp_port_unreach_rlc_compress(struct in_addr src_addr, in_port_t src_port,
269     struct in_addr dst_addr, in_port_t dst_port);
270 
271 void
udp_init(struct protosw * pp,struct domain * dp)272 udp_init(struct protosw *pp, struct domain *dp)
273 {
274 #pragma unused(dp)
275 	static int udp_initialized = 0;
276 	struct inpcbinfo        *pcbinfo;
277 	uint32_t pool_size = 0;
278 
279 	VERIFY((pp->pr_flags & (PR_INITIALIZED | PR_ATTACHED)) == PR_ATTACHED);
280 
281 	if (udp_memacct == NULL) {
282 		udp_memacct = mem_acct_register("UDP", 0, 0);
283 		if (udp_memacct == NULL) {
284 			panic("mem_acct_register returned NULL");
285 		}
286 	}
287 	pp->pr_mem_acct = udp_memacct;
288 
289 	if (!os_atomic_cmpxchg(&udp_initialized, 0, 1, relaxed)) {
290 		return;
291 	}
292 
293 	pool_size = (nmbclusters << MCLSHIFT) >> MBSHIFT;
294 	if (pool_size >= 96) {
295 		/* Improves 10GbE UDP performance. */
296 		udp_recvspace = 786896;
297 	}
298 
299 	if (PE_parse_boot_argn("udp_log", &udp_log_enable_flags, sizeof(udp_log_enable_flags))) {
300 		os_log(OS_LOG_DEFAULT, "udp_init: set udp_log_enable_flags to 0x%x", udp_log_enable_flags);
301 	}
302 
303 	bzero(&udp_port_unreach_rlc_state, sizeof(struct in_endpoints));
304 
305 	LIST_INIT(&udb);
306 	udbinfo.ipi_listhead = &udb;
307 	hashinit_counted_by(UDBHASHSIZE, udbinfo.ipi_hashbase,
308 	    udbinfo.ipi_hashbase_count);
309 	udbinfo.ipi_hashmask = udbinfo.ipi_hashbase_count - 1;
310 	hashinit_counted_by(UDBHASHSIZE, udbinfo.ipi_porthashbase,
311 	    udbinfo.ipi_porthashbase_count);
312 	udbinfo.ipi_porthashmask = udbinfo.ipi_porthashbase_count - 1;
313 	udbinfo.ipi_zone = inpcbzone;
314 
315 	pcbinfo = &udbinfo;
316 	/*
317 	 * allocate lock group and attribute for udp pcb mutexes
318 	 */
319 	pcbinfo->ipi_lock_grp = lck_grp_alloc_init("udppcb",
320 	    LCK_GRP_ATTR_NULL);
321 	lck_attr_setdefault(&pcbinfo->ipi_lock_attr);
322 	lck_rw_init(&pcbinfo->ipi_lock, pcbinfo->ipi_lock_grp,
323 	    &pcbinfo->ipi_lock_attr);
324 
325 	udbinfo.ipi_gc = udp_gc;
326 	in_pcbinfo_attach(&udbinfo);
327 }
328 
329 void
udp_input(struct mbuf * m,int iphlen)330 udp_input(struct mbuf *m, int iphlen)
331 {
332 	struct ip *ip;
333 	struct udphdr *uh;
334 	struct inpcb *inp;
335 	mbuf_ref_t opts = NULL;
336 	int len, isbroadcast;
337 	struct ip save_ip;
338 	struct sockaddr *append_sa = NULL;
339 	struct sockaddr *append_da = NULL;
340 	struct inpcbinfo *pcbinfo = &udbinfo;
341 	struct sockaddr_in udp_in;
342 	struct sockaddr_in udp_dst;
343 	struct ip_moptions *imo = NULL;
344 	int foundmembership = 0, ret = 0;
345 	struct udp_in6 udp_in6;
346 	struct udp_in6 udp_dst6;
347 	struct udp_ip6 udp_ip6;
348 	struct ifnet *ifp = m->m_pkthdr.rcvif;
349 	u_int16_t pf_tag = 0;
350 	boolean_t is_wake_pkt = false;
351 	boolean_t check_cfil = cfil_filter_present();
352 	drop_reason_t drop_reason = DROP_REASON_UNSPECIFIED;
353 
354 	SOCKADDR_ZERO(&udp_in, sizeof(udp_in));
355 	udp_in.sin_len = sizeof(struct sockaddr_in);
356 	udp_in.sin_family = AF_INET;
357 	bzero(&udp_in6, sizeof(udp_in6));
358 	udp_in6.uin6_sin.sin6_len = sizeof(struct sockaddr_in6);
359 	udp_in6.uin6_sin.sin6_family = AF_INET6;
360 
361 	if (m->m_flags & M_PKTHDR) {
362 		pf_tag = m_pftag(m)->pftag_tag;
363 		if (m->m_pkthdr.pkt_flags & PKTF_WAKE_PKT) {
364 			is_wake_pkt = true;
365 		}
366 	}
367 
368 	udpstat.udps_ipackets++;
369 
370 	KERNEL_DEBUG(DBG_FNC_UDP_INPUT | DBG_FUNC_START, 0, 0, 0, 0, 0);
371 
372 	/* Expect 32-bit aligned data pointer on strict-align platforms */
373 	MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);
374 
375 	m_add_crumb(m, PKT_CRUMB_UDP_INPUT);
376 
377 	/*
378 	 * Strip IP options, if any; should skip this,
379 	 * make available to user, and use on returned packets,
380 	 * but we don't yet have a way to check the checksum
381 	 * with options still present.
382 	 */
383 	if (iphlen > sizeof(struct ip)) {
384 		ip_stripoptions(m);
385 		iphlen = sizeof(struct ip);
386 	}
387 
388 	/*
389 	 * Get IP and UDP header together in first mbuf.
390 	 */
391 	ip = mtod(m, struct ip *);
392 	if (m->m_len < iphlen + sizeof(struct udphdr)) {
393 		m = m_pullup(m, iphlen + sizeof(struct udphdr));
394 		if (m == NULL) {
395 			udpstat.udps_hdrops++;
396 			KERNEL_DEBUG(DBG_FNC_UDP_INPUT | DBG_FUNC_END,
397 			    0, 0, 0, 0, 0);
398 			return;
399 		}
400 		ip = mtod(m, struct ip *);
401 	}
402 	uh = (struct udphdr *)(void *)((caddr_t)ip + iphlen);
403 
404 	/* destination port of 0 is illegal, based on RFC768. */
405 	if (uh->uh_dport == 0) {
406 		drop_reason = DROP_REASON_UDP_DST_PORT_ZERO;
407 		IF_UDP_STATINC(ifp, port0);
408 		goto bad;
409 	}
410 
411 	KERNEL_DEBUG(DBG_LAYER_IN_BEG, uh->uh_dport, uh->uh_sport,
412 	    ip->ip_src.s_addr, ip->ip_dst.s_addr, uh->uh_ulen);
413 
414 	/*
415 	 * Make mbuf data length reflect UDP length.
416 	 * If not enough data to reflect UDP length, drop.
417 	 */
418 	len = ntohs((u_short)uh->uh_ulen);
419 	if (ip->ip_len != len) {
420 		if (len > ip->ip_len || len < sizeof(struct udphdr)) {
421 			udpstat.udps_badlen++;
422 			IF_UDP_STATINC(ifp, badlength);
423 			drop_reason = DROP_REASON_UDP_BAD_LENGTH;
424 			goto bad;
425 		}
426 		m_adj(m, len - ip->ip_len);
427 		/* ip->ip_len = len; */
428 	}
429 	/*
430 	 * Save a copy of the IP header in case we want restore it
431 	 * for sending an ICMP error message in response.
432 	 */
433 	save_ip = *ip;
434 
435 	/*
436 	 * Checksum extended UDP header and data.
437 	 */
438 	if (udp_input_checksum(m, uh, iphlen, len)) {
439 		drop_reason = DROP_REASON_UDP_BAD_CHECKSUM;
440 		goto bad;
441 	}
442 
443 	isbroadcast = in_broadcast(ip->ip_dst, ifp);
444 
445 	if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) || isbroadcast) {
446 		int reuse_sock = 0, mcast_delivered = 0;
447 
448 		lck_rw_lock_shared(&pcbinfo->ipi_lock);
449 		/*
450 		 * Deliver a multicast or broadcast datagram to *all* sockets
451 		 * for which the local and remote addresses and ports match
452 		 * those of the incoming datagram.  This allows more than
453 		 * one process to receive multi/broadcasts on the same port.
454 		 * (This really ought to be done for unicast datagrams as
455 		 * well, but that would cause problems with existing
456 		 * applications that open both address-specific sockets and
457 		 * a wildcard socket listening to the same port -- they would
458 		 * end up receiving duplicates of every unicast datagram.
459 		 * Those applications open the multiple sockets to overcome an
460 		 * inadequacy of the UDP socket interface, but for backwards
461 		 * compatibility we avoid the problem here rather than
462 		 * fixing the interface.  Maybe 4.5BSD will remedy this?)
463 		 */
464 
465 		/*
466 		 * Construct sockaddr format source address.
467 		 */
468 		udp_in.sin_port = uh->uh_sport;
469 		udp_in.sin_addr = ip->ip_src;
470 		/*
471 		 * Locate pcb(s) for datagram.
472 		 * (Algorithm copied from raw_intr().)
473 		 */
474 		udp_in6.uin6_init_done = udp_ip6.uip6_init_done = 0;
475 		LIST_FOREACH(inp, &udb, inp_list) {
476 #if IPSEC
477 			int skipit;
478 #endif /* IPSEC */
479 
480 			if (inp->inp_socket == NULL) {
481 				continue;
482 			}
483 			if (inp != sotoinpcb(inp->inp_socket)) {
484 				panic("%s: bad so back ptr inp=%p",
485 				    __func__, inp);
486 				/* NOTREACHED */
487 			}
488 			if ((inp->inp_vflag & INP_IPV4) == 0) {
489 				continue;
490 			}
491 			if (inp_restricted_recv(inp, ifp)) {
492 				continue;
493 			}
494 
495 			if ((inp->inp_moptions == NULL) &&
496 			    (ntohl(ip->ip_dst.s_addr) !=
497 			    INADDR_ALLHOSTS_GROUP) && (isbroadcast == 0)) {
498 				continue;
499 			}
500 			/*
501 			 * Skip unbound sockets before taking the lock on the socket as
502 			 * the test with the destination port in the header will fail
503 			 */
504 			if (inp->inp_lport == 0) {
505 				continue;
506 			}
507 
508 			if (in_pcb_checkstate(inp, WNT_ACQUIRE, 0) ==
509 			    WNT_STOPUSING) {
510 				continue;
511 			}
512 
513 			udp_lock(inp->inp_socket, 1, 0);
514 
515 			if (in_pcb_checkstate(inp, WNT_RELEASE, 1) ==
516 			    WNT_STOPUSING) {
517 				udp_unlock(inp->inp_socket, 1, 0);
518 				continue;
519 			}
520 
521 			if (inp->inp_lport != uh->uh_dport) {
522 				udp_unlock(inp->inp_socket, 1, 0);
523 				continue;
524 			}
525 			if (inp->inp_laddr.s_addr != INADDR_ANY) {
526 				if (inp->inp_laddr.s_addr !=
527 				    ip->ip_dst.s_addr) {
528 					udp_unlock(inp->inp_socket, 1, 0);
529 					continue;
530 				}
531 			}
532 			if (inp->inp_faddr.s_addr != INADDR_ANY) {
533 				if (inp->inp_faddr.s_addr !=
534 				    ip->ip_src.s_addr ||
535 				    inp->inp_fport != uh->uh_sport) {
536 					udp_unlock(inp->inp_socket, 1, 0);
537 					continue;
538 				}
539 			}
540 
541 			if (isbroadcast == 0 && (ntohl(ip->ip_dst.s_addr) !=
542 			    INADDR_ALLHOSTS_GROUP)) {
543 				struct sockaddr_in group;
544 				int blocked;
545 
546 				if ((imo = inp->inp_moptions) == NULL) {
547 					udp_unlock(inp->inp_socket, 1, 0);
548 					continue;
549 				}
550 				IMO_LOCK(imo);
551 
552 				SOCKADDR_ZERO(&group, sizeof(struct sockaddr_in));
553 				group.sin_len = sizeof(struct sockaddr_in);
554 				group.sin_family = AF_INET;
555 				group.sin_addr = ip->ip_dst;
556 
557 				blocked = imo_multi_filter(imo, ifp,
558 				    &group, &udp_in);
559 				if (blocked == MCAST_PASS) {
560 					foundmembership = 1;
561 				}
562 
563 				IMO_UNLOCK(imo);
564 				if (!foundmembership) {
565 					udp_unlock(inp->inp_socket, 1, 0);
566 					if (blocked == MCAST_NOTSMEMBER ||
567 					    blocked == MCAST_MUTED) {
568 						udpstat.udps_filtermcast++;
569 					}
570 					continue;
571 				}
572 				foundmembership = 0;
573 			}
574 
575 			reuse_sock = (inp->inp_socket->so_options &
576 			    (SO_REUSEPORT | SO_REUSEADDR));
577 
578 #if NECP
579 			skipit = 0;
580 			if (!necp_socket_is_allowed_to_send_recv_v4(inp,
581 			    uh->uh_dport, uh->uh_sport, &ip->ip_dst,
582 			    &ip->ip_src, ifp, pf_tag, NULL, NULL, NULL, NULL)) {
583 				/* do not inject data to pcb */
584 				skipit = 1;
585 				UDP_LOG_DROP_NECP(ip, uh, inp, false);
586 			}
587 			if (skipit == 0)
588 #endif /* NECP */
589 			{
590 				mbuf_ref_t n = NULL;
591 
592 				if (reuse_sock) {
593 					n = m_copy(m, 0, M_COPYALL);
594 				}
595 				udp_append(inp, ip, m,
596 				    iphlen + sizeof(struct udphdr),
597 				    &udp_in, &udp_in6, &udp_ip6, ifp);
598 				mcast_delivered++;
599 
600 				m = n;
601 			}
602 			if (is_wake_pkt) {
603 				soevent(inp->inp_socket, SO_FILT_HINT_LOCKED | SO_FILT_HINT_WAKE_PKT);
604 			}
605 
606 			udp_unlock(inp->inp_socket, 1, 0);
607 
608 
609 			/*
610 			 * Don't look for additional matches if this one does
611 			 * not have either the SO_REUSEPORT or SO_REUSEADDR
612 			 * socket options set.  This heuristic avoids searching
613 			 * through all pcbs in the common case of a non-shared
614 			 * port.  It assumes that an application will never
615 			 * clear these options after setting them.
616 			 */
617 			if (reuse_sock == 0 || m == NULL) {
618 				break;
619 			}
620 
621 			/*
622 			 * Expect 32-bit aligned data pointer on strict-align
623 			 * platforms.
624 			 */
625 			MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);
626 			/*
627 			 * Recompute IP and UDP header pointers for new mbuf
628 			 */
629 			ip = mtod(m, struct ip *);
630 			uh = (struct udphdr *)(void *)((caddr_t)ip + iphlen);
631 		}
632 		lck_rw_done(&pcbinfo->ipi_lock);
633 
634 		if (mcast_delivered == 0) {
635 			/*
636 			 * No matching pcb found; discard datagram.
637 			 * (No need to send an ICMP Port Unreachable
638 			 * for a broadcast or multicast datgram.)
639 			 */
640 			udpstat.udps_noportbcast++;
641 			IF_UDP_STATINC(ifp, port_unreach);
642 			drop_reason = DROP_REASON_UDP_PORT_UNREACHEABLE;
643 			goto bad;
644 		}
645 
646 		/* free the extra copy of mbuf or skipped by IPsec */
647 		if (m != NULL) {
648 			m_freem(m);
649 		}
650 		KERNEL_DEBUG(DBG_FNC_UDP_INPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
651 		return;
652 	}
653 
654 #if IPSEC
655 	/*
656 	 * UDP to port 4500 with a payload where the first four bytes are
657 	 * not zero is a UDP encapsulated IPsec packet. Packets where
658 	 * the payload is one byte and that byte is 0xFF are NAT keepalive
659 	 * packets. Decapsulate the ESP packet and carry on with IPsec input
660 	 * or discard the NAT keep-alive.
661 	 */
662 	if (ipsec_bypass == 0 && (esp_udp_encap_port & 0xFFFF) != 0 &&
663 	    (uh->uh_dport == ntohs((u_short)esp_udp_encap_port) ||
664 	    uh->uh_sport == ntohs((u_short)esp_udp_encap_port))) {
665 		/*
666 		 * Check if ESP or keepalive:
667 		 *      1. If the destination port of the incoming packet is 4500.
668 		 *      2. If the source port of the incoming packet is 4500,
669 		 *         then check the SADB to match IP address and port.
670 		 */
671 		bool check_esp = true;
672 		if (uh->uh_dport != ntohs((u_short)esp_udp_encap_port)) {
673 			union sockaddr_in_4_6 src = {};
674 			union sockaddr_in_4_6 dst = {};
675 
676 			ipsec_fill_ip_sockaddr_4_6(&src, ip->ip_src, uh->uh_sport);
677 			ipsec_fill_ip_sockaddr_4_6(&dst, ip->ip_dst, uh->uh_dport);
678 
679 			check_esp = key_checksa_present(&dst, &src);
680 		}
681 
682 		if (check_esp) {
683 			int payload_len = len - sizeof(struct udphdr) > 4 ? 4 :
684 			    len - sizeof(struct udphdr);
685 
686 			if (m->m_len < iphlen + sizeof(struct udphdr) + payload_len) {
687 				if ((m = m_pullup(m, iphlen + sizeof(struct udphdr) +
688 				    payload_len)) == NULL) {
689 					udpstat.udps_hdrops++;
690 					KERNEL_DEBUG(DBG_FNC_UDP_INPUT | DBG_FUNC_END,
691 					    0, 0, 0, 0, 0);
692 					return;
693 				}
694 				/*
695 				 * Expect 32-bit aligned data pointer on strict-align
696 				 * platforms.
697 				 */
698 				MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);
699 
700 				ip = mtod(m, struct ip *);
701 				uh = (struct udphdr *)(void *)((caddr_t)ip + iphlen);
702 			}
703 			/* Check for NAT keepalive packet */
704 			if (payload_len == 1 && *(u_int8_t *)
705 			    ((caddr_t)uh + sizeof(struct udphdr)) == 0xFF) {
706 				m_freem(m);
707 				KERNEL_DEBUG(DBG_FNC_UDP_INPUT | DBG_FUNC_END,
708 				    0, 0, 0, 0, 0);
709 				return;
710 			} else if (payload_len == 4 && *(u_int32_t *)(void *)
711 			    ((caddr_t)uh + sizeof(struct udphdr)) != 0) {
712 				/* UDP encapsulated IPsec packet to pass through NAT */
713 				KERNEL_DEBUG(DBG_FNC_UDP_INPUT | DBG_FUNC_END,
714 				    0, 0, 0, 0, 0);
715 				/* preserve the udp header */
716 				esp4_input(m, iphlen + sizeof(struct udphdr));
717 				return;
718 			}
719 		}
720 	}
721 #endif /* IPSEC */
722 
723 	/*
724 	 * Locate pcb for datagram.
725 	 */
726 	inp = in_pcblookup_hash(&udbinfo, ip->ip_src, uh->uh_sport,
727 	    ip->ip_dst, uh->uh_dport, 1, ifp);
728 	if (inp == NULL) {
729 		IF_UDP_STATINC(ifp, port_unreach);
730 
731 		if (udp_log_in_vain) {
732 			char buf[MAX_IPv4_STR_LEN];
733 			char buf2[MAX_IPv4_STR_LEN];
734 
735 			/* check src and dst address */
736 			if (udp_log_in_vain < 3) {
737 				log(LOG_INFO, "Connection attempt to "
738 				    "UDP %s:%d from %s:%d\n", inet_ntop(AF_INET,
739 				    &ip->ip_dst, buf, sizeof(buf)),
740 				    ntohs(uh->uh_dport), inet_ntop(AF_INET,
741 				    &ip->ip_src, buf2, sizeof(buf2)),
742 				    ntohs(uh->uh_sport));
743 			} else if (!(m->m_flags & (M_BCAST | M_MCAST)) &&
744 			    ip->ip_dst.s_addr != ip->ip_src.s_addr) {
745 				log_in_vain_log((LOG_INFO,
746 				    "Stealth Mode connection attempt to "
747 				    "UDP %s:%d from %s:%d\n", inet_ntop(AF_INET,
748 				    &ip->ip_dst, buf, sizeof(buf)),
749 				    ntohs(uh->uh_dport), inet_ntop(AF_INET,
750 				    &ip->ip_src, buf2, sizeof(buf2)),
751 				    ntohs(uh->uh_sport)))
752 			}
753 		}
754 		udpstat.udps_noport++;
755 		if (m->m_flags & (M_BCAST | M_MCAST)) {
756 			udpstat.udps_noportbcast++;
757 			drop_reason = DROP_REASON_UDP_PORT_UNREACHEABLE;
758 			goto bad;
759 		}
760 		if (udp_port_unreach_rlc_compress(ip->ip_src, uh->uh_sport,
761 		    ip->ip_dst, uh->uh_dport) == true) {
762 			drop_reason = DROP_REASON_UDP_PORT_UNREACHEABLE;
763 			goto bad;
764 		}
765 		if (blackhole) {
766 			if (ifp && ifp->if_type != IFT_LOOP) {
767 				drop_reason = DROP_REASON_UDP_PORT_UNREACHEABLE;
768 				goto bad;
769 			}
770 		}
771 		if (if_link_heuristics_enabled(ifp)) {
772 			drop_reason = DROP_REASON_UDP_PORT_UNREACHEABLE;
773 			IF_UDP_STATINC(ifp, linkheur_stealthdrop);
774 			goto bad;
775 		}
776 
777 		*ip = save_ip;
778 		ip->ip_len += iphlen;
779 		icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_PORT, 0, 0);
780 		KERNEL_DEBUG(DBG_FNC_UDP_INPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
781 		return;
782 	}
783 	udp_lock(inp->inp_socket, 1, 0);
784 
785 	if (in_pcb_checkstate(inp, WNT_RELEASE, 1) == WNT_STOPUSING) {
786 		udp_unlock(inp->inp_socket, 1, 0);
787 		IF_UDP_STATINC(ifp, cleanup);
788 		drop_reason = DROP_REASON_UDP_SOCKET_CLOSING;
789 		goto bad;
790 	}
791 #if NECP
792 	if (!necp_socket_is_allowed_to_send_recv_v4(inp, uh->uh_dport,
793 	    uh->uh_sport, &ip->ip_dst, &ip->ip_src, ifp, pf_tag, NULL, NULL, NULL, NULL)) {
794 		udp_unlock(inp->inp_socket, 1, 0);
795 		IF_UDP_STATINC(ifp, badipsec);
796 		drop_reason = DROP_REASON_UDP_NECP;
797 		goto bad;
798 	}
799 #endif /* NECP */
800 
801 	/*
802 	 * Construct sockaddr format source address.
803 	 * Stuff source address and datagram in user buffer.
804 	 */
805 	udp_in.sin_port = uh->uh_sport;
806 	udp_in.sin_addr = ip->ip_src;
807 	if ((inp->inp_flags & INP_CONTROLOPTS) != 0 ||
808 	    SOFLOW_ENABLED(inp->inp_socket) ||
809 	    SO_RECV_CONTROL_OPTS(inp->inp_socket)) {
810 		if (inp->inp_vflag & INP_IPV6 || inp->inp_vflag & INP_V4MAPPEDV6) {
811 			int savedflags;
812 
813 			ip_2_ip6_hdr(&udp_ip6.uip6_ip6, ip);
814 			savedflags = inp->inp_flags;
815 			inp->inp_flags &= ~INP_UNMAPPABLEOPTS;
816 			ret = ip6_savecontrol(inp, m, &opts);
817 			inp->inp_flags = savedflags;
818 		} else {
819 			ret = ip_savecontrol(inp, &opts, ip, m);
820 		}
821 		if (ret != 0) {
822 			udp_unlock(inp->inp_socket, 1, 0);
823 			drop_reason = DROP_REASON_UDP_CANNOT_SAVE_CONTROL;
824 			goto bad;
825 		}
826 	}
827 	m_adj(m, iphlen + sizeof(struct udphdr));
828 
829 	KERNEL_DEBUG(DBG_LAYER_IN_END, uh->uh_dport, uh->uh_sport,
830 	    save_ip.ip_src.s_addr, save_ip.ip_dst.s_addr, uh->uh_ulen);
831 
832 	if (inp->inp_vflag & INP_IPV6) {
833 		in6_sin_2_v4mapsin6(&udp_in, &udp_in6.uin6_sin);
834 		append_sa = SA(&udp_in6.uin6_sin);
835 	} else {
836 		append_sa = SA(&udp_in);
837 	}
838 	if (nstat_collect) {
839 		stats_functional_type ifnet_count_type = IFNET_COUNT_TYPE(ifp);
840 		INP_ADD_RXSTAT(inp, ifnet_count_type, 1, m->m_pkthdr.len);
841 	}
842 #if CONTENT_FILTER && NECP
843 	if (check_cfil && inp != NULL && inp->inp_policyresult.results.filter_control_unit == 0) {
844 		if (inp->inp_vflag & INP_IPV6) {
845 			bzero(&udp_dst6, sizeof(udp_dst6));
846 			udp_dst6.uin6_sin.sin6_len = sizeof(struct sockaddr_in6);
847 			udp_dst6.uin6_sin.sin6_family = AF_INET6;
848 			in6_sin_2_v4mapsin6(&udp_dst, &udp_dst6.uin6_sin);
849 			append_da = SA(&udp_dst6.uin6_sin);
850 		} else {
851 			SOCKADDR_ZERO(&udp_dst, sizeof(udp_dst));
852 			udp_dst.sin_len = sizeof(struct sockaddr_in);
853 			udp_dst.sin_family = AF_INET;
854 			udp_dst.sin_port = uh->uh_dport;
855 			udp_dst.sin_addr = ip->ip_dst;
856 			append_da = SA(&udp_dst);
857 		}
858 		// Override the dst input here so NECP can pick up the policy
859 		// and CFIL can find an existing control socket.
860 		necp_socket_find_policy_match(inp, append_da, append_sa, 0);
861 	}
862 #endif /* CONTENT_FILTER and NECP */
863 	so_recv_data_stat(inp->inp_socket, m, 0);
864 	if (sbappendaddr(&inp->inp_socket->so_rcv, append_sa,
865 	    m, opts, NULL) == 0) {
866 		udpstat.udps_fullsock++;
867 	} else {
868 		sorwakeup(inp->inp_socket);
869 	}
870 	if (is_wake_pkt) {
871 		soevent(inp->inp_socket, SO_FILT_HINT_LOCKED | SO_FILT_HINT_WAKE_PKT);
872 	}
873 	udp_unlock(inp->inp_socket, 1, 0);
874 	KERNEL_DEBUG(DBG_FNC_UDP_INPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
875 	return;
876 bad:
877 	m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, drop_reason, NULL, 0);
878 	if (opts) {
879 		m_freem(opts);
880 	}
881 	KERNEL_DEBUG(DBG_FNC_UDP_INPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
882 }
883 
884 static void
ip_2_ip6_hdr(struct ip6_hdr * ip6,struct ip * ip)885 ip_2_ip6_hdr(struct ip6_hdr *ip6, struct ip *ip)
886 {
887 	bzero(ip6, sizeof(*ip6));
888 
889 	ip6->ip6_vfc = IPV6_VERSION;
890 	ip6->ip6_plen = ip->ip_len;
891 	ip6->ip6_nxt = ip->ip_p;
892 	ip6->ip6_hlim = ip->ip_ttl;
893 	if (ip->ip_src.s_addr) {
894 		ip6->ip6_src.s6_addr32[2] = IPV6_ADDR_INT32_SMP;
895 		ip6->ip6_src.s6_addr32[3] = ip->ip_src.s_addr;
896 	}
897 	if (ip->ip_dst.s_addr) {
898 		ip6->ip6_dst.s6_addr32[2] = IPV6_ADDR_INT32_SMP;
899 		ip6->ip6_dst.s6_addr32[3] = ip->ip_dst.s_addr;
900 	}
901 }
902 
903 /*
904  * subroutine of udp_input(), mainly for source code readability.
905  */
906 static void
udp_append(struct inpcb * last,struct ip * ip,struct mbuf * n,int off,struct sockaddr_in * pudp_in,struct udp_in6 * pudp_in6,struct udp_ip6 * pudp_ip6,struct ifnet * ifp)907 udp_append(struct inpcb *last, struct ip *ip, struct mbuf *n, int off,
908     struct sockaddr_in *pudp_in, struct udp_in6 *pudp_in6,
909     struct udp_ip6 *pudp_ip6, struct ifnet *ifp)
910 {
911 	struct sockaddr *append_sa;
912 	mbuf_ref_t opts = NULL;
913 	int ret = 0;
914 
915 	if ((last->inp_flags & INP_CONTROLOPTS) != 0 ||
916 	    SOFLOW_ENABLED(last->inp_socket) ||
917 	    SO_RECV_CONTROL_OPTS(last->inp_socket)) {
918 		if (last->inp_vflag & INP_IPV6 || last->inp_vflag & INP_V4MAPPEDV6) {
919 			int savedflags;
920 
921 			if (pudp_ip6->uip6_init_done == 0) {
922 				ip_2_ip6_hdr(&pudp_ip6->uip6_ip6, ip);
923 				pudp_ip6->uip6_init_done = 1;
924 			}
925 			savedflags = last->inp_flags;
926 			last->inp_flags &= ~INP_UNMAPPABLEOPTS;
927 			ret = ip6_savecontrol(last, n, &opts);
928 			if (ret != 0) {
929 				last->inp_flags = savedflags;
930 				UDP_LOG(last, "ip6_savecontrol error %d", ret);
931 				goto error;
932 			}
933 			last->inp_flags = savedflags;
934 		} else {
935 			ret = ip_savecontrol(last, &opts, ip, n);
936 			if (ret != 0) {
937 				UDP_LOG(last, "ip_savecontrol error %d", ret);
938 				goto error;
939 			}
940 		}
941 	}
942 	if (last->inp_vflag & INP_IPV6) {
943 		if (pudp_in6->uin6_init_done == 0) {
944 			in6_sin_2_v4mapsin6(pudp_in, &pudp_in6->uin6_sin);
945 			pudp_in6->uin6_init_done = 1;
946 		}
947 		append_sa = SA(&pudp_in6->uin6_sin);
948 	} else {
949 		append_sa = SA(pudp_in);
950 	}
951 	if (nstat_collect) {
952 		stats_functional_type ifnet_count_type = IFNET_COUNT_TYPE(ifp);
953 		INP_ADD_RXSTAT(last, ifnet_count_type, 1, n->m_pkthdr.len);
954 	}
955 	so_recv_data_stat(last->inp_socket, n, 0);
956 	m_adj(n, off);
957 	if (sbappendaddr(&last->inp_socket->so_rcv, append_sa,
958 	    n, opts, NULL) == 0) {
959 		udpstat.udps_fullsock++;
960 		UDP_LOG(last, "sbappendaddr full receive socket buffer");
961 	} else {
962 		sorwakeup(last->inp_socket);
963 	}
964 	return;
965 error:
966 	m_freem(n);
967 	m_freem(opts);
968 }
969 
970 /*
971  * Notify a udp user of an asynchronous error;
972  * just wake up so that he can collect error status.
973  */
974 void
udp_notify(struct inpcb * inp,int errno)975 udp_notify(struct inpcb *inp, int errno)
976 {
977 	inp->inp_socket->so_error = (u_short)errno;
978 	sorwakeup(inp->inp_socket);
979 	sowwakeup(inp->inp_socket);
980 }
981 
982 void
udp_ctlinput(int cmd,struct sockaddr * sa,void * vip,__unused struct ifnet * ifp)983 udp_ctlinput(int cmd, struct sockaddr *sa, void *vip, __unused struct ifnet * ifp)
984 {
985 	struct ipctlparam *__single ctl_param = vip;
986 	struct ip *ip = NULL;
987 	mbuf_ref_t m = NULL;
988 	void (*notify)(struct inpcb *, int) = udp_notify;
989 	struct in_addr faddr;
990 	struct inpcb *inp = NULL;
991 	struct icmp *icp = NULL;
992 	size_t off;
993 
994 	if (ctl_param != NULL) {
995 		ip = ctl_param->ipc_icmp_ip;
996 		icp = ctl_param->ipc_icmp;
997 		m = ctl_param->ipc_m;
998 		off = ctl_param->ipc_off;
999 	} else {
1000 		ip = NULL;
1001 		icp = NULL;
1002 		m = NULL;
1003 		off = 0;
1004 	}
1005 
1006 	faddr = SIN(sa)->sin_addr;
1007 	if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY) {
1008 		return;
1009 	}
1010 
1011 	if (PRC_IS_REDIRECT(cmd)) {
1012 		ip = 0;
1013 		notify = in_rtchange;
1014 	} else if (cmd == PRC_HOSTDEAD) {
1015 		ip = 0;
1016 	} else if ((unsigned)cmd >= PRC_NCMDS || inetctlerrmap[cmd] == 0) {
1017 		return;
1018 	}
1019 	if (ip) {
1020 		struct udphdr uh;
1021 
1022 		/* Check if we can safely get the ports from the UDP header */
1023 		if (m == NULL ||
1024 		    (m->m_len < off + sizeof(uh))) {
1025 			/* Insufficient length */
1026 			return;
1027 		}
1028 
1029 		bcopy(m_mtod_current(m) + off, &uh, sizeof(uh));
1030 		inp = in_pcblookup_hash(&udbinfo, faddr, uh.uh_dport,
1031 		    ip->ip_src, uh.uh_sport, 0, NULL);
1032 
1033 		if (inp != NULL && inp->inp_socket != NULL) {
1034 			udp_lock(inp->inp_socket, 1, 0);
1035 			if (in_pcb_checkstate(inp, WNT_RELEASE, 1) ==
1036 			    WNT_STOPUSING) {
1037 				udp_unlock(inp->inp_socket, 1, 0);
1038 				return;
1039 			}
1040 			if (cmd == PRC_MSGSIZE && !uuid_is_null(inp->necp_client_uuid)) {
1041 				uuid_t null_uuid;
1042 				uuid_clear(null_uuid);
1043 				necp_update_flow_protoctl_event(null_uuid, inp->necp_client_uuid,
1044 				    PRC_MSGSIZE, ntohs(icp->icmp_nextmtu), 0);
1045 				/*
1046 				 * Avoid calling udp_notify() to set so_error
1047 				 * when using Network.framework since the notification
1048 				 * of PRC_MSGSIZE has been delivered through NECP.
1049 				 */
1050 			} else {
1051 				(*notify)(inp, inetctlerrmap[cmd]);
1052 			}
1053 			udp_unlock(inp->inp_socket, 1, 0);
1054 		}
1055 #if SKYWALK
1056 		else {
1057 			union sockaddr_in_4_6 sock_laddr;
1058 			struct protoctl_ev_val prctl_ev_val;
1059 			bzero(&prctl_ev_val, sizeof(prctl_ev_val));
1060 			bzero(&sock_laddr, sizeof(sock_laddr));
1061 
1062 			if (cmd == PRC_MSGSIZE) {
1063 				prctl_ev_val.val = ntohs(icp->icmp_nextmtu);
1064 			}
1065 
1066 			sock_laddr.sin.sin_family = AF_INET;
1067 			sock_laddr.sin.sin_len = sizeof(sock_laddr.sin);
1068 			sock_laddr.sin.sin_addr = ip->ip_src;
1069 
1070 			protoctl_event_enqueue_nwk_wq_entry(ifp,
1071 			    SA(&sock_laddr), sa,
1072 			    uh.uh_sport, uh.uh_dport, IPPROTO_UDP,
1073 			    cmd, &prctl_ev_val);
1074 		}
1075 #endif /* SKYWALK */
1076 	} else {
1077 		in_pcbnotifyall(&udbinfo, faddr, inetctlerrmap[cmd], notify);
1078 	}
1079 }
1080 
1081 int
udp_ctloutput(struct socket * so,struct sockopt * sopt)1082 udp_ctloutput(struct socket *so, struct sockopt *sopt)
1083 {
1084 	int     error = 0, optval = 0;
1085 	struct  inpcb *inp;
1086 
1087 	/* Allow <SOL_SOCKET,SO_FLUSH/SO_BINDTODEVICE> at this level */
1088 	if (sopt->sopt_level == SOL_SOCKET) {
1089 		if (sopt->sopt_name == SO_BINDTODEVICE) {
1090 			if (SOCK_CHECK_DOM(so, PF_INET6)) {
1091 				error = ip6_ctloutput(so, sopt);
1092 			} else {
1093 				error = ip_ctloutput(so, sopt);
1094 			}
1095 			return error;
1096 		} else if (sopt->sopt_name != SO_FLUSH) {
1097 			return EINVAL;
1098 		}
1099 	}
1100 	if (sopt->sopt_level != IPPROTO_UDP) {
1101 		if (SOCK_CHECK_DOM(so, PF_INET6)) {
1102 			error = ip6_ctloutput(so, sopt);
1103 		} else {
1104 			error = ip_ctloutput(so, sopt);
1105 		}
1106 		return error;
1107 	}
1108 
1109 	inp = sotoinpcb(so);
1110 
1111 	switch (sopt->sopt_dir) {
1112 	case SOPT_SET:
1113 		switch (sopt->sopt_name) {
1114 		case UDP_NOCKSUM:
1115 			/* This option is settable only for UDP over IPv4 */
1116 			if (!(inp->inp_vflag & INP_IPV4)) {
1117 				error = EINVAL;
1118 				break;
1119 			}
1120 
1121 			if ((error = sooptcopyin(sopt, &optval, sizeof(optval),
1122 			    sizeof(optval))) != 0) {
1123 				break;
1124 			}
1125 
1126 			if (optval != 0) {
1127 				inp->inp_flags |= INP_UDP_NOCKSUM;
1128 			} else {
1129 				inp->inp_flags &= ~INP_UDP_NOCKSUM;
1130 			}
1131 			break;
1132 		case UDP_KEEPALIVE_OFFLOAD:
1133 		{
1134 			struct udp_keepalive_offload ka;
1135 			/*
1136 			 * If the socket is not connected, the stack will
1137 			 * not know the destination address to put in the
1138 			 * keepalive datagram. Return an error now instead
1139 			 * of failing later.
1140 			 */
1141 			if (!(so->so_state & SS_ISCONNECTED)) {
1142 				error = EINVAL;
1143 				break;
1144 			}
1145 			if (sopt->sopt_valsize != sizeof(ka)) {
1146 				error = EINVAL;
1147 				break;
1148 			}
1149 			if ((error = sooptcopyin(sopt, &ka, sizeof(ka),
1150 			    sizeof(ka))) != 0) {
1151 				break;
1152 			}
1153 
1154 			/* application should specify the type */
1155 			if (ka.ka_type == 0) {
1156 				return EINVAL;
1157 			}
1158 
1159 			if (ka.ka_interval == 0) {
1160 				/*
1161 				 * if interval is 0, disable the offload
1162 				 * mechanism
1163 				 */
1164 				if (inp->inp_keepalive_data != NULL) {
1165 					kfree_data_sized_by(inp->inp_keepalive_data,
1166 					    inp->inp_keepalive_datalen);
1167 				}
1168 				inp->inp_keepalive_data = NULL;
1169 				inp->inp_keepalive_datalen = 0;
1170 				inp->inp_keepalive_interval = 0;
1171 				inp->inp_keepalive_type = 0;
1172 				inp->inp_flags2 &= ~INP2_KEEPALIVE_OFFLOAD;
1173 			} else {
1174 				if (inp->inp_keepalive_data != NULL) {
1175 					kfree_data_sized_by(inp->inp_keepalive_data,
1176 					    inp->inp_keepalive_datalen);
1177 				}
1178 
1179 				uint8_t datalen = (uint8_t)min(
1180 					ka.ka_data_len,
1181 					UDP_KEEPALIVE_OFFLOAD_DATA_SIZE);
1182 				if (datalen > 0) {
1183 					uint8_t *data = kalloc_data(datalen, Z_WAITOK);
1184 					if (data == NULL) {
1185 						inp->inp_keepalive_data = NULL;
1186 						inp->inp_keepalive_datalen = 0;
1187 						error = ENOMEM;
1188 						break;
1189 					} else {
1190 						inp->inp_keepalive_data = data;
1191 						inp->inp_keepalive_datalen = datalen;
1192 					}
1193 					bcopy(ka.ka_data,
1194 					    inp->inp_keepalive_data,
1195 					    inp->inp_keepalive_datalen);
1196 				} else {
1197 					inp->inp_keepalive_datalen = 0;
1198 					inp->inp_keepalive_data = NULL;
1199 				}
1200 				inp->inp_keepalive_interval = (uint8_t)
1201 				    min(UDP_KEEPALIVE_INTERVAL_MAX_SECONDS,
1202 				    ka.ka_interval);
1203 				inp->inp_keepalive_type = ka.ka_type;
1204 				inp->inp_flags2 |= INP2_KEEPALIVE_OFFLOAD;
1205 			}
1206 			break;
1207 		}
1208 		case SO_FLUSH:
1209 			if ((error = sooptcopyin(sopt, &optval, sizeof(optval),
1210 			    sizeof(optval))) != 0) {
1211 				break;
1212 			}
1213 
1214 			error = inp_flush(inp, optval);
1215 			break;
1216 
1217 		default:
1218 			error = ENOPROTOOPT;
1219 			break;
1220 		}
1221 		break;
1222 
1223 	case SOPT_GET:
1224 		switch (sopt->sopt_name) {
1225 		case UDP_NOCKSUM:
1226 			optval = inp->inp_flags & INP_UDP_NOCKSUM;
1227 			break;
1228 
1229 		default:
1230 			error = ENOPROTOOPT;
1231 			break;
1232 		}
1233 		if (error == 0) {
1234 			error = sooptcopyout(sopt, &optval, sizeof(optval));
1235 		}
1236 		break;
1237 	}
1238 	return error;
1239 }
1240 
1241 static int
1242 udp_pcblist SYSCTL_HANDLER_ARGS
1243 {
1244 #pragma unused(oidp, arg1, arg2)
1245 	int error, i, n, sz;
1246 	struct inpcb *inp, **inp_list;
1247 	inp_gen_t gencnt;
1248 	struct xinpgen xig;
1249 
1250 	/*
1251 	 * The process of preparing the TCB list is too time-consuming and
1252 	 * resource-intensive to repeat twice on every request.
1253 	 */
1254 	lck_rw_lock_exclusive(&udbinfo.ipi_lock);
1255 	if (req->oldptr == USER_ADDR_NULL) {
1256 		n = udbinfo.ipi_count;
1257 		req->oldidx = 2 * (sizeof(xig))
1258 		    + (n + n / 8) * sizeof(struct xinpcb);
1259 		lck_rw_done(&udbinfo.ipi_lock);
1260 		return 0;
1261 	}
1262 
1263 	if (req->newptr != USER_ADDR_NULL) {
1264 		lck_rw_done(&udbinfo.ipi_lock);
1265 		return EPERM;
1266 	}
1267 
1268 	/*
1269 	 * OK, now we're committed to doing something.
1270 	 */
1271 	gencnt = udbinfo.ipi_gencnt;
1272 	sz = n = udbinfo.ipi_count;
1273 
1274 	bzero(&xig, sizeof(xig));
1275 	xig.xig_len = sizeof(xig);
1276 	xig.xig_count = n;
1277 	xig.xig_gen = gencnt;
1278 	xig.xig_sogen = so_gencnt;
1279 	error = SYSCTL_OUT(req, &xig, sizeof(xig));
1280 	if (error) {
1281 		lck_rw_done(&udbinfo.ipi_lock);
1282 		return error;
1283 	}
1284 	/*
1285 	 * We are done if there is no pcb
1286 	 */
1287 	if (n == 0) {
1288 		lck_rw_done(&udbinfo.ipi_lock);
1289 		return 0;
1290 	}
1291 
1292 	inp_list = kalloc_type(struct inpcb *, n, Z_WAITOK);
1293 	if (inp_list == NULL) {
1294 		lck_rw_done(&udbinfo.ipi_lock);
1295 		return ENOMEM;
1296 	}
1297 
1298 	for (inp = LIST_FIRST(udbinfo.ipi_listhead), i = 0; inp && i < n;
1299 	    inp = LIST_NEXT(inp, inp_list)) {
1300 		if (inp->inp_gencnt <= gencnt &&
1301 		    inp->inp_state != INPCB_STATE_DEAD) {
1302 			inp_list[i++] = inp;
1303 		}
1304 	}
1305 	n = i;
1306 
1307 	error = 0;
1308 	for (i = 0; i < n; i++) {
1309 		struct xinpcb xi;
1310 
1311 		inp = inp_list[i];
1312 
1313 		if (in_pcb_checkstate(inp, WNT_ACQUIRE, 0) == WNT_STOPUSING) {
1314 			continue;
1315 		}
1316 		udp_lock(inp->inp_socket, 1, 0);
1317 		if (in_pcb_checkstate(inp, WNT_RELEASE, 1) == WNT_STOPUSING) {
1318 			udp_unlock(inp->inp_socket, 1, 0);
1319 			continue;
1320 		}
1321 		if (inp->inp_gencnt > gencnt) {
1322 			udp_unlock(inp->inp_socket, 1, 0);
1323 			continue;
1324 		}
1325 
1326 		bzero(&xi, sizeof(xi));
1327 		xi.xi_len = sizeof(xi);
1328 		/* XXX should avoid extra copy */
1329 		inpcb_to_compat(inp, &xi.xi_inp);
1330 		if (inp->inp_socket) {
1331 			sotoxsocket(inp->inp_socket, &xi.xi_socket);
1332 		}
1333 
1334 		udp_unlock(inp->inp_socket, 1, 0);
1335 
1336 		error = SYSCTL_OUT(req, &xi, sizeof(xi));
1337 	}
1338 	if (!error) {
1339 		/*
1340 		 * Give the user an updated idea of our state.
1341 		 * If the generation differs from what we told
1342 		 * her before, she knows that something happened
1343 		 * while we were processing this request, and it
1344 		 * might be necessary to retry.
1345 		 */
1346 		bzero(&xig, sizeof(xig));
1347 		xig.xig_len = sizeof(xig);
1348 		xig.xig_gen = udbinfo.ipi_gencnt;
1349 		xig.xig_sogen = so_gencnt;
1350 		xig.xig_count = udbinfo.ipi_count;
1351 		error = SYSCTL_OUT(req, &xig, sizeof(xig));
1352 	}
1353 
1354 	lck_rw_done(&udbinfo.ipi_lock);
1355 	kfree_type(struct inpcb *, sz, inp_list);
1356 	return error;
1357 }
1358 
1359 SYSCTL_PROC(_net_inet_udp, UDPCTL_PCBLIST, pcblist,
1360     CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0, udp_pcblist,
1361     "S,xinpcb", "List of active UDP sockets");
1362 
1363 #if XNU_TARGET_OS_OSX
1364 
1365 static int
1366 udp_pcblist64 SYSCTL_HANDLER_ARGS
1367 {
1368 #pragma unused(oidp, arg1, arg2)
1369 	int error, i, n, sz;
1370 	struct inpcb *inp, **inp_list;
1371 	inp_gen_t gencnt;
1372 	struct xinpgen xig;
1373 
1374 	/*
1375 	 * The process of preparing the TCB list is too time-consuming and
1376 	 * resource-intensive to repeat twice on every request.
1377 	 */
1378 	lck_rw_lock_shared(&udbinfo.ipi_lock);
1379 	if (req->oldptr == USER_ADDR_NULL) {
1380 		n = udbinfo.ipi_count;
1381 		req->oldidx =
1382 		    2 * (sizeof(xig)) + (n + n / 8) * sizeof(struct xinpcb64);
1383 		lck_rw_done(&udbinfo.ipi_lock);
1384 		return 0;
1385 	}
1386 
1387 	if (req->newptr != USER_ADDR_NULL) {
1388 		lck_rw_done(&udbinfo.ipi_lock);
1389 		return EPERM;
1390 	}
1391 
1392 	/*
1393 	 * OK, now we're committed to doing something.
1394 	 */
1395 	gencnt = udbinfo.ipi_gencnt;
1396 	sz = n = udbinfo.ipi_count;
1397 
1398 	bzero(&xig, sizeof(xig));
1399 	xig.xig_len = sizeof(xig);
1400 	xig.xig_count = n;
1401 	xig.xig_gen = gencnt;
1402 	xig.xig_sogen = so_gencnt;
1403 	error = SYSCTL_OUT(req, &xig, sizeof(xig));
1404 	if (error) {
1405 		lck_rw_done(&udbinfo.ipi_lock);
1406 		return error;
1407 	}
1408 	/*
1409 	 * We are done if there is no pcb
1410 	 */
1411 	if (n == 0) {
1412 		lck_rw_done(&udbinfo.ipi_lock);
1413 		return 0;
1414 	}
1415 
1416 	inp_list = kalloc_type(struct inpcb *, n, Z_WAITOK);
1417 	if (inp_list == NULL) {
1418 		lck_rw_done(&udbinfo.ipi_lock);
1419 		return ENOMEM;
1420 	}
1421 
1422 	for (inp = LIST_FIRST(udbinfo.ipi_listhead), i = 0; inp && i < n;
1423 	    inp = LIST_NEXT(inp, inp_list)) {
1424 		if (inp->inp_gencnt <= gencnt &&
1425 		    inp->inp_state != INPCB_STATE_DEAD) {
1426 			inp_list[i++] = inp;
1427 		}
1428 	}
1429 	n = i;
1430 
1431 	error = 0;
1432 	for (i = 0; i < n; i++) {
1433 		struct xinpcb64 xi;
1434 
1435 		inp = inp_list[i];
1436 
1437 		if (in_pcb_checkstate(inp, WNT_ACQUIRE, 0) == WNT_STOPUSING) {
1438 			continue;
1439 		}
1440 		udp_lock(inp->inp_socket, 1, 0);
1441 		if (in_pcb_checkstate(inp, WNT_RELEASE, 1) == WNT_STOPUSING) {
1442 			udp_unlock(inp->inp_socket, 1, 0);
1443 			continue;
1444 		}
1445 		if (inp->inp_gencnt > gencnt) {
1446 			udp_unlock(inp->inp_socket, 1, 0);
1447 			continue;
1448 		}
1449 
1450 		bzero(&xi, sizeof(xi));
1451 		xi.xi_len = sizeof(xi);
1452 		inpcb_to_xinpcb64(inp, &xi);
1453 		if (inp->inp_socket) {
1454 			sotoxsocket64(inp->inp_socket, &xi.xi_socket);
1455 		}
1456 
1457 		udp_unlock(inp->inp_socket, 1, 0);
1458 
1459 		error = SYSCTL_OUT(req, &xi, sizeof(xi));
1460 	}
1461 	if (!error) {
1462 		/*
1463 		 * Give the user an updated idea of our state.
1464 		 * If the generation differs from what we told
1465 		 * her before, she knows that something happened
1466 		 * while we were processing this request, and it
1467 		 * might be necessary to retry.
1468 		 */
1469 		bzero(&xig, sizeof(xig));
1470 		xig.xig_len = sizeof(xig);
1471 		xig.xig_gen = udbinfo.ipi_gencnt;
1472 		xig.xig_sogen = so_gencnt;
1473 		xig.xig_count = udbinfo.ipi_count;
1474 		error = SYSCTL_OUT(req, &xig, sizeof(xig));
1475 	}
1476 
1477 	lck_rw_done(&udbinfo.ipi_lock);
1478 	kfree_type(struct inpcb *, sz, inp_list);
1479 	return error;
1480 }
1481 
1482 SYSCTL_PROC(_net_inet_udp, OID_AUTO, pcblist64,
1483     CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0, udp_pcblist64,
1484     "S,xinpcb64", "List of active UDP sockets");
1485 
1486 #endif /* XNU_TARGET_OS_OSX */
1487 
1488 static int
1489 udp_pcblist_n SYSCTL_HANDLER_ARGS
1490 {
1491 #pragma unused(oidp, arg1, arg2)
1492 	return get_pcblist_n(IPPROTO_UDP, req, &udbinfo);
1493 }
1494 
1495 SYSCTL_PROC(_net_inet_udp, OID_AUTO, pcblist_n,
1496     CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0, udp_pcblist_n,
1497     "S,xinpcb_n", "List of active UDP sockets");
1498 
1499 __private_extern__ void
udp_get_ports_used(ifnet_t ifp,int protocol,uint32_t flags,bitstr_t * __counted_by (bitstr_size (IP_PORTRANGE_SIZE))bitfield)1500 udp_get_ports_used(ifnet_t ifp, int protocol, uint32_t flags,
1501     bitstr_t *__counted_by(bitstr_size(IP_PORTRANGE_SIZE)) bitfield)
1502 {
1503 	inpcb_get_ports_used(ifp, protocol, flags, bitfield,
1504 	    &udbinfo);
1505 }
1506 
1507 __private_extern__ uint32_t
udp_count_opportunistic(unsigned int ifindex,u_int32_t flags)1508 udp_count_opportunistic(unsigned int ifindex, u_int32_t flags)
1509 {
1510 	return inpcb_count_opportunistic(ifindex, &udbinfo, flags);
1511 }
1512 
1513 __private_extern__ uint32_t
udp_find_anypcb_byaddr(struct ifaddr * ifa)1514 udp_find_anypcb_byaddr(struct ifaddr *ifa)
1515 {
1516 #if SKYWALK
1517 	if (netns_is_enabled()) {
1518 		return netns_find_anyres_byaddr(ifa, IPPROTO_UDP);
1519 	} else
1520 #endif /* SKYWALK */
1521 	return inpcb_find_anypcb_byaddr(ifa, &udbinfo);
1522 }
1523 
1524 static int
udp_check_pktinfo(struct mbuf * control,struct ifnet ** outif,struct in_addr * laddr)1525 udp_check_pktinfo(struct mbuf *control, struct ifnet **outif,
1526     struct in_addr *laddr)
1527 {
1528 	struct cmsghdr *cm = 0;
1529 	struct in_pktinfo *pktinfo;
1530 	struct ifnet *ifp;
1531 
1532 	*outif = NULL;
1533 
1534 	/*
1535 	 * XXX: Currently, we assume all the optional information is stored
1536 	 * in a single mbuf.
1537 	 */
1538 	if (control->m_next) {
1539 		return EINVAL;
1540 	}
1541 
1542 	if (control->m_len < CMSG_LEN(0)) {
1543 		return EINVAL;
1544 	}
1545 
1546 	for (cm = M_FIRST_CMSGHDR(control);
1547 	    is_cmsg_valid(control, cm);
1548 	    cm = M_NXT_CMSGHDR(control, cm)) {
1549 		if (cm->cmsg_level != IPPROTO_IP ||
1550 		    cm->cmsg_type != IP_PKTINFO) {
1551 			continue;
1552 		}
1553 
1554 		if (cm->cmsg_len != CMSG_LEN(sizeof(struct in_pktinfo))) {
1555 			return EINVAL;
1556 		}
1557 
1558 		pktinfo =  (struct in_pktinfo *)(void *)CMSG_DATA(cm);
1559 
1560 		/* Check for a valid ifindex in pktinfo */
1561 		ifnet_head_lock_shared();
1562 
1563 		if (pktinfo->ipi_ifindex > if_index) {
1564 			ifnet_head_done();
1565 			return ENXIO;
1566 		}
1567 
1568 		/*
1569 		 * If ipi_ifindex is specified it takes precedence
1570 		 * over ipi_spec_dst.
1571 		 */
1572 		if (pktinfo->ipi_ifindex) {
1573 			ifp = ifindex2ifnet[pktinfo->ipi_ifindex];
1574 			if (ifp == NULL) {
1575 				ifnet_head_done();
1576 				return ENXIO;
1577 			}
1578 			ifnet_reference(ifp);
1579 			*outif = ifp;
1580 			ifnet_head_done();
1581 			laddr->s_addr = INADDR_ANY;
1582 			break;
1583 		}
1584 
1585 		ifnet_head_done();
1586 
1587 		/*
1588 		 * Use the provided ipi_spec_dst address for temp
1589 		 * source address.
1590 		 */
1591 		*laddr = pktinfo->ipi_spec_dst;
1592 		break;
1593 	}
1594 	return 0;
1595 }
1596 
1597 static int
udp_output(struct inpcb * inp,struct mbuf * m,struct sockaddr * addr,struct mbuf * control,struct proc * p)1598 udp_output(struct inpcb *inp, struct mbuf *m, struct sockaddr *addr,
1599     struct mbuf *control, struct proc *p)
1600 {
1601 	struct udpiphdr *ui;
1602 	int len = m->m_pkthdr.len;
1603 	struct sockaddr_in *sin;
1604 	struct in_addr laddr, faddr, pi_laddr;
1605 	u_short lport, fport;
1606 	int error = 0, pktinfo = 0;
1607 	struct socket *so = inp->inp_socket;
1608 	int soopts = 0;
1609 	struct mbuf *inpopts;
1610 	struct ip_moptions *__single mopts;
1611 	struct route ro;
1612 	struct ip_out_args ipoa;
1613 	bool sndinprog_cnt_used = false;
1614 #if CONTENT_FILTER
1615 	struct m_tag *__single cfil_tag = NULL;
1616 	bool cfil_faddr_use = false;
1617 	uint32_t cfil_so_state_change_cnt = 0;
1618 	uint32_t cfil_so_options = 0;
1619 	struct sockaddr *__single cfil_faddr = NULL;
1620 #endif
1621 	bool check_qos_marking_again = (so->so_flags1 & SOF1_QOSMARKING_POLICY_OVERRIDE) ? FALSE : TRUE;
1622 
1623 	bzero(&ipoa, sizeof(ipoa));
1624 	ipoa.ipoa_boundif = IFSCOPE_NONE;
1625 	ipoa.ipoa_flags = IPOAF_SELECT_SRCIF;
1626 
1627 	ifnet_ref_t outif = NULL;
1628 	struct flowadv *adv = &ipoa.ipoa_flowadv;
1629 	struct sock_cm_info sockcminfo;
1630 	int flowadv = 0;
1631 	int tos = IPTOS_UNSPEC;
1632 
1633 	/* Enable flow advisory only when connected */
1634 	flowadv = (so->so_state & SS_ISCONNECTED) ? 1 : 0;
1635 	pi_laddr.s_addr = INADDR_ANY;
1636 
1637 	KERNEL_DEBUG(DBG_FNC_UDP_OUTPUT | DBG_FUNC_START, 0, 0, 0, 0, 0);
1638 
1639 	socket_lock_assert_owned(so);
1640 
1641 #if CONTENT_FILTER
1642 	/*
1643 	 * If socket is subject to UDP Content Filter and no addr is passed in,
1644 	 * retrieve CFIL saved state from mbuf and use it if necessary.
1645 	 */
1646 	if (CFIL_DGRAM_FILTERED(so) && !addr) {
1647 		cfil_tag = cfil_dgram_get_socket_state(m, &cfil_so_state_change_cnt, &cfil_so_options, &cfil_faddr, NULL);
1648 		if (cfil_tag) {
1649 			sin = SIN(cfil_faddr);
1650 			if (inp && inp->inp_faddr.s_addr == INADDR_ANY) {
1651 				/*
1652 				 * Socket is unconnected, simply use the saved faddr as 'addr' to go through
1653 				 * the connect/disconnect logic.
1654 				 */
1655 				addr = SA(cfil_faddr);
1656 			} else if ((so->so_state_change_cnt != cfil_so_state_change_cnt) &&
1657 			    (inp->inp_fport != sin->sin_port ||
1658 			    inp->inp_faddr.s_addr != sin->sin_addr.s_addr)) {
1659 				/*
1660 				 * Socket is connected but socket state and dest addr/port changed.
1661 				 * We need to use the saved faddr info.
1662 				 */
1663 				cfil_faddr_use = true;
1664 			}
1665 		}
1666 	}
1667 #endif
1668 
1669 	sock_init_cm_info(&sockcminfo, so);
1670 
1671 	if (control != NULL) {
1672 		tos = ip_tos_from_control(control);
1673 
1674 		sock_parse_cm_info(control, &sockcminfo);
1675 
1676 		error = udp_check_pktinfo(control, &outif, &pi_laddr);
1677 		m_freem(control);
1678 		control = NULL;
1679 		if (error) {
1680 			UDP_LOG(inp, "udp_check_pktinfo error %d", error);
1681 			goto release;
1682 		}
1683 		if (outif != NULL) {
1684 			pktinfo++;
1685 			ipoa.ipoa_boundif = outif->if_index;
1686 		}
1687 	}
1688 
1689 	KERNEL_DEBUG(DBG_LAYER_OUT_BEG, inp->inp_fport, inp->inp_lport,
1690 	    inp->inp_laddr.s_addr, inp->inp_faddr.s_addr,
1691 	    (htons((u_short)len + sizeof(struct udphdr))));
1692 
1693 	if (len + sizeof(struct udpiphdr) > IP_MAXPACKET) {
1694 		error = EMSGSIZE;
1695 		UDP_LOG(inp, "len %d too big error EMSGSIZE", len);
1696 		goto release;
1697 	}
1698 
1699 	if (flowadv && INP_WAIT_FOR_IF_FEEDBACK(inp)) {
1700 		/*
1701 		 * The socket is flow-controlled, drop the packets
1702 		 * until the inp is not flow controlled
1703 		 */
1704 		error = ENOBUFS;
1705 		UDP_LOG(inp, "flow controlled error ENOBUFS");
1706 		goto release;
1707 	}
1708 	/*
1709 	 * If socket was bound to an ifindex, tell ip_output about it.
1710 	 * If the ancillary IP_PKTINFO option contains an interface index,
1711 	 * it takes precedence over the one specified by IP_BOUND_IF.
1712 	 */
1713 	if (ipoa.ipoa_boundif == IFSCOPE_NONE &&
1714 	    (inp->inp_flags & INP_BOUND_IF)) {
1715 		VERIFY(inp->inp_boundifp != NULL);
1716 		ifnet_reference(inp->inp_boundifp);     /* for this routine */
1717 		if (outif != NULL) {
1718 			ifnet_release(outif);
1719 		}
1720 		outif = inp->inp_boundifp;
1721 		ipoa.ipoa_boundif = outif->if_index;
1722 	}
1723 	if (INP_NO_CELLULAR(inp)) {
1724 		ipoa.ipoa_flags |=  IPOAF_NO_CELLULAR;
1725 	}
1726 	if (INP_NO_EXPENSIVE(inp)) {
1727 		ipoa.ipoa_flags |=  IPOAF_NO_EXPENSIVE;
1728 	}
1729 	if (INP_NO_CONSTRAINED(inp)) {
1730 		ipoa.ipoa_flags |=  IPOAF_NO_CONSTRAINED;
1731 	}
1732 	if (INP_AWDL_UNRESTRICTED(inp)) {
1733 		ipoa.ipoa_flags |=  IPOAF_AWDL_UNRESTRICTED;
1734 	}
1735 	if (INP_MANAGEMENT_ALLOWED(inp)) {
1736 		ipoa.ipoa_flags |= IPOAF_MANAGEMENT_ALLOWED;
1737 	}
1738 	if (INP_ULTRA_CONSTRAINED_ALLOWED(inp)) {
1739 		ipoa.ipoa_flags |= IPOAF_ULTRA_CONSTRAINED_ALLOWED;
1740 	}
1741 	ipoa.ipoa_sotc = sockcminfo.sotc;
1742 	ipoa.ipoa_netsvctype = sockcminfo.netsvctype;
1743 	soopts |= IP_OUTARGS;
1744 
1745 	/*
1746 	 * If there was a routing change, discard cached route and check
1747 	 * that we have a valid source address.  Reacquire a new source
1748 	 * address if INADDR_ANY was specified.
1749 	 *
1750 	 * If we are using cfil saved state, go through this cache cleanup
1751 	 * so that we can get a new route.
1752 	 */
1753 	if (ROUTE_UNUSABLE(&inp->inp_route)
1754 #if CONTENT_FILTER
1755 	    || cfil_faddr_use
1756 #endif
1757 	    ) {
1758 		struct in_ifaddr *ia = NULL;
1759 
1760 		ROUTE_RELEASE(&inp->inp_route);
1761 
1762 		/* src address is gone? */
1763 		if (inp->inp_laddr.s_addr != INADDR_ANY &&
1764 		    (ia = ifa_foraddr(inp->inp_laddr.s_addr)) == NULL) {
1765 			if (!(inp->inp_flags & INP_INADDR_ANY) ||
1766 			    (so->so_state & SS_ISCONNECTED)) {
1767 				/*
1768 				 * Rdar://5448998
1769 				 * If the source address is gone, return an
1770 				 * error if:
1771 				 * - the source was specified
1772 				 * - the socket was already connected
1773 				 */
1774 				soevent(so, (SO_FILT_HINT_LOCKED |
1775 				    SO_FILT_HINT_NOSRCADDR));
1776 				error = EADDRNOTAVAIL;
1777 				UDP_LOG(inp, "source address not available error EADDRNOTAVAIL");
1778 				goto release;
1779 			} else {
1780 				/* new src will be set later */
1781 				inp->inp_laddr.s_addr = INADDR_ANY;
1782 				inp->inp_last_outifp = NULL;
1783 #if SKYWALK
1784 				if (NETNS_TOKEN_VALID(&inp->inp_netns_token)) {
1785 					netns_set_ifnet(&inp->inp_netns_token, NULL);
1786 				}
1787 #endif /* SKYWALK */
1788 			}
1789 		}
1790 		if (ia != NULL) {
1791 			ifa_remref(&ia->ia_ifa);
1792 		}
1793 	}
1794 
1795 	/*
1796 	 * IP_PKTINFO option check.  If a temporary scope or src address
1797 	 * is provided, use it for this packet only and make sure we forget
1798 	 * it after sending this datagram.
1799 	 */
1800 	if (pi_laddr.s_addr != INADDR_ANY ||
1801 	    (ipoa.ipoa_boundif != IFSCOPE_NONE && pktinfo)) {
1802 		/* temp src address for this datagram only */
1803 		laddr = pi_laddr;
1804 	} else {
1805 		laddr = inp->inp_laddr;
1806 	}
1807 
1808 	faddr = inp->inp_faddr;
1809 	lport = inp->inp_lport;
1810 	fport = inp->inp_fport;
1811 
1812 #if CONTENT_FILTER
1813 	if (cfil_faddr_use) {
1814 		faddr = SIN(cfil_faddr)->sin_addr;
1815 		fport = SIN(cfil_faddr)->sin_port;
1816 	}
1817 #endif
1818 	inp->inp_sndinprog_cnt++;
1819 	sndinprog_cnt_used = true;
1820 
1821 	if (addr) {
1822 		if (inp->inp_faddr.s_addr != INADDR_ANY) {
1823 			error = EISCONN;
1824 			UDP_LOG(inp, "socket already connected error EISCONN");
1825 			goto release;
1826 		}
1827 		sin = SIN(addr);
1828 		faddr = sin->sin_addr;
1829 		fport = sin->sin_port; /* allow 0 port */
1830 
1831 		/*
1832 		 * Fast path case
1833 		 *
1834 		 * If neeed get a local address and a local port  to build
1835 		 * the packet without changing the pcb
1836 		 * and interfering with the input path. See 3851370.
1837 		 *
1838 		 * And don't disconnect as this could unbind the local port
1839 		 *
1840 		 * Scope from IP_PKTINFO takes precendence over the
1841 		 * the scope set via INP_BOUND_IF.
1842 		 */
1843 		if (laddr.s_addr == INADDR_ANY) {
1844 			char laddr_str[MAX_IPv4_STR_LEN];
1845 			char addr_str[MAX_IPv4_STR_LEN];
1846 
1847 			inet_ntop(AF_INET, &laddr.s_addr, laddr_str, sizeof(laddr_str));
1848 			inet_ntop(AF_INET, &sin->sin_addr.s_addr, addr_str, sizeof(addr_str));
1849 			UDP_LOG(inp, "calling in_pcbladdr addr %s laddr %s ipoa_boundif %u outif %s",
1850 			    addr_str, laddr_str, ipoa.ipoa_boundif, outif != NULL ? if_name(outif) : "<null>");
1851 
1852 			if ((error = in_pcbladdr(inp, addr, &laddr,
1853 			    ipoa.ipoa_boundif, &outif, 0)) != 0) {
1854 				UDP_LOG(inp, "in_pcbladdr error %d", error);
1855 				goto release;
1856 			}
1857 
1858 			/* synch up in case in_pcbladdr() overrides */
1859 			if (outif != NULL &&
1860 			    ipoa.ipoa_boundif != IFSCOPE_NONE) {
1861 				ipoa.ipoa_boundif = outif->if_index;
1862 			}
1863 
1864 			inet_ntop(AF_INET, &laddr.s_addr, laddr_str, sizeof(laddr_str));
1865 			inet_ntop(AF_INET, &sin->sin_addr.s_addr, addr_str, sizeof(addr_str));
1866 			UDP_LOG(inp, "after in_pcbladdr addr %s laddr %s ipoa_boundif %u outif %s",
1867 			    addr_str, laddr_str, ipoa.ipoa_boundif, outif != NULL ? if_name(outif) : "<null>");
1868 		}
1869 
1870 		if (lport == 0) {
1871 			inp_enter_bind_in_progress(so);
1872 
1873 			error = in_pcbsetport(laddr, addr, inp, p, 0);
1874 
1875 			if (error == 0) {
1876 				ASSERT(inp->inp_lport != 0);
1877 			}
1878 
1879 			inp_exit_bind_in_progress(so);
1880 
1881 			if (error != 0) {
1882 				UDP_LOG(inp, "in_pcbsetport error %d", error);
1883 				goto release;
1884 			}
1885 			lport = inp->inp_lport;
1886 			UDP_LOG(inp, "in_pcbsetport returned lport %u",
1887 			    ntohs(lport));
1888 		}
1889 	} else {
1890 		if (faddr.s_addr == INADDR_ANY) {
1891 			error = ENOTCONN;
1892 			UDP_LOG(inp, "not connected error ENOTCONN");
1893 			goto release;
1894 		}
1895 	}
1896 
1897 	if (inp->inp_flowhash == 0) {
1898 		inp_calc_flowhash(inp);
1899 		ASSERT(inp->inp_flowhash != 0);
1900 	}
1901 
1902 	if (fport == htons(53) && !(so->so_flags1 & SOF1_DNS_COUNTED)) {
1903 		so->so_flags1 |= SOF1_DNS_COUNTED;
1904 		INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_inet_dgram_dns);
1905 	}
1906 
1907 	/*
1908 	 * Calculate data length and get a mbuf
1909 	 * for UDP and IP headers.
1910 	 */
1911 	M_PREPEND(m, sizeof(struct udpiphdr), M_DONTWAIT, 1);
1912 	if (m == 0) {
1913 		error = ENOBUFS;
1914 		UDP_LOG(inp, "M_PREPEND error ENOBUFS");
1915 		goto abort;
1916 	}
1917 
1918 	/*
1919 	 * Fill in mbuf with extended UDP header
1920 	 * and addresses and length put into network format.
1921 	 */
1922 	ui = mtod(m, struct udpiphdr *);
1923 	bzero(ui->ui_x1, sizeof(ui->ui_x1));    /* XXX still needed? */
1924 	ui->ui_pr = IPPROTO_UDP;
1925 	ui->ui_src = laddr;
1926 	ui->ui_dst = faddr;
1927 	ui->ui_sport = lport;
1928 	ui->ui_dport = fport;
1929 	ui->ui_ulen = htons((u_short)len + sizeof(struct udphdr));
1930 
1931 	/*
1932 	 * Set the Don't Fragment bit in the IP header.
1933 	 */
1934 	if (inp->inp_flags2 & INP2_DONTFRAG) {
1935 		struct ip *ip;
1936 
1937 		ip = (struct ip *)&ui->ui_i;
1938 		ip->ip_off |= IP_DF;
1939 	}
1940 
1941 	/*
1942 	 * Set up checksum to pseudo header checksum and output datagram.
1943 	 *
1944 	 * Treat flows to be CLAT46'd as IPv6 flow and compute checksum
1945 	 * no matter what, as IPv6 mandates checksum for UDP.
1946 	 *
1947 	 * Here we only compute the one's complement sum of the pseudo header.
1948 	 * The payload computation and final complement is delayed to much later
1949 	 * in IP processing to decide if remaining computation needs to be done
1950 	 * through offload.
1951 	 *
1952 	 * That is communicated by setting CSUM_UDP in csum_flags.
1953 	 * The offset of checksum from the start of ULP header is communicated
1954 	 * through csum_data.
1955 	 *
1956 	 * Note since this already contains the pseudo checksum header, any
1957 	 * later operation at IP layer that modify the values used here must
1958 	 * update the checksum as well (for example NAT etc).
1959 	 */
1960 	if ((inp->inp_flags2 & INP2_CLAT46_FLOW) ||
1961 	    (udpcksum && !(inp->inp_flags & INP_UDP_NOCKSUM))) {
1962 		ui->ui_sum = in_pseudo(ui->ui_src.s_addr, ui->ui_dst.s_addr,
1963 		    htons((u_short)len + sizeof(struct udphdr) + IPPROTO_UDP));
1964 		m->m_pkthdr.csum_flags = (CSUM_UDP | CSUM_ZERO_INVERT);
1965 		m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
1966 	} else {
1967 		ui->ui_sum = 0;
1968 	}
1969 	((struct ip *)ui)->ip_len = (uint16_t)(sizeof(struct udpiphdr) + len);
1970 	((struct ip *)ui)->ip_ttl = inp->inp_ip_ttl;    /* XXX */
1971 	if (tos != IPTOS_UNSPEC) {
1972 		((struct ip *)ui)->ip_tos = (uint8_t)(tos & IPTOS_MASK);
1973 	} else {
1974 		((struct ip *)ui)->ip_tos = inp->inp_ip_tos;    /* XXX */
1975 	}
1976 	udpstat.udps_opackets++;
1977 
1978 	KERNEL_DEBUG(DBG_LAYER_OUT_END, ui->ui_dport, ui->ui_sport,
1979 	    ui->ui_src.s_addr, ui->ui_dst.s_addr, ui->ui_ulen);
1980 
1981 #if NECP
1982 	{
1983 		necp_kernel_policy_id policy_id;
1984 		necp_kernel_policy_id skip_policy_id;
1985 		u_int32_t route_rule_id;
1986 		u_int32_t pass_flags;
1987 
1988 		/*
1989 		 * We need a route to perform NECP route rule checks
1990 		 */
1991 		if (net_qos_policy_restricted != 0 &&
1992 		    ROUTE_UNUSABLE(&inp->inp_route)) {
1993 			struct sockaddr_in to;
1994 			struct sockaddr_in from;
1995 
1996 			ROUTE_RELEASE(&inp->inp_route);
1997 
1998 			SOCKADDR_ZERO(&from, sizeof(struct sockaddr_in));
1999 			from.sin_family = AF_INET;
2000 			from.sin_len = sizeof(struct sockaddr_in);
2001 			from.sin_addr = laddr;
2002 
2003 			SOCKADDR_ZERO(&to, sizeof(struct sockaddr_in));
2004 			to.sin_family = AF_INET;
2005 			to.sin_len = sizeof(struct sockaddr_in);
2006 			to.sin_addr = faddr;
2007 
2008 			inp->inp_route.ro_dst.sa_family = AF_INET;
2009 			inp->inp_route.ro_dst.sa_len = sizeof(struct sockaddr_in);
2010 			SIN(&inp->inp_route.ro_dst)->sin_addr = faddr;
2011 
2012 			rtalloc_scoped(&inp->inp_route, ipoa.ipoa_boundif);
2013 
2014 			inp_update_necp_policy(inp, SA(&from),
2015 			    SA(&to), ipoa.ipoa_boundif);
2016 			inp->inp_policyresult.results.qos_marking_gencount = 0;
2017 		}
2018 
2019 		if (!necp_socket_is_allowed_to_send_recv_v4(inp, lport, fport,
2020 		    &laddr, &faddr, NULL, 0, &policy_id, &route_rule_id, &skip_policy_id, &pass_flags)) {
2021 			error = EHOSTUNREACH;
2022 			UDP_LOG_DROP_NECP((struct ip *)&ui->ui_i, &ui->ui_u, inp, true);
2023 			m_drop_if(m, outif, DROPTAP_FLAG_DIR_OUT | DROPTAP_FLAG_L2_MISSING, DROP_REASON_UDP_NECP, NULL, 0);
2024 			m = NULL;
2025 			UDP_LOG(inp, "necp_socket_is_allowed_to_send_recv_v4 error %d", error);
2026 			goto abort;
2027 		}
2028 
2029 		necp_mark_packet_from_socket(m, inp, policy_id, route_rule_id, skip_policy_id, pass_flags);
2030 
2031 		if (net_qos_policy_restricted != 0) {
2032 			necp_socket_update_qos_marking(inp, inp->inp_route.ro_rt, route_rule_id);
2033 		}
2034 	}
2035 #endif /* NECP */
2036 	if ((so->so_flags1 & SOF1_QOSMARKING_ALLOWED)) {
2037 		ipoa.ipoa_flags |= IPOAF_QOSMARKING_ALLOWED;
2038 	}
2039 	if (check_qos_marking_again) {
2040 		ipoa.ipoa_flags |= IPOAF_REDO_QOSMARKING_POLICY;
2041 	}
2042 	ipoa.qos_marking_gencount = inp->inp_policyresult.results.qos_marking_gencount;
2043 
2044 #if IPSEC
2045 	if (inp->inp_sp != NULL && ipsec_setsocket(m, inp->inp_socket) != 0) {
2046 		error = ENOBUFS;
2047 		UDP_LOG_DROP_PCB((struct ip *)&ui->ui_i, &ui->ui_u, inp, true, "ipsec_setsocket error ENOBUFS");
2048 		m_drop_if(m, outif, DROPTAP_FLAG_DIR_OUT | DROPTAP_FLAG_L2_MISSING, DROP_REASON_UDP_IPSEC, NULL, 0);
2049 		m = NULL;
2050 		UDP_LOG(inp, "necp_socket_is_allowed_to_send_recv_v4 error %d", error);
2051 		goto abort;
2052 	}
2053 #endif /* IPSEC */
2054 
2055 	inpopts = inp->inp_options;
2056 #if CONTENT_FILTER
2057 	if (cfil_tag && (inp->inp_socket->so_options != cfil_so_options)) {
2058 		soopts |= (cfil_so_options & (SO_DONTROUTE | SO_BROADCAST));
2059 	} else
2060 #endif
2061 	soopts |= (inp->inp_socket->so_options & (SO_DONTROUTE | SO_BROADCAST));
2062 
2063 	mopts = inp->inp_moptions;
2064 	if (mopts != NULL) {
2065 		IMO_LOCK(mopts);
2066 		IMO_ADDREF_LOCKED(mopts);
2067 		if (IN_MULTICAST(ntohl(ui->ui_dst.s_addr)) &&
2068 		    mopts->imo_multicast_ifp != NULL) {
2069 			/* no reference needed */
2070 			inp->inp_last_outifp = mopts->imo_multicast_ifp;
2071 #if SKYWALK
2072 			if (NETNS_TOKEN_VALID(&inp->inp_netns_token)) {
2073 				netns_set_ifnet(&inp->inp_netns_token,
2074 				    inp->inp_last_outifp);
2075 			}
2076 #endif /* SKYWALK */
2077 		}
2078 		IMO_UNLOCK(mopts);
2079 	}
2080 
2081 	/* Copy the cached route and take an extra reference */
2082 	inp_route_copyout(inp, &ro);
2083 
2084 	set_packet_service_class(m, so, sockcminfo.sotc, 0);
2085 	if (sockcminfo.tx_time) {
2086 		mbuf_set_tx_time(m, sockcminfo.tx_time);
2087 	}
2088 	m->m_pkthdr.pkt_flowsrc = FLOWSRC_INPCB;
2089 	m->m_pkthdr.pkt_flowid = inp->inp_flowhash;
2090 	m->m_pkthdr.pkt_proto = IPPROTO_UDP;
2091 	m->m_pkthdr.pkt_flags |= (PKTF_FLOW_ID | PKTF_FLOW_LOCALSRC);
2092 	if (flowadv) {
2093 		m->m_pkthdr.pkt_flags |= PKTF_FLOW_ADV;
2094 	}
2095 	m->m_pkthdr.tx_udp_pid = so->last_pid;
2096 	if (so->so_flags & SOF_DELEGATED) {
2097 		m->m_pkthdr.tx_udp_e_pid = so->e_pid;
2098 	} else {
2099 		m->m_pkthdr.tx_udp_e_pid = 0;
2100 	}
2101 #if (DEBUG || DEVELOPMENT)
2102 	if (so->so_flags & SOF_MARK_WAKE_PKT) {
2103 		so->so_flags &= ~SOF_MARK_WAKE_PKT;
2104 		m->m_pkthdr.pkt_flags |= PKTF_WAKE_PKT;
2105 	}
2106 #endif /* (DEBUG || DEVELOPMENT) */
2107 
2108 	m_add_crumb(m, PKT_CRUMB_UDP_OUTPUT);
2109 
2110 	if (ipoa.ipoa_boundif != IFSCOPE_NONE) {
2111 		ipoa.ipoa_flags |= IPOAF_BOUND_IF;
2112 	}
2113 
2114 	if (laddr.s_addr != INADDR_ANY) {
2115 		ipoa.ipoa_flags |= IPOAF_BOUND_SRCADDR;
2116 	}
2117 
2118 	socket_unlock(so, 0);
2119 	error = ip_output(m, inpopts, &ro, soopts, mopts, &ipoa);
2120 	m = NULL;
2121 	socket_lock(so, 0);
2122 	if (mopts != NULL) {
2123 		IMO_REMREF(mopts);
2124 	}
2125 
2126 	if (error != 0) {
2127 		UDP_LOG(inp, "ip_output error %d", error);
2128 	}
2129 
2130 	if (check_qos_marking_again) {
2131 		inp->inp_policyresult.results.qos_marking_gencount = ipoa.qos_marking_gencount;
2132 
2133 		if (ipoa.ipoa_flags & IPOAF_QOSMARKING_ALLOWED) {
2134 			inp->inp_socket->so_flags1 |= SOF1_QOSMARKING_ALLOWED;
2135 		} else {
2136 			inp->inp_socket->so_flags1 &= ~SOF1_QOSMARKING_ALLOWED;
2137 		}
2138 	}
2139 
2140 	if (error == 0 && nstat_collect) {
2141 		stats_functional_type ifnet_count_type = stats_functional_type_unclassified;
2142 
2143 		if (ro.ro_rt != NULL) {
2144 			ifnet_count_type = IFNET_COUNT_TYPE(ro.ro_rt->rt_ifp);
2145 		}
2146 		INP_ADD_TXSTAT(inp, ifnet_count_type, 1, len);
2147 	}
2148 
2149 	if (flowadv && (adv->code == FADV_FLOW_CONTROLLED ||
2150 	    adv->code == FADV_SUSPENDED)) {
2151 		/*
2152 		 * return a hint to the application that
2153 		 * the packet has been dropped
2154 		 */
2155 		error = ENOBUFS;
2156 		inp_set_fc_state(inp, adv->code);
2157 	}
2158 
2159 	/* Synchronize PCB cached route */
2160 	inp_route_copyin(inp, &ro);
2161 
2162 	if (inp->inp_route.ro_rt != NULL) {
2163 		if (IS_LOCALNET_ROUTE(inp->inp_route.ro_rt)) {
2164 			inp->inp_flags2 |= INP2_LAST_ROUTE_LOCAL;
2165 		} else {
2166 			inp->inp_flags2 &= ~INP2_LAST_ROUTE_LOCAL;
2167 		}
2168 	}
2169 
2170 abort:
2171 	if (inp->inp_route.ro_rt != NULL) {
2172 		struct rtentry *rt = inp->inp_route.ro_rt;
2173 		struct ifnet *outifp;
2174 
2175 		if (rt->rt_flags & (RTF_MULTICAST | RTF_BROADCAST)) {
2176 			rt = NULL;      /* unusable */
2177 		}
2178 #if CONTENT_FILTER
2179 		/*
2180 		 * Discard temporary route for cfil case
2181 		 */
2182 		if (cfil_faddr_use) {
2183 			rt = NULL;      /* unusable */
2184 		}
2185 #endif
2186 
2187 		/*
2188 		 * Always discard if it is a multicast or broadcast route.
2189 		 */
2190 		if (rt == NULL) {
2191 			ROUTE_RELEASE(&inp->inp_route);
2192 		}
2193 
2194 		/*
2195 		 * If the destination route is unicast, update outifp with
2196 		 * that of the route interface used by IP.
2197 		 */
2198 		if (rt != NULL &&
2199 		    (outifp = rt->rt_ifp) != inp->inp_last_outifp) {
2200 			inp->inp_last_outifp = outifp; /* no reference needed */
2201 #if SKYWALK
2202 			if (NETNS_TOKEN_VALID(&inp->inp_netns_token)) {
2203 				netns_set_ifnet(&inp->inp_netns_token,
2204 				    inp->inp_last_outifp);
2205 			}
2206 #endif /* SKYWALK */
2207 
2208 			so->so_pktheadroom = (uint16_t)P2ROUNDUP(
2209 				sizeof(struct udphdr) +
2210 				sizeof(struct ip) +
2211 				ifnet_hdrlen(outifp) +
2212 				ifnet_mbuf_packetpreamblelen(outifp),
2213 				sizeof(u_int32_t));
2214 		}
2215 	} else {
2216 		ROUTE_RELEASE(&inp->inp_route);
2217 	}
2218 
2219 	/*
2220 	 * If output interface was cellular/expensive, and this socket is
2221 	 * denied access to it, generate an event.
2222 	 */
2223 	if (error != 0 && (ipoa.ipoa_flags & IPOAF_R_IFDENIED) &&
2224 	    (INP_NO_CELLULAR(inp) || INP_NO_EXPENSIVE(inp) || INP_NO_CONSTRAINED(inp))) {
2225 		soevent(so, (SO_FILT_HINT_LOCKED | SO_FILT_HINT_IFDENIED));
2226 	}
2227 
2228 release:
2229 	KERNEL_DEBUG(DBG_FNC_UDP_OUTPUT | DBG_FUNC_END, error, 0, 0, 0, 0);
2230 
2231 	if (m != NULL) {
2232 		m_freem(m);
2233 	}
2234 
2235 	if (outif != NULL) {
2236 		ifnet_release(outif);
2237 	}
2238 
2239 #if CONTENT_FILTER
2240 	if (cfil_tag) {
2241 		m_tag_free(cfil_tag);
2242 	}
2243 #endif
2244 	if (sndinprog_cnt_used) {
2245 		VERIFY(inp->inp_sndinprog_cnt > 0);
2246 		if (--inp->inp_sndinprog_cnt == 0) {
2247 			inp->inp_flags &= ~(INP_FC_FEEDBACK);
2248 			if (inp->inp_sndingprog_waiters > 0) {
2249 				wakeup(&inp->inp_sndinprog_cnt);
2250 			}
2251 		}
2252 		sndinprog_cnt_used = false;
2253 	}
2254 
2255 	return error;
2256 }
2257 
2258 u_int32_t       udp_sendspace = 9216;           /* really max datagram size */
2259 /* 187 1K datagrams (approx 192 KB) */
2260 u_int32_t       udp_recvspace = 187 * (1024 + sizeof(struct sockaddr_in6));
2261 
2262 /* Check that the values of udp send and recv space do not exceed sb_max */
2263 static int
sysctl_udp_sospace(struct sysctl_oid * oidp,void * arg1,int arg2,struct sysctl_req * req)2264 sysctl_udp_sospace(struct sysctl_oid *oidp, void *arg1, int arg2,
2265     struct sysctl_req *req)
2266 {
2267 #pragma unused(arg1, arg2)
2268 	u_int32_t new_value = 0, *space_p = NULL;
2269 	int changed = 0, error = 0;
2270 
2271 	switch (oidp->oid_number) {
2272 	case UDPCTL_RECVSPACE:
2273 		space_p = &udp_recvspace;
2274 		break;
2275 	case UDPCTL_MAXDGRAM:
2276 		space_p = &udp_sendspace;
2277 		break;
2278 	default:
2279 		return EINVAL;
2280 	}
2281 	error = sysctl_io_number(req, *space_p, sizeof(u_int32_t),
2282 	    &new_value, &changed);
2283 	if (changed) {
2284 		if (new_value > 0 && new_value <= sb_max) {
2285 			*space_p = new_value;
2286 		} else {
2287 			error = ERANGE;
2288 		}
2289 	}
2290 	return error;
2291 }
2292 
2293 SYSCTL_PROC(_net_inet_udp, UDPCTL_RECVSPACE, recvspace,
2294     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED, &udp_recvspace, 0,
2295     &sysctl_udp_sospace, "IU", "Maximum incoming UDP datagram size");
2296 
2297 SYSCTL_PROC(_net_inet_udp, UDPCTL_MAXDGRAM, maxdgram,
2298     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED, &udp_sendspace, 0,
2299     &sysctl_udp_sospace, "IU", "Maximum outgoing UDP datagram size");
2300 
2301 static int
udp_abort(struct socket * so)2302 udp_abort(struct socket *so)
2303 {
2304 	struct inpcb *inp;
2305 
2306 	inp = sotoinpcb(so);
2307 	if (inp == NULL) {
2308 		panic("%s: so=%p null inp", __func__, so);
2309 		/* NOTREACHED */
2310 	}
2311 	soisdisconnected(so);
2312 	in_pcbdetach(inp);
2313 	return 0;
2314 }
2315 
2316 static int
udp_attach(struct socket * so,int proto,struct proc * p)2317 udp_attach(struct socket *so, int proto, struct proc *p)
2318 {
2319 #pragma unused(proto)
2320 	struct inpcb *inp;
2321 	int error;
2322 
2323 	error = soreserve(so, udp_sendspace, udp_recvspace);
2324 	if (error != 0) {
2325 		return error;
2326 	}
2327 	inp = sotoinpcb(so);
2328 	if (inp != NULL) {
2329 		panic("%s so=%p inp=%p", __func__, so, inp);
2330 		/* NOTREACHED */
2331 	}
2332 	error = in_pcballoc(so, &udbinfo, p);
2333 	if (error != 0) {
2334 		return error;
2335 	}
2336 	inp = (struct inpcb *)so->so_pcb;
2337 	inp->inp_vflag |= INP_IPV4;
2338 	inp->inp_ip_ttl = (uint8_t)ip_defttl;
2339 	if (nstat_collect) {
2340 		nstat_udp_new_pcb(inp);
2341 	}
2342 	return 0;
2343 }
2344 
2345 static int
udp_bind(struct socket * so,struct sockaddr * nam,struct proc * p)2346 udp_bind(struct socket *so, struct sockaddr *nam, struct proc *p)
2347 {
2348 	struct inpcb *inp;
2349 	int error;
2350 
2351 	if (nam->sa_family != 0 && nam->sa_family != AF_INET &&
2352 	    nam->sa_family != AF_INET6) {
2353 		return EAFNOSUPPORT;
2354 	}
2355 
2356 	inp = sotoinpcb(so);
2357 	if (inp == NULL) {
2358 		return EINVAL;
2359 	}
2360 
2361 	inp_enter_bind_in_progress(so);
2362 
2363 	error = in_pcbbind(inp, nam, NULL, p);
2364 
2365 #if NECP
2366 	/* Update NECP client with bind result if not in middle of connect */
2367 	if (error == 0 &&
2368 	    (inp->inp_flags2 & INP2_CONNECT_IN_PROGRESS) &&
2369 	    !uuid_is_null(inp->necp_client_uuid)) {
2370 		socket_unlock(so, 0);
2371 		necp_client_assign_from_socket(so->last_pid, inp->necp_client_uuid, inp);
2372 		socket_lock(so, 0);
2373 	}
2374 #endif /* NECP */
2375 
2376 	UDP_LOG_BIND(inp, error);
2377 
2378 	inp_exit_bind_in_progress(so);
2379 
2380 	return error;
2381 }
2382 
2383 static int
udp_connect(struct socket * so,struct sockaddr * nam,struct proc * p)2384 udp_connect(struct socket *so, struct sockaddr *nam, struct proc *p)
2385 {
2386 	struct inpcb *inp;
2387 	int error;
2388 
2389 	inp = sotoinpcb(so);
2390 	if (inp == NULL) {
2391 		return EINVAL;
2392 	}
2393 	inp_enter_bind_in_progress(so);
2394 
2395 	if (inp->inp_faddr.s_addr != INADDR_ANY) {
2396 		error = EISCONN;
2397 		goto done;
2398 	}
2399 
2400 	if (!(so->so_flags1 & SOF1_CONNECT_COUNTED)) {
2401 		so->so_flags1 |= SOF1_CONNECT_COUNTED;
2402 		INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_inet_dgram_connected);
2403 	}
2404 
2405 #if NECP
2406 #if FLOW_DIVERT
2407 	if (necp_socket_should_use_flow_divert(inp)) {
2408 		error = flow_divert_pcb_init(so);
2409 		if (error == 0) {
2410 			error = flow_divert_connect_out(so, nam, p);
2411 		}
2412 		goto done;
2413 	} else {
2414 		so->so_flags1 |= SOF1_FLOW_DIVERT_SKIP;
2415 	}
2416 #endif /* FLOW_DIVERT */
2417 #endif /* NECP */
2418 
2419 	error = in_pcbconnect(inp, nam, p, IFSCOPE_NONE, NULL);
2420 	if (error == 0) {
2421 #if NECP
2422 		/* Update NECP client with connected five-tuple */
2423 		if (!uuid_is_null(inp->necp_client_uuid)) {
2424 			socket_unlock(so, 0);
2425 			necp_client_assign_from_socket(so->last_pid, inp->necp_client_uuid, inp);
2426 			socket_lock(so, 0);
2427 		}
2428 #endif /* NECP */
2429 
2430 		soisconnected(so);
2431 		if (inp->inp_flowhash == 0) {
2432 			inp_calc_flowhash(inp);
2433 			ASSERT(inp->inp_flowhash != 0);
2434 		}
2435 		inp->inp_connect_timestamp = mach_continuous_time();
2436 	}
2437 done:
2438 	UDP_LOG_CONNECT(inp, error);
2439 
2440 	inp_exit_bind_in_progress(so);
2441 
2442 	return error;
2443 }
2444 
2445 int
udp_connectx_common(struct socket * so,int af,struct sockaddr * src,struct sockaddr * dst,struct proc * p,uint32_t ifscope,sae_associd_t aid,sae_connid_t * pcid,uint32_t flags,void * arg,uint32_t arglen,struct uio * uio,user_ssize_t * bytes_written)2446 udp_connectx_common(struct socket *so, int af, struct sockaddr *src, struct sockaddr *dst,
2447     struct proc *p, uint32_t ifscope, sae_associd_t aid, sae_connid_t *pcid,
2448     uint32_t flags, void *arg, uint32_t arglen,
2449     struct uio *uio, user_ssize_t *bytes_written)
2450 {
2451 #pragma unused(aid, flags, arg, arglen)
2452 	struct inpcb *inp = sotoinpcb(so);
2453 	int error = 0;
2454 	user_ssize_t datalen = 0;
2455 
2456 	if (inp == NULL) {
2457 		return EINVAL;
2458 	}
2459 
2460 	VERIFY(dst != NULL);
2461 
2462 	ASSERT(!(inp->inp_flags2 & INP2_CONNECT_IN_PROGRESS));
2463 	inp->inp_flags2 |= INP2_CONNECT_IN_PROGRESS;
2464 
2465 #if NECP
2466 	inp_update_necp_policy(inp, src, dst, ifscope);
2467 #endif /* NECP */
2468 
2469 	/* bind socket to the specified interface, if requested */
2470 	if (ifscope != IFSCOPE_NONE &&
2471 	    (error = inp_bindif(inp, ifscope, NULL)) != 0) {
2472 		goto done;
2473 	}
2474 
2475 	/* if source address and/or port is specified, bind to it */
2476 	if (src != NULL) {
2477 		error = sobindlock(so, src, 0); /* already locked */
2478 		if (error != 0) {
2479 			goto done;
2480 		}
2481 	}
2482 
2483 	switch (af) {
2484 	case AF_INET:
2485 		error = udp_connect(so, dst, p);
2486 		break;
2487 	case AF_INET6:
2488 		error = udp6_connect(so, dst, p);
2489 		break;
2490 	default:
2491 		VERIFY(0);
2492 		/* NOTREACHED */
2493 	}
2494 
2495 	if (error != 0) {
2496 		goto done;
2497 	}
2498 
2499 	/*
2500 	 * If there is data, copy it. DATA_IDEMPOTENT is ignored.
2501 	 * CONNECT_RESUME_ON_READ_WRITE is ignored.
2502 	 */
2503 	if (uio != NULL) {
2504 		socket_unlock(so, 0);
2505 
2506 		VERIFY(bytes_written != NULL);
2507 
2508 		datalen = uio_resid(uio);
2509 		error = so->so_proto->pr_usrreqs->pru_sosend(so, NULL,
2510 		    (uio_t)uio, NULL, NULL, 0);
2511 		socket_lock(so, 0);
2512 
2513 		/* If error returned is EMSGSIZE, for example, disconnect */
2514 		if (error == 0 || error == EWOULDBLOCK) {
2515 			*bytes_written = datalen - uio_resid(uio);
2516 		} else {
2517 			(void) so->so_proto->pr_usrreqs->pru_disconnectx(so,
2518 			    SAE_ASSOCID_ANY, SAE_CONNID_ANY);
2519 		}
2520 		/*
2521 		 * mask the EWOULDBLOCK error so that the caller
2522 		 * knows that atleast the connect was successful.
2523 		 */
2524 		if (error == EWOULDBLOCK) {
2525 			error = 0;
2526 		}
2527 	}
2528 
2529 	if (error == 0 && pcid != NULL) {
2530 		*pcid = 1;      /* there is only 1 connection for UDP */
2531 	}
2532 done:
2533 	inp->inp_flags2 &= ~INP2_CONNECT_IN_PROGRESS;
2534 	return error;
2535 }
2536 
2537 static int
udp_connectx(struct socket * so,struct sockaddr * src,struct sockaddr * dst,struct proc * p,uint32_t ifscope,sae_associd_t aid,sae_connid_t * pcid,uint32_t flags,void * arg,uint32_t arglen,struct uio * uio,user_ssize_t * bytes_written)2538 udp_connectx(struct socket *so, struct sockaddr *src,
2539     struct sockaddr *dst, struct proc *p, uint32_t ifscope,
2540     sae_associd_t aid, sae_connid_t *pcid, uint32_t flags, void *arg,
2541     uint32_t arglen, struct uio *uio, user_ssize_t *bytes_written)
2542 {
2543 	return udp_connectx_common(so, AF_INET, src, dst,
2544 	           p, ifscope, aid, pcid, flags, arg, arglen, uio, bytes_written);
2545 }
2546 
2547 static int
udp_detach(struct socket * so)2548 udp_detach(struct socket *so)
2549 {
2550 	struct inpcb *inp;
2551 
2552 	inp = sotoinpcb(so);
2553 	if (inp == NULL) {
2554 		panic("%s: so=%p null inp", __func__, so);
2555 		/* NOTREACHED */
2556 	}
2557 
2558 	/*
2559 	 * If this is a socket that does not want to wakeup the device
2560 	 * for it's traffic, the application might be waiting for
2561 	 * close to complete before going to sleep. Send a notification
2562 	 * for this kind of sockets
2563 	 */
2564 	if (so->so_options & SO_NOWAKEFROMSLEEP) {
2565 		socket_post_kev_msg_closed(so);
2566 	}
2567 
2568 	UDP_LOG_CONNECTION_SUMMARY(inp);
2569 
2570 	in_pcbdetach(inp);
2571 	inp->inp_state = INPCB_STATE_DEAD;
2572 	return 0;
2573 }
2574 
2575 static int
udp_disconnect(struct socket * so)2576 udp_disconnect(struct socket *so)
2577 {
2578 	struct inpcb *inp;
2579 
2580 	inp = sotoinpcb(so);
2581 	if (inp == NULL) {
2582 		return EINVAL;
2583 	}
2584 	if (inp->inp_faddr.s_addr == INADDR_ANY) {
2585 		return ENOTCONN;
2586 	}
2587 
2588 	UDP_LOG_CONNECTION_SUMMARY(inp);
2589 
2590 	in_pcbdisconnect(inp);
2591 
2592 	/* reset flow controlled state, just in case */
2593 	inp_reset_fc_state(inp);
2594 
2595 	inp->inp_laddr.s_addr = INADDR_ANY;
2596 	so->so_state &= ~SS_ISCONNECTED;                /* XXX */
2597 	inp->inp_last_outifp = NULL;
2598 #if SKYWALK
2599 	if (NETNS_TOKEN_VALID(&inp->inp_netns_token)) {
2600 		netns_set_ifnet(&inp->inp_netns_token, NULL);
2601 	}
2602 #endif /* SKYWALK */
2603 
2604 	return 0;
2605 }
2606 
2607 static int
udp_disconnectx(struct socket * so,sae_associd_t aid,sae_connid_t cid)2608 udp_disconnectx(struct socket *so, sae_associd_t aid, sae_connid_t cid)
2609 {
2610 #pragma unused(cid)
2611 	if (aid != SAE_ASSOCID_ANY && aid != SAE_ASSOCID_ALL) {
2612 		return EINVAL;
2613 	}
2614 
2615 	return udp_disconnect(so);
2616 }
2617 
2618 static int
udp_send(struct socket * so,int flags,struct mbuf * m,struct sockaddr * addr,struct mbuf * control,struct proc * p)2619 udp_send(struct socket *so, int flags, struct mbuf *m,
2620     struct sockaddr *addr, struct mbuf *control, struct proc *p)
2621 {
2622 #ifndef FLOW_DIVERT
2623 #pragma unused(flags)
2624 #endif /* !(FLOW_DIVERT) */
2625 	struct inpcb *inp;
2626 	int error;
2627 
2628 	inp = sotoinpcb(so);
2629 	if (inp == NULL) {
2630 		if (m != NULL) {
2631 			m_freem(m);
2632 		}
2633 		if (control != NULL) {
2634 			m_freem(control);
2635 		}
2636 		return EINVAL;
2637 	}
2638 
2639 #if NECP
2640 #if FLOW_DIVERT
2641 	if (necp_socket_should_use_flow_divert(inp)) {
2642 		/* Implicit connect */
2643 		return flow_divert_implicit_data_out(so, flags, m, addr,
2644 		           control, p);
2645 	} else {
2646 		so->so_flags1 |= SOF1_FLOW_DIVERT_SKIP;
2647 	}
2648 #endif /* FLOW_DIVERT */
2649 #endif /* NECP */
2650 
2651 	so_update_tx_data_stats(so, 1, m->m_pkthdr.len);
2652 
2653 	in_pcb_check_management_entitled(inp);
2654 	in_pcb_check_ultra_constrained_entitled(inp);
2655 
2656 #if SKYWALK
2657 	sk_protect_t protect = sk_async_transmit_protect();
2658 #endif /* SKYWALK */
2659 	error = udp_output(inp, m, addr, control, p);
2660 #if SKYWALK
2661 	sk_async_transmit_unprotect(protect);
2662 #endif /* SKYWALK */
2663 
2664 	return error;
2665 }
2666 
2667 int
udp_shutdown(struct socket * so)2668 udp_shutdown(struct socket *so)
2669 {
2670 	struct inpcb *inp;
2671 
2672 	inp = sotoinpcb(so);
2673 	if (inp == NULL) {
2674 		return EINVAL;
2675 	}
2676 	socantsendmore(so);
2677 	return 0;
2678 }
2679 
2680 int
udp_lock(struct socket * so,int refcount,void * debug)2681 udp_lock(struct socket *so, int refcount, void *debug)
2682 {
2683 	void *__single lr_saved;
2684 
2685 	if (debug == NULL) {
2686 		lr_saved = __unsafe_forge_single(void *, __builtin_return_address(0));
2687 	} else {
2688 		lr_saved = debug;
2689 	}
2690 
2691 	if (so->so_pcb != NULL) {
2692 		LCK_MTX_ASSERT(&((struct inpcb *)so->so_pcb)->inpcb_mtx,
2693 		    LCK_MTX_ASSERT_NOTOWNED);
2694 		lck_mtx_lock(&((struct inpcb *)so->so_pcb)->inpcb_mtx);
2695 	} else {
2696 		panic("%s: so=%p NO PCB! lr=%p lrh= %s", __func__,
2697 		    so, lr_saved, solockhistory_nr(so));
2698 		/* NOTREACHED */
2699 	}
2700 	if (refcount) {
2701 		so->so_usecount++;
2702 	}
2703 
2704 	so->lock_lr[so->next_lock_lr] = lr_saved;
2705 	so->next_lock_lr = (so->next_lock_lr + 1) % SO_LCKDBG_MAX;
2706 	return 0;
2707 }
2708 
2709 int
udp_unlock(struct socket * so,int refcount,void * debug)2710 udp_unlock(struct socket *so, int refcount, void *debug)
2711 {
2712 	void *__single lr_saved;
2713 
2714 	if (debug == NULL) {
2715 		lr_saved = __unsafe_forge_single(void *, __builtin_return_address(0));
2716 	} else {
2717 		lr_saved = debug;
2718 	}
2719 
2720 	if (refcount) {
2721 		VERIFY(so->so_usecount > 0);
2722 		so->so_usecount--;
2723 	}
2724 	if (so->so_pcb == NULL) {
2725 		panic("%s: so=%p NO PCB! lr=%p lrh= %s", __func__,
2726 		    so, lr_saved, solockhistory_nr(so));
2727 		/* NOTREACHED */
2728 	} else {
2729 		LCK_MTX_ASSERT(&((struct inpcb *)so->so_pcb)->inpcb_mtx,
2730 		    LCK_MTX_ASSERT_OWNED);
2731 		so->unlock_lr[so->next_unlock_lr] = lr_saved;
2732 		so->next_unlock_lr = (so->next_unlock_lr + 1) % SO_LCKDBG_MAX;
2733 		lck_mtx_unlock(&((struct inpcb *)so->so_pcb)->inpcb_mtx);
2734 	}
2735 	return 0;
2736 }
2737 
2738 lck_mtx_t *
udp_getlock(struct socket * so,int flags)2739 udp_getlock(struct socket *so, int flags)
2740 {
2741 #pragma unused(flags)
2742 	struct inpcb *__single inp = sotoinpcb(so);
2743 
2744 	if (so->so_pcb == NULL) {
2745 		panic("%s: so=%p NULL so_pcb lrh= %s", __func__,
2746 		    so, solockhistory_nr(so));
2747 		/* NOTREACHED */
2748 	}
2749 	return &inp->inpcb_mtx;
2750 }
2751 
2752 /*
2753  * UDP garbage collector callback (inpcb_timer_func_t).
2754  *
2755  * Returns > 0 to keep timer active.
2756  */
2757 static void
udp_gc(struct inpcbinfo * ipi)2758 udp_gc(struct inpcbinfo *ipi)
2759 {
2760 	struct inpcb *inp, *inpnxt;
2761 	struct socket *so;
2762 
2763 	if (lck_rw_try_lock_exclusive(&ipi->ipi_lock) == FALSE) {
2764 		if (udp_gc_done == TRUE) {
2765 			udp_gc_done = FALSE;
2766 			/* couldn't get the lock, must lock next time */
2767 			os_atomic_inc(&ipi->ipi_gc_req.intimer_fast, relaxed);
2768 			return;
2769 		}
2770 		lck_rw_lock_exclusive(&ipi->ipi_lock);
2771 	}
2772 
2773 	udp_gc_done = TRUE;
2774 
2775 	for (inp = udb.lh_first; inp != NULL; inp = inpnxt) {
2776 		inpnxt = inp->inp_list.le_next;
2777 
2778 		/*
2779 		 * Skip unless it's STOPUSING; garbage collector will
2780 		 * be triggered by in_pcb_checkstate() upon setting
2781 		 * wantcnt to that value.  If the PCB is already dead,
2782 		 * keep gc active to anticipate wantcnt changing.
2783 		 */
2784 		if (inp->inp_wantcnt != WNT_STOPUSING) {
2785 			continue;
2786 		}
2787 
2788 		/*
2789 		 * Skip if busy, no hurry for cleanup.  Keep gc active
2790 		 * and try the lock again during next round.
2791 		 */
2792 		if (!socket_try_lock(inp->inp_socket)) {
2793 			os_atomic_inc(&ipi->ipi_gc_req.intimer_fast, relaxed);
2794 			continue;
2795 		}
2796 
2797 		/*
2798 		 * Keep gc active unless usecount is 0.
2799 		 */
2800 		so = inp->inp_socket;
2801 		if (so->so_usecount == 0) {
2802 			if (inp->inp_state != INPCB_STATE_DEAD) {
2803 				if (SOCK_CHECK_DOM(so, PF_INET6)) {
2804 					in6_pcbdetach(inp);
2805 				} else {
2806 					in_pcbdetach(inp);
2807 				}
2808 			}
2809 			in_pcbdispose(inp);
2810 		} else {
2811 			socket_unlock(so, 0);
2812 			os_atomic_inc(&ipi->ipi_gc_req.intimer_fast, relaxed);
2813 		}
2814 	}
2815 	lck_rw_done(&ipi->ipi_lock);
2816 }
2817 
2818 static int
2819 udp_getstat SYSCTL_HANDLER_ARGS
2820 {
2821 #pragma unused(oidp, arg1, arg2)
2822 	if (req->oldptr == USER_ADDR_NULL) {
2823 		req->oldlen = (size_t)sizeof(struct udpstat);
2824 	}
2825 
2826 	return SYSCTL_OUT(req, &udpstat, MIN(sizeof(udpstat), req->oldlen));
2827 }
2828 
2829 void
udp_in_cksum_stats(u_int32_t len)2830 udp_in_cksum_stats(u_int32_t len)
2831 {
2832 	udpstat.udps_rcv_swcsum++;
2833 	udpstat.udps_rcv_swcsum_bytes += len;
2834 }
2835 
2836 void
udp_out_cksum_stats(u_int32_t len)2837 udp_out_cksum_stats(u_int32_t len)
2838 {
2839 	udpstat.udps_snd_swcsum++;
2840 	udpstat.udps_snd_swcsum_bytes += len;
2841 }
2842 
2843 void
udp_in6_cksum_stats(u_int32_t len)2844 udp_in6_cksum_stats(u_int32_t len)
2845 {
2846 	udpstat.udps_rcv6_swcsum++;
2847 	udpstat.udps_rcv6_swcsum_bytes += len;
2848 }
2849 
2850 void
udp_out6_cksum_stats(u_int32_t len)2851 udp_out6_cksum_stats(u_int32_t len)
2852 {
2853 	udpstat.udps_snd6_swcsum++;
2854 	udpstat.udps_snd6_swcsum_bytes += len;
2855 }
2856 
2857 /*
2858  * Checksum extended UDP header and data.
2859  */
2860 static int
udp_input_checksum(struct mbuf * m,struct udphdr * uh,int off,int ulen)2861 udp_input_checksum(struct mbuf *m, struct udphdr *uh, int off, int ulen)
2862 {
2863 	ifnet_ref_t ifp = m->m_pkthdr.rcvif;
2864 	struct ip *__single ip = mtod(m, struct ip *);
2865 	struct ipovly *__single ipov = (struct ipovly *)ip;
2866 
2867 	if (uh->uh_sum == 0) {
2868 		udpstat.udps_nosum++;
2869 		return 0;
2870 	}
2871 
2872 	/* ip_stripoptions() must have been called before we get here */
2873 	ASSERT((ip->ip_hl << 2) == sizeof(*ip));
2874 
2875 	if ((hwcksum_rx || (ifp->if_flags & IFF_LOOPBACK) ||
2876 	    (m->m_pkthdr.pkt_flags & PKTF_LOOP)) &&
2877 	    (m->m_pkthdr.csum_flags & CSUM_DATA_VALID)) {
2878 		if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
2879 			uh->uh_sum = m->m_pkthdr.csum_rx_val;
2880 		} else {
2881 			uint32_t sum = m->m_pkthdr.csum_rx_val;
2882 			uint32_t start = m->m_pkthdr.csum_rx_start;
2883 			int32_t trailer = (m_pktlen(m) - (off + ulen));
2884 
2885 			/*
2886 			 * Perform 1's complement adjustment of octets
2887 			 * that got included/excluded in the hardware-
2888 			 * calculated checksum value.  Ignore cases
2889 			 * where the value already includes the entire
2890 			 * IP header span, as the sum for those octets
2891 			 * would already be 0 by the time we get here;
2892 			 * IP has already performed its header checksum
2893 			 * checks.  If we do need to adjust, restore
2894 			 * the original fields in the IP header when
2895 			 * computing the adjustment value.  Also take
2896 			 * care of any trailing bytes and subtract out
2897 			 * their partial sum.
2898 			 */
2899 			ASSERT(trailer >= 0);
2900 			if ((m->m_pkthdr.csum_flags & CSUM_PARTIAL) &&
2901 			    ((start != 0 && start != off) || trailer != 0)) {
2902 				uint32_t swbytes = (uint32_t)trailer;
2903 
2904 				if (start < off) {
2905 					ip->ip_len += sizeof(*ip);
2906 #if BYTE_ORDER != BIG_ENDIAN
2907 					HTONS(ip->ip_len);
2908 					HTONS(ip->ip_off);
2909 #endif /* BYTE_ORDER != BIG_ENDIAN */
2910 				}
2911 				/* callee folds in sum */
2912 				sum = m_adj_sum16(m, start, off, ulen, sum);
2913 				if (off > start) {
2914 					swbytes += (off - start);
2915 				} else {
2916 					swbytes += (start - off);
2917 				}
2918 
2919 				if (start < off) {
2920 #if BYTE_ORDER != BIG_ENDIAN
2921 					NTOHS(ip->ip_off);
2922 					NTOHS(ip->ip_len);
2923 #endif /* BYTE_ORDER != BIG_ENDIAN */
2924 					ip->ip_len -= sizeof(*ip);
2925 				}
2926 
2927 				if (swbytes != 0) {
2928 					udp_in_cksum_stats(swbytes);
2929 				}
2930 				if (trailer != 0) {
2931 					m_adj(m, -trailer);
2932 				}
2933 			}
2934 
2935 			/* callee folds in sum */
2936 			uh->uh_sum = in_pseudo(ip->ip_src.s_addr,
2937 			    ip->ip_dst.s_addr, sum + htonl(ulen + IPPROTO_UDP));
2938 		}
2939 		uh->uh_sum ^= 0xffff;
2940 	} else {
2941 		uint16_t ip_sum;
2942 		char b[9];
2943 
2944 		bcopy(ipov->ih_x1, b, sizeof(ipov->ih_x1));
2945 		bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
2946 		ip_sum = ipov->ih_len;
2947 		ipov->ih_len = uh->uh_ulen;
2948 		uh->uh_sum = in_cksum(m, ulen + sizeof(struct ip));
2949 		bcopy(b, ipov->ih_x1, sizeof(ipov->ih_x1));
2950 		ipov->ih_len = ip_sum;
2951 
2952 		udp_in_cksum_stats(ulen);
2953 	}
2954 
2955 	if (uh->uh_sum != 0) {
2956 		udpstat.udps_badsum++;
2957 		IF_UDP_STATINC(ifp, badchksum);
2958 		return -1;
2959 	}
2960 
2961 	return 0;
2962 }
2963 
2964 void
udp_fill_keepalive_offload_frames(ifnet_t ifp,struct ifnet_keepalive_offload_frame * __counted_by (frames_array_count)frames_array,u_int32_t frames_array_count,size_t frame_data_offset,u_int32_t * used_frames_count)2965 udp_fill_keepalive_offload_frames(ifnet_t ifp,
2966     struct ifnet_keepalive_offload_frame *__counted_by(frames_array_count) frames_array,
2967     u_int32_t frames_array_count, size_t frame_data_offset,
2968     u_int32_t *used_frames_count)
2969 {
2970 	struct inpcb *inp;
2971 	inp_gen_t gencnt;
2972 	u_int32_t frame_index = *used_frames_count;
2973 
2974 	if (ifp == NULL || frames_array == NULL ||
2975 	    frames_array_count == 0 ||
2976 	    frame_index >= frames_array_count ||
2977 	    frame_data_offset >= IFNET_KEEPALIVE_OFFLOAD_FRAME_DATA_SIZE) {
2978 		return;
2979 	}
2980 
2981 	lck_rw_lock_shared(&udbinfo.ipi_lock);
2982 	gencnt = udbinfo.ipi_gencnt;
2983 	LIST_FOREACH(inp, udbinfo.ipi_listhead, inp_list) {
2984 		struct socket *so;
2985 		u_int8_t *data;
2986 		struct ifnet_keepalive_offload_frame *frame;
2987 		mbuf_ref_t m = NULL;
2988 
2989 		if (frame_index >= frames_array_count) {
2990 			break;
2991 		}
2992 
2993 		if (inp->inp_gencnt > gencnt ||
2994 		    inp->inp_state == INPCB_STATE_DEAD) {
2995 			continue;
2996 		}
2997 
2998 		if ((so = inp->inp_socket) == NULL ||
2999 		    (so->so_state & SS_DEFUNCT)) {
3000 			continue;
3001 		}
3002 		/*
3003 		 * check for keepalive offload flag without socket
3004 		 * lock to avoid a deadlock
3005 		 */
3006 		if (!(inp->inp_flags2 & INP2_KEEPALIVE_OFFLOAD)) {
3007 			continue;
3008 		}
3009 
3010 		udp_lock(so, 1, 0);
3011 		if (!(inp->inp_vflag & (INP_IPV4 | INP_IPV6))) {
3012 			udp_unlock(so, 1, 0);
3013 			continue;
3014 		}
3015 		if ((inp->inp_vflag & INP_IPV4) &&
3016 		    (inp->inp_laddr.s_addr == INADDR_ANY ||
3017 		    inp->inp_faddr.s_addr == INADDR_ANY)) {
3018 			udp_unlock(so, 1, 0);
3019 			continue;
3020 		}
3021 		if ((inp->inp_vflag & INP_IPV6) &&
3022 		    (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr) ||
3023 		    IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr))) {
3024 			udp_unlock(so, 1, 0);
3025 			continue;
3026 		}
3027 		if (inp->inp_lport == 0 || inp->inp_fport == 0) {
3028 			udp_unlock(so, 1, 0);
3029 			continue;
3030 		}
3031 		if (inp->inp_last_outifp == NULL ||
3032 		    inp->inp_last_outifp->if_index != ifp->if_index) {
3033 			udp_unlock(so, 1, 0);
3034 			continue;
3035 		}
3036 		if ((inp->inp_vflag & INP_IPV4)) {
3037 			if ((frame_data_offset + sizeof(struct udpiphdr) +
3038 			    inp->inp_keepalive_datalen) >
3039 			    IFNET_KEEPALIVE_OFFLOAD_FRAME_DATA_SIZE) {
3040 				udp_unlock(so, 1, 0);
3041 				continue;
3042 			}
3043 			if ((sizeof(struct udpiphdr) +
3044 			    inp->inp_keepalive_datalen) > _MHLEN) {
3045 				udp_unlock(so, 1, 0);
3046 				continue;
3047 			}
3048 		} else {
3049 			if ((frame_data_offset + sizeof(struct ip6_hdr) +
3050 			    sizeof(struct udphdr) +
3051 			    inp->inp_keepalive_datalen) >
3052 			    IFNET_KEEPALIVE_OFFLOAD_FRAME_DATA_SIZE) {
3053 				udp_unlock(so, 1, 0);
3054 				continue;
3055 			}
3056 			if ((sizeof(struct ip6_hdr) + sizeof(struct udphdr) +
3057 			    inp->inp_keepalive_datalen) > _MHLEN) {
3058 				udp_unlock(so, 1, 0);
3059 				continue;
3060 			}
3061 		}
3062 		MGETHDR(m, M_WAIT, MT_HEADER);
3063 		if (m == NULL) {
3064 			udp_unlock(so, 1, 0);
3065 			continue;
3066 		}
3067 		/*
3068 		 * This inp has all the information that is needed to
3069 		 * generate an offload frame.
3070 		 */
3071 		if (inp->inp_vflag & INP_IPV4) {
3072 			struct ip *ip;
3073 			struct udphdr *udp;
3074 
3075 			frame = &frames_array[frame_index];
3076 			frame->length = (uint8_t)(frame_data_offset +
3077 			    sizeof(struct udpiphdr) +
3078 			    inp->inp_keepalive_datalen);
3079 			frame->ether_type =
3080 			    IFNET_KEEPALIVE_OFFLOAD_FRAME_ETHERTYPE_IPV4;
3081 			frame->interval = inp->inp_keepalive_interval;
3082 			switch (inp->inp_keepalive_type) {
3083 			case UDP_KEEPALIVE_OFFLOAD_TYPE_AIRPLAY:
3084 				frame->type =
3085 				    IFNET_KEEPALIVE_OFFLOAD_FRAME_AIRPLAY;
3086 				break;
3087 			default:
3088 				break;
3089 			}
3090 			data = mtod(m, u_int8_t *);
3091 			bzero(data, sizeof(struct udpiphdr));
3092 			ip = (__typeof__(ip))(void *)data;
3093 			udp = (__typeof__(udp))(void *) (data +
3094 			    sizeof(struct ip));
3095 			m->m_len = sizeof(struct udpiphdr);
3096 			data = data + sizeof(struct udpiphdr);
3097 			if (inp->inp_keepalive_datalen > 0 &&
3098 			    inp->inp_keepalive_data != NULL) {
3099 				bcopy(inp->inp_keepalive_data, data,
3100 				    inp->inp_keepalive_datalen);
3101 				m->m_len += inp->inp_keepalive_datalen;
3102 			}
3103 			m->m_pkthdr.len = m->m_len;
3104 
3105 			ip->ip_v = IPVERSION;
3106 			ip->ip_hl = (sizeof(struct ip) >> 2);
3107 			ip->ip_p = IPPROTO_UDP;
3108 			ip->ip_len = htons(sizeof(struct udpiphdr) +
3109 			    (u_short)inp->inp_keepalive_datalen);
3110 			ip->ip_ttl = inp->inp_ip_ttl;
3111 			ip->ip_tos |= (inp->inp_ip_tos & ~IPTOS_ECN_MASK);
3112 			ip->ip_src = inp->inp_laddr;
3113 			ip->ip_dst = inp->inp_faddr;
3114 			ip->ip_sum = in_cksum_hdr_opt(ip);
3115 
3116 			udp->uh_sport = inp->inp_lport;
3117 			udp->uh_dport = inp->inp_fport;
3118 			udp->uh_ulen = htons(sizeof(struct udphdr) +
3119 			    (u_short)inp->inp_keepalive_datalen);
3120 
3121 			if (!(inp->inp_flags & INP_UDP_NOCKSUM)) {
3122 				udp->uh_sum = in_pseudo(ip->ip_src.s_addr,
3123 				    ip->ip_dst.s_addr,
3124 				    htons(sizeof(struct udphdr) +
3125 				    (u_short)inp->inp_keepalive_datalen +
3126 				    IPPROTO_UDP));
3127 				m->m_pkthdr.csum_flags =
3128 				    (CSUM_UDP | CSUM_ZERO_INVERT);
3129 				m->m_pkthdr.csum_data = offsetof(struct udphdr,
3130 				    uh_sum);
3131 			}
3132 			m->m_pkthdr.pkt_proto = IPPROTO_UDP;
3133 			in_delayed_cksum(m);
3134 			bcopy(m_mtod_current(m), frame->data + frame_data_offset,
3135 			    m->m_len);
3136 		} else {
3137 			struct ip6_hdr *ip6;
3138 			struct udphdr *udp6;
3139 
3140 			VERIFY(inp->inp_vflag & INP_IPV6);
3141 			frame = &frames_array[frame_index];
3142 			frame->length = (uint8_t)(frame_data_offset +
3143 			    sizeof(struct ip6_hdr) +
3144 			    sizeof(struct udphdr) +
3145 			    inp->inp_keepalive_datalen);
3146 			frame->ether_type =
3147 			    IFNET_KEEPALIVE_OFFLOAD_FRAME_ETHERTYPE_IPV6;
3148 			frame->interval = inp->inp_keepalive_interval;
3149 			switch (inp->inp_keepalive_type) {
3150 			case UDP_KEEPALIVE_OFFLOAD_TYPE_AIRPLAY:
3151 				frame->type =
3152 				    IFNET_KEEPALIVE_OFFLOAD_FRAME_AIRPLAY;
3153 				break;
3154 			default:
3155 				break;
3156 			}
3157 			data = mtod(m, u_int8_t *);
3158 			bzero(data, sizeof(struct ip6_hdr) + sizeof(struct udphdr));
3159 			ip6 = (__typeof__(ip6))(void *)data;
3160 			udp6 = (__typeof__(udp6))(void *)(data +
3161 			    sizeof(struct ip6_hdr));
3162 			m->m_len = sizeof(struct ip6_hdr) +
3163 			    sizeof(struct udphdr);
3164 			data = data + (sizeof(struct ip6_hdr) +
3165 			    sizeof(struct udphdr));
3166 			if (inp->inp_keepalive_datalen > 0 &&
3167 			    inp->inp_keepalive_data != NULL) {
3168 				bcopy(inp->inp_keepalive_data, data,
3169 				    inp->inp_keepalive_datalen);
3170 				m->m_len += inp->inp_keepalive_datalen;
3171 			}
3172 			m->m_pkthdr.len = m->m_len;
3173 			ip6->ip6_flow = inp->inp_flow & IPV6_FLOWINFO_MASK;
3174 			ip6->ip6_flow = ip6->ip6_flow & ~IPV6_FLOW_ECN_MASK;
3175 			ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
3176 			ip6->ip6_vfc |= IPV6_VERSION;
3177 			ip6->ip6_nxt = IPPROTO_UDP;
3178 			ip6->ip6_hlim = (uint8_t)ip6_defhlim;
3179 			ip6->ip6_plen = htons(sizeof(struct udphdr) +
3180 			    (u_short)inp->inp_keepalive_datalen);
3181 			ip6->ip6_src = inp->in6p_laddr;
3182 			if (IN6_IS_SCOPE_EMBED(&ip6->ip6_src)) {
3183 				ip6->ip6_src.s6_addr16[1] = 0;
3184 			}
3185 
3186 			ip6->ip6_dst = inp->in6p_faddr;
3187 			if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst)) {
3188 				ip6->ip6_dst.s6_addr16[1] = 0;
3189 			}
3190 
3191 			udp6->uh_sport = inp->in6p_lport;
3192 			udp6->uh_dport = inp->in6p_fport;
3193 			udp6->uh_ulen = htons(sizeof(struct udphdr) +
3194 			    (u_short)inp->inp_keepalive_datalen);
3195 			if (!(inp->inp_flags & INP_UDP_NOCKSUM)) {
3196 				udp6->uh_sum = in6_pseudo(&ip6->ip6_src,
3197 				    &ip6->ip6_dst,
3198 				    htonl(sizeof(struct udphdr) +
3199 				    (u_short)inp->inp_keepalive_datalen +
3200 				    IPPROTO_UDP));
3201 				m->m_pkthdr.csum_flags =
3202 				    (CSUM_UDPIPV6 | CSUM_ZERO_INVERT);
3203 				m->m_pkthdr.csum_data = offsetof(struct udphdr,
3204 				    uh_sum);
3205 			}
3206 			m->m_pkthdr.pkt_proto = IPPROTO_UDP;
3207 			in6_delayed_cksum(m);
3208 			bcopy(m_mtod_current(m), frame->data + frame_data_offset, m->m_len);
3209 		}
3210 		if (m != NULL) {
3211 			m_freem(m);
3212 			m = NULL;
3213 		}
3214 		frame_index++;
3215 		udp_unlock(so, 1, 0);
3216 	}
3217 	lck_rw_done(&udbinfo.ipi_lock);
3218 	*used_frames_count = frame_index;
3219 }
3220 
3221 int
udp_defunct(struct socket * so)3222 udp_defunct(struct socket *so)
3223 {
3224 	struct ip_moptions *__single imo;
3225 	struct inpcb *__single inp;
3226 
3227 	inp = sotoinpcb(so);
3228 	if (inp == NULL) {
3229 		return EINVAL;
3230 	}
3231 
3232 	imo = inp->inp_moptions;
3233 	if (imo != NULL) {
3234 		struct proc *p = current_proc();
3235 
3236 		SODEFUNCTLOG("%s[%d, %s]: defuncting so 0x%llu drop multicast memberships",
3237 		    __func__, proc_pid(p), proc_best_name(p),
3238 		    so->so_gencnt);
3239 
3240 		inp->inp_moptions = NULL;
3241 
3242 		IMO_REMREF(imo);
3243 	}
3244 
3245 	return 0;
3246 }
3247 
3248 static bool
udp_port_unreach_rlc_common(struct in_endpoints * flow)3249 udp_port_unreach_rlc_common(struct in_endpoints *flow)
3250 {
3251 	bool should_throttle = false;
3252 	uint32_t last_udp_port_unreach_rlc_cnt = 0;
3253 	in_port_t last_dport = 0;
3254 	in_port_t last_sport = 0;
3255 	struct timeval ts;
3256 	uint32_t now;
3257 
3258 	microuptime(&ts);
3259 	now = (uint32_t)ts.tv_sec * 1000 + ts.tv_usec / 1000;
3260 
3261 	lck_mtx_lock(udp_port_unreach_rlc_mtx);
3262 	if (__improbable((udp_port_unreach_rlc_use_ts == false || now - udp_port_unreach_rlc_ts < udp_port_unreach_rlc_bucket_ms) &&
3263 	    bcmp(flow, &udp_port_unreach_rlc_state, sizeof(struct in_endpoints)) == 0)) {
3264 		/*
3265 		 * The rst rlc state hasn't changed changed, we should throttle.
3266 		 */
3267 		should_throttle = true;
3268 		udp_port_unreach_rlc_cnt++;
3269 		udpstat.udps_port_unreach_dup_suppressed++;
3270 	} else {
3271 		should_throttle = false;
3272 		last_udp_port_unreach_rlc_cnt = udp_port_unreach_rlc_cnt;
3273 		last_sport = udp_port_unreach_rlc_state.ie_lport;
3274 		last_dport = udp_port_unreach_rlc_state.ie_fport;
3275 		bcopy(flow, &udp_port_unreach_rlc_state, sizeof(struct in_endpoints));
3276 		udp_port_unreach_rlc_cnt = 0;
3277 		udp_port_unreach_rlc_ts = now;
3278 		udpstat.udps_port_unreach_not_suppressed++;
3279 	}
3280 	lck_mtx_unlock(udp_port_unreach_rlc_mtx);
3281 
3282 	if (udp_port_unreach_rlc_verbose) {
3283 		if (last_udp_port_unreach_rlc_cnt != 0) {
3284 			os_log(OS_LOG_DEFAULT, "UDP port unreachable RLC compression: compressed %u ICMP packets [%hu:%hu]",
3285 			    last_udp_port_unreach_rlc_cnt, ntohs(last_sport), ntohs(last_dport));
3286 		}
3287 	}
3288 
3289 	return should_throttle;
3290 }
3291 
3292 static bool
udp_port_unreach_rlc_compress(struct in_addr src_addr,in_port_t src_port,struct in_addr dst_addr,in_port_t dst_port)3293 udp_port_unreach_rlc_compress(struct in_addr src_addr, in_port_t src_port,
3294     struct in_addr dst_addr, in_port_t dst_port)
3295 {
3296 	struct in_endpoints flow;
3297 
3298 	if (udp_port_unreach_rlc_enable == 0) {
3299 		return false;
3300 	}
3301 
3302 	bzero(&flow, sizeof(struct in_endpoints));
3303 
3304 	flow.ie_lport = src_port;
3305 	flow.ie_fport = dst_port;
3306 	bcopy(&src_addr, &flow.ie_laddr, sizeof(struct in_addr));
3307 	bcopy(&dst_addr, &flow.ie_faddr, sizeof(struct in_addr));
3308 
3309 	return udp_port_unreach_rlc_common(&flow);
3310 }
3311 
3312 bool
udp6_port_unreach_rlc_compress(struct in6_addr * src_addr,in_port_t src_port,struct in6_addr * dst_addr,in_port_t dst_port)3313 udp6_port_unreach_rlc_compress(struct in6_addr *src_addr, in_port_t src_port,
3314     struct in6_addr *dst_addr, in_port_t dst_port)
3315 {
3316 	struct in_endpoints flow;
3317 
3318 	if (udp_port_unreach_rlc_enable == 0) {
3319 		return false;
3320 	}
3321 
3322 	bzero(&flow, sizeof(struct in_endpoints));
3323 
3324 	flow.ie_lport = src_port;
3325 	flow.ie_fport = dst_port;
3326 	bcopy(src_addr, &flow.ie6_laddr, sizeof(struct in6_addr));
3327 	bcopy(dst_addr, &flow.ie6_faddr, sizeof(struct in6_addr));
3328 
3329 	return udp_port_unreach_rlc_common(&flow);
3330 }
3331