xref: /xnu-11215.41.3/bsd/netinet6/udp6_usrreq.c (revision 33de042d024d46de5ff4e89f2471de6608e37fa4)
1 /*
2  * Copyright (c) 2000-2024 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 
29 /*	$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 			m_freem(n);
219 			m_freem(opts);
220 			return;
221 		}
222 	}
223 	m_adj(n, off);
224 	if (nstat_collect) {
225 		stats_functional_type ifnet_count_type = IFNET_COUNT_TYPE(ifp);
226 		INP_ADD_STAT(last, ifnet_count_type, rxpackets, 1);
227 		INP_ADD_STAT(last, ifnet_count_type, rxbytes, n->m_pkthdr.len);
228 		inp_set_activity_bitmap(last);
229 	}
230 	so_recv_data_stat(last->in6p_socket, n, 0);
231 	if (sbappendaddr(&last->in6p_socket->so_rcv,
232 	    SA(udp_in6), n, opts, NULL) == 0) {
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_none;
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_IP_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_IP_BAD_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 			}
437 			if (skipit == 0)
438 #endif /* NECP */
439 			{
440 				struct mbuf *__single n = NULL;
441 				/*
442 				 * KAME NOTE: do not
443 				 * m_copy(m, offset, ...) below.
444 				 * sbappendaddr() expects M_PKTHDR,
445 				 * and m_copy() will copy M_PKTHDR
446 				 * only if offset is 0.
447 				 */
448 				if (reuse_sock) {
449 					n = m_copy(m, 0, M_COPYALL);
450 				}
451 				udp6_append(in6p, ip6, &udp_in6, m,
452 				    off + sizeof(struct udphdr), ifp);
453 				mcast_delivered++;
454 				m = n;
455 			}
456 			if (is_wake_pkt) {
457 				soevent(in6p->in6p_socket,
458 				    SO_FILT_HINT_LOCKED | SO_FILT_HINT_WAKE_PKT);
459 			}
460 			udp_unlock(in6p->in6p_socket, 1, 0);
461 
462 			/*
463 			 * Don't look for additional matches if this one does
464 			 * not have either the SO_REUSEPORT or SO_REUSEADDR
465 			 * socket options set.  This heuristic avoids searching
466 			 * through all pcbs in the common case of a non-shared
467 			 * port.  It assumes that an application will never
468 			 * clear these options after setting them.
469 			 */
470 			if (reuse_sock == 0 || m == NULL) {
471 				break;
472 			}
473 
474 			/*
475 			 * Expect 32-bit aligned data pointer on strict-align
476 			 * platforms.
477 			 */
478 			MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);
479 
480 			/*
481 			 * Recompute IP and UDP header pointers for new mbuf
482 			 */
483 			ip6 = mtod(m, struct ip6_hdr *);
484 			uh = (struct udphdr *)(void *)((caddr_t)ip6 + off);
485 		}
486 		lck_rw_done(&pcbinfo->ipi_lock);
487 
488 		if (mcast_delivered == 0) {
489 			/*
490 			 * No matching pcb found; discard datagram.
491 			 * (No need to send an ICMP Port Unreachable
492 			 * for a broadcast or multicast datgram.)
493 			 */
494 			udpstat.udps_noport++;
495 			udpstat.udps_noportmcast++;
496 			IF_UDP_STATINC(ifp, port_unreach);
497 			drop_reason = DROP_REASON_IP_UNREACHABLE_PORT;
498 			goto bad;
499 		}
500 
501 		/* free the extra copy of mbuf or skipped by NECP */
502 		if (m != NULL) {
503 			m_freem(m);
504 		}
505 		return IPPROTO_DONE;
506 	}
507 
508 #if IPSEC
509 	/*
510 	 * UDP to port 4500 with a payload where the first four bytes are
511 	 * not zero is a UDP encapsulated IPsec packet. Packets where
512 	 * the payload is one byte and that byte is 0xFF are NAT keepalive
513 	 * packets. Decapsulate the ESP packet and carry on with IPsec input
514 	 * or discard the NAT keep-alive.
515 	 */
516 	if (ipsec_bypass == 0 && (esp_udp_encap_port & 0xFFFF) != 0 &&
517 	    (uh->uh_dport == ntohs((u_short)esp_udp_encap_port) ||
518 	    uh->uh_sport == ntohs((u_short)esp_udp_encap_port))) {
519 		union sockaddr_in_4_6 src = {};
520 		union sockaddr_in_4_6 dst = {};
521 
522 		ipsec_fill_ip6_sockaddr_4_6_with_ifscope(&src, &ip6->ip6_src,
523 		    uh->uh_sport, ip6_input_getsrcifscope(m));
524 		ipsec_fill_ip6_sockaddr_4_6_with_ifscope(&dst, &ip6->ip6_dst,
525 		    uh->uh_dport, ip6_input_getdstifscope(m));
526 
527 		/*
528 		 * Check if ESP or keepalive:
529 		 *      1. If the destination port of the incoming packet is 4500.
530 		 *      2. If the source port of the incoming packet is 4500,
531 		 *         then check the SADB to match IP address and port.
532 		 */
533 		bool check_esp = true;
534 		if (uh->uh_dport != ntohs((u_short)esp_udp_encap_port)) {
535 			check_esp = key_checksa_present(&dst, &src);
536 		}
537 
538 		if (check_esp) {
539 			int payload_len = ulen - sizeof(struct udphdr) > 4 ? 4 :
540 			    ulen - sizeof(struct udphdr);
541 
542 			if (m->m_len < off + sizeof(struct udphdr) + payload_len) {
543 				if ((m = m_pullup(m, off + sizeof(struct udphdr) +
544 				    payload_len)) == NULL) {
545 					udpstat.udps_hdrops++;
546 					goto bad;
547 				}
548 				/*
549 				 * Expect 32-bit aligned data pointer on strict-align
550 				 * platforms.
551 				 */
552 				MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);
553 
554 				ip6 = mtod(m, struct ip6_hdr *);
555 				uh = (struct udphdr *)(void *)((caddr_t)ip6 + off);
556 			}
557 			/* Check for NAT keepalive packet */
558 			if (payload_len == 1 && *(u_int8_t*)
559 			    ((caddr_t)uh + sizeof(struct udphdr)) == 0xFF) {
560 				goto bad;
561 			} else if (payload_len == 4 && *(u_int32_t*)(void *)
562 			    ((caddr_t)uh + sizeof(struct udphdr)) != 0) {
563 				/* UDP encapsulated IPsec packet to pass through NAT */
564 				/* preserve the udp header */
565 				*offp = off + sizeof(struct udphdr);
566 				return esp6_input(mp, offp, IPPROTO_UDP);
567 			}
568 		}
569 	}
570 #endif /* IPSEC */
571 
572 	/*
573 	 * Locate pcb for datagram.
574 	 */
575 	in6p = in6_pcblookup_hash(&udbinfo, &ip6->ip6_src, uh->uh_sport, ip6_input_getsrcifscope(m),
576 	    &ip6->ip6_dst, uh->uh_dport, ip6_input_getdstifscope(m), 1, m->m_pkthdr.rcvif);
577 	if (in6p == NULL) {
578 		IF_UDP_STATINC(ifp, port_unreach);
579 
580 		if (udp_log_in_vain) {
581 			char buf[INET6_ADDRSTRLEN];
582 
583 			strlcpy(buf, ip6_sprintf(&ip6->ip6_dst), sizeof(buf));
584 			if (udp_log_in_vain < 3) {
585 				log(LOG_INFO, "Connection attempt to UDP "
586 				    "%s:%d from %s:%d\n", buf,
587 				    ntohs(uh->uh_dport),
588 				    ip6_sprintf(&ip6->ip6_src),
589 				    ntohs(uh->uh_sport));
590 			} else if (!(m->m_flags & (M_BCAST | M_MCAST)) &&
591 			    !in6_are_addr_equal_scoped(&ip6->ip6_dst, &ip6->ip6_src, ip6_input_getdstifscope(m), ip6_input_getsrcifscope(m))) {
592 				log(LOG_INFO, "Connection attempt "
593 				    "to UDP %s:%d from %s:%d\n", buf,
594 				    ntohs(uh->uh_dport),
595 				    ip6_sprintf(&ip6->ip6_src),
596 				    ntohs(uh->uh_sport));
597 			}
598 		}
599 		udpstat.udps_noport++;
600 		if (m->m_flags & M_MCAST) {
601 			printf("UDP6: M_MCAST is set in a unicast packet.\n");
602 			udpstat.udps_noportmcast++;
603 			IF_UDP_STATINC(ifp, badmcast);
604 			drop_reason = DROP_REASON_IP_MULTICAST_NO_PORT;
605 			goto bad;
606 		}
607 		icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_NOPORT, 0);
608 		return IPPROTO_DONE;
609 	}
610 
611 	/*
612 	 * Construct sockaddr format source address.
613 	 * Stuff source address and datagram in user buffer.
614 	 */
615 	udp_lock(in6p->in6p_socket, 1, 0);
616 
617 #if NECP
618 	if (!necp_socket_is_allowed_to_send_recv_v6(in6p, uh->uh_dport,
619 	    uh->uh_sport, &ip6->ip6_dst, &ip6->ip6_src, ifp, pf_tag, NULL, NULL, NULL, NULL)) {
620 		in_pcb_checkstate(in6p, WNT_RELEASE, 1);
621 		udp_unlock(in6p->in6p_socket, 1, 0);
622 		IF_UDP_STATINC(ifp, badipsec);
623 		drop_reason = DROP_REASON_IP_NECP_POLICY_DROP;
624 		goto bad;
625 	}
626 #endif /* NECP */
627 
628 	if (in_pcb_checkstate(in6p, WNT_RELEASE, 1) == WNT_STOPUSING) {
629 		udp_unlock(in6p->in6p_socket, 1, 0);
630 		IF_UDP_STATINC(ifp, cleanup);
631 		goto bad;
632 	}
633 
634 	init_sin6(&udp_in6, m); /* general init */
635 	udp_in6.sin6_port = uh->uh_sport;
636 	if ((in6p->in6p_flags & INP_CONTROLOPTS) != 0 ||
637 	    SOFLOW_ENABLED(in6p->in6p_socket) ||
638 	    SO_RECV_CONTROL_OPTS(in6p->in6p_socket)) {
639 		ret = ip6_savecontrol(in6p, m, &opts);
640 		if (ret != 0) {
641 			udp_unlock(in6p->in6p_socket, 1, 0);
642 			drop_reason = DROP_REASON_IP_ENOBUFS;
643 			goto bad;
644 		}
645 	}
646 	m_adj(m, off + sizeof(struct udphdr));
647 	if (nstat_collect) {
648 		ifnet_count_type = IFNET_COUNT_TYPE(ifp);
649 		INP_ADD_STAT(in6p, ifnet_count_type, rxpackets, 1);
650 		INP_ADD_STAT(in6p, ifnet_count_type, rxbytes, m->m_pkthdr.len);
651 		inp_set_activity_bitmap(in6p);
652 	}
653 	so_recv_data_stat(in6p->in6p_socket, m, 0);
654 	if (sbappendaddr(&in6p->in6p_socket->so_rcv,
655 	    SA(&udp_in6), m, opts, NULL) == 0) {
656 		m = NULL;
657 		opts = NULL;
658 		udpstat.udps_fullsock++;
659 		udp_unlock(in6p->in6p_socket, 1, 0);
660 		goto bad;
661 	}
662 	if (is_wake_pkt) {
663 		soevent(in6p->in6p_socket, SO_FILT_HINT_LOCKED | SO_FILT_HINT_WAKE_PKT);
664 	}
665 	sorwakeup(in6p->in6p_socket);
666 	udp_unlock(in6p->in6p_socket, 1, 0);
667 	return IPPROTO_DONE;
668 bad:
669 	if (m != NULL) {
670 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, drop_reason, NULL, 0);
671 	}
672 	if (opts != NULL) {
673 		m_freem(opts);
674 	}
675 	return IPPROTO_DONE;
676 }
677 
678 void
udp6_ctlinput(int cmd,struct sockaddr * sa,void * d,__unused struct ifnet * ifp)679 udp6_ctlinput(int cmd, struct sockaddr *sa, void *d, __unused struct ifnet *ifp)
680 {
681 	struct udphdr uh;
682 	struct ip6_hdr *ip6;
683 	struct mbuf *m;
684 	int off = 0;
685 	struct ip6ctlparam *__single ip6cp = NULL;
686 	struct icmp6_hdr *__single icmp6 = NULL;
687 	const struct sockaddr_in6 *__single sa6_src = NULL;
688 	void *__single cmdarg = NULL;
689 	void (*notify)(struct inpcb *, int) = udp_notify;
690 	struct inpcb *__single in6p;
691 	struct udp_portonly {
692 		u_int16_t uh_sport;
693 		u_int16_t uh_dport;
694 	} *uhp;
695 
696 	if (sa->sa_family != AF_INET6 ||
697 	    sa->sa_len != sizeof(struct sockaddr_in6)) {
698 		return;
699 	}
700 
701 	if ((unsigned)cmd >= PRC_NCMDS) {
702 		return;
703 	}
704 	if (PRC_IS_REDIRECT(cmd)) {
705 		notify = in6_rtchange;
706 		d = NULL;
707 	} else if (cmd == PRC_HOSTDEAD) {
708 		d = NULL;
709 	} else if (inet6ctlerrmap[cmd] == 0) {
710 		return;
711 	}
712 
713 	/* if the parameter is from icmp6, decode it. */
714 	if (d != NULL) {
715 		ip6cp = (struct ip6ctlparam *)d;
716 		icmp6 = ip6cp->ip6c_icmp6;
717 		m = ip6cp->ip6c_m;
718 		ip6 = ip6cp->ip6c_ip6;
719 		off = ip6cp->ip6c_off;
720 		cmdarg = ip6cp->ip6c_cmdarg;
721 		sa6_src = ip6cp->ip6c_src;
722 	} else {
723 		m = NULL;
724 		ip6 = NULL;
725 		cmdarg = NULL;
726 		sa6_src = &sa6_any;
727 	}
728 
729 	if (ip6 != NULL) {
730 #if SKYWALK
731 		union sockaddr_in_4_6 sock_laddr;
732 		struct protoctl_ev_val prctl_ev_val;
733 #endif /* SKYWALK */
734 		/*
735 		 * XXX: We assume that when IPV6 is non NULL,
736 		 * M and OFF are valid.
737 		 */
738 		/* check if we can safely examine src and dst ports */
739 		if (m->m_pkthdr.len < off + sizeof(*uhp)) {
740 			return;
741 		}
742 
743 		bzero(&uh, sizeof(uh));
744 		m_copydata(m, off, sizeof(*uhp), (caddr_t)&uh);
745 
746 		in6p = in6_pcblookup_hash(&udbinfo, &ip6->ip6_dst, uh.uh_dport, ip6_input_getdstifscope(m),
747 		    &ip6->ip6_src, uh.uh_sport, ip6_input_getsrcifscope(m), 0, NULL);
748 		if (cmd == PRC_MSGSIZE && in6p != NULL && !uuid_is_null(in6p->necp_client_uuid)) {
749 			uuid_t null_uuid;
750 			uuid_clear(null_uuid);
751 			necp_update_flow_protoctl_event(null_uuid, in6p->necp_client_uuid,
752 			    PRC_MSGSIZE, ntohl(icmp6->icmp6_mtu), 0);
753 			/*
754 			 * Avoid setting so_error when using Network.framework
755 			 * since the notification of PRC_MSGSIZE has been delivered
756 			 * through NECP.
757 			 */
758 			in6_pcbnotify(&udbinfo, sa, uh.uh_dport,
759 			    SA(ip6cp->ip6c_src), uh.uh_sport,
760 			    cmd, cmdarg, NULL);
761 		} else {
762 			in6_pcbnotify(&udbinfo, sa, uh.uh_dport,
763 			    SA(ip6cp->ip6c_src), uh.uh_sport,
764 			    cmd, cmdarg, notify);
765 		}
766 #if SKYWALK
767 		bzero(&prctl_ev_val, sizeof(prctl_ev_val));
768 		bzero(&sock_laddr, sizeof(sock_laddr));
769 
770 		if (cmd == PRC_MSGSIZE && icmp6 != NULL) {
771 			prctl_ev_val.val = ntohl(icmp6->icmp6_mtu);
772 		}
773 		sock_laddr.sin6.sin6_family = AF_INET6;
774 		sock_laddr.sin6.sin6_len = sizeof(sock_laddr.sin6);
775 		sock_laddr.sin6.sin6_addr = ip6->ip6_src;
776 
777 		protoctl_event_enqueue_nwk_wq_entry(ifp,
778 		    SA(&sock_laddr), sa,
779 		    uh.uh_sport, uh.uh_dport, IPPROTO_UDP,
780 		    cmd, &prctl_ev_val);
781 #endif /* SKYWALK */
782 	}
783 	/*
784 	 * XXX The else condition here was broken for a long time.
785 	 * Fixing it made us deliver notification correctly but broke
786 	 * some frameworks that didn't handle it well.
787 	 * For now we have removed it and will revisit it later.
788 	 */
789 }
790 
791 static int
udp6_abort(struct socket * so)792 udp6_abort(struct socket *so)
793 {
794 	struct inpcb *__single inp;
795 
796 	inp = sotoinpcb(so);
797 	if (inp == NULL) {
798 		panic("%s: so=%p null inp", __func__, so);
799 		/* NOTREACHED */
800 	}
801 	soisdisconnected(so);
802 	in6_pcbdetach(inp);
803 	return 0;
804 }
805 
806 static int
udp6_attach(struct socket * so,int proto,struct proc * p)807 udp6_attach(struct socket *so, int proto, struct proc *p)
808 {
809 #pragma unused(proto)
810 	struct inpcb *__single inp;
811 	int error;
812 
813 	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
814 		error = soreserve(so, udp_sendspace, udp_recvspace);
815 		if (error) {
816 			return error;
817 		}
818 	}
819 
820 	inp = sotoinpcb(so);
821 	if (inp != NULL) {
822 		return EINVAL;
823 	}
824 
825 	error = in_pcballoc(so, &udbinfo, p);
826 	if (error) {
827 		return error;
828 	}
829 
830 	inp = (struct inpcb *)so->so_pcb;
831 	inp->inp_vflag |= INP_IPV6;
832 	if (ip6_mapped_addr_on) {
833 		inp->inp_vflag |= INP_IPV4;
834 	}
835 	inp->in6p_hops = -1;    /* use kernel default */
836 	inp->in6p_cksum = -1;   /* just to be sure */
837 	/*
838 	 * XXX: ugly!!
839 	 * IPv4 TTL initialization is necessary for an IPv6 socket as well,
840 	 * because the socket may be bound to an IPv6 wildcard address,
841 	 * which may match an IPv4-mapped IPv6 address.
842 	 */
843 	inp->inp_ip_ttl = (u_char)ip_defttl;
844 	if (nstat_collect) {
845 		nstat_udp_new_pcb(inp);
846 	}
847 	return 0;
848 }
849 
850 static int
udp6_bind(struct socket * so,struct sockaddr * nam,struct proc * p)851 udp6_bind(struct socket *so, struct sockaddr *nam, struct proc *p)
852 {
853 	struct inpcb *__single inp;
854 	int error;
855 
856 	inp = sotoinpcb(so);
857 	if (inp == NULL) {
858 		return EINVAL;
859 	}
860 	/*
861 	 * Another thread won the binding race so do not change inp_vflag
862 	 */
863 	if (inp->inp_flags2 & INP2_BIND_IN_PROGRESS) {
864 		return EINVAL;
865 	}
866 
867 	const uint8_t old_flags = inp->inp_vflag;
868 	inp->inp_vflag &= ~INP_IPV4;
869 	inp->inp_vflag |= INP_IPV6;
870 
871 	if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0) {
872 		struct sockaddr_in6 *__single sin6_p;
873 
874 		sin6_p = SIN6(nam);
875 
876 		if (IN6_IS_ADDR_UNSPECIFIED(&sin6_p->sin6_addr)) {
877 			inp->inp_vflag |= INP_IPV4;
878 			inp->inp_vflag &= ~INP_V4MAPPEDV6;
879 		} else if (IN6_IS_ADDR_V4MAPPED(&sin6_p->sin6_addr)) {
880 			struct sockaddr_in sin;
881 
882 			in6_sin6_2_sin(&sin, sin6_p);
883 			inp->inp_vflag |= INP_IPV4;
884 			inp->inp_vflag &= ~INP_IPV6;
885 			inp->inp_vflag |= INP_V4MAPPEDV6;
886 
887 			error = in_pcbbind(inp, SA(&sin), NULL, p);
888 			if (error != 0) {
889 				inp->inp_vflag = old_flags;
890 			}
891 			return error;
892 		}
893 	}
894 
895 	error = in6_pcbbind(inp, nam, NULL, p);
896 	if (error != 0) {
897 		inp->inp_vflag = old_flags;
898 	}
899 
900 	UDP_LOG_BIND(inp, error);
901 
902 	return error;
903 }
904 
905 int
udp6_connect(struct socket * so,struct sockaddr * nam,struct proc * p)906 udp6_connect(struct socket *so, struct sockaddr *nam, struct proc *p)
907 {
908 	struct inpcb *__single inp;
909 	int error;
910 	struct sockaddr_in6 *__single sin6_p = SIN6(nam);
911 
912 #if defined(NECP) && defined(FLOW_DIVERT)
913 	int should_use_flow_divert = 0;
914 #endif /* defined(NECP) && defined(FLOW_DIVERT) */
915 
916 	inp = sotoinpcb(so);
917 	if (inp == NULL) {
918 		return EINVAL;
919 	}
920 
921 #if defined(NECP) && defined(FLOW_DIVERT)
922 	should_use_flow_divert = necp_socket_should_use_flow_divert(inp);
923 #endif /* defined(NECP) && defined(FLOW_DIVERT) */
924 
925 	/*
926 	 * It is possible that the socket is bound to v4 mapped v6 address.
927 	 * Post that do not allow connect to a v6 endpoint.
928 	 */
929 	if (inp->inp_vflag & INP_V4MAPPEDV6 &&
930 	    !IN6_IS_ADDR_V4MAPPED(&sin6_p->sin6_addr)) {
931 		if (IN6_IS_ADDR_UNSPECIFIED(&sin6_p->sin6_addr)) {
932 			sin6_p->sin6_addr.s6_addr[10] = 0xff;
933 			sin6_p->sin6_addr.s6_addr[11] = 0xff;
934 		} else {
935 			return EINVAL;
936 		}
937 	}
938 
939 	if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0) {
940 		if (IN6_IS_ADDR_V4MAPPED(&sin6_p->sin6_addr)) {
941 			struct sockaddr_in sin;
942 			const uint8_t old_flags = inp->inp_vflag;
943 
944 			if (inp->inp_faddr.s_addr != INADDR_ANY) {
945 				return EISCONN;
946 			}
947 
948 			if (!(so->so_flags1 & SOF1_CONNECT_COUNTED)) {
949 				so->so_flags1 |= SOF1_CONNECT_COUNTED;
950 				INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_inet_dgram_connected);
951 			}
952 
953 			in6_sin6_2_sin(&sin, sin6_p);
954 #if defined(NECP) && defined(FLOW_DIVERT)
955 			if (should_use_flow_divert) {
956 				goto do_flow_divert;
957 			}
958 #endif /* defined(NECP) && defined(FLOW_DIVERT) */
959 			inp->inp_vflag |= INP_IPV4;
960 			inp->inp_vflag &= ~INP_IPV6;
961 			inp->inp_vflag |= INP_V4MAPPEDV6;
962 
963 			error = in_pcbconnect(inp, SA(&sin), p, IFSCOPE_NONE, NULL);
964 			if (error == 0) {
965 #if NECP
966 				/* Update NECP client with connected five-tuple */
967 				if (!uuid_is_null(inp->necp_client_uuid)) {
968 					socket_unlock(so, 0);
969 					necp_client_assign_from_socket(so->last_pid, inp->necp_client_uuid, inp);
970 					socket_lock(so, 0);
971 				}
972 #endif /* NECP */
973 				soisconnected(so);
974 			} else {
975 				inp->inp_vflag = old_flags;
976 			}
977 			UDP_LOG_CONNECT(inp, error);
978 			return error;
979 		}
980 	}
981 
982 	if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
983 		return EISCONN;
984 	}
985 
986 	if (!(so->so_flags1 & SOF1_CONNECT_COUNTED)) {
987 		so->so_flags1 |= SOF1_CONNECT_COUNTED;
988 		INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_inet6_dgram_connected);
989 	}
990 
991 #if defined(NECP) && defined(FLOW_DIVERT)
992 do_flow_divert:
993 	if (should_use_flow_divert) {
994 		error = flow_divert_pcb_init(so);
995 		if (error == 0) {
996 			error = flow_divert_connect_out(so, nam, p);
997 		}
998 		return error;
999 	}
1000 #endif /* defined(NECP) && defined(FLOW_DIVERT) */
1001 
1002 	error = in6_pcbconnect(inp, nam, p);
1003 	if (error == 0) {
1004 		/* should be non mapped addr */
1005 		if (ip6_mapped_addr_on ||
1006 		    (inp->inp_flags & IN6P_IPV6_V6ONLY) == 0) {
1007 			inp->inp_vflag &= ~INP_IPV4;
1008 			inp->inp_vflag |= INP_IPV6;
1009 		}
1010 #if NECP
1011 		/* Update NECP client with connected five-tuple */
1012 		if (!uuid_is_null(inp->necp_client_uuid)) {
1013 			socket_unlock(so, 0);
1014 			necp_client_assign_from_socket(so->last_pid, inp->necp_client_uuid, inp);
1015 			socket_lock(so, 0);
1016 		}
1017 #endif /* NECP */
1018 		soisconnected(so);
1019 		if (inp->inp_flowhash == 0) {
1020 			inp_calc_flowhash(inp);
1021 			ASSERT(inp->inp_flowhash != 0);
1022 		}
1023 		/* update flowinfo - RFC 6437 */
1024 		if (inp->inp_flow == 0 &&
1025 		    inp->in6p_flags & IN6P_AUTOFLOWLABEL) {
1026 			inp->inp_flow &= ~IPV6_FLOWLABEL_MASK;
1027 			inp->inp_flow |=
1028 			    (htonl(ip6_randomflowlabel()) & IPV6_FLOWLABEL_MASK);
1029 		}
1030 		inp->inp_connect_timestamp = mach_continuous_time();
1031 	}
1032 	UDP_LOG_CONNECT(inp, error);
1033 	return error;
1034 }
1035 
1036 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)1037 udp6_connectx(struct socket *so, struct sockaddr *src,
1038     struct sockaddr *dst, struct proc *p, uint32_t ifscope,
1039     sae_associd_t aid, sae_connid_t *pcid, uint32_t flags, void *arg,
1040     uint32_t arglen, struct uio *uio, user_ssize_t *bytes_written)
1041 {
1042 	return udp_connectx_common(so, AF_INET6, src, dst,
1043 	           p, ifscope, aid, pcid, flags, arg, arglen, uio, bytes_written);
1044 }
1045 
1046 static int
udp6_detach(struct socket * so)1047 udp6_detach(struct socket *so)
1048 {
1049 	struct inpcb *__single inp;
1050 
1051 	inp = sotoinpcb(so);
1052 	if (inp == NULL) {
1053 		return EINVAL;
1054 	}
1055 
1056 	UDP_LOG_CONNECTION_SUMMARY(inp);
1057 
1058 	in6_pcbdetach(inp);
1059 	return 0;
1060 }
1061 
1062 static int
udp6_disconnect(struct socket * so)1063 udp6_disconnect(struct socket *so)
1064 {
1065 	struct inpcb *__single inp;
1066 
1067 	inp = sotoinpcb(so);
1068 	if (inp == NULL
1069 #if NECP
1070 	    || (necp_socket_should_use_flow_divert(inp))
1071 #endif /* NECP */
1072 	    ) {
1073 		return inp == NULL ? EINVAL : EPROTOTYPE;
1074 	}
1075 
1076 	if (inp->inp_vflag & INP_IPV4) {
1077 		struct pr_usrreqs *__single pru;
1078 
1079 		pru = ip_protox[IPPROTO_UDP]->pr_usrreqs;
1080 		return (*pru->pru_disconnect)(so);
1081 	}
1082 
1083 	if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
1084 		return ENOTCONN;
1085 	}
1086 
1087 	UDP_LOG_CONNECTION_SUMMARY(inp);
1088 
1089 	in6_pcbdisconnect(inp);
1090 
1091 	/* reset flow-controlled state, just in case */
1092 	inp_reset_fc_state(inp);
1093 
1094 	inp->in6p_laddr = in6addr_any;
1095 	inp->inp_lifscope = IFSCOPE_NONE;
1096 	inp->in6p_last_outifp = NULL;
1097 #if SKYWALK
1098 	if (NETNS_TOKEN_VALID(&inp->inp_netns_token)) {
1099 		netns_set_ifnet(&inp->inp_netns_token, NULL);
1100 	}
1101 #endif /* SKYWALK */
1102 
1103 	so->so_state &= ~SS_ISCONNECTED;                /* XXX */
1104 	return 0;
1105 }
1106 
1107 static int
udp6_disconnectx(struct socket * so,sae_associd_t aid,sae_connid_t cid)1108 udp6_disconnectx(struct socket *so, sae_associd_t aid, sae_connid_t cid)
1109 {
1110 #pragma unused(cid)
1111 	if (aid != SAE_ASSOCID_ANY && aid != SAE_ASSOCID_ALL) {
1112 		return EINVAL;
1113 	}
1114 
1115 	return udp6_disconnect(so);
1116 }
1117 
1118 static int
udp6_send(struct socket * so,int flags,struct mbuf * m,struct sockaddr * addr,struct mbuf * control,struct proc * p)1119 udp6_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *addr,
1120     struct mbuf *control, struct proc *p)
1121 {
1122 	struct inpcb *__single inp;
1123 	int error = 0;
1124 #if defined(NECP) && defined(FLOW_DIVERT)
1125 	int should_use_flow_divert = 0;
1126 #endif /* defined(NECP) && defined(FLOW_DIVERT) */
1127 #if CONTENT_FILTER
1128 	struct m_tag *__single cfil_tag = NULL;
1129 	struct sockaddr *__single cfil_faddr = NULL;
1130 #endif
1131 
1132 	inp = sotoinpcb(so);
1133 	if (inp == NULL) {
1134 		error = EINVAL;
1135 		goto bad;
1136 	}
1137 
1138 #if CONTENT_FILTER
1139 	/* If socket is subject to UDP Content Filter and unconnected, get addr from tag. */
1140 	if (CFIL_DGRAM_FILTERED(so) && !addr && IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
1141 		cfil_tag = cfil_dgram_get_socket_state(m, NULL, NULL, &cfil_faddr, NULL);
1142 		if (cfil_tag) {
1143 			addr = SA(cfil_faddr);
1144 		}
1145 	}
1146 #endif
1147 
1148 #if defined(NECP) && defined(FLOW_DIVERT)
1149 	should_use_flow_divert = necp_socket_should_use_flow_divert(inp);
1150 #endif /* defined(NECP) && defined(FLOW_DIVERT) */
1151 
1152 	if (addr != NULL) {
1153 		if (addr->sa_len != sizeof(struct sockaddr_in6)) {
1154 			error = EINVAL;
1155 			goto bad;
1156 		}
1157 		if (addr->sa_family != AF_INET6) {
1158 			error = EAFNOSUPPORT;
1159 			goto bad;
1160 		}
1161 	}
1162 
1163 	if (ip6_mapped_addr_on || (inp->inp_flags & IN6P_IPV6_V6ONLY) == 0) {
1164 		int hasv4addr;
1165 		struct sockaddr_in6 *__single sin6 = NULL;
1166 
1167 		if (addr == NULL) {
1168 			hasv4addr = (inp->inp_vflag & INP_IPV4);
1169 		} else {
1170 			sin6 = SIN6(addr);
1171 			hasv4addr =
1172 			    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ? 1 : 0;
1173 		}
1174 		if (hasv4addr) {
1175 			struct pr_usrreqs *__single pru;
1176 
1177 			if (sin6 != NULL) {
1178 				in6_sin6_2_sin_in_sock(addr);
1179 			}
1180 #if defined(NECP) && defined(FLOW_DIVERT)
1181 			if (should_use_flow_divert) {
1182 				goto do_flow_divert;
1183 			}
1184 #endif /* defined(NECP) && defined(FLOW_DIVERT) */
1185 			pru = ip_protox[IPPROTO_UDP]->pr_usrreqs;
1186 			error = ((*pru->pru_send)(so, flags, m, addr,
1187 			    control, p));
1188 #if CONTENT_FILTER
1189 			if (cfil_tag) {
1190 				m_tag_free(cfil_tag);
1191 			}
1192 #endif
1193 			/* addr will just be freed in sendit(). */
1194 			return error;
1195 		}
1196 	}
1197 
1198 #if defined(NECP) && defined(FLOW_DIVERT)
1199 do_flow_divert:
1200 	if (should_use_flow_divert) {
1201 		/* Implicit connect */
1202 		error = flow_divert_implicit_data_out(so, flags, m, addr, control, p);
1203 #if CONTENT_FILTER
1204 		if (cfil_tag) {
1205 			m_tag_free(cfil_tag);
1206 		}
1207 #endif
1208 		return error;
1209 	}
1210 #endif /* defined(NECP) && defined(FLOW_DIVERT) */
1211 
1212 	so_update_tx_data_stats(so, 1, m->m_pkthdr.len);
1213 
1214 #if SKYWALK
1215 	sk_protect_t __single protect = sk_async_transmit_protect();
1216 #endif /* SKYWALK */
1217 	error = udp6_output(inp, m, addr, control, p);
1218 #if SKYWALK
1219 	sk_async_transmit_unprotect(protect);
1220 #endif /* SKYWALK */
1221 
1222 #if CONTENT_FILTER
1223 	if (cfil_tag) {
1224 		m_tag_free(cfil_tag);
1225 	}
1226 #endif
1227 	return error;
1228 
1229 bad:
1230 	VERIFY(error != 0);
1231 
1232 	if (m != NULL) {
1233 		m_freem(m);
1234 	}
1235 	if (control != NULL) {
1236 		m_freem(control);
1237 	}
1238 #if CONTENT_FILTER
1239 	if (cfil_tag) {
1240 		m_tag_free(cfil_tag);
1241 	}
1242 #endif
1243 	return error;
1244 }
1245 
1246 /*
1247  * Checksum extended UDP header and data.
1248  */
1249 static int
udp6_input_checksum(struct mbuf * m,struct udphdr * uh,int off,int ulen)1250 udp6_input_checksum(struct mbuf *m, struct udphdr *uh, int off, int ulen)
1251 {
1252 	struct ifnet *__single ifp = m->m_pkthdr.rcvif;
1253 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
1254 
1255 	if (!(m->m_pkthdr.csum_flags & CSUM_DATA_VALID) &&
1256 	    uh->uh_sum == 0) {
1257 		/* UDP/IPv6 checksum is mandatory (RFC2460) */
1258 
1259 		/*
1260 		 * If checksum was already validated, ignore this check.
1261 		 * This is necessary for transport-mode ESP, which may be
1262 		 * getting UDP payloads without checksums when the network
1263 		 * has a NAT64.
1264 		 */
1265 		udpstat.udps_nosum++;
1266 		goto badsum;
1267 	}
1268 
1269 	if ((hwcksum_rx || (ifp->if_flags & IFF_LOOPBACK) ||
1270 	    (m->m_pkthdr.pkt_flags & PKTF_LOOP)) &&
1271 	    (m->m_pkthdr.csum_flags & CSUM_DATA_VALID)) {
1272 		if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
1273 			uh->uh_sum = m->m_pkthdr.csum_rx_val;
1274 		} else {
1275 			uint32_t sum = m->m_pkthdr.csum_rx_val;
1276 			uint32_t start = m->m_pkthdr.csum_rx_start;
1277 			int32_t trailer = (m_pktlen(m) - (off + ulen));
1278 
1279 			/*
1280 			 * Perform 1's complement adjustment of octets
1281 			 * that got included/excluded in the hardware-
1282 			 * calculated checksum value.  Also take care
1283 			 * of any trailing bytes and subtract out
1284 			 * their partial sum.
1285 			 */
1286 			ASSERT(trailer >= 0);
1287 			if ((m->m_pkthdr.csum_flags & CSUM_PARTIAL) &&
1288 			    (start != off || trailer != 0)) {
1289 				uint32_t swbytes = (uint32_t)trailer;
1290 				uint16_t s = 0, d = 0;
1291 
1292 				if (IN6_IS_SCOPE_EMBED(&ip6->ip6_src)) {
1293 					s = ip6->ip6_src.s6_addr16[1];
1294 					ip6->ip6_src.s6_addr16[1] = 0;
1295 				}
1296 				if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst)) {
1297 					d = ip6->ip6_dst.s6_addr16[1];
1298 					ip6->ip6_dst.s6_addr16[1] = 0;
1299 				}
1300 
1301 				/* callee folds in sum */
1302 				sum = m_adj_sum16(m, start, off, ulen, sum);
1303 				if (off > start) {
1304 					swbytes += (off - start);
1305 				} else {
1306 					swbytes += (start - off);
1307 				}
1308 
1309 				if (IN6_IS_SCOPE_EMBED(&ip6->ip6_src)) {
1310 					ip6->ip6_src.s6_addr16[1] = s;
1311 				}
1312 				if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst)) {
1313 					ip6->ip6_dst.s6_addr16[1] = d;
1314 				}
1315 
1316 				if (swbytes != 0) {
1317 					udp_in_cksum_stats(swbytes);
1318 				}
1319 				if (trailer != 0) {
1320 					m_adj(m, -trailer);
1321 				}
1322 			}
1323 
1324 			uh->uh_sum = in6_pseudo(&ip6->ip6_src, &ip6->ip6_dst,
1325 			    sum + htonl(ulen + IPPROTO_UDP));
1326 		}
1327 		uh->uh_sum ^= 0xffff;
1328 	} else {
1329 		udp_in6_cksum_stats(ulen);
1330 		uh->uh_sum = in6_cksum(m, IPPROTO_UDP, off, ulen);
1331 	}
1332 
1333 	if (uh->uh_sum != 0) {
1334 badsum:
1335 		udpstat.udps_badsum++;
1336 		IF_UDP_STATINC(ifp, badchksum);
1337 		return -1;
1338 	}
1339 
1340 	return 0;
1341 }
1342 
1343 int
udp6_defunct(struct socket * so)1344 udp6_defunct(struct socket *so)
1345 {
1346 	struct ip_moptions *__single imo;
1347 	struct ip6_moptions *__single im6o;
1348 	struct inpcb *__single inp;
1349 
1350 	inp = sotoinpcb(so);
1351 	if (inp == NULL) {
1352 		return EINVAL;
1353 	}
1354 
1355 	im6o = inp->in6p_moptions;
1356 	inp->in6p_moptions = NULL;
1357 	if (im6o != NULL) {
1358 		struct proc *p = current_proc();
1359 
1360 		SODEFUNCTLOG("%s[%d, %s]: defuncting so 0x%llu drop ipv6 multicast memberships",
1361 		    __func__, proc_pid(p), proc_best_name(p),
1362 		    so->so_gencnt);
1363 		IM6O_REMREF(im6o);
1364 	}
1365 	imo = inp->inp_moptions;
1366 	if (imo != NULL) {
1367 		struct proc *__single p = current_proc();
1368 
1369 		SODEFUNCTLOG("%s[%d, %s]: defuncting so 0x%llu drop ipv4 multicast memberships",
1370 		    __func__, proc_pid(p), proc_best_name(p),
1371 		    so->so_gencnt);
1372 
1373 		inp->inp_moptions = NULL;
1374 
1375 		IMO_REMREF(imo);
1376 	}
1377 
1378 	return 0;
1379 }
1380