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