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