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