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 inp_enter_bind_in_progress(so);
1771
1772 /*
1773 * In case we don't have a local port set, go through
1774 * the full connect. We don't have a local port yet
1775 * (i.e., we can't be looked up), so it's not an issue
1776 * if the input runs at the same time we do this.
1777 */
1778 /* if we have a source address specified, use that */
1779 if (pi_laddr.s_addr != INADDR_ANY) {
1780 inp->inp_laddr = pi_laddr;
1781 }
1782 /*
1783 * If a scope is specified, use it. Scope from
1784 * IP_PKTINFO takes precendence over the the scope
1785 * set via INP_BOUND_IF.
1786 */
1787 error = in_pcbconnect(inp, addr, p, ipoa.ipoa_boundif,
1788 &outif);
1789
1790 inp_exit_bind_in_progress(so);
1791
1792 if (error) {
1793 goto release;
1794 }
1795
1796 laddr = inp->inp_laddr;
1797 lport = inp->inp_lport;
1798 faddr = inp->inp_faddr;
1799 fport = inp->inp_fport;
1800 udp_dodisconnect = 1;
1801
1802 /* synch up in case in_pcbladdr() overrides */
1803 if (outif != NULL && ipoa.ipoa_boundif != IFSCOPE_NONE) {
1804 ipoa.ipoa_boundif = outif->if_index;
1805 }
1806 } else {
1807 /*
1808 * Fast path case
1809 *
1810 * We have a full address and a local port; use those
1811 * info to build the packet without changing the pcb
1812 * and interfering with the input path. See 3851370.
1813 *
1814 * Scope from IP_PKTINFO takes precendence over the
1815 * the scope set via INP_BOUND_IF.
1816 */
1817 if (laddr.s_addr == INADDR_ANY) {
1818 if ((error = in_pcbladdr(inp, addr, &laddr,
1819 ipoa.ipoa_boundif, &outif, 0)) != 0) {
1820 goto release;
1821 }
1822 /*
1823 * from pcbconnect: remember we don't
1824 * care about src addr.
1825 */
1826 inp->inp_flags |= INP_INADDR_ANY;
1827
1828 /* synch up in case in_pcbladdr() overrides */
1829 if (outif != NULL &&
1830 ipoa.ipoa_boundif != IFSCOPE_NONE) {
1831 ipoa.ipoa_boundif = outif->if_index;
1832 }
1833 }
1834
1835 faddr = sin->sin_addr;
1836 fport = sin->sin_port;
1837 }
1838 } else {
1839 if (faddr.s_addr == INADDR_ANY) {
1840 error = ENOTCONN;
1841 goto release;
1842 }
1843 }
1844
1845 if (inp->inp_flowhash == 0) {
1846 inp_calc_flowhash(inp);
1847 ASSERT(inp->inp_flowhash != 0);
1848 }
1849
1850 if (fport == htons(53) && !(so->so_flags1 & SOF1_DNS_COUNTED)) {
1851 so->so_flags1 |= SOF1_DNS_COUNTED;
1852 INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_inet_dgram_dns);
1853 }
1854
1855 /*
1856 * Calculate data length and get a mbuf
1857 * for UDP and IP headers.
1858 */
1859 M_PREPEND(m, sizeof(struct udpiphdr), M_DONTWAIT, 1);
1860 if (m == 0) {
1861 error = ENOBUFS;
1862 goto abort;
1863 }
1864
1865 /*
1866 * Fill in mbuf with extended UDP header
1867 * and addresses and length put into network format.
1868 */
1869 ui = mtod(m, struct udpiphdr *);
1870 bzero(ui->ui_x1, sizeof(ui->ui_x1)); /* XXX still needed? */
1871 ui->ui_pr = IPPROTO_UDP;
1872 ui->ui_src = laddr;
1873 ui->ui_dst = faddr;
1874 ui->ui_sport = lport;
1875 ui->ui_dport = fport;
1876 ui->ui_ulen = htons((u_short)len + sizeof(struct udphdr));
1877
1878 /*
1879 * Set the Don't Fragment bit in the IP header.
1880 */
1881 if (inp->inp_flags2 & INP2_DONTFRAG) {
1882 struct ip *ip;
1883
1884 ip = (struct ip *)&ui->ui_i;
1885 ip->ip_off |= IP_DF;
1886 }
1887
1888 /*
1889 * Set up checksum to pseudo header checksum and output datagram.
1890 *
1891 * Treat flows to be CLAT46'd as IPv6 flow and compute checksum
1892 * no matter what, as IPv6 mandates checksum for UDP.
1893 *
1894 * Here we only compute the one's complement sum of the pseudo header.
1895 * The payload computation and final complement is delayed to much later
1896 * in IP processing to decide if remaining computation needs to be done
1897 * through offload.
1898 *
1899 * That is communicated by setting CSUM_UDP in csum_flags.
1900 * The offset of checksum from the start of ULP header is communicated
1901 * through csum_data.
1902 *
1903 * Note since this already contains the pseudo checksum header, any
1904 * later operation at IP layer that modify the values used here must
1905 * update the checksum as well (for example NAT etc).
1906 */
1907 if ((inp->inp_flags2 & INP2_CLAT46_FLOW) ||
1908 (udpcksum && !(inp->inp_flags & INP_UDP_NOCKSUM))) {
1909 ui->ui_sum = in_pseudo(ui->ui_src.s_addr, ui->ui_dst.s_addr,
1910 htons((u_short)len + sizeof(struct udphdr) + IPPROTO_UDP));
1911 m->m_pkthdr.csum_flags = (CSUM_UDP | CSUM_ZERO_INVERT);
1912 m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
1913 } else {
1914 ui->ui_sum = 0;
1915 }
1916 ((struct ip *)ui)->ip_len = (uint16_t)(sizeof(struct udpiphdr) + len);
1917 ((struct ip *)ui)->ip_ttl = inp->inp_ip_ttl; /* XXX */
1918 if (tos != IPTOS_UNSPEC) {
1919 ((struct ip *)ui)->ip_tos = (uint8_t)(tos & IPTOS_MASK);
1920 } else {
1921 ((struct ip *)ui)->ip_tos = inp->inp_ip_tos; /* XXX */
1922 }
1923 udpstat.udps_opackets++;
1924
1925 KERNEL_DEBUG(DBG_LAYER_OUT_END, ui->ui_dport, ui->ui_sport,
1926 ui->ui_src.s_addr, ui->ui_dst.s_addr, ui->ui_ulen);
1927
1928 #if NECP
1929 {
1930 necp_kernel_policy_id policy_id;
1931 necp_kernel_policy_id skip_policy_id;
1932 u_int32_t route_rule_id;
1933 u_int32_t pass_flags;
1934
1935 /*
1936 * We need a route to perform NECP route rule checks
1937 */
1938 if (net_qos_policy_restricted != 0 &&
1939 ROUTE_UNUSABLE(&inp->inp_route)) {
1940 struct sockaddr_in to;
1941 struct sockaddr_in from;
1942
1943 ROUTE_RELEASE(&inp->inp_route);
1944
1945 SOCKADDR_ZERO(&from, sizeof(struct sockaddr_in));
1946 from.sin_family = AF_INET;
1947 from.sin_len = sizeof(struct sockaddr_in);
1948 from.sin_addr = laddr;
1949
1950 SOCKADDR_ZERO(&to, sizeof(struct sockaddr_in));
1951 to.sin_family = AF_INET;
1952 to.sin_len = sizeof(struct sockaddr_in);
1953 to.sin_addr = faddr;
1954
1955 inp->inp_route.ro_dst.sa_family = AF_INET;
1956 inp->inp_route.ro_dst.sa_len = sizeof(struct sockaddr_in);
1957 SIN(&inp->inp_route.ro_dst)->sin_addr = faddr;
1958
1959 rtalloc_scoped(&inp->inp_route, ipoa.ipoa_boundif);
1960
1961 inp_update_necp_policy(inp, SA(&from),
1962 SA(&to), ipoa.ipoa_boundif);
1963 inp->inp_policyresult.results.qos_marking_gencount = 0;
1964 }
1965
1966 if (!necp_socket_is_allowed_to_send_recv_v4(inp, lport, fport,
1967 &laddr, &faddr, NULL, 0, &policy_id, &route_rule_id, &skip_policy_id, &pass_flags)) {
1968 error = EHOSTUNREACH;
1969 goto abort;
1970 }
1971
1972 necp_mark_packet_from_socket(m, inp, policy_id, route_rule_id, skip_policy_id, pass_flags);
1973
1974 if (net_qos_policy_restricted != 0) {
1975 necp_socket_update_qos_marking(inp, inp->inp_route.ro_rt, route_rule_id);
1976 }
1977 }
1978 #endif /* NECP */
1979 if ((so->so_flags1 & SOF1_QOSMARKING_ALLOWED)) {
1980 ipoa.ipoa_flags |= IPOAF_QOSMARKING_ALLOWED;
1981 }
1982 if (check_qos_marking_again) {
1983 ipoa.ipoa_flags |= IPOAF_REDO_QOSMARKING_POLICY;
1984 }
1985 ipoa.qos_marking_gencount = inp->inp_policyresult.results.qos_marking_gencount;
1986
1987 #if IPSEC
1988 if (inp->inp_sp != NULL && ipsec_setsocket(m, inp->inp_socket) != 0) {
1989 error = ENOBUFS;
1990 goto abort;
1991 }
1992 #endif /* IPSEC */
1993
1994 inpopts = inp->inp_options;
1995 #if CONTENT_FILTER
1996 if (cfil_tag && (inp->inp_socket->so_options != cfil_so_options)) {
1997 soopts |= (cfil_so_options & (SO_DONTROUTE | SO_BROADCAST));
1998 } else
1999 #endif
2000 soopts |= (inp->inp_socket->so_options & (SO_DONTROUTE | SO_BROADCAST));
2001
2002 mopts = inp->inp_moptions;
2003 if (mopts != NULL) {
2004 IMO_LOCK(mopts);
2005 IMO_ADDREF_LOCKED(mopts);
2006 if (IN_MULTICAST(ntohl(ui->ui_dst.s_addr)) &&
2007 mopts->imo_multicast_ifp != NULL) {
2008 /* no reference needed */
2009 inp->inp_last_outifp = mopts->imo_multicast_ifp;
2010 #if SKYWALK
2011 if (NETNS_TOKEN_VALID(&inp->inp_netns_token)) {
2012 netns_set_ifnet(&inp->inp_netns_token,
2013 inp->inp_last_outifp);
2014 }
2015 #endif /* SKYWALK */
2016 }
2017 IMO_UNLOCK(mopts);
2018 }
2019
2020 /* Copy the cached route and take an extra reference */
2021 inp_route_copyout(inp, &ro);
2022
2023 set_packet_service_class(m, so, sotc, 0);
2024 m->m_pkthdr.pkt_flowsrc = FLOWSRC_INPCB;
2025 m->m_pkthdr.pkt_flowid = inp->inp_flowhash;
2026 m->m_pkthdr.pkt_proto = IPPROTO_UDP;
2027 m->m_pkthdr.pkt_flags |= (PKTF_FLOW_ID | PKTF_FLOW_LOCALSRC);
2028 if (flowadv) {
2029 m->m_pkthdr.pkt_flags |= PKTF_FLOW_ADV;
2030 }
2031 m->m_pkthdr.tx_udp_pid = so->last_pid;
2032 if (so->so_flags & SOF_DELEGATED) {
2033 m->m_pkthdr.tx_udp_e_pid = so->e_pid;
2034 } else {
2035 m->m_pkthdr.tx_udp_e_pid = 0;
2036 }
2037 #if (DEBUG || DEVELOPMENT)
2038 if (so->so_flags & SOF_MARK_WAKE_PKT) {
2039 so->so_flags &= ~SOF_MARK_WAKE_PKT;
2040 m->m_pkthdr.pkt_flags |= PKTF_WAKE_PKT;
2041 }
2042 #endif /* (DEBUG || DEVELOPMENT) */
2043
2044 m_add_crumb(m, PKT_CRUMB_UDP_OUTPUT);
2045
2046 if (ipoa.ipoa_boundif != IFSCOPE_NONE) {
2047 ipoa.ipoa_flags |= IPOAF_BOUND_IF;
2048 }
2049
2050 if (laddr.s_addr != INADDR_ANY) {
2051 ipoa.ipoa_flags |= IPOAF_BOUND_SRCADDR;
2052 }
2053
2054 socket_unlock(so, 0);
2055 error = ip_output(m, inpopts, &ro, soopts, mopts, &ipoa);
2056 m = NULL;
2057 socket_lock(so, 0);
2058 if (mopts != NULL) {
2059 IMO_REMREF(mopts);
2060 }
2061
2062 if (check_qos_marking_again) {
2063 inp->inp_policyresult.results.qos_marking_gencount = ipoa.qos_marking_gencount;
2064
2065 if (ipoa.ipoa_flags & IPOAF_QOSMARKING_ALLOWED) {
2066 inp->inp_socket->so_flags1 |= SOF1_QOSMARKING_ALLOWED;
2067 } else {
2068 inp->inp_socket->so_flags1 &= ~SOF1_QOSMARKING_ALLOWED;
2069 }
2070 }
2071
2072 if (error == 0 && nstat_collect) {
2073 stats_functional_type ifnet_count_type = stats_functional_type_none;
2074
2075 if (ro.ro_rt != NULL) {
2076 ifnet_count_type = IFNET_COUNT_TYPE(ro.ro_rt->rt_ifp);
2077 }
2078 INP_ADD_STAT(inp, ifnet_count_type, txpackets, 1);
2079 INP_ADD_STAT(inp, ifnet_count_type, txbytes, len);
2080 inp_set_activity_bitmap(inp);
2081 }
2082
2083 if (flowadv && (adv->code == FADV_FLOW_CONTROLLED ||
2084 adv->code == FADV_SUSPENDED)) {
2085 /*
2086 * return a hint to the application that
2087 * the packet has been dropped
2088 */
2089 error = ENOBUFS;
2090 inp_set_fc_state(inp, adv->code);
2091 }
2092
2093 /* Synchronize PCB cached route */
2094 inp_route_copyin(inp, &ro);
2095
2096 if (inp->inp_route.ro_rt != NULL) {
2097 if (IS_LOCALNET_ROUTE(inp->inp_route.ro_rt)) {
2098 inp->inp_flags2 |= INP2_LAST_ROUTE_LOCAL;
2099 } else {
2100 inp->inp_flags2 &= ~INP2_LAST_ROUTE_LOCAL;
2101 }
2102 }
2103
2104 abort:
2105 if (udp_dodisconnect) {
2106 /* Always discard the cached route for unconnected socket */
2107 ROUTE_RELEASE(&inp->inp_route);
2108 in_pcbdisconnect(inp);
2109 inp->inp_laddr = origladdr; /* XXX rehash? */
2110 /* no reference needed */
2111 inp->inp_last_outifp = origoutifp;
2112 #if SKYWALK
2113 if (NETNS_TOKEN_VALID(&inp->inp_netns_token)) {
2114 netns_set_ifnet(&inp->inp_netns_token,
2115 inp->inp_last_outifp);
2116 }
2117 #endif /* SKYWALK */
2118 } else if (inp->inp_route.ro_rt != NULL) {
2119 struct rtentry *rt = inp->inp_route.ro_rt;
2120 struct ifnet *outifp;
2121
2122 if (rt->rt_flags & (RTF_MULTICAST | RTF_BROADCAST)) {
2123 rt = NULL; /* unusable */
2124 }
2125 #if CONTENT_FILTER
2126 /*
2127 * Discard temporary route for cfil case
2128 */
2129 if (cfil_faddr_use) {
2130 rt = NULL; /* unusable */
2131 }
2132 #endif
2133
2134 /*
2135 * Always discard if it is a multicast or broadcast route.
2136 */
2137 if (rt == NULL) {
2138 ROUTE_RELEASE(&inp->inp_route);
2139 }
2140
2141 /*
2142 * If the destination route is unicast, update outifp with
2143 * that of the route interface used by IP.
2144 */
2145 if (rt != NULL &&
2146 (outifp = rt->rt_ifp) != inp->inp_last_outifp) {
2147 inp->inp_last_outifp = outifp; /* no reference needed */
2148 #if SKYWALK
2149 if (NETNS_TOKEN_VALID(&inp->inp_netns_token)) {
2150 netns_set_ifnet(&inp->inp_netns_token,
2151 inp->inp_last_outifp);
2152 }
2153 #endif /* SKYWALK */
2154
2155 so->so_pktheadroom = (uint16_t)P2ROUNDUP(
2156 sizeof(struct udphdr) +
2157 sizeof(struct ip) +
2158 ifnet_hdrlen(outifp) +
2159 ifnet_mbuf_packetpreamblelen(outifp),
2160 sizeof(u_int32_t));
2161 }
2162 } else {
2163 ROUTE_RELEASE(&inp->inp_route);
2164 }
2165
2166 /*
2167 * If output interface was cellular/expensive, and this socket is
2168 * denied access to it, generate an event.
2169 */
2170 if (error != 0 && (ipoa.ipoa_flags & IPOAF_R_IFDENIED) &&
2171 (INP_NO_CELLULAR(inp) || INP_NO_EXPENSIVE(inp) || INP_NO_CONSTRAINED(inp))) {
2172 soevent(so, (SO_FILT_HINT_LOCKED | SO_FILT_HINT_IFDENIED));
2173 }
2174
2175 release:
2176 KERNEL_DEBUG(DBG_FNC_UDP_OUTPUT | DBG_FUNC_END, error, 0, 0, 0, 0);
2177
2178 if (m != NULL) {
2179 m_freem(m);
2180 }
2181
2182 if (outif != NULL) {
2183 ifnet_release(outif);
2184 }
2185
2186 #if CONTENT_FILTER
2187 if (cfil_tag) {
2188 m_tag_free(cfil_tag);
2189 }
2190 #endif
2191 if (sndinprog_cnt_used) {
2192 VERIFY(inp->inp_sndinprog_cnt > 0);
2193 if (--inp->inp_sndinprog_cnt == 0) {
2194 inp->inp_flags &= ~(INP_FC_FEEDBACK);
2195 if (inp->inp_sndingprog_waiters > 0) {
2196 wakeup(&inp->inp_sndinprog_cnt);
2197 }
2198 }
2199 sndinprog_cnt_used = false;
2200 }
2201
2202 return error;
2203 }
2204
2205 u_int32_t udp_sendspace = 9216; /* really max datagram size */
2206 /* 187 1K datagrams (approx 192 KB) */
2207 u_int32_t udp_recvspace = 187 * (1024 + sizeof(struct sockaddr_in6));
2208
2209 /* Check that the values of udp send and recv space do not exceed sb_max */
2210 static int
sysctl_udp_sospace(struct sysctl_oid * oidp,void * arg1,int arg2,struct sysctl_req * req)2211 sysctl_udp_sospace(struct sysctl_oid *oidp, void *arg1, int arg2,
2212 struct sysctl_req *req)
2213 {
2214 #pragma unused(arg1, arg2)
2215 u_int32_t new_value = 0, *space_p = NULL;
2216 int changed = 0, error = 0;
2217
2218 switch (oidp->oid_number) {
2219 case UDPCTL_RECVSPACE:
2220 space_p = &udp_recvspace;
2221 break;
2222 case UDPCTL_MAXDGRAM:
2223 space_p = &udp_sendspace;
2224 break;
2225 default:
2226 return EINVAL;
2227 }
2228 error = sysctl_io_number(req, *space_p, sizeof(u_int32_t),
2229 &new_value, &changed);
2230 if (changed) {
2231 if (new_value > 0 && new_value <= sb_max) {
2232 *space_p = new_value;
2233 } else {
2234 error = ERANGE;
2235 }
2236 }
2237 return error;
2238 }
2239
2240 SYSCTL_PROC(_net_inet_udp, UDPCTL_RECVSPACE, recvspace,
2241 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED, &udp_recvspace, 0,
2242 &sysctl_udp_sospace, "IU", "Maximum incoming UDP datagram size");
2243
2244 SYSCTL_PROC(_net_inet_udp, UDPCTL_MAXDGRAM, maxdgram,
2245 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED, &udp_sendspace, 0,
2246 &sysctl_udp_sospace, "IU", "Maximum outgoing UDP datagram size");
2247
2248 int
udp_abort(struct socket * so)2249 udp_abort(struct socket *so)
2250 {
2251 struct inpcb *inp;
2252
2253 inp = sotoinpcb(so);
2254 if (inp == NULL) {
2255 panic("%s: so=%p null inp", __func__, so);
2256 /* NOTREACHED */
2257 }
2258 soisdisconnected(so);
2259 in_pcbdetach(inp);
2260 return 0;
2261 }
2262
2263 int
udp_attach(struct socket * so,int proto,struct proc * p)2264 udp_attach(struct socket *so, int proto, struct proc *p)
2265 {
2266 #pragma unused(proto)
2267 struct inpcb *inp;
2268 int error;
2269
2270 error = soreserve(so, udp_sendspace, udp_recvspace);
2271 if (error != 0) {
2272 return error;
2273 }
2274 inp = sotoinpcb(so);
2275 if (inp != NULL) {
2276 panic("%s so=%p inp=%p", __func__, so, inp);
2277 /* NOTREACHED */
2278 }
2279 error = in_pcballoc(so, &udbinfo, p);
2280 if (error != 0) {
2281 return error;
2282 }
2283 inp = (struct inpcb *)so->so_pcb;
2284 inp->inp_vflag |= INP_IPV4;
2285 inp->inp_ip_ttl = (uint8_t)ip_defttl;
2286 if (nstat_collect) {
2287 nstat_udp_new_pcb(inp);
2288 }
2289 return 0;
2290 }
2291
2292 int
udp_bind(struct socket * so,struct sockaddr * nam,struct proc * p)2293 udp_bind(struct socket *so, struct sockaddr *nam, struct proc *p)
2294 {
2295 struct inpcb *inp;
2296 int error;
2297
2298 if (nam->sa_family != 0 && nam->sa_family != AF_INET &&
2299 nam->sa_family != AF_INET6) {
2300 return EAFNOSUPPORT;
2301 }
2302
2303 inp = sotoinpcb(so);
2304 if (inp == NULL) {
2305 return EINVAL;
2306 }
2307
2308 inp_enter_bind_in_progress(so);
2309
2310 error = in_pcbbind(inp, nam, NULL, p);
2311
2312 #if NECP
2313 /* Update NECP client with bind result if not in middle of connect */
2314 if (error == 0 &&
2315 (inp->inp_flags2 & INP2_CONNECT_IN_PROGRESS) &&
2316 !uuid_is_null(inp->necp_client_uuid)) {
2317 socket_unlock(so, 0);
2318 necp_client_assign_from_socket(so->last_pid, inp->necp_client_uuid, inp);
2319 socket_lock(so, 0);
2320 }
2321 #endif /* NECP */
2322
2323 UDP_LOG_BIND(inp, error);
2324
2325 inp_exit_bind_in_progress(so);
2326
2327 return error;
2328 }
2329
2330 int
udp_connect(struct socket * so,struct sockaddr * nam,struct proc * p)2331 udp_connect(struct socket *so, struct sockaddr *nam, struct proc *p)
2332 {
2333 struct inpcb *inp;
2334 int error;
2335
2336 inp = sotoinpcb(so);
2337 if (inp == NULL) {
2338 return EINVAL;
2339 }
2340 inp_enter_bind_in_progress(so);
2341
2342 if (inp->inp_faddr.s_addr != INADDR_ANY) {
2343 error = EISCONN;
2344 goto done;
2345 }
2346
2347 if (!(so->so_flags1 & SOF1_CONNECT_COUNTED)) {
2348 so->so_flags1 |= SOF1_CONNECT_COUNTED;
2349 INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_inet_dgram_connected);
2350 }
2351
2352 #if NECP
2353 #if FLOW_DIVERT
2354 if (necp_socket_should_use_flow_divert(inp)) {
2355 error = flow_divert_pcb_init(so);
2356 if (error == 0) {
2357 error = flow_divert_connect_out(so, nam, p);
2358 }
2359 goto done;
2360 } else {
2361 so->so_flags1 |= SOF1_FLOW_DIVERT_SKIP;
2362 }
2363 #endif /* FLOW_DIVERT */
2364 #endif /* NECP */
2365
2366 error = in_pcbconnect(inp, nam, p, IFSCOPE_NONE, NULL);
2367 if (error == 0) {
2368 #if NECP
2369 /* Update NECP client with connected five-tuple */
2370 if (!uuid_is_null(inp->necp_client_uuid)) {
2371 socket_unlock(so, 0);
2372 necp_client_assign_from_socket(so->last_pid, inp->necp_client_uuid, inp);
2373 socket_lock(so, 0);
2374 }
2375 #endif /* NECP */
2376
2377 soisconnected(so);
2378 if (inp->inp_flowhash == 0) {
2379 inp_calc_flowhash(inp);
2380 ASSERT(inp->inp_flowhash != 0);
2381 }
2382 inp->inp_connect_timestamp = mach_continuous_time();
2383 }
2384 done:
2385 UDP_LOG_CONNECT(inp, error);
2386
2387 inp_exit_bind_in_progress(so);
2388
2389 return error;
2390 }
2391
2392 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)2393 udp_connectx_common(struct socket *so, int af, struct sockaddr *src, struct sockaddr *dst,
2394 struct proc *p, uint32_t ifscope, sae_associd_t aid, sae_connid_t *pcid,
2395 uint32_t flags, void *arg, uint32_t arglen,
2396 struct uio *uio, user_ssize_t *bytes_written)
2397 {
2398 #pragma unused(aid, flags, arg, arglen)
2399 struct inpcb *inp = sotoinpcb(so);
2400 int error = 0;
2401 user_ssize_t datalen = 0;
2402
2403 if (inp == NULL) {
2404 return EINVAL;
2405 }
2406
2407 VERIFY(dst != NULL);
2408
2409 ASSERT(!(inp->inp_flags2 & INP2_CONNECT_IN_PROGRESS));
2410 inp->inp_flags2 |= INP2_CONNECT_IN_PROGRESS;
2411
2412 #if NECP
2413 inp_update_necp_policy(inp, src, dst, ifscope);
2414 #endif /* NECP */
2415
2416 /* bind socket to the specified interface, if requested */
2417 if (ifscope != IFSCOPE_NONE &&
2418 (error = inp_bindif(inp, ifscope, NULL)) != 0) {
2419 goto done;
2420 }
2421
2422 /* if source address and/or port is specified, bind to it */
2423 if (src != NULL) {
2424 error = sobindlock(so, src, 0); /* already locked */
2425 if (error != 0) {
2426 goto done;
2427 }
2428 }
2429
2430 switch (af) {
2431 case AF_INET:
2432 error = udp_connect(so, dst, p);
2433 break;
2434 case AF_INET6:
2435 error = udp6_connect(so, dst, p);
2436 break;
2437 default:
2438 VERIFY(0);
2439 /* NOTREACHED */
2440 }
2441
2442 if (error != 0) {
2443 goto done;
2444 }
2445
2446 /*
2447 * If there is data, copy it. DATA_IDEMPOTENT is ignored.
2448 * CONNECT_RESUME_ON_READ_WRITE is ignored.
2449 */
2450 if (uio != NULL) {
2451 socket_unlock(so, 0);
2452
2453 VERIFY(bytes_written != NULL);
2454
2455 datalen = uio_resid(uio);
2456 error = so->so_proto->pr_usrreqs->pru_sosend(so, NULL,
2457 (uio_t)uio, NULL, NULL, 0);
2458 socket_lock(so, 0);
2459
2460 /* If error returned is EMSGSIZE, for example, disconnect */
2461 if (error == 0 || error == EWOULDBLOCK) {
2462 *bytes_written = datalen - uio_resid(uio);
2463 } else {
2464 (void) so->so_proto->pr_usrreqs->pru_disconnectx(so,
2465 SAE_ASSOCID_ANY, SAE_CONNID_ANY);
2466 }
2467 /*
2468 * mask the EWOULDBLOCK error so that the caller
2469 * knows that atleast the connect was successful.
2470 */
2471 if (error == EWOULDBLOCK) {
2472 error = 0;
2473 }
2474 }
2475
2476 if (error == 0 && pcid != NULL) {
2477 *pcid = 1; /* there is only 1 connection for UDP */
2478 }
2479 done:
2480 inp->inp_flags2 &= ~INP2_CONNECT_IN_PROGRESS;
2481 return error;
2482 }
2483
2484 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)2485 udp_connectx(struct socket *so, struct sockaddr *src,
2486 struct sockaddr *dst, struct proc *p, uint32_t ifscope,
2487 sae_associd_t aid, sae_connid_t *pcid, uint32_t flags, void *arg,
2488 uint32_t arglen, struct uio *uio, user_ssize_t *bytes_written)
2489 {
2490 return udp_connectx_common(so, AF_INET, src, dst,
2491 p, ifscope, aid, pcid, flags, arg, arglen, uio, bytes_written);
2492 }
2493
2494 int
udp_detach(struct socket * so)2495 udp_detach(struct socket *so)
2496 {
2497 struct inpcb *inp;
2498
2499 inp = sotoinpcb(so);
2500 if (inp == NULL) {
2501 panic("%s: so=%p null inp", __func__, so);
2502 /* NOTREACHED */
2503 }
2504
2505 /*
2506 * If this is a socket that does not want to wakeup the device
2507 * for it's traffic, the application might be waiting for
2508 * close to complete before going to sleep. Send a notification
2509 * for this kind of sockets
2510 */
2511 if (so->so_options & SO_NOWAKEFROMSLEEP) {
2512 socket_post_kev_msg_closed(so);
2513 }
2514
2515 UDP_LOG_CONNECTION_SUMMARY(inp);
2516
2517 in_pcbdetach(inp);
2518 inp->inp_state = INPCB_STATE_DEAD;
2519 return 0;
2520 }
2521
2522 int
udp_disconnect(struct socket * so)2523 udp_disconnect(struct socket *so)
2524 {
2525 struct inpcb *inp;
2526
2527 inp = sotoinpcb(so);
2528 if (inp == NULL) {
2529 return EINVAL;
2530 }
2531 if (inp->inp_faddr.s_addr == INADDR_ANY) {
2532 return ENOTCONN;
2533 }
2534
2535 UDP_LOG_CONNECTION_SUMMARY(inp);
2536
2537 in_pcbdisconnect(inp);
2538
2539 /* reset flow controlled state, just in case */
2540 inp_reset_fc_state(inp);
2541
2542 inp->inp_laddr.s_addr = INADDR_ANY;
2543 so->so_state &= ~SS_ISCONNECTED; /* XXX */
2544 inp->inp_last_outifp = NULL;
2545 #if SKYWALK
2546 if (NETNS_TOKEN_VALID(&inp->inp_netns_token)) {
2547 netns_set_ifnet(&inp->inp_netns_token, NULL);
2548 }
2549 #endif /* SKYWALK */
2550
2551 return 0;
2552 }
2553
2554 int
udp_disconnectx(struct socket * so,sae_associd_t aid,sae_connid_t cid)2555 udp_disconnectx(struct socket *so, sae_associd_t aid, sae_connid_t cid)
2556 {
2557 #pragma unused(cid)
2558 if (aid != SAE_ASSOCID_ANY && aid != SAE_ASSOCID_ALL) {
2559 return EINVAL;
2560 }
2561
2562 return udp_disconnect(so);
2563 }
2564
2565 int
udp_send(struct socket * so,int flags,struct mbuf * m,struct sockaddr * addr,struct mbuf * control,struct proc * p)2566 udp_send(struct socket *so, int flags, struct mbuf *m,
2567 struct sockaddr *addr, struct mbuf *control, struct proc *p)
2568 {
2569 #ifndef FLOW_DIVERT
2570 #pragma unused(flags)
2571 #endif /* !(FLOW_DIVERT) */
2572 struct inpcb *inp;
2573 int error;
2574
2575 inp = sotoinpcb(so);
2576 if (inp == NULL) {
2577 if (m != NULL) {
2578 m_freem(m);
2579 }
2580 if (control != NULL) {
2581 m_freem(control);
2582 }
2583 return EINVAL;
2584 }
2585
2586 #if NECP
2587 #if FLOW_DIVERT
2588 if (necp_socket_should_use_flow_divert(inp)) {
2589 /* Implicit connect */
2590 return flow_divert_implicit_data_out(so, flags, m, addr,
2591 control, p);
2592 } else {
2593 so->so_flags1 |= SOF1_FLOW_DIVERT_SKIP;
2594 }
2595 #endif /* FLOW_DIVERT */
2596 #endif /* NECP */
2597
2598 so_update_tx_data_stats(so, 1, m->m_pkthdr.len);
2599
2600 #if SKYWALK
2601 sk_protect_t protect = sk_async_transmit_protect();
2602 #endif /* SKYWALK */
2603 error = udp_output(inp, m, addr, control, p);
2604 #if SKYWALK
2605 sk_async_transmit_unprotect(protect);
2606 #endif /* SKYWALK */
2607
2608 return error;
2609 }
2610
2611 int
udp_shutdown(struct socket * so)2612 udp_shutdown(struct socket *so)
2613 {
2614 struct inpcb *inp;
2615
2616 inp = sotoinpcb(so);
2617 if (inp == NULL) {
2618 return EINVAL;
2619 }
2620 socantsendmore(so);
2621 return 0;
2622 }
2623
2624 int
udp_lock(struct socket * so,int refcount,void * debug)2625 udp_lock(struct socket *so, int refcount, void *debug)
2626 {
2627 void *__single lr_saved;
2628
2629 if (debug == NULL) {
2630 lr_saved = __unsafe_forge_single(void *, __builtin_return_address(0));
2631 } else {
2632 lr_saved = debug;
2633 }
2634
2635 if (so->so_pcb != NULL) {
2636 LCK_MTX_ASSERT(&((struct inpcb *)so->so_pcb)->inpcb_mtx,
2637 LCK_MTX_ASSERT_NOTOWNED);
2638 lck_mtx_lock(&((struct inpcb *)so->so_pcb)->inpcb_mtx);
2639 } else {
2640 panic("%s: so=%p NO PCB! lr=%p lrh= %s", __func__,
2641 so, lr_saved, solockhistory_nr(so));
2642 /* NOTREACHED */
2643 }
2644 if (refcount) {
2645 so->so_usecount++;
2646 }
2647
2648 so->lock_lr[so->next_lock_lr] = lr_saved;
2649 so->next_lock_lr = (so->next_lock_lr + 1) % SO_LCKDBG_MAX;
2650 return 0;
2651 }
2652
2653 int
udp_unlock(struct socket * so,int refcount,void * debug)2654 udp_unlock(struct socket *so, int refcount, void *debug)
2655 {
2656 void *__single lr_saved;
2657
2658 if (debug == NULL) {
2659 lr_saved = __unsafe_forge_single(void *, __builtin_return_address(0));
2660 } else {
2661 lr_saved = debug;
2662 }
2663
2664 if (refcount) {
2665 VERIFY(so->so_usecount > 0);
2666 so->so_usecount--;
2667 }
2668 if (so->so_pcb == NULL) {
2669 panic("%s: so=%p NO PCB! lr=%p lrh= %s", __func__,
2670 so, lr_saved, solockhistory_nr(so));
2671 /* NOTREACHED */
2672 } else {
2673 LCK_MTX_ASSERT(&((struct inpcb *)so->so_pcb)->inpcb_mtx,
2674 LCK_MTX_ASSERT_OWNED);
2675 so->unlock_lr[so->next_unlock_lr] = lr_saved;
2676 so->next_unlock_lr = (so->next_unlock_lr + 1) % SO_LCKDBG_MAX;
2677 lck_mtx_unlock(&((struct inpcb *)so->so_pcb)->inpcb_mtx);
2678 }
2679 return 0;
2680 }
2681
2682 lck_mtx_t *
udp_getlock(struct socket * so,int flags)2683 udp_getlock(struct socket *so, int flags)
2684 {
2685 #pragma unused(flags)
2686 struct inpcb *__single inp = sotoinpcb(so);
2687
2688 if (so->so_pcb == NULL) {
2689 panic("%s: so=%p NULL so_pcb lrh= %s", __func__,
2690 so, solockhistory_nr(so));
2691 /* NOTREACHED */
2692 }
2693 return &inp->inpcb_mtx;
2694 }
2695
2696 /*
2697 * UDP garbage collector callback (inpcb_timer_func_t).
2698 *
2699 * Returns > 0 to keep timer active.
2700 */
2701 static void
udp_gc(struct inpcbinfo * ipi)2702 udp_gc(struct inpcbinfo *ipi)
2703 {
2704 struct inpcb *inp, *inpnxt;
2705 struct socket *so;
2706
2707 if (lck_rw_try_lock_exclusive(&ipi->ipi_lock) == FALSE) {
2708 if (udp_gc_done == TRUE) {
2709 udp_gc_done = FALSE;
2710 /* couldn't get the lock, must lock next time */
2711 os_atomic_inc(&ipi->ipi_gc_req.intimer_fast, relaxed);
2712 return;
2713 }
2714 lck_rw_lock_exclusive(&ipi->ipi_lock);
2715 }
2716
2717 udp_gc_done = TRUE;
2718
2719 for (inp = udb.lh_first; inp != NULL; inp = inpnxt) {
2720 inpnxt = inp->inp_list.le_next;
2721
2722 /*
2723 * Skip unless it's STOPUSING; garbage collector will
2724 * be triggered by in_pcb_checkstate() upon setting
2725 * wantcnt to that value. If the PCB is already dead,
2726 * keep gc active to anticipate wantcnt changing.
2727 */
2728 if (inp->inp_wantcnt != WNT_STOPUSING) {
2729 continue;
2730 }
2731
2732 /*
2733 * Skip if busy, no hurry for cleanup. Keep gc active
2734 * and try the lock again during next round.
2735 */
2736 if (!socket_try_lock(inp->inp_socket)) {
2737 os_atomic_inc(&ipi->ipi_gc_req.intimer_fast, relaxed);
2738 continue;
2739 }
2740
2741 /*
2742 * Keep gc active unless usecount is 0.
2743 */
2744 so = inp->inp_socket;
2745 if (so->so_usecount == 0) {
2746 if (inp->inp_state != INPCB_STATE_DEAD) {
2747 if (SOCK_CHECK_DOM(so, PF_INET6)) {
2748 in6_pcbdetach(inp);
2749 } else {
2750 in_pcbdetach(inp);
2751 }
2752 }
2753 in_pcbdispose(inp);
2754 } else {
2755 socket_unlock(so, 0);
2756 os_atomic_inc(&ipi->ipi_gc_req.intimer_fast, relaxed);
2757 }
2758 }
2759 lck_rw_done(&ipi->ipi_lock);
2760 }
2761
2762 static int
2763 udp_getstat SYSCTL_HANDLER_ARGS
2764 {
2765 #pragma unused(oidp, arg1, arg2)
2766 if (req->oldptr == USER_ADDR_NULL) {
2767 req->oldlen = (size_t)sizeof(struct udpstat);
2768 }
2769
2770 return SYSCTL_OUT(req, &udpstat, MIN(sizeof(udpstat), req->oldlen));
2771 }
2772
2773 void
udp_in_cksum_stats(u_int32_t len)2774 udp_in_cksum_stats(u_int32_t len)
2775 {
2776 udpstat.udps_rcv_swcsum++;
2777 udpstat.udps_rcv_swcsum_bytes += len;
2778 }
2779
2780 void
udp_out_cksum_stats(u_int32_t len)2781 udp_out_cksum_stats(u_int32_t len)
2782 {
2783 udpstat.udps_snd_swcsum++;
2784 udpstat.udps_snd_swcsum_bytes += len;
2785 }
2786
2787 void
udp_in6_cksum_stats(u_int32_t len)2788 udp_in6_cksum_stats(u_int32_t len)
2789 {
2790 udpstat.udps_rcv6_swcsum++;
2791 udpstat.udps_rcv6_swcsum_bytes += len;
2792 }
2793
2794 void
udp_out6_cksum_stats(u_int32_t len)2795 udp_out6_cksum_stats(u_int32_t len)
2796 {
2797 udpstat.udps_snd6_swcsum++;
2798 udpstat.udps_snd6_swcsum_bytes += len;
2799 }
2800
2801 /*
2802 * Checksum extended UDP header and data.
2803 */
2804 static int
udp_input_checksum(struct mbuf * m,struct udphdr * uh,int off,int ulen)2805 udp_input_checksum(struct mbuf *m, struct udphdr *uh, int off, int ulen)
2806 {
2807 ifnet_ref_t ifp = m->m_pkthdr.rcvif;
2808 struct ip *__single ip = mtod(m, struct ip *);
2809 struct ipovly *__single ipov = (struct ipovly *)ip;
2810
2811 if (uh->uh_sum == 0) {
2812 udpstat.udps_nosum++;
2813 return 0;
2814 }
2815
2816 /* ip_stripoptions() must have been called before we get here */
2817 ASSERT((ip->ip_hl << 2) == sizeof(*ip));
2818
2819 if ((hwcksum_rx || (ifp->if_flags & IFF_LOOPBACK) ||
2820 (m->m_pkthdr.pkt_flags & PKTF_LOOP)) &&
2821 (m->m_pkthdr.csum_flags & CSUM_DATA_VALID)) {
2822 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
2823 uh->uh_sum = m->m_pkthdr.csum_rx_val;
2824 } else {
2825 uint32_t sum = m->m_pkthdr.csum_rx_val;
2826 uint32_t start = m->m_pkthdr.csum_rx_start;
2827 int32_t trailer = (m_pktlen(m) - (off + ulen));
2828
2829 /*
2830 * Perform 1's complement adjustment of octets
2831 * that got included/excluded in the hardware-
2832 * calculated checksum value. Ignore cases
2833 * where the value already includes the entire
2834 * IP header span, as the sum for those octets
2835 * would already be 0 by the time we get here;
2836 * IP has already performed its header checksum
2837 * checks. If we do need to adjust, restore
2838 * the original fields in the IP header when
2839 * computing the adjustment value. Also take
2840 * care of any trailing bytes and subtract out
2841 * their partial sum.
2842 */
2843 ASSERT(trailer >= 0);
2844 if ((m->m_pkthdr.csum_flags & CSUM_PARTIAL) &&
2845 ((start != 0 && start != off) || trailer != 0)) {
2846 uint32_t swbytes = (uint32_t)trailer;
2847
2848 if (start < off) {
2849 ip->ip_len += sizeof(*ip);
2850 #if BYTE_ORDER != BIG_ENDIAN
2851 HTONS(ip->ip_len);
2852 HTONS(ip->ip_off);
2853 #endif /* BYTE_ORDER != BIG_ENDIAN */
2854 }
2855 /* callee folds in sum */
2856 sum = m_adj_sum16(m, start, off, ulen, sum);
2857 if (off > start) {
2858 swbytes += (off - start);
2859 } else {
2860 swbytes += (start - off);
2861 }
2862
2863 if (start < off) {
2864 #if BYTE_ORDER != BIG_ENDIAN
2865 NTOHS(ip->ip_off);
2866 NTOHS(ip->ip_len);
2867 #endif /* BYTE_ORDER != BIG_ENDIAN */
2868 ip->ip_len -= sizeof(*ip);
2869 }
2870
2871 if (swbytes != 0) {
2872 udp_in_cksum_stats(swbytes);
2873 }
2874 if (trailer != 0) {
2875 m_adj(m, -trailer);
2876 }
2877 }
2878
2879 /* callee folds in sum */
2880 uh->uh_sum = in_pseudo(ip->ip_src.s_addr,
2881 ip->ip_dst.s_addr, sum + htonl(ulen + IPPROTO_UDP));
2882 }
2883 uh->uh_sum ^= 0xffff;
2884 } else {
2885 uint16_t ip_sum;
2886 char b[9];
2887
2888 bcopy(ipov->ih_x1, b, sizeof(ipov->ih_x1));
2889 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
2890 ip_sum = ipov->ih_len;
2891 ipov->ih_len = uh->uh_ulen;
2892 uh->uh_sum = in_cksum(m, ulen + sizeof(struct ip));
2893 bcopy(b, ipov->ih_x1, sizeof(ipov->ih_x1));
2894 ipov->ih_len = ip_sum;
2895
2896 udp_in_cksum_stats(ulen);
2897 }
2898
2899 if (uh->uh_sum != 0) {
2900 udpstat.udps_badsum++;
2901 IF_UDP_STATINC(ifp, badchksum);
2902 return -1;
2903 }
2904
2905 return 0;
2906 }
2907
2908 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)2909 udp_fill_keepalive_offload_frames(ifnet_t ifp,
2910 struct ifnet_keepalive_offload_frame *__counted_by(frames_array_count) frames_array,
2911 u_int32_t frames_array_count, size_t frame_data_offset,
2912 u_int32_t *used_frames_count)
2913 {
2914 struct inpcb *inp;
2915 inp_gen_t gencnt;
2916 u_int32_t frame_index = *used_frames_count;
2917
2918 if (ifp == NULL || frames_array == NULL ||
2919 frames_array_count == 0 ||
2920 frame_index >= frames_array_count ||
2921 frame_data_offset >= IFNET_KEEPALIVE_OFFLOAD_FRAME_DATA_SIZE) {
2922 return;
2923 }
2924
2925 lck_rw_lock_shared(&udbinfo.ipi_lock);
2926 gencnt = udbinfo.ipi_gencnt;
2927 LIST_FOREACH(inp, udbinfo.ipi_listhead, inp_list) {
2928 struct socket *so;
2929 u_int8_t *data;
2930 struct ifnet_keepalive_offload_frame *frame;
2931 mbuf_ref_t m = NULL;
2932
2933 if (frame_index >= frames_array_count) {
2934 break;
2935 }
2936
2937 if (inp->inp_gencnt > gencnt ||
2938 inp->inp_state == INPCB_STATE_DEAD) {
2939 continue;
2940 }
2941
2942 if ((so = inp->inp_socket) == NULL ||
2943 (so->so_state & SS_DEFUNCT)) {
2944 continue;
2945 }
2946 /*
2947 * check for keepalive offload flag without socket
2948 * lock to avoid a deadlock
2949 */
2950 if (!(inp->inp_flags2 & INP2_KEEPALIVE_OFFLOAD)) {
2951 continue;
2952 }
2953
2954 udp_lock(so, 1, 0);
2955 if (!(inp->inp_vflag & (INP_IPV4 | INP_IPV6))) {
2956 udp_unlock(so, 1, 0);
2957 continue;
2958 }
2959 if ((inp->inp_vflag & INP_IPV4) &&
2960 (inp->inp_laddr.s_addr == INADDR_ANY ||
2961 inp->inp_faddr.s_addr == INADDR_ANY)) {
2962 udp_unlock(so, 1, 0);
2963 continue;
2964 }
2965 if ((inp->inp_vflag & INP_IPV6) &&
2966 (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr) ||
2967 IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr))) {
2968 udp_unlock(so, 1, 0);
2969 continue;
2970 }
2971 if (inp->inp_lport == 0 || inp->inp_fport == 0) {
2972 udp_unlock(so, 1, 0);
2973 continue;
2974 }
2975 if (inp->inp_last_outifp == NULL ||
2976 inp->inp_last_outifp->if_index != ifp->if_index) {
2977 udp_unlock(so, 1, 0);
2978 continue;
2979 }
2980 if ((inp->inp_vflag & INP_IPV4)) {
2981 if ((frame_data_offset + sizeof(struct udpiphdr) +
2982 inp->inp_keepalive_datalen) >
2983 IFNET_KEEPALIVE_OFFLOAD_FRAME_DATA_SIZE) {
2984 udp_unlock(so, 1, 0);
2985 continue;
2986 }
2987 if ((sizeof(struct udpiphdr) +
2988 inp->inp_keepalive_datalen) > _MHLEN) {
2989 udp_unlock(so, 1, 0);
2990 continue;
2991 }
2992 } else {
2993 if ((frame_data_offset + sizeof(struct ip6_hdr) +
2994 sizeof(struct udphdr) +
2995 inp->inp_keepalive_datalen) >
2996 IFNET_KEEPALIVE_OFFLOAD_FRAME_DATA_SIZE) {
2997 udp_unlock(so, 1, 0);
2998 continue;
2999 }
3000 if ((sizeof(struct ip6_hdr) + sizeof(struct udphdr) +
3001 inp->inp_keepalive_datalen) > _MHLEN) {
3002 udp_unlock(so, 1, 0);
3003 continue;
3004 }
3005 }
3006 MGETHDR(m, M_WAIT, MT_HEADER);
3007 if (m == NULL) {
3008 udp_unlock(so, 1, 0);
3009 continue;
3010 }
3011 /*
3012 * This inp has all the information that is needed to
3013 * generate an offload frame.
3014 */
3015 if (inp->inp_vflag & INP_IPV4) {
3016 struct ip *ip;
3017 struct udphdr *udp;
3018
3019 frame = &frames_array[frame_index];
3020 frame->length = (uint8_t)(frame_data_offset +
3021 sizeof(struct udpiphdr) +
3022 inp->inp_keepalive_datalen);
3023 frame->ether_type =
3024 IFNET_KEEPALIVE_OFFLOAD_FRAME_ETHERTYPE_IPV4;
3025 frame->interval = inp->inp_keepalive_interval;
3026 switch (inp->inp_keepalive_type) {
3027 case UDP_KEEPALIVE_OFFLOAD_TYPE_AIRPLAY:
3028 frame->type =
3029 IFNET_KEEPALIVE_OFFLOAD_FRAME_AIRPLAY;
3030 break;
3031 default:
3032 break;
3033 }
3034 data = mtod(m, u_int8_t *);
3035 bzero(data, sizeof(struct udpiphdr));
3036 ip = (__typeof__(ip))(void *)data;
3037 udp = (__typeof__(udp))(void *) (data +
3038 sizeof(struct ip));
3039 m->m_len = sizeof(struct udpiphdr);
3040 data = data + sizeof(struct udpiphdr);
3041 if (inp->inp_keepalive_datalen > 0 &&
3042 inp->inp_keepalive_data != NULL) {
3043 bcopy(inp->inp_keepalive_data, data,
3044 inp->inp_keepalive_datalen);
3045 m->m_len += inp->inp_keepalive_datalen;
3046 }
3047 m->m_pkthdr.len = m->m_len;
3048
3049 ip->ip_v = IPVERSION;
3050 ip->ip_hl = (sizeof(struct ip) >> 2);
3051 ip->ip_p = IPPROTO_UDP;
3052 ip->ip_len = htons(sizeof(struct udpiphdr) +
3053 (u_short)inp->inp_keepalive_datalen);
3054 ip->ip_ttl = inp->inp_ip_ttl;
3055 ip->ip_tos |= (inp->inp_ip_tos & ~IPTOS_ECN_MASK);
3056 ip->ip_src = inp->inp_laddr;
3057 ip->ip_dst = inp->inp_faddr;
3058 ip->ip_sum = in_cksum_hdr_opt(ip);
3059
3060 udp->uh_sport = inp->inp_lport;
3061 udp->uh_dport = inp->inp_fport;
3062 udp->uh_ulen = htons(sizeof(struct udphdr) +
3063 (u_short)inp->inp_keepalive_datalen);
3064
3065 if (!(inp->inp_flags & INP_UDP_NOCKSUM)) {
3066 udp->uh_sum = in_pseudo(ip->ip_src.s_addr,
3067 ip->ip_dst.s_addr,
3068 htons(sizeof(struct udphdr) +
3069 (u_short)inp->inp_keepalive_datalen +
3070 IPPROTO_UDP));
3071 m->m_pkthdr.csum_flags =
3072 (CSUM_UDP | CSUM_ZERO_INVERT);
3073 m->m_pkthdr.csum_data = offsetof(struct udphdr,
3074 uh_sum);
3075 }
3076 m->m_pkthdr.pkt_proto = IPPROTO_UDP;
3077 in_delayed_cksum(m);
3078 bcopy(m_mtod_current(m), frame->data + frame_data_offset,
3079 m->m_len);
3080 } else {
3081 struct ip6_hdr *ip6;
3082 struct udphdr *udp6;
3083
3084 VERIFY(inp->inp_vflag & INP_IPV6);
3085 frame = &frames_array[frame_index];
3086 frame->length = (uint8_t)(frame_data_offset +
3087 sizeof(struct ip6_hdr) +
3088 sizeof(struct udphdr) +
3089 inp->inp_keepalive_datalen);
3090 frame->ether_type =
3091 IFNET_KEEPALIVE_OFFLOAD_FRAME_ETHERTYPE_IPV6;
3092 frame->interval = inp->inp_keepalive_interval;
3093 switch (inp->inp_keepalive_type) {
3094 case UDP_KEEPALIVE_OFFLOAD_TYPE_AIRPLAY:
3095 frame->type =
3096 IFNET_KEEPALIVE_OFFLOAD_FRAME_AIRPLAY;
3097 break;
3098 default:
3099 break;
3100 }
3101 data = mtod(m, u_int8_t *);
3102 bzero(data, sizeof(struct ip6_hdr) + sizeof(struct udphdr));
3103 ip6 = (__typeof__(ip6))(void *)data;
3104 udp6 = (__typeof__(udp6))(void *)(data +
3105 sizeof(struct ip6_hdr));
3106 m->m_len = sizeof(struct ip6_hdr) +
3107 sizeof(struct udphdr);
3108 data = data + (sizeof(struct ip6_hdr) +
3109 sizeof(struct udphdr));
3110 if (inp->inp_keepalive_datalen > 0 &&
3111 inp->inp_keepalive_data != NULL) {
3112 bcopy(inp->inp_keepalive_data, data,
3113 inp->inp_keepalive_datalen);
3114 m->m_len += inp->inp_keepalive_datalen;
3115 }
3116 m->m_pkthdr.len = m->m_len;
3117 ip6->ip6_flow = inp->inp_flow & IPV6_FLOWINFO_MASK;
3118 ip6->ip6_flow = ip6->ip6_flow & ~IPV6_FLOW_ECN_MASK;
3119 ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
3120 ip6->ip6_vfc |= IPV6_VERSION;
3121 ip6->ip6_nxt = IPPROTO_UDP;
3122 ip6->ip6_hlim = (uint8_t)ip6_defhlim;
3123 ip6->ip6_plen = htons(sizeof(struct udphdr) +
3124 (u_short)inp->inp_keepalive_datalen);
3125 ip6->ip6_src = inp->in6p_laddr;
3126 if (IN6_IS_SCOPE_EMBED(&ip6->ip6_src)) {
3127 ip6->ip6_src.s6_addr16[1] = 0;
3128 }
3129
3130 ip6->ip6_dst = inp->in6p_faddr;
3131 if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst)) {
3132 ip6->ip6_dst.s6_addr16[1] = 0;
3133 }
3134
3135 udp6->uh_sport = inp->in6p_lport;
3136 udp6->uh_dport = inp->in6p_fport;
3137 udp6->uh_ulen = htons(sizeof(struct udphdr) +
3138 (u_short)inp->inp_keepalive_datalen);
3139 if (!(inp->inp_flags & INP_UDP_NOCKSUM)) {
3140 udp6->uh_sum = in6_pseudo(&ip6->ip6_src,
3141 &ip6->ip6_dst,
3142 htonl(sizeof(struct udphdr) +
3143 (u_short)inp->inp_keepalive_datalen +
3144 IPPROTO_UDP));
3145 m->m_pkthdr.csum_flags =
3146 (CSUM_UDPIPV6 | CSUM_ZERO_INVERT);
3147 m->m_pkthdr.csum_data = offsetof(struct udphdr,
3148 uh_sum);
3149 }
3150 m->m_pkthdr.pkt_proto = IPPROTO_UDP;
3151 in6_delayed_cksum(m);
3152 bcopy(m_mtod_current(m), frame->data + frame_data_offset, m->m_len);
3153 }
3154 if (m != NULL) {
3155 m_freem(m);
3156 m = NULL;
3157 }
3158 frame_index++;
3159 udp_unlock(so, 1, 0);
3160 }
3161 lck_rw_done(&udbinfo.ipi_lock);
3162 *used_frames_count = frame_index;
3163 }
3164
3165 int
udp_defunct(struct socket * so)3166 udp_defunct(struct socket *so)
3167 {
3168 struct ip_moptions *__single imo;
3169 struct inpcb *__single inp;
3170
3171 inp = sotoinpcb(so);
3172 if (inp == NULL) {
3173 return EINVAL;
3174 }
3175
3176 imo = inp->inp_moptions;
3177 if (imo != NULL) {
3178 struct proc *p = current_proc();
3179
3180 SODEFUNCTLOG("%s[%d, %s]: defuncting so 0x%llu drop multicast memberships",
3181 __func__, proc_pid(p), proc_best_name(p),
3182 so->so_gencnt);
3183
3184 inp->inp_moptions = NULL;
3185
3186 IMO_REMREF(imo);
3187 }
3188
3189 return 0;
3190 }
3191