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