xref: /xnu-12377.41.6/bsd/netinet6/udp6_usrreq.c (revision bbb1b6f9e71b8cdde6e5cd6f4841f207dee3d828)
1 /*
2  * Copyright (c) 2000-2024 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 
29 /*	$FreeBSD: src/sys/netinet6/udp6_usrreq.c,v 1.6.2.6 2001/07/29 19:32:40 ume Exp $	*/
30 /*	$KAME: udp6_usrreq.c,v 1.27 2001/05/21 05:45:10 jinmei Exp $	*/
31 
32 /*
33  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
34  * All rights reserved.
35  *
36  * Redistribution and use in source and binary forms, with or without
37  * modification, are permitted provided that the following conditions
38  * are met:
39  * 1. Redistributions of source code must retain the above copyright
40  *    notice, this list of conditions and the following disclaimer.
41  * 2. Redistributions in binary form must reproduce the above copyright
42  *    notice, this list of conditions and the following disclaimer in the
43  *    documentation and/or other materials provided with the distribution.
44  * 3. Neither the name of the project 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 PROJECT 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 PROJECT 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 
61 /*
62  * Copyright (c) 1982, 1986, 1989, 1993
63  *	The Regents of the University of California.  All rights reserved.
64  *
65  * Redistribution and use in source and binary forms, with or without
66  * modification, are permitted provided that the following conditions
67  * are met:
68  * 1. Redistributions of source code must retain the above copyright
69  *    notice, this list of conditions and the following disclaimer.
70  * 2. Redistributions in binary form must reproduce the above copyright
71  *    notice, this list of conditions and the following disclaimer in the
72  *    documentation and/or other materials provided with the distribution.
73  * 3. All advertising materials mentioning features or use of this software
74  *    must display the following acknowledgement:
75  *	This product includes software developed by the University of
76  *	California, Berkeley and its contributors.
77  * 4. Neither the name of the University nor the names of its contributors
78  *    may be used to endorse or promote products derived from this software
79  *    without specific prior written permission.
80  *
81  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
82  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
83  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
84  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
85  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
86  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
87  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
88  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
89  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
90  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
91  * SUCH DAMAGE.
92  *
93  *	@(#)udp_var.h	8.1 (Berkeley) 6/10/93
94  */
95 #include <sys/kernel.h>
96 #include <sys/malloc.h>
97 #include <sys/mbuf.h>
98 #include <sys/param.h>
99 #include <sys/protosw.h>
100 #include <sys/socket.h>
101 #include <sys/socketvar.h>
102 #include <sys/sysctl.h>
103 #include <sys/errno.h>
104 #include <sys/stat.h>
105 #include <sys/systm.h>
106 #include <sys/syslog.h>
107 #include <sys/proc.h>
108 #include <sys/kauth.h>
109 
110 #include <net/if.h>
111 #include <net/route.h>
112 #include <net/if_types.h>
113 #include <net/ntstat.h>
114 #include <net/dlil.h>
115 #include <net/net_api_stats.h>
116 #include <net/droptap.h>
117 
118 #include <netinet/in.h>
119 #include <netinet/in_systm.h>
120 #include <netinet/ip.h>
121 #include <netinet/in_pcb.h>
122 #include <netinet/in_var.h>
123 #include <netinet/ip_var.h>
124 #include <netinet/udp.h>
125 #include <netinet/udp_var.h>
126 #include <netinet/udp_log.h>
127 
128 #include <netinet/ip6.h>
129 #include <netinet6/ip6_var.h>
130 #include <netinet6/in6_pcb.h>
131 #include <netinet/icmp6.h>
132 #include <netinet6/udp6_var.h>
133 #include <netinet6/ip6protosw.h>
134 
135 #if IPSEC
136 #include <netinet6/ipsec.h>
137 #include <netinet6/ipsec6.h>
138 #include <netinet6/esp6.h>
139 #include <netkey/key.h>
140 extern int ipsec_bypass;
141 extern int esp_udp_encap_port;
142 #endif /* IPSEC */
143 
144 #if NECP
145 #include <net/necp.h>
146 #endif /* NECP */
147 
148 #if FLOW_DIVERT
149 #include <netinet/flow_divert.h>
150 #endif /* FLOW_DIVERT */
151 
152 #if CONTENT_FILTER
153 #include <net/content_filter.h>
154 #endif /* CONTENT_FILTER */
155 
156 #if SKYWALK
157 #include <skywalk/core/skywalk_var.h>
158 #endif /* SKYWALK */
159 
160 #include <net/sockaddr_utils.h>
161 
162 /*
163  * UDP protocol inplementation.
164  * Per RFC 768, August, 1980.
165  */
166 
167 static int udp6_abort(struct socket *);
168 static int udp6_attach(struct socket *, int, struct proc *);
169 static int udp6_bind(struct socket *, struct sockaddr *, struct proc *);
170 static int udp6_connectx(struct socket *, struct sockaddr *,
171     struct sockaddr *, struct proc *, uint32_t, sae_associd_t,
172     sae_connid_t *, uint32_t, void *, uint32_t, struct uio *, user_ssize_t *);
173 static  int udp6_detach(struct socket *);
174 static int udp6_disconnect(struct socket *);
175 static int udp6_disconnectx(struct socket *, sae_associd_t, sae_connid_t);
176 static int udp6_send(struct socket *, int, struct mbuf *, struct sockaddr *,
177     struct mbuf *, struct proc *);
178 static void udp6_append(struct inpcb *, struct ip6_hdr *,
179     struct sockaddr_in6 *, struct mbuf *, int, struct ifnet *);
180 static int udp6_input_checksum(struct mbuf *, struct udphdr *, int, int);
181 static int udp6_defunct(struct socket *);
182 
183 struct pr_usrreqs udp6_usrreqs = {
184 	.pru_abort =            udp6_abort,
185 	.pru_attach =           udp6_attach,
186 	.pru_bind =             udp6_bind,
187 	.pru_connect =          udp6_connect,
188 	.pru_connectx =         udp6_connectx,
189 	.pru_control =          in6_control,
190 	.pru_detach =           udp6_detach,
191 	.pru_disconnect =       udp6_disconnect,
192 	.pru_disconnectx =      udp6_disconnectx,
193 	.pru_peeraddr =         in6_mapped_peeraddr,
194 	.pru_send =             udp6_send,
195 	.pru_shutdown =         udp_shutdown,
196 	.pru_sockaddr =         in6_mapped_sockaddr,
197 	.pru_sosend =           sosend,
198 	.pru_soreceive =        soreceive,
199 	.pru_defunct =          udp6_defunct,
200 };
201 
202 /*
203  * subroutine of udp6_input(), mainly for source code readability.
204  */
205 static void
udp6_append(struct inpcb * last,struct ip6_hdr * ip6,struct sockaddr_in6 * udp_in6,struct mbuf * n,int off,struct ifnet * ifp)206 udp6_append(struct inpcb *last, struct ip6_hdr *ip6,
207     struct sockaddr_in6 *udp_in6, struct mbuf *n, int off, struct ifnet *ifp)
208 {
209 #pragma unused(ip6)
210 	struct mbuf *__single opts = NULL;
211 	int ret = 0;
212 
213 	if ((last->in6p_flags & INP_CONTROLOPTS) != 0 ||
214 	    SOFLOW_ENABLED(last->in6p_socket) ||
215 	    SO_RECV_CONTROL_OPTS(last->in6p_socket)) {
216 		ret = ip6_savecontrol(last, n, &opts);
217 		if (ret != 0) {
218 			UDP_LOG(last, "ip_savecontrol error %d", ret);
219 			m_freem(n);
220 			m_freem(opts);
221 			return;
222 		}
223 	}
224 	m_adj(n, off);
225 	if (nstat_collect) {
226 		stats_functional_type ifnet_count_type = IFNET_COUNT_TYPE(ifp);
227 		INP_ADD_RXSTAT(last, ifnet_count_type, 1, n->m_pkthdr.len);
228 	}
229 	so_recv_data_stat(last->in6p_socket, n, 0);
230 	if (sbappendaddr(&last->in6p_socket->so_rcv,
231 	    SA(udp_in6), n, opts, NULL) == 0) {
232 		UDP_LOG(last, "sbappendaddr full receive socket buffer");
233 		udpstat.udps_fullsock++;
234 	} else {
235 		sorwakeup(last->in6p_socket);
236 	}
237 }
238 
239 int
udp6_input(struct mbuf ** mp,int * offp,int proto)240 udp6_input(struct mbuf **mp, int *offp, int proto)
241 {
242 #pragma unused(proto)
243 	struct mbuf *m = *mp;
244 	struct ifnet *__single ifp;
245 	struct ip6_hdr *ip6;
246 	struct udphdr *uh;
247 	struct inpcb *__single in6p;
248 	struct  mbuf *__single opts = NULL;
249 	int off = *offp;
250 	int plen, ulen, ret = 0;
251 	stats_functional_type ifnet_count_type = stats_functional_type_unclassified;
252 	struct sockaddr_in6 udp_in6;
253 	struct inpcbinfo *__single pcbinfo = &udbinfo;
254 	struct sockaddr_in6 fromsa;
255 	u_int16_t pf_tag = 0;
256 	boolean_t is_wake_pkt = false;
257 	drop_reason_t drop_reason = DROP_REASON_UNSPECIFIED;
258 
259 	IP6_EXTHDR_CHECK(m, off, sizeof(struct udphdr), return IPPROTO_DONE);
260 
261 	/* Expect 32-bit aligned data pointer on strict-align platforms */
262 	MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);
263 
264 	ifp = m->m_pkthdr.rcvif;
265 	ip6 = mtod(m, struct ip6_hdr *);
266 
267 	if (m->m_flags & M_PKTHDR) {
268 		pf_tag = m_pftag(m)->pftag_tag;
269 		if (m->m_pkthdr.pkt_flags & PKTF_WAKE_PKT) {
270 			is_wake_pkt = true;
271 		}
272 	}
273 
274 	udpstat.udps_ipackets++;
275 
276 	plen = ntohs(ip6->ip6_plen) - off + sizeof(*ip6);
277 	uh = (struct udphdr *)(void *)((caddr_t)ip6 + off);
278 	ulen = ntohs((u_short)uh->uh_ulen);
279 
280 	if (plen != ulen) {
281 		udpstat.udps_badlen++;
282 		IF_UDP_STATINC(ifp, badlength);
283 		drop_reason = DROP_REASON_IP_BAD_LENGTH;
284 		goto bad;
285 	}
286 
287 	/* destination port of 0 is illegal, based on RFC768. */
288 	if (uh->uh_dport == 0) {
289 		IF_UDP_STATINC(ifp, port0);
290 		drop_reason = DROP_REASON_IP6_ILLEGAL_PORT;
291 		goto bad;
292 	}
293 
294 	/*
295 	 * Checksum extended UDP header and data.
296 	 */
297 	if (udp6_input_checksum(m, uh, off, ulen)) {
298 		drop_reason = DROP_REASON_IP6_BAD_UDP_CHECKSUM;
299 		goto bad;
300 	}
301 
302 	/*
303 	 * Construct sockaddr format source address.
304 	 */
305 	init_sin6(&fromsa, m);
306 	fromsa.sin6_port = uh->uh_sport;
307 
308 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
309 		int reuse_sock = 0, mcast_delivered = 0;
310 		struct ip6_moptions *imo;
311 
312 		/*
313 		 * Deliver a multicast datagram to all sockets
314 		 * for which the local and remote addresses and ports match
315 		 * those of the incoming datagram.  This allows more than
316 		 * one process to receive multicasts on the same port.
317 		 * (This really ought to be done for unicast datagrams as
318 		 * well, but that would cause problems with existing
319 		 * applications that open both address-specific sockets and
320 		 * a wildcard socket listening to the same port -- they would
321 		 * end up receiving duplicates of every unicast datagram.
322 		 * Those applications open the multiple sockets to overcome an
323 		 * inadequacy of the UDP socket interface, but for backwards
324 		 * compatibility we avoid the problem here rather than
325 		 * fixing the interface.  Maybe 4.5BSD will remedy this?)
326 		 */
327 
328 		/*
329 		 * In a case that laddr should be set to the link-local
330 		 * address (this happens in RIPng), the multicast address
331 		 * specified in the received packet does not match with
332 		 * laddr. To cure this situation, the matching is relaxed
333 		 * if the receiving interface is the same as one specified
334 		 * in the socket and if the destination multicast address
335 		 * matches one of the multicast groups specified in the socket.
336 		 */
337 
338 		/*
339 		 * Construct sockaddr format source address.
340 		 */
341 		init_sin6(&udp_in6, m); /* general init */
342 		udp_in6.sin6_port = uh->uh_sport;
343 		/*
344 		 * KAME note: usually we drop udphdr from mbuf here.
345 		 * We need udphdr for IPsec processing so we do that later.
346 		 */
347 
348 		/*
349 		 * Locate pcb(s) for datagram.
350 		 * (Algorithm copied from raw_intr().)
351 		 */
352 		lck_rw_lock_shared(&pcbinfo->ipi_lock);
353 
354 		LIST_FOREACH(in6p, &udb, inp_list) {
355 #if IPSEC
356 			int skipit;
357 #endif /* IPSEC */
358 
359 			if ((in6p->inp_vflag & INP_IPV6) == 0) {
360 				continue;
361 			}
362 
363 			if (inp_restricted_recv(in6p, ifp)) {
364 				continue;
365 			}
366 			/*
367 			 * Skip unbound sockets before taking the lock on the socket as
368 			 * the test with the destination port in the header will fail
369 			 */
370 			if (in6p->in6p_lport == 0) {
371 				continue;
372 			}
373 
374 			if (in_pcb_checkstate(in6p, WNT_ACQUIRE, 0) ==
375 			    WNT_STOPUSING) {
376 				continue;
377 			}
378 
379 			udp_lock(in6p->in6p_socket, 1, 0);
380 
381 			if (in_pcb_checkstate(in6p, WNT_RELEASE, 1) ==
382 			    WNT_STOPUSING) {
383 				udp_unlock(in6p->in6p_socket, 1, 0);
384 				continue;
385 			}
386 			if (in6p->in6p_lport != uh->uh_dport) {
387 				udp_unlock(in6p->in6p_socket, 1, 0);
388 				continue;
389 			}
390 
391 			/*
392 			 * Handle socket delivery policy for any-source
393 			 * and source-specific multicast. [RFC3678]
394 			 */
395 			imo = in6p->in6p_moptions;
396 			if (imo && IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
397 				struct sockaddr_in6 mcaddr;
398 				int blocked;
399 
400 				IM6O_LOCK(imo);
401 				SOCKADDR_ZERO(&mcaddr, sizeof(struct sockaddr_in6));
402 				mcaddr.sin6_len = sizeof(struct sockaddr_in6);
403 				mcaddr.sin6_family = AF_INET6;
404 				mcaddr.sin6_addr = ip6->ip6_dst;
405 
406 				blocked = im6o_mc_filter(imo, ifp,
407 				    &mcaddr, &fromsa);
408 				IM6O_UNLOCK(imo);
409 				if (blocked != MCAST_PASS) {
410 					udp_unlock(in6p->in6p_socket, 1, 0);
411 					if (blocked == MCAST_NOTSMEMBER ||
412 					    blocked == MCAST_MUTED) {
413 						udpstat.udps_filtermcast++;
414 					}
415 					continue;
416 				}
417 			}
418 			if (!IN6_IS_ADDR_UNSPECIFIED(&in6p->in6p_faddr) &&
419 			    (!in6_are_addr_equal_scoped(&in6p->in6p_faddr,
420 			    &ip6->ip6_src, in6p->inp_fifscope, ifp->if_index) ||
421 			    in6p->in6p_fport != uh->uh_sport)) {
422 				udp_unlock(in6p->in6p_socket, 1, 0);
423 				continue;
424 			}
425 
426 			reuse_sock = in6p->inp_socket->so_options &
427 			    (SO_REUSEPORT | SO_REUSEADDR);
428 
429 #if NECP
430 			skipit = 0;
431 			if (!necp_socket_is_allowed_to_send_recv_v6(in6p,
432 			    uh->uh_dport, uh->uh_sport, &ip6->ip6_dst,
433 			    &ip6->ip6_src, ifp, pf_tag, NULL, NULL, NULL, NULL)) {
434 				/* do not inject data to pcb */
435 				skipit = 1;
436 				UDP_LOG_DROP_NECP(ip6, uh, in6p, false);
437 			}
438 			if (skipit == 0)
439 #endif /* NECP */
440 			{
441 				struct mbuf *__single n = NULL;
442 				/*
443 				 * KAME NOTE: do not
444 				 * m_copy(m, offset, ...) below.
445 				 * sbappendaddr() expects M_PKTHDR,
446 				 * and m_copy() will copy M_PKTHDR
447 				 * only if offset is 0.
448 				 */
449 				if (reuse_sock) {
450 					n = m_copy(m, 0, M_COPYALL);
451 				}
452 				udp6_append(in6p, ip6, &udp_in6, m,
453 				    off + sizeof(struct udphdr), ifp);
454 				mcast_delivered++;
455 				m = n;
456 			}
457 			if (is_wake_pkt) {
458 				soevent(in6p->in6p_socket,
459 				    SO_FILT_HINT_LOCKED | SO_FILT_HINT_WAKE_PKT);
460 			}
461 			udp_unlock(in6p->in6p_socket, 1, 0);
462 
463 			/*
464 			 * Don't look for additional matches if this one does
465 			 * not have either the SO_REUSEPORT or SO_REUSEADDR
466 			 * socket options set.  This heuristic avoids searching
467 			 * through all pcbs in the common case of a non-shared
468 			 * port.  It assumes that an application will never
469 			 * clear these options after setting them.
470 			 */
471 			if (reuse_sock == 0 || m == NULL) {
472 				break;
473 			}
474 
475 			/*
476 			 * Expect 32-bit aligned data pointer on strict-align
477 			 * platforms.
478 			 */
479 			MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);
480 
481 			/*
482 			 * Recompute IP and UDP header pointers for new mbuf
483 			 */
484 			ip6 = mtod(m, struct ip6_hdr *);
485 			uh = (struct udphdr *)(void *)((caddr_t)ip6 + off);
486 		}
487 		lck_rw_done(&pcbinfo->ipi_lock);
488 
489 		if (mcast_delivered == 0) {
490 			/*
491 			 * No matching pcb found; discard datagram.
492 			 * (No need to send an ICMP Port Unreachable
493 			 * for a broadcast or multicast datgram.)
494 			 */
495 			udpstat.udps_noport++;
496 			udpstat.udps_noportmcast++;
497 			IF_UDP_STATINC(ifp, port_unreach);
498 			drop_reason = DROP_REASON_IP_UNREACHABLE_PORT;
499 			goto bad;
500 		}
501 
502 		/* free the extra copy of mbuf or skipped by NECP */
503 		if (m != NULL) {
504 			m_freem(m);
505 		}
506 		return IPPROTO_DONE;
507 	}
508 
509 #if IPSEC
510 	/*
511 	 * UDP to port 4500 with a payload where the first four bytes are
512 	 * not zero is a UDP encapsulated IPsec packet. Packets where
513 	 * the payload is one byte and that byte is 0xFF are NAT keepalive
514 	 * packets. Decapsulate the ESP packet and carry on with IPsec input
515 	 * or discard the NAT keep-alive.
516 	 */
517 	if (ipsec_bypass == 0 && (esp_udp_encap_port & 0xFFFF) != 0 &&
518 	    (uh->uh_dport == ntohs((u_short)esp_udp_encap_port) ||
519 	    uh->uh_sport == ntohs((u_short)esp_udp_encap_port))) {
520 		union sockaddr_in_4_6 src = {};
521 		union sockaddr_in_4_6 dst = {};
522 
523 		ipsec_fill_ip6_sockaddr_4_6_with_ifscope(&src, &ip6->ip6_src,
524 		    uh->uh_sport, ip6_input_getsrcifscope(m));
525 		ipsec_fill_ip6_sockaddr_4_6_with_ifscope(&dst, &ip6->ip6_dst,
526 		    uh->uh_dport, ip6_input_getdstifscope(m));
527 
528 		/*
529 		 * Check if ESP or keepalive:
530 		 *      1. If the destination port of the incoming packet is 4500.
531 		 *      2. If the source port of the incoming packet is 4500,
532 		 *         then check the SADB to match IP address and port.
533 		 */
534 		bool check_esp = true;
535 		if (uh->uh_dport != ntohs((u_short)esp_udp_encap_port)) {
536 			check_esp = key_checksa_present(&dst, &src);
537 		}
538 
539 		if (check_esp) {
540 			int payload_len = ulen - sizeof(struct udphdr) > 4 ? 4 :
541 			    ulen - sizeof(struct udphdr);
542 
543 			if (m->m_len < off + sizeof(struct udphdr) + payload_len) {
544 				if ((m = m_pullup(m, off + sizeof(struct udphdr) +
545 				    payload_len)) == NULL) {
546 					udpstat.udps_hdrops++;
547 					drop_reason = DROP_REASON_UDP_PACKET_SHORTER_THAN_HEADER;
548 					goto bad;
549 				}
550 				/*
551 				 * Expect 32-bit aligned data pointer on strict-align
552 				 * platforms.
553 				 */
554 				MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);
555 
556 				ip6 = mtod(m, struct ip6_hdr *);
557 				uh = (struct udphdr *)(void *)((caddr_t)ip6 + off);
558 			}
559 			/* Check for NAT keepalive packet */
560 			if (payload_len == 1 && *(u_int8_t*)
561 			    ((caddr_t)uh + sizeof(struct udphdr)) == 0xFF) {
562 				drop_reason = DROP_REASON_UDP_PACKET_SHORTER_THAN_HEADER;
563 				goto bad;
564 			} else if (payload_len == 4 && *(u_int32_t*)(void *)
565 			    ((caddr_t)uh + sizeof(struct udphdr)) != 0) {
566 				/* UDP encapsulated IPsec packet to pass through NAT */
567 				/* preserve the udp header */
568 				*offp = off + sizeof(struct udphdr);
569 				return esp6_input(mp, offp, IPPROTO_UDP);
570 			}
571 		}
572 	}
573 #endif /* IPSEC */
574 
575 	/*
576 	 * Locate pcb for datagram.
577 	 */
578 	in6p = in6_pcblookup_hash(&udbinfo, &ip6->ip6_src, uh->uh_sport, ip6_input_getsrcifscope(m),
579 	    &ip6->ip6_dst, uh->uh_dport, ip6_input_getdstifscope(m), 1, m->m_pkthdr.rcvif);
580 	if (in6p == NULL) {
581 		IF_UDP_STATINC(ifp, port_unreach);
582 
583 		if (udp_log_in_vain) {
584 			char buf[INET6_ADDRSTRLEN];
585 
586 			strlcpy(buf, ip6_sprintf(&ip6->ip6_dst), sizeof(buf));
587 			if (udp_log_in_vain < 3) {
588 				log(LOG_INFO, "Connection attempt to UDP "
589 				    "%s:%d from %s:%d\n", buf,
590 				    ntohs(uh->uh_dport),
591 				    ip6_sprintf(&ip6->ip6_src),
592 				    ntohs(uh->uh_sport));
593 			} else if (!(m->m_flags & (M_BCAST | M_MCAST)) &&
594 			    !in6_are_addr_equal_scoped(&ip6->ip6_dst, &ip6->ip6_src, ip6_input_getdstifscope(m), ip6_input_getsrcifscope(m))) {
595 				log(LOG_INFO, "Connection attempt "
596 				    "to UDP %s:%d from %s:%d\n", buf,
597 				    ntohs(uh->uh_dport),
598 				    ip6_sprintf(&ip6->ip6_src),
599 				    ntohs(uh->uh_sport));
600 			}
601 		}
602 		udpstat.udps_noport++;
603 		if (m->m_flags & M_MCAST) {
604 			printf("UDP6: M_MCAST is set in a unicast packet.\n");
605 			udpstat.udps_noportmcast++;
606 			IF_UDP_STATINC(ifp, badmcast);
607 			drop_reason = DROP_REASON_IP_MULTICAST_NO_PORT;
608 			goto bad;
609 		}
610 
611 		if (udp6_port_unreach_rlc_compress(&ip6->ip6_src, uh->uh_sport,
612 		    &ip6->ip6_dst, uh->uh_dport) == true) {
613 			drop_reason = DROP_REASON_IP_UNREACHABLE_PORT;
614 			goto bad;
615 		}
616 		icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_NOPORT, 0);
617 		return IPPROTO_DONE;
618 	}
619 
620 	/*
621 	 * Construct sockaddr format source address.
622 	 * Stuff source address and datagram in user buffer.
623 	 */
624 	udp_lock(in6p->in6p_socket, 1, 0);
625 
626 #if NECP
627 	if (!necp_socket_is_allowed_to_send_recv_v6(in6p, uh->uh_dport,
628 	    uh->uh_sport, &ip6->ip6_dst, &ip6->ip6_src, ifp, pf_tag, NULL, NULL, NULL, NULL)) {
629 		in_pcb_checkstate(in6p, WNT_RELEASE, 1);
630 		UDP_LOG_DROP_NECP(ip6, uh, in6p, false);
631 		udp_unlock(in6p->in6p_socket, 1, 0);
632 		IF_UDP_STATINC(ifp, badipsec);
633 		drop_reason = DROP_REASON_IP_NECP_POLICY_DROP;
634 		goto bad;
635 	}
636 #endif /* NECP */
637 
638 	if (in_pcb_checkstate(in6p, WNT_RELEASE, 1) == WNT_STOPUSING) {
639 		udp_unlock(in6p->in6p_socket, 1, 0);
640 		IF_UDP_STATINC(ifp, cleanup);
641 		drop_reason = DROP_REASON_UDP_PCB_GARBAGE_COLLECTED;
642 		goto bad;
643 	}
644 
645 	init_sin6(&udp_in6, m); /* general init */
646 	udp_in6.sin6_port = uh->uh_sport;
647 	if ((in6p->in6p_flags & INP_CONTROLOPTS) != 0 ||
648 	    SOFLOW_ENABLED(in6p->in6p_socket) ||
649 	    SO_RECV_CONTROL_OPTS(in6p->in6p_socket)) {
650 		ret = ip6_savecontrol(in6p, m, &opts);
651 		if (ret != 0) {
652 			UDP_LOG(in6p, "ip_savecontrol error %d", ret);
653 			udp_unlock(in6p->in6p_socket, 1, 0);
654 			drop_reason = DROP_REASON_IP_ENOBUFS;
655 			goto bad;
656 		}
657 	}
658 	m_adj(m, off + sizeof(struct udphdr));
659 	if (nstat_collect) {
660 		ifnet_count_type = IFNET_COUNT_TYPE(ifp);
661 		INP_ADD_RXSTAT(in6p, ifnet_count_type, 1, m->m_pkthdr.len);
662 	}
663 	so_recv_data_stat(in6p->in6p_socket, m, 0);
664 	if (sbappendaddr(&in6p->in6p_socket->so_rcv,
665 	    SA(&udp_in6), m, opts, NULL) == 0) {
666 		UDP_LOG(in6p, "sbappendaddr full receive socket buffer");
667 		m = NULL;
668 		opts = NULL;
669 		udpstat.udps_fullsock++;
670 		udp_unlock(in6p->in6p_socket, 1, 0);
671 		goto bad;
672 	}
673 	if (is_wake_pkt) {
674 		soevent(in6p->in6p_socket, SO_FILT_HINT_LOCKED | SO_FILT_HINT_WAKE_PKT);
675 	}
676 	sorwakeup(in6p->in6p_socket);
677 	udp_unlock(in6p->in6p_socket, 1, 0);
678 	return IPPROTO_DONE;
679 bad:
680 	if (m != NULL) {
681 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, drop_reason, NULL, 0);
682 	}
683 	if (opts != NULL) {
684 		m_freem(opts);
685 	}
686 	return IPPROTO_DONE;
687 }
688 
689 void
udp6_ctlinput(int cmd,struct sockaddr * sa,void * d,__unused struct ifnet * ifp)690 udp6_ctlinput(int cmd, struct sockaddr *sa, void *d, __unused struct ifnet *ifp)
691 {
692 	struct udphdr uh;
693 	struct ip6_hdr *ip6;
694 	struct mbuf *m;
695 	int off = 0;
696 	struct ip6ctlparam *__single ip6cp = NULL;
697 	struct icmp6_hdr *__single icmp6 = NULL;
698 	const struct sockaddr_in6 *__single sa6_src = NULL;
699 	void *__single cmdarg = NULL;
700 	void (*notify)(struct inpcb *, int) = udp_notify;
701 	struct inpcb *__single in6p;
702 	struct udp_portonly {
703 		u_int16_t uh_sport;
704 		u_int16_t uh_dport;
705 	} *uhp;
706 
707 	if (sa->sa_family != AF_INET6 ||
708 	    sa->sa_len != sizeof(struct sockaddr_in6)) {
709 		return;
710 	}
711 
712 	if ((unsigned)cmd >= PRC_NCMDS) {
713 		return;
714 	}
715 	if (PRC_IS_REDIRECT(cmd)) {
716 		notify = in6_rtchange;
717 		d = NULL;
718 	} else if (cmd == PRC_HOSTDEAD) {
719 		d = NULL;
720 	} else if (inet6ctlerrmap[cmd] == 0) {
721 		return;
722 	}
723 
724 	/* if the parameter is from icmp6, decode it. */
725 	if (d != NULL) {
726 		ip6cp = (struct ip6ctlparam *)d;
727 		icmp6 = ip6cp->ip6c_icmp6;
728 		m = ip6cp->ip6c_m;
729 		ip6 = ip6cp->ip6c_ip6;
730 		off = ip6cp->ip6c_off;
731 		cmdarg = ip6cp->ip6c_cmdarg;
732 		sa6_src = ip6cp->ip6c_src;
733 	} else {
734 		m = NULL;
735 		ip6 = NULL;
736 		cmdarg = NULL;
737 		sa6_src = &sa6_any;
738 	}
739 
740 	if (ip6 != NULL) {
741 #if SKYWALK
742 		union sockaddr_in_4_6 sock_laddr;
743 		struct protoctl_ev_val prctl_ev_val;
744 #endif /* SKYWALK */
745 		/*
746 		 * XXX: We assume that when IPV6 is non NULL,
747 		 * M and OFF are valid.
748 		 */
749 		/* check if we can safely examine src and dst ports */
750 		if (m->m_pkthdr.len < off + sizeof(*uhp)) {
751 			return;
752 		}
753 
754 		bzero(&uh, sizeof(uh));
755 		m_copydata(m, off, sizeof(*uhp), (caddr_t)&uh);
756 
757 		in6p = in6_pcblookup_hash(&udbinfo, &ip6->ip6_dst, uh.uh_dport, ip6_input_getdstifscope(m),
758 		    &ip6->ip6_src, uh.uh_sport, ip6_input_getsrcifscope(m), 0, NULL);
759 		if (cmd == PRC_MSGSIZE && in6p != NULL && !uuid_is_null(in6p->necp_client_uuid)) {
760 			uuid_t null_uuid;
761 			uuid_clear(null_uuid);
762 			necp_update_flow_protoctl_event(null_uuid, in6p->necp_client_uuid,
763 			    PRC_MSGSIZE, ntohl(icmp6->icmp6_mtu), 0);
764 			/*
765 			 * Avoid setting so_error when using Network.framework
766 			 * since the notification of PRC_MSGSIZE has been delivered
767 			 * through NECP.
768 			 */
769 			in6_pcbnotify(&udbinfo, sa, uh.uh_dport,
770 			    SA(ip6cp->ip6c_src), uh.uh_sport,
771 			    cmd, cmdarg, NULL);
772 		} else {
773 			in6_pcbnotify(&udbinfo, sa, uh.uh_dport,
774 			    SA(ip6cp->ip6c_src), uh.uh_sport,
775 			    cmd, cmdarg, notify);
776 		}
777 #if SKYWALK
778 		bzero(&prctl_ev_val, sizeof(prctl_ev_val));
779 		bzero(&sock_laddr, sizeof(sock_laddr));
780 
781 		if (cmd == PRC_MSGSIZE && icmp6 != NULL) {
782 			prctl_ev_val.val = ntohl(icmp6->icmp6_mtu);
783 		}
784 		sock_laddr.sin6.sin6_family = AF_INET6;
785 		sock_laddr.sin6.sin6_len = sizeof(sock_laddr.sin6);
786 		sock_laddr.sin6.sin6_addr = ip6->ip6_src;
787 
788 		protoctl_event_enqueue_nwk_wq_entry(ifp,
789 		    SA(&sock_laddr), sa,
790 		    uh.uh_sport, uh.uh_dport, IPPROTO_UDP,
791 		    cmd, &prctl_ev_val);
792 #endif /* SKYWALK */
793 	}
794 	/*
795 	 * XXX The else condition here was broken for a long time.
796 	 * Fixing it made us deliver notification correctly but broke
797 	 * some frameworks that didn't handle it well.
798 	 * For now we have removed it and will revisit it later.
799 	 */
800 }
801 
802 static int
udp6_abort(struct socket * so)803 udp6_abort(struct socket *so)
804 {
805 	struct inpcb *__single inp;
806 
807 	inp = sotoinpcb(so);
808 	if (inp == NULL) {
809 		panic("%s: so=%p null inp", __func__, so);
810 		/* NOTREACHED */
811 	}
812 	soisdisconnected(so);
813 	in6_pcbdetach(inp);
814 	return 0;
815 }
816 
817 static int
udp6_attach(struct socket * so,int proto,struct proc * p)818 udp6_attach(struct socket *so, int proto, struct proc *p)
819 {
820 #pragma unused(proto)
821 	struct inpcb *__single inp;
822 	int error;
823 
824 	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
825 		error = soreserve(so, udp_sendspace, udp_recvspace);
826 		if (error) {
827 			return error;
828 		}
829 	}
830 
831 	inp = sotoinpcb(so);
832 	if (inp != NULL) {
833 		return EINVAL;
834 	}
835 
836 	error = in_pcballoc(so, &udbinfo, p);
837 	if (error) {
838 		return error;
839 	}
840 
841 	inp = (struct inpcb *)so->so_pcb;
842 	inp->inp_vflag |= INP_IPV6;
843 	if (ip6_mapped_addr_on) {
844 		inp->inp_vflag |= INP_IPV4;
845 	}
846 	inp->in6p_hops = -1;    /* use kernel default */
847 	inp->in6p_cksum = -1;   /* just to be sure */
848 	/*
849 	 * XXX: ugly!!
850 	 * IPv4 TTL initialization is necessary for an IPv6 socket as well,
851 	 * because the socket may be bound to an IPv6 wildcard address,
852 	 * which may match an IPv4-mapped IPv6 address.
853 	 */
854 	inp->inp_ip_ttl = (u_char)ip_defttl;
855 	if (nstat_collect) {
856 		nstat_udp_new_pcb(inp);
857 	}
858 	return 0;
859 }
860 
861 static int
udp6_bind(struct socket * so,struct sockaddr * nam,struct proc * p)862 udp6_bind(struct socket *so, struct sockaddr *nam, struct proc *p)
863 {
864 	struct inpcb *__single inp;
865 	int error;
866 
867 	inp = sotoinpcb(so);
868 	if (inp == NULL) {
869 		return EINVAL;
870 	}
871 	inp_enter_bind_in_progress(so);
872 
873 	const uint8_t old_flags = inp->inp_vflag;
874 	inp->inp_vflag &= ~INP_IPV4;
875 	inp->inp_vflag |= INP_IPV6;
876 
877 	if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0) {
878 		struct sockaddr_in6 *__single sin6_p;
879 
880 		sin6_p = SIN6(nam);
881 
882 		if (IN6_IS_ADDR_UNSPECIFIED(&sin6_p->sin6_addr)) {
883 			inp->inp_vflag |= INP_IPV4;
884 			inp->inp_vflag &= ~INP_V4MAPPEDV6;
885 		} else if (IN6_IS_ADDR_V4MAPPED(&sin6_p->sin6_addr)) {
886 			struct sockaddr_in sin;
887 
888 			in6_sin6_2_sin(&sin, sin6_p);
889 			inp->inp_vflag |= INP_IPV4;
890 			inp->inp_vflag &= ~INP_IPV6;
891 			inp->inp_vflag |= INP_V4MAPPEDV6;
892 
893 			error = in_pcbbind(inp, SA(&sin), NULL, p);
894 			if (error != 0) {
895 				inp->inp_vflag = old_flags;
896 			}
897 			goto out;
898 		}
899 	}
900 
901 	error = in6_pcbbind(inp, nam, NULL, p);
902 	if (error != 0) {
903 		inp->inp_vflag = old_flags;
904 	}
905 out:
906 	UDP_LOG_BIND(inp, error);
907 
908 	inp_exit_bind_in_progress(so);
909 
910 	return error;
911 }
912 
913 int
udp6_connect(struct socket * so,struct sockaddr * nam,struct proc * p)914 udp6_connect(struct socket *so, struct sockaddr *nam, struct proc *p)
915 {
916 	struct inpcb *__single inp;
917 	int error;
918 	struct sockaddr_in6 *__single sin6_p = SIN6(nam);
919 
920 #if defined(NECP) && defined(FLOW_DIVERT)
921 	int should_use_flow_divert = 0;
922 #endif /* defined(NECP) && defined(FLOW_DIVERT) */
923 
924 	inp = sotoinpcb(so);
925 	if (inp == NULL) {
926 		return EINVAL;
927 	}
928 
929 	inp_enter_bind_in_progress(so);
930 
931 #if defined(NECP) && defined(FLOW_DIVERT)
932 	should_use_flow_divert = necp_socket_should_use_flow_divert(inp);
933 #endif /* defined(NECP) && defined(FLOW_DIVERT) */
934 
935 	/*
936 	 * It is possible that the socket is bound to v4 mapped v6 address.
937 	 * Post that do not allow connect to a v6 endpoint.
938 	 */
939 	if (inp->inp_vflag & INP_V4MAPPEDV6 &&
940 	    !IN6_IS_ADDR_V4MAPPED(&sin6_p->sin6_addr)) {
941 		if (IN6_IS_ADDR_UNSPECIFIED(&sin6_p->sin6_addr)) {
942 			sin6_p->sin6_addr.s6_addr[10] = 0xff;
943 			sin6_p->sin6_addr.s6_addr[11] = 0xff;
944 		} else {
945 			error = EINVAL;
946 			goto done;
947 		}
948 	}
949 
950 	if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0) {
951 		if (IN6_IS_ADDR_V4MAPPED(&sin6_p->sin6_addr)) {
952 			struct sockaddr_in sin;
953 			const uint8_t old_flags = inp->inp_vflag;
954 
955 			if (inp->inp_faddr.s_addr != INADDR_ANY) {
956 				error = EISCONN;
957 				goto done;
958 			}
959 			/*
960 			 * If bound to an IPv6 address, we cannot connect to
961 			 * an IPv4 mapped address
962 			 */
963 			if (inp->inp_vflag == INP_IPV6) {
964 				error = EINVAL;
965 				goto done;
966 			}
967 
968 			if (!(so->so_flags1 & SOF1_CONNECT_COUNTED)) {
969 				so->so_flags1 |= SOF1_CONNECT_COUNTED;
970 				INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_inet_dgram_connected);
971 			}
972 
973 			in6_sin6_2_sin(&sin, sin6_p);
974 #if defined(NECP) && defined(FLOW_DIVERT)
975 			if (should_use_flow_divert) {
976 				goto do_flow_divert;
977 			}
978 #endif /* defined(NECP) && defined(FLOW_DIVERT) */
979 			inp->inp_vflag |= INP_IPV4;
980 			inp->inp_vflag &= ~INP_IPV6;
981 			inp->inp_vflag |= INP_V4MAPPEDV6;
982 
983 			error = in_pcbconnect(inp, SA(&sin), p, IFSCOPE_NONE, NULL);
984 			if (error == 0) {
985 #if NECP
986 				/* Update NECP client with connected five-tuple */
987 				if (!uuid_is_null(inp->necp_client_uuid)) {
988 					socket_unlock(so, 0);
989 					necp_client_assign_from_socket(so->last_pid, inp->necp_client_uuid, inp);
990 					socket_lock(so, 0);
991 				}
992 #endif /* NECP */
993 				soisconnected(so);
994 			} else {
995 				inp->inp_vflag = old_flags;
996 			}
997 			goto done;
998 		}
999 	}
1000 
1001 	/*
1002 	 * If bound to an IPv4 mapped address, we cannot connect to
1003 	 * an IPv6 address
1004 	 */
1005 	if (inp->inp_vflag == INP_IPV4) {
1006 		error = EINVAL;
1007 		goto done;
1008 	}
1009 
1010 	if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
1011 		error = EISCONN;
1012 		goto done;
1013 	}
1014 
1015 	if (!(so->so_flags1 & SOF1_CONNECT_COUNTED)) {
1016 		so->so_flags1 |= SOF1_CONNECT_COUNTED;
1017 		INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_inet6_dgram_connected);
1018 	}
1019 
1020 #if defined(NECP) && defined(FLOW_DIVERT)
1021 do_flow_divert:
1022 	if (should_use_flow_divert) {
1023 		error = flow_divert_pcb_init(so);
1024 		if (error == 0) {
1025 			error = flow_divert_connect_out(so, nam, p);
1026 		}
1027 		goto done;
1028 	}
1029 #endif /* defined(NECP) && defined(FLOW_DIVERT) */
1030 
1031 	error = in6_pcbconnect(inp, nam, p);
1032 	if (error == 0) {
1033 		/* should be non mapped addr */
1034 		if (ip6_mapped_addr_on ||
1035 		    (inp->inp_flags & IN6P_IPV6_V6ONLY) == 0) {
1036 			inp->inp_vflag &= ~INP_IPV4;
1037 			inp->inp_vflag |= INP_IPV6;
1038 		}
1039 #if NECP
1040 		/* Update NECP client with connected five-tuple */
1041 		if (!uuid_is_null(inp->necp_client_uuid)) {
1042 			socket_unlock(so, 0);
1043 			necp_client_assign_from_socket(so->last_pid, inp->necp_client_uuid, inp);
1044 			socket_lock(so, 0);
1045 		}
1046 #endif /* NECP */
1047 		soisconnected(so);
1048 		if (inp->inp_flowhash == 0) {
1049 			inp_calc_flowhash(inp);
1050 			ASSERT(inp->inp_flowhash != 0);
1051 		}
1052 		/* update flowinfo - RFC 6437 */
1053 		if (inp->inp_flow == 0 &&
1054 		    inp->in6p_flags & IN6P_AUTOFLOWLABEL) {
1055 			inp->inp_flow &= ~IPV6_FLOWLABEL_MASK;
1056 			inp->inp_flow |=
1057 			    (htonl(ip6_randomflowlabel()) & IPV6_FLOWLABEL_MASK);
1058 		}
1059 		inp->inp_connect_timestamp = mach_continuous_time();
1060 	}
1061 done:
1062 	UDP_LOG_CONNECT(inp, error);
1063 
1064 	inp_exit_bind_in_progress(so);
1065 
1066 	return error;
1067 }
1068 
1069 static int
udp6_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)1070 udp6_connectx(struct socket *so, struct sockaddr *src,
1071     struct sockaddr *dst, struct proc *p, uint32_t ifscope,
1072     sae_associd_t aid, sae_connid_t *pcid, uint32_t flags, void *arg,
1073     uint32_t arglen, struct uio *uio, user_ssize_t *bytes_written)
1074 {
1075 	return udp_connectx_common(so, AF_INET6, src, dst,
1076 	           p, ifscope, aid, pcid, flags, arg, arglen, uio, bytes_written);
1077 }
1078 
1079 static int
udp6_detach(struct socket * so)1080 udp6_detach(struct socket *so)
1081 {
1082 	struct inpcb *__single inp;
1083 
1084 	inp = sotoinpcb(so);
1085 	if (inp == NULL) {
1086 		return EINVAL;
1087 	}
1088 
1089 	UDP_LOG_CONNECTION_SUMMARY(inp);
1090 
1091 	in6_pcbdetach(inp);
1092 	return 0;
1093 }
1094 
1095 static int
udp6_disconnect(struct socket * so)1096 udp6_disconnect(struct socket *so)
1097 {
1098 	struct inpcb *__single inp;
1099 
1100 	inp = sotoinpcb(so);
1101 	if (inp == NULL
1102 #if NECP
1103 	    || (necp_socket_should_use_flow_divert(inp))
1104 #endif /* NECP */
1105 	    ) {
1106 		return inp == NULL ? EINVAL : EPROTOTYPE;
1107 	}
1108 
1109 	if (inp->inp_vflag & INP_IPV4) {
1110 		struct pr_usrreqs *__single pru;
1111 
1112 		pru = ip_protox[IPPROTO_UDP]->pr_usrreqs;
1113 		return (*pru->pru_disconnect)(so);
1114 	}
1115 
1116 	if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
1117 		return ENOTCONN;
1118 	}
1119 
1120 	UDP_LOG_CONNECTION_SUMMARY(inp);
1121 
1122 	in6_pcbdisconnect(inp);
1123 
1124 	/* reset flow-controlled state, just in case */
1125 	inp_reset_fc_state(inp);
1126 
1127 	inp->in6p_laddr = in6addr_any;
1128 	inp->inp_lifscope = IFSCOPE_NONE;
1129 	inp->in6p_last_outifp = NULL;
1130 #if SKYWALK
1131 	if (NETNS_TOKEN_VALID(&inp->inp_netns_token)) {
1132 		netns_set_ifnet(&inp->inp_netns_token, NULL);
1133 	}
1134 #endif /* SKYWALK */
1135 
1136 	so->so_state &= ~SS_ISCONNECTED;                /* XXX */
1137 	return 0;
1138 }
1139 
1140 static int
udp6_disconnectx(struct socket * so,sae_associd_t aid,sae_connid_t cid)1141 udp6_disconnectx(struct socket *so, sae_associd_t aid, sae_connid_t cid)
1142 {
1143 #pragma unused(cid)
1144 	if (aid != SAE_ASSOCID_ANY && aid != SAE_ASSOCID_ALL) {
1145 		return EINVAL;
1146 	}
1147 
1148 	return udp6_disconnect(so);
1149 }
1150 
1151 static int
udp6_send(struct socket * so,int flags,struct mbuf * m,struct sockaddr * addr,struct mbuf * control,struct proc * p)1152 udp6_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *addr,
1153     struct mbuf *control, struct proc *p)
1154 {
1155 	struct inpcb *__single inp;
1156 	int error = 0;
1157 #if defined(NECP) && defined(FLOW_DIVERT)
1158 	int should_use_flow_divert = 0;
1159 #endif /* defined(NECP) && defined(FLOW_DIVERT) */
1160 #if CONTENT_FILTER
1161 	struct m_tag *__single cfil_tag = NULL;
1162 	struct sockaddr *__single cfil_faddr = NULL;
1163 #endif
1164 
1165 	inp = sotoinpcb(so);
1166 	if (inp == NULL) {
1167 		error = EINVAL;
1168 		goto bad;
1169 	}
1170 
1171 #if CONTENT_FILTER
1172 	/* If socket is subject to UDP Content Filter and unconnected, get addr from tag. */
1173 	if (CFIL_DGRAM_FILTERED(so) && !addr && IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
1174 		cfil_tag = cfil_dgram_get_socket_state(m, NULL, NULL, &cfil_faddr, NULL);
1175 		if (cfil_tag) {
1176 			addr = SA(cfil_faddr);
1177 		}
1178 	}
1179 #endif
1180 
1181 #if defined(NECP) && defined(FLOW_DIVERT)
1182 	should_use_flow_divert = necp_socket_should_use_flow_divert(inp);
1183 #endif /* defined(NECP) && defined(FLOW_DIVERT) */
1184 
1185 	if (addr != NULL) {
1186 		if (addr->sa_len != sizeof(struct sockaddr_in6)) {
1187 			error = EINVAL;
1188 			goto bad;
1189 		}
1190 		if (addr->sa_family != AF_INET6) {
1191 			error = EAFNOSUPPORT;
1192 			goto bad;
1193 		}
1194 	}
1195 
1196 	if (ip6_mapped_addr_on || (inp->inp_flags & IN6P_IPV6_V6ONLY) == 0) {
1197 		int hasv4addr;
1198 		struct sockaddr_in6 *__single sin6 = NULL;
1199 
1200 		if (addr == NULL) {
1201 			hasv4addr = (inp->inp_vflag & INP_IPV4);
1202 		} else {
1203 			sin6 = SIN6(addr);
1204 			hasv4addr =
1205 			    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ? 1 : 0;
1206 		}
1207 		if (hasv4addr) {
1208 			struct pr_usrreqs *__single pru;
1209 
1210 			if (sin6 != NULL) {
1211 				in6_sin6_2_sin_in_sock(addr);
1212 			}
1213 #if defined(NECP) && defined(FLOW_DIVERT)
1214 			if (should_use_flow_divert) {
1215 				goto do_flow_divert;
1216 			}
1217 #endif /* defined(NECP) && defined(FLOW_DIVERT) */
1218 			pru = ip_protox[IPPROTO_UDP]->pr_usrreqs;
1219 			error = ((*pru->pru_send)(so, flags, m, addr,
1220 			    control, p));
1221 			if (error == EJUSTRETURN) {
1222 				error = 0;
1223 			}
1224 #if CONTENT_FILTER
1225 			if (cfil_tag) {
1226 				m_tag_free(cfil_tag);
1227 			}
1228 #endif
1229 			/* addr will just be freed in sendit(). */
1230 			return error;
1231 		}
1232 	}
1233 
1234 #if defined(NECP) && defined(FLOW_DIVERT)
1235 do_flow_divert:
1236 	if (should_use_flow_divert) {
1237 		/* Implicit connect */
1238 		error = flow_divert_implicit_data_out(so, flags, m, addr, control, p);
1239 #if CONTENT_FILTER
1240 		if (cfil_tag) {
1241 			m_tag_free(cfil_tag);
1242 		}
1243 #endif
1244 		return error;
1245 	}
1246 #endif /* defined(NECP) && defined(FLOW_DIVERT) */
1247 
1248 	so_update_tx_data_stats(so, 1, m->m_pkthdr.len);
1249 
1250 	in_pcb_check_management_entitled(inp);
1251 	in_pcb_check_ultra_constrained_entitled(inp);
1252 
1253 #if SKYWALK
1254 	sk_protect_t __single protect = sk_async_transmit_protect();
1255 #endif /* SKYWALK */
1256 	error = udp6_output(inp, m, addr, control, p);
1257 #if SKYWALK
1258 	sk_async_transmit_unprotect(protect);
1259 #endif /* SKYWALK */
1260 
1261 #if CONTENT_FILTER
1262 	if (cfil_tag) {
1263 		m_tag_free(cfil_tag);
1264 	}
1265 #endif
1266 	return error;
1267 
1268 bad:
1269 	VERIFY(error != 0);
1270 
1271 	if (m != NULL) {
1272 		m_freem(m);
1273 	}
1274 	if (control != NULL) {
1275 		m_freem(control);
1276 	}
1277 #if CONTENT_FILTER
1278 	if (cfil_tag) {
1279 		m_tag_free(cfil_tag);
1280 	}
1281 #endif
1282 	return error;
1283 }
1284 
1285 /*
1286  * Checksum extended UDP header and data.
1287  */
1288 static int
udp6_input_checksum(struct mbuf * m,struct udphdr * uh,int off,int ulen)1289 udp6_input_checksum(struct mbuf *m, struct udphdr *uh, int off, int ulen)
1290 {
1291 	struct ifnet *__single ifp = m->m_pkthdr.rcvif;
1292 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
1293 
1294 	if (!(m->m_pkthdr.csum_flags & CSUM_DATA_VALID) &&
1295 	    uh->uh_sum == 0) {
1296 		/* UDP/IPv6 checksum is mandatory (RFC2460) */
1297 
1298 		/*
1299 		 * If checksum was already validated, ignore this check.
1300 		 * This is necessary for transport-mode ESP, which may be
1301 		 * getting UDP payloads without checksums when the network
1302 		 * has a NAT64.
1303 		 */
1304 		udpstat.udps_nosum++;
1305 		goto badsum;
1306 	}
1307 
1308 	if ((hwcksum_rx || (ifp->if_flags & IFF_LOOPBACK) ||
1309 	    (m->m_pkthdr.pkt_flags & PKTF_LOOP)) &&
1310 	    (m->m_pkthdr.csum_flags & CSUM_DATA_VALID)) {
1311 		if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
1312 			uh->uh_sum = m->m_pkthdr.csum_rx_val;
1313 		} else {
1314 			uint32_t sum = m->m_pkthdr.csum_rx_val;
1315 			uint32_t start = m->m_pkthdr.csum_rx_start;
1316 			int32_t trailer = (m_pktlen(m) - (off + ulen));
1317 
1318 			/*
1319 			 * Perform 1's complement adjustment of octets
1320 			 * that got included/excluded in the hardware-
1321 			 * calculated checksum value.  Also take care
1322 			 * of any trailing bytes and subtract out
1323 			 * their partial sum.
1324 			 */
1325 			ASSERT(trailer >= 0);
1326 			if ((m->m_pkthdr.csum_flags & CSUM_PARTIAL) &&
1327 			    (start != off || trailer != 0)) {
1328 				uint32_t swbytes = (uint32_t)trailer;
1329 				uint16_t s = 0, d = 0;
1330 
1331 				if (IN6_IS_SCOPE_EMBED(&ip6->ip6_src)) {
1332 					s = ip6->ip6_src.s6_addr16[1];
1333 					ip6->ip6_src.s6_addr16[1] = 0;
1334 				}
1335 				if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst)) {
1336 					d = ip6->ip6_dst.s6_addr16[1];
1337 					ip6->ip6_dst.s6_addr16[1] = 0;
1338 				}
1339 
1340 				/* callee folds in sum */
1341 				sum = m_adj_sum16(m, start, off, ulen, sum);
1342 				if (off > start) {
1343 					swbytes += (off - start);
1344 				} else {
1345 					swbytes += (start - off);
1346 				}
1347 
1348 				if (IN6_IS_SCOPE_EMBED(&ip6->ip6_src)) {
1349 					ip6->ip6_src.s6_addr16[1] = s;
1350 				}
1351 				if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst)) {
1352 					ip6->ip6_dst.s6_addr16[1] = d;
1353 				}
1354 
1355 				if (swbytes != 0) {
1356 					udp_in_cksum_stats(swbytes);
1357 				}
1358 				if (trailer != 0) {
1359 					m_adj(m, -trailer);
1360 				}
1361 			}
1362 
1363 			uh->uh_sum = in6_pseudo(&ip6->ip6_src, &ip6->ip6_dst,
1364 			    sum + htonl(ulen + IPPROTO_UDP));
1365 		}
1366 		uh->uh_sum ^= 0xffff;
1367 	} else {
1368 		udp_in6_cksum_stats(ulen);
1369 		uh->uh_sum = in6_cksum(m, IPPROTO_UDP, off, ulen);
1370 	}
1371 
1372 	if (uh->uh_sum != 0) {
1373 badsum:
1374 		udpstat.udps_badsum++;
1375 		IF_UDP_STATINC(ifp, badchksum);
1376 		return -1;
1377 	}
1378 
1379 	return 0;
1380 }
1381 
1382 int
udp6_defunct(struct socket * so)1383 udp6_defunct(struct socket *so)
1384 {
1385 	struct ip_moptions *__single imo;
1386 	struct ip6_moptions *__single im6o;
1387 	struct inpcb *__single inp;
1388 
1389 	inp = sotoinpcb(so);
1390 	if (inp == NULL) {
1391 		return EINVAL;
1392 	}
1393 
1394 	im6o = inp->in6p_moptions;
1395 	inp->in6p_moptions = NULL;
1396 	if (im6o != NULL) {
1397 		struct proc *p = current_proc();
1398 
1399 		SODEFUNCTLOG("%s[%d, %s]: defuncting so 0x%llu drop ipv6 multicast memberships",
1400 		    __func__, proc_pid(p), proc_best_name(p),
1401 		    so->so_gencnt);
1402 		IM6O_REMREF(im6o);
1403 	}
1404 	imo = inp->inp_moptions;
1405 	if (imo != NULL) {
1406 		struct proc *__single p = current_proc();
1407 
1408 		SODEFUNCTLOG("%s[%d, %s]: defuncting so 0x%llu drop ipv4 multicast memberships",
1409 		    __func__, proc_pid(p), proc_best_name(p),
1410 		    so->so_gencnt);
1411 
1412 		inp->inp_moptions = NULL;
1413 
1414 		IMO_REMREF(imo);
1415 	}
1416 
1417 	return 0;
1418 }
1419