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