xref: /xnu-10002.41.9/bsd/netinet/tcp_usrreq.c (revision 699cd48037512bf4380799317ca44ca453c82f57)
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  * Copyright (c) 1982, 1986, 1988, 1993
30  *	The Regents of the University of California.  All rights reserved.
31  *
32  * Redistribution and use in source and binary forms, with or without
33  * modification, are permitted provided that the following conditions
34  * are met:
35  * 1. Redistributions of source code must retain the above copyright
36  *    notice, this list of conditions and the following disclaimer.
37  * 2. Redistributions in binary form must reproduce the above copyright
38  *    notice, this list of conditions and the following disclaimer in the
39  *    documentation and/or other materials provided with the distribution.
40  * 3. All advertising materials mentioning features or use of this software
41  *    must display the following acknowledgement:
42  *	This product includes software developed by the University of
43  *	California, Berkeley and its contributors.
44  * 4. Neither the name of the University nor the names of its contributors
45  *    may be used to endorse or promote products derived from this software
46  *    without specific prior written permission.
47  *
48  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58  * SUCH DAMAGE.
59  *
60  *	From: @(#)tcp_usrreq.c	8.2 (Berkeley) 1/3/94
61  * $FreeBSD: src/sys/netinet/tcp_usrreq.c,v 1.51.2.9 2001/08/22 00:59:12 silby Exp $
62  */
63 
64 
65 #include <sys/param.h>
66 #include <sys/systm.h>
67 #include <sys/kernel.h>
68 #include <sys/sysctl.h>
69 #include <sys/mbuf.h>
70 #include <sys/domain.h>
71 #include <sys/priv.h>
72 #include <sys/socket.h>
73 #include <sys/socketvar.h>
74 #include <sys/protosw.h>
75 #include <sys/syslog.h>
76 
77 #include <net/if.h>
78 #include <net/route.h>
79 #include <net/ntstat.h>
80 #include <net/content_filter.h>
81 #include <net/multi_layer_pkt_log.h>
82 
83 #include <netinet/in.h>
84 #include <netinet/in_systm.h>
85 #include <netinet/ip6.h>
86 #include <netinet/in_pcb.h>
87 #include <netinet6/in6_pcb.h>
88 #include <netinet/in_var.h>
89 #include <netinet/ip_var.h>
90 #include <netinet6/ip6_var.h>
91 #include <netinet/tcp.h>
92 #include <netinet/tcp_fsm.h>
93 #include <netinet/tcp_seq.h>
94 #include <netinet/tcp_timer.h>
95 #include <netinet/tcp_var.h>
96 #include <netinet/tcpip.h>
97 #include <netinet/tcp_cc.h>
98 #include <netinet/tcp_log.h>
99 #include <mach/sdt.h>
100 #if TCPDEBUG
101 #include <netinet/tcp_debug.h>
102 #endif
103 #if MPTCP
104 #include <netinet/mptcp_var.h>
105 #endif /* MPTCP */
106 
107 #if IPSEC
108 #include <netinet6/ipsec.h>
109 #endif /*IPSEC*/
110 
111 #if FLOW_DIVERT
112 #include <netinet/flow_divert.h>
113 #endif /* FLOW_DIVERT */
114 
115 #if SKYWALK
116 #include <libkern/sysctl.h>
117 #include <skywalk/os_stats_private.h>
118 #endif /* SKYWALK */
119 
120 extern char *proc_name_address(void *p);
121 
122 errno_t tcp_fill_info_for_info_tuple(struct info_tuple *, struct tcp_info *);
123 
124 static int tcp_sysctl_info(struct sysctl_oid *, void *, int, struct sysctl_req *);
125 static void tcp_connection_fill_info(struct tcpcb *tp,
126     struct tcp_connection_info *tci);
127 static int tcp_get_mpkl_send_info(struct mbuf *, struct so_mpkl_send_info *);
128 
129 /*
130  * TCP protocol interface to socket abstraction.
131  */
132 static int      tcp_attach(struct socket *, struct proc *);
133 static int      tcp_connect(struct tcpcb *, struct sockaddr *, struct proc *);
134 static int      tcp6_connect(struct tcpcb *, struct sockaddr *, struct proc *);
135 static int      tcp6_usr_connect(struct socket *, struct sockaddr *,
136     struct proc *);
137 static struct tcpcb *tcp_disconnect(struct tcpcb *);
138 static struct tcpcb *tcp_usrclosed(struct tcpcb *);
139 extern void tcp_sbrcv_trim(struct tcpcb *tp, struct sockbuf *sb);
140 
141 #if TCPDEBUG
142 #define TCPDEBUG0       int ostate = 0
143 #define TCPDEBUG1()     ostate = tp ? tp->t_state : 0
144 #define TCPDEBUG2(req)  if (tp && (so->so_options & SO_DEBUG)) \
145 	                        tcp_trace(TA_USER, ostate, tp, 0, 0, req)
146 #else
147 #define TCPDEBUG0
148 #define TCPDEBUG1()
149 #define TCPDEBUG2(req)
150 #endif
151 
152 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, info,
153     CTLFLAG_RW | CTLFLAG_LOCKED | CTLFLAG_ANYBODY | CTLFLAG_KERN,
154     0, 0, tcp_sysctl_info, "S", "TCP info per tuple");
155 
156 int faster_mcopy = 0;
157 SYSCTL_INT(_net_inet_tcp, OID_AUTO, faster_mcopy,
158     CTLFLAG_RW | CTLFLAG_LOCKED, &faster_mcopy, 0,
159     "Speed up m_copym");
160 
161 /*
162  * TCP attaches to socket via pru_attach(), reserving space,
163  * and an internet control block.
164  *
165  * Returns:	0			Success
166  *		EISCONN
167  *	tcp_attach:ENOBUFS
168  *	tcp_attach:ENOMEM
169  *	tcp_attach:???			[IPSEC specific]
170  */
171 static int
tcp_usr_attach(struct socket * so,__unused int proto,struct proc * p)172 tcp_usr_attach(struct socket *so, __unused int proto, struct proc *p)
173 {
174 	int error;
175 	struct inpcb *inp = sotoinpcb(so);
176 	struct tcpcb *tp = 0;
177 	TCPDEBUG0;
178 
179 	TCPDEBUG1();
180 	if (inp) {
181 		error = EISCONN;
182 		goto out;
183 	}
184 
185 	error = tcp_attach(so, p);
186 	if (error) {
187 		goto out;
188 	}
189 
190 	if ((so->so_options & SO_LINGER) && so->so_linger == 0) {
191 		so->so_linger = (short)(TCP_LINGERTIME * hz);
192 	}
193 	if (faster_mcopy) {
194 		so->so_snd.sb_flags |= SB_SENDHEAD;
195 		so->so_snd.sb_sendhead = NULL;
196 		so->so_snd.sb_sendoff = 0;
197 	}
198 
199 	tp = sototcpcb(so);
200 out:
201 	TCPDEBUG2(PRU_ATTACH);
202 	return error;
203 }
204 
205 /*
206  * pru_detach() detaches the TCP protocol from the socket.
207  * If the protocol state is non-embryonic, then can't
208  * do this directly: have to initiate a pru_disconnect(),
209  * which may finish later; embryonic TCB's can just
210  * be discarded here.
211  */
212 static int
tcp_usr_detach(struct socket * so)213 tcp_usr_detach(struct socket *so)
214 {
215 	int error = 0;
216 	struct inpcb *inp = sotoinpcb(so);
217 	struct tcpcb *tp;
218 	TCPDEBUG0;
219 
220 	if (inp == 0 || (inp->inp_state == INPCB_STATE_DEAD)) {
221 		return EINVAL;  /* XXX */
222 	}
223 	socket_lock_assert_owned(so);
224 	tp = intotcpcb(inp);
225 	/* In case we got disconnected from the peer */
226 	if (tp == NULL) {
227 		goto out;
228 	}
229 	TCPDEBUG1();
230 
231 	calculate_tcp_clock();
232 
233 	tp = tcp_disconnect(tp);
234 out:
235 	TCPDEBUG2(PRU_DETACH);
236 	return error;
237 }
238 
239 #if NECP
240 #define COMMON_START_ALLOW_FLOW_DIVERT(allow)  TCPDEBUG0;               \
241 do {                                                                    \
242 	if (inp == NULL || inp->inp_state == INPCB_STATE_DEAD)          \
243 	        return (EINVAL);                                        \
244 	if (!(allow) && necp_socket_should_use_flow_divert(inp))        \
245 	        return (EPROTOTYPE);                                    \
246 	tp = intotcpcb(inp);                                            \
247 	TCPDEBUG1();                                                    \
248 	calculate_tcp_clock();                                          \
249 } while (0)
250 #else /* NECP */
251 #define COMMON_START_ALLOW_FLOW_DIVERT(allow)  TCPDEBUG0;               \
252 do {                                                                    \
253 	if (inp == NULL || inp->inp_state == INPCB_STATE_DEAD)          \
254 	        return (EINVAL);                                        \
255 	tp = intotcpcb(inp);                                            \
256 	TCPDEBUG1();                                                    \
257 	calculate_tcp_clock();                                          \
258 } while (0)
259 #endif /* !NECP */
260 
261 #define COMMON_START() COMMON_START_ALLOW_FLOW_DIVERT(false)
262 #define COMMON_END(req) out: TCPDEBUG2(req); return error; goto out
263 
264 
265 /*
266  * Give the socket an address.
267  *
268  * Returns:	0			Success
269  *		EINVAL			Invalid argument [COMMON_START]
270  *		EAFNOSUPPORT		Address family not supported
271  *	in_pcbbind:EADDRNOTAVAIL	Address not available.
272  *	in_pcbbind:EINVAL		Invalid argument
273  *	in_pcbbind:EAFNOSUPPORT		Address family not supported [notdef]
274  *	in_pcbbind:EACCES		Permission denied
275  *	in_pcbbind:EADDRINUSE		Address in use
276  *	in_pcbbind:EAGAIN		Resource unavailable, try again
277  *	in_pcbbind:EPERM		Operation not permitted
278  */
279 static int
tcp_usr_bind(struct socket * so,struct sockaddr * nam,struct proc * p)280 tcp_usr_bind(struct socket *so, struct sockaddr *nam, struct proc *p)
281 {
282 	int error = 0;
283 	struct inpcb *inp = sotoinpcb(so);
284 	struct tcpcb *tp;
285 	struct sockaddr_in *sinp;
286 
287 	COMMON_START_ALLOW_FLOW_DIVERT(true);
288 
289 	if (nam->sa_family != 0 && nam->sa_family != AF_INET) {
290 		error = EAFNOSUPPORT;
291 		goto out;
292 	}
293 	/*
294 	 * Must check for multicast and broadcast addresses and disallow binding
295 	 * to them.
296 	 */
297 	sinp = (struct sockaddr_in *)(void *)nam;
298 	if (sinp->sin_family == AF_INET &&
299 	    (IN_MULTICAST(ntohl(sinp->sin_addr.s_addr)) ||
300 	    sinp->sin_addr.s_addr == INADDR_BROADCAST)) {
301 		error = EAFNOSUPPORT;
302 		goto out;
303 	}
304 
305 	error = in_pcbbind(inp, nam, p);
306 	if (error) {
307 		goto out;
308 	}
309 
310 #if NECP
311 	/* Update NECP client with bind result if not in middle of connect */
312 	if ((inp->inp_flags2 & INP2_CONNECT_IN_PROGRESS) &&
313 	    !uuid_is_null(inp->necp_client_uuid)) {
314 		socket_unlock(so, 0);
315 		necp_client_assign_from_socket(so->last_pid, inp->necp_client_uuid, inp);
316 		socket_lock(so, 0);
317 	}
318 #endif /* NECP */
319 
320 	COMMON_END(PRU_BIND);
321 }
322 
323 static int
tcp6_usr_bind(struct socket * so,struct sockaddr * nam,struct proc * p)324 tcp6_usr_bind(struct socket *so, struct sockaddr *nam, struct proc *p)
325 {
326 	int error = 0;
327 	struct inpcb *inp = sotoinpcb(so);
328 	const uint8_t old_flags = inp->inp_vflag;
329 	struct tcpcb *tp;
330 	struct sockaddr_in6 *sin6p;
331 
332 	COMMON_START_ALLOW_FLOW_DIVERT(true);
333 
334 	if (nam->sa_family != 0 && nam->sa_family != AF_INET6) {
335 		error = EAFNOSUPPORT;
336 		goto out;
337 	}
338 	/*
339 	 * Must check for multicast and broadcast addresses and disallow binding
340 	 * to them.
341 	 */
342 	sin6p = (struct sockaddr_in6 *)(void *)nam;
343 	if (sin6p->sin6_family == AF_INET6 &&
344 	    (IN6_IS_ADDR_MULTICAST(&sin6p->sin6_addr) ||
345 	    ((IN6_IS_ADDR_V4MAPPED(&sin6p->sin6_addr) ||
346 	    IN6_IS_ADDR_V4COMPAT(&sin6p->sin6_addr)) &&
347 	    (IN_MULTICAST(ntohl(sin6p->sin6_addr.s6_addr32[3])) ||
348 	    sin6p->sin6_addr.s6_addr32[3] == INADDR_BROADCAST)))) {
349 		error = EAFNOSUPPORT;
350 		goto out;
351 	}
352 
353 	/*
354 	 * Another thread won the binding race so do not change inp_vflag
355 	 */
356 	if (inp->inp_flags2 & INP2_BIND_IN_PROGRESS) {
357 		error = EINVAL;
358 		goto out;
359 	}
360 
361 	inp->inp_vflag &= ~INP_IPV4;
362 	inp->inp_vflag |= INP_IPV6;
363 	if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0) {
364 		if (IN6_IS_ADDR_UNSPECIFIED(&sin6p->sin6_addr)) {
365 			inp->inp_vflag |= INP_IPV4;
366 		} else if (IN6_IS_ADDR_V4MAPPED(&sin6p->sin6_addr)) {
367 			struct sockaddr_in sin;
368 
369 			in6_sin6_2_sin(&sin, sin6p);
370 			inp->inp_vflag |= INP_IPV4;
371 			inp->inp_vflag &= ~INP_IPV6;
372 
373 			error = in_pcbbind(inp, (struct sockaddr *)&sin, p);
374 			if (error != 0) {
375 				inp->inp_vflag = old_flags;
376 				route_clear(&inp->inp_route);
377 			}
378 			goto out;
379 		}
380 	}
381 	error = in6_pcbbind(inp, nam, p);
382 	if (error) {
383 		inp->inp_vflag = old_flags;
384 		route_clear(&inp->inp_route);
385 		goto out;
386 	}
387 
388 	COMMON_END(PRU_BIND);
389 }
390 
391 /*
392  * Prepare to accept connections.
393  *
394  * Returns:	0			Success
395  *		EINVAL [COMMON_START]
396  *	in_pcbbind:EADDRNOTAVAIL	Address not available.
397  *	in_pcbbind:EINVAL		Invalid argument
398  *	in_pcbbind:EAFNOSUPPORT		Address family not supported [notdef]
399  *	in_pcbbind:EACCES		Permission denied
400  *	in_pcbbind:EADDRINUSE		Address in use
401  *	in_pcbbind:EAGAIN		Resource unavailable, try again
402  *	in_pcbbind:EPERM		Operation not permitted
403  */
404 static int
tcp_usr_listen(struct socket * so,struct proc * p)405 tcp_usr_listen(struct socket *so, struct proc *p)
406 {
407 	int error = 0;
408 	struct inpcb *inp = sotoinpcb(so);
409 	struct tcpcb *tp;
410 
411 	COMMON_START_ALLOW_FLOW_DIVERT(true);
412 	if (inp->inp_lport == 0) {
413 		error = in_pcbbind(inp, NULL, p);
414 	}
415 	if (error == 0) {
416 		TCP_LOG_STATE(tp, TCPS_LISTEN);
417 		tp->t_state = TCPS_LISTEN;
418 		if (nstat_collect) {
419 			nstat_pcb_event(inp, NSTAT_EVENT_SRC_FLOW_STATE_LISTEN);
420 		}
421 	}
422 	TCP_LOG_LISTEN(tp, error);
423 	COMMON_END(PRU_LISTEN);
424 }
425 
426 static int
tcp6_usr_listen(struct socket * so,struct proc * p)427 tcp6_usr_listen(struct socket *so, struct proc *p)
428 {
429 	int error = 0;
430 	struct inpcb *inp = sotoinpcb(so);
431 	struct tcpcb *tp;
432 
433 	COMMON_START_ALLOW_FLOW_DIVERT(true);
434 	if (inp->inp_lport == 0) {
435 		inp->inp_vflag &= ~INP_IPV4;
436 		if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0) {
437 			inp->inp_vflag |= INP_IPV4;
438 		}
439 		error = in6_pcbbind(inp, NULL, p);
440 	}
441 	if (error == 0) {
442 		TCP_LOG_STATE(tp, TCPS_LISTEN);
443 		tp->t_state = TCPS_LISTEN;
444 		if (nstat_collect) {
445 			nstat_pcb_event(inp, NSTAT_EVENT_SRC_FLOW_STATE_LISTEN);
446 		}
447 	}
448 	TCP_LOG_LISTEN(tp, error);
449 	COMMON_END(PRU_LISTEN);
450 }
451 
452 static int
tcp_connect_complete(struct socket * so)453 tcp_connect_complete(struct socket *so)
454 {
455 	struct tcpcb *tp = sototcpcb(so);
456 	struct inpcb *inp = sotoinpcb(so);
457 	int error = 0;
458 
459 	/* TFO delays the tcp_output until later, when the app calls write() */
460 	if (so->so_flags1 & SOF1_PRECONNECT_DATA) {
461 		if (!necp_socket_is_allowed_to_send_recv(sotoinpcb(so), NULL, 0, NULL, NULL, NULL, NULL)) {
462 			TCP_LOG_DROP_NECP(NULL, NULL, tp, true);
463 			return EHOSTUNREACH;
464 		}
465 
466 		/* Initialize enough state so that we can actually send data */
467 		tcp_mss(tp, -1, IFSCOPE_NONE);
468 		tp->snd_wnd = tp->t_maxseg;
469 		tp->max_sndwnd = tp->snd_wnd;
470 	} else {
471 		tp->t_flagsext |= TF_USR_OUTPUT;
472 		error = tcp_output(tp);
473 		tp->t_flagsext &= ~TF_USR_OUTPUT;
474 	}
475 
476 #if NECP
477 	/* Update NECP client with connected five-tuple */
478 	if (error == 0 && !uuid_is_null(inp->necp_client_uuid)) {
479 		socket_unlock(so, 0);
480 		necp_client_assign_from_socket(so->last_pid, inp->necp_client_uuid, inp);
481 		socket_lock(so, 0);
482 	}
483 #endif /* NECP */
484 
485 	return error;
486 }
487 
488 __attribute__((noinline))
489 static void
tcp_log_address_error(int error,struct sockaddr * nam,struct proc * p)490 tcp_log_address_error(int error, struct sockaddr *nam, struct proc *p)
491 {
492 	char buffer[MAX_IPv6_STR_LEN];
493 
494 	if (nam->sa_family == AF_INET6) {
495 		struct sockaddr_in6 *sin6p = (struct sockaddr_in6 *)(void *)nam;
496 
497 		inet_ntop(AF_INET6, &sin6p->sin6_addr, buffer, sizeof(buffer));
498 	} else {
499 		struct sockaddr_in *sinp = (struct sockaddr_in *)(void *)nam;
500 
501 		inet_ntop(AF_INET, &sinp->sin_addr, buffer, sizeof(buffer));
502 	}
503 	if (p == NULL) {
504 		p = current_proc();
505 	}
506 	os_log(OS_LOG_DEFAULT, "connect address error %d for %s process %s:%u",
507 	    error, buffer, proc_name_address(p), proc_pid(p));
508 }
509 
510 /*
511  * Note that connecting to the all-zeros address is OK and is treated as the
512  * loopback address
513  */
514 static int
tcp_usr_connect_common(struct socket * so,struct tcpcb * tp,struct sockaddr * nam,struct proc * p,bool isipv6,bool need_connect_complete)515 tcp_usr_connect_common(struct socket *so, struct tcpcb *tp, struct sockaddr *nam,
516     struct proc *p, bool isipv6, bool need_connect_complete)
517 {
518 	int error = 0;
519 	struct inpcb *inp = sotoinpcb(so);
520 
521 	if (isipv6 == 0) {
522 		struct sockaddr_in *sinp;
523 
524 		if (nam->sa_family != 0 && nam->sa_family != AF_INET) {
525 			error = EAFNOSUPPORT;
526 			goto out;
527 		}
528 		/*
529 		 * Disallow connecting to multicast and broadcast addresses.
530 		 */
531 		sinp = (struct sockaddr_in *)(void *)nam;
532 		if (sinp->sin_family == AF_INET &&
533 		    (IN_MULTICAST(ntohl(sinp->sin_addr.s_addr)) ||
534 		    sinp->sin_addr.s_addr == INADDR_BROADCAST)) {
535 			error = EAFNOSUPPORT;
536 			goto out;
537 		}
538 
539 		if ((error = tcp_connect(tp, nam, p)) != 0) {
540 			goto out;
541 		}
542 	} else {
543 		struct sockaddr_in6 *sin6p;
544 
545 		if (nam->sa_family != 0 && nam->sa_family != AF_INET6) {
546 			error = EAFNOSUPPORT;
547 			goto out;
548 		}
549 
550 		/*
551 		 * Disallow connecting to multicast and broadcast addresses.
552 		 */
553 		sin6p = (struct sockaddr_in6 *)(void *)nam;
554 		if (sin6p->sin6_family == AF_INET6 &&
555 		    IN6_IS_ADDR_MULTICAST(&sin6p->sin6_addr)) {
556 			error = EAFNOSUPPORT;
557 			goto out;
558 		}
559 
560 		if (IN6_IS_ADDR_V4MAPPED(&sin6p->sin6_addr)) {
561 			struct sockaddr_in sin;
562 
563 			if ((inp->inp_flags & IN6P_IPV6_V6ONLY) != 0) {
564 				error = EINVAL;
565 				goto out;
566 			}
567 
568 			in6_sin6_2_sin(&sin, sin6p);
569 			/*
570 			 * Disallow connecting to multicast and broadcast addresses.
571 			 */
572 			if (IN_MULTICAST(ntohl(sin.sin_addr.s_addr)) ||
573 			    sin.sin_addr.s_addr == INADDR_BROADCAST) {
574 				error = EAFNOSUPPORT;
575 				goto out;
576 			}
577 			inp->inp_vflag |= INP_IPV4;
578 			inp->inp_vflag &= ~INP_IPV6;
579 			if ((error = tcp_connect(tp, (struct sockaddr *)&sin, p)) != 0) {
580 				goto out;
581 			}
582 
583 			goto out;
584 		} else if (IN6_IS_ADDR_V4COMPAT(&sin6p->sin6_addr)) {
585 			/*
586 			 * Disallow connecting to multicast and broadcast addresses.
587 			 */
588 			if (IN_MULTICAST(ntohl(sin6p->sin6_addr.s6_addr32[3])) ||
589 			    sin6p->sin6_addr.s6_addr32[3] == INADDR_BROADCAST) {
590 				error = EAFNOSUPPORT;
591 				goto out;
592 			}
593 		}
594 
595 		inp->inp_vflag &= ~INP_IPV4;
596 		inp->inp_vflag |= INP_IPV6;
597 		if ((error = tcp6_connect(tp, nam, p)) != 0) {
598 			goto out;
599 		}
600 	}
601 out:
602 	if (need_connect_complete && error == 0) {
603 		error = tcp_connect_complete(so);
604 	}
605 	TCP_LOG_CONNECT(tp, true, error);
606 	if (error == EAFNOSUPPORT) {
607 		tcp_log_address_error(error, nam, p);
608 	}
609 	return error;
610 }
611 
612 /*
613  * Initiate connection to peer.
614  * Create a template for use in transmissions on this connection.
615  * Enter SYN_SENT state, and mark socket as connecting.
616  * Start keep-alive timer, and seed output sequence space.
617  * Send initial segment on connection.
618  */
619 static int
tcp_usr_connect(struct socket * so,struct sockaddr * nam,struct proc * p)620 tcp_usr_connect(struct socket *so, struct sockaddr *nam, struct proc *p)
621 {
622 	int error = 0;
623 	struct inpcb *inp = sotoinpcb(so);
624 	struct tcpcb *tp;
625 
626 	TCPDEBUG0;
627 	if (inp == NULL) {
628 		return EINVAL;
629 	} else if (inp->inp_state == INPCB_STATE_DEAD) {
630 		if (so->so_error) {
631 			error = so->so_error;
632 			so->so_error = 0;
633 			return error;
634 		} else {
635 			return EINVAL;
636 		}
637 	}
638 #if NECP
639 #if CONTENT_FILTER
640 	error = cfil_sock_attach(so, NULL, nam, CFS_CONNECTION_DIR_OUT);
641 	if (error != 0) {
642 		return error;
643 	}
644 #endif /* CONTENT_FILTER */
645 #if FLOW_DIVERT
646 	if (necp_socket_should_use_flow_divert(inp)) {
647 		error = flow_divert_pcb_init(so);
648 		if (error == 0) {
649 			error = flow_divert_connect_out(so, nam, p);
650 		}
651 		return error;
652 	}
653 #endif /* FLOW_DIVERT */
654 #endif /* NECP */
655 	tp = intotcpcb(inp);
656 	TCPDEBUG1();
657 
658 	calculate_tcp_clock();
659 
660 	error = tcp_usr_connect_common(so, tp, nam, p, false, true);
661 	if (error != 0) {
662 		goto out;
663 	}
664 
665 	COMMON_END(PRU_CONNECT);
666 }
667 
668 static int
tcp_usr_connectx_common(struct socket * so,int af,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 * auio,user_ssize_t * bytes_written)669 tcp_usr_connectx_common(struct socket *so, int af,
670     struct sockaddr *src, struct sockaddr *dst,
671     struct proc *p, uint32_t ifscope, sae_associd_t aid, sae_connid_t *pcid,
672     uint32_t flags, void *arg, uint32_t arglen, struct uio *auio,
673     user_ssize_t *bytes_written)
674 {
675 #pragma unused(aid, flags, arg, arglen)
676 	struct inpcb *inp = sotoinpcb(so);
677 	int error = 0;
678 	user_ssize_t datalen = 0;
679 
680 	if (inp == NULL) {
681 		return EINVAL;
682 	}
683 
684 	VERIFY(dst != NULL);
685 
686 	ASSERT(!(inp->inp_flags2 & INP2_CONNECT_IN_PROGRESS));
687 	inp->inp_flags2 |= INP2_CONNECT_IN_PROGRESS;
688 
689 #if NECP
690 	inp_update_necp_policy(inp, src, dst, ifscope);
691 #endif /* NECP */
692 
693 	if ((so->so_flags1 & SOF1_DATA_IDEMPOTENT) &&
694 	    (tcp_fastopen & TCP_FASTOPEN_CLIENT)) {
695 		sototcpcb(so)->t_flagsext |= TF_FASTOPEN;
696 	}
697 
698 	/* bind socket to the specified interface, if requested */
699 	if (ifscope != IFSCOPE_NONE &&
700 	    (error = inp_bindif(inp, ifscope, NULL)) != 0) {
701 		goto done;
702 	}
703 
704 	/* if source address and/or port is specified, bind to it */
705 	if (src != NULL) {
706 		error = sobindlock(so, src, 0); /* already locked */
707 		if (error != 0) {
708 			goto done;
709 		}
710 	}
711 
712 	switch (af) {
713 	case AF_INET:
714 		error = tcp_usr_connect(so, dst, p);
715 		break;
716 	case AF_INET6:
717 		error = tcp6_usr_connect(so, dst, p);
718 		break;
719 	default:
720 		VERIFY(0);
721 		/* NOTREACHED */
722 	}
723 
724 	if (error != 0) {
725 		goto done;
726 	}
727 
728 	/* if there is data, copy it */
729 	if (auio != NULL) {
730 		socket_unlock(so, 0);
731 
732 		VERIFY(bytes_written != NULL);
733 
734 		datalen = uio_resid(auio);
735 		error = so->so_proto->pr_usrreqs->pru_sosend(so, NULL,
736 		    (uio_t)auio, NULL, NULL, 0);
737 		socket_lock(so, 0);
738 
739 		if (error == 0 || error == EWOULDBLOCK) {
740 			*bytes_written = datalen - uio_resid(auio);
741 		}
742 
743 		/*
744 		 * sosend returns EWOULDBLOCK if it's a non-blocking
745 		 * socket or a timeout occured (this allows to return
746 		 * the amount of queued data through sendit()).
747 		 *
748 		 * However, connectx() returns EINPROGRESS in case of a
749 		 * blocking socket. So we change the return value here.
750 		 */
751 		if (error == EWOULDBLOCK) {
752 			error = EINPROGRESS;
753 		}
754 	}
755 
756 	if (error == 0 && pcid != NULL) {
757 		*pcid = 1; /* there is only one connection in regular TCP */
758 	}
759 done:
760 	if (error && error != EINPROGRESS) {
761 		so->so_flags1 &= ~SOF1_PRECONNECT_DATA;
762 	}
763 
764 	inp->inp_flags2 &= ~INP2_CONNECT_IN_PROGRESS;
765 	return error;
766 }
767 
768 static int
tcp_usr_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)769 tcp_usr_connectx(struct socket *so, struct sockaddr *src,
770     struct sockaddr *dst, struct proc *p, uint32_t ifscope,
771     sae_associd_t aid, sae_connid_t *pcid, uint32_t flags, void *arg,
772     uint32_t arglen, struct uio *uio, user_ssize_t *bytes_written)
773 {
774 	return tcp_usr_connectx_common(so, AF_INET, src, dst, p, ifscope, aid,
775 	           pcid, flags, arg, arglen, uio, bytes_written);
776 }
777 
778 static int
tcp6_usr_connect(struct socket * so,struct sockaddr * nam,struct proc * p)779 tcp6_usr_connect(struct socket *so, struct sockaddr *nam, struct proc *p)
780 {
781 	int error = 0;
782 	struct inpcb *inp = sotoinpcb(so);
783 	struct tcpcb *tp;
784 
785 	TCPDEBUG0;
786 	if (inp == NULL) {
787 		return EINVAL;
788 	} else if (inp->inp_state == INPCB_STATE_DEAD) {
789 		if (so->so_error) {
790 			error = so->so_error;
791 			so->so_error = 0;
792 			return error;
793 		} else {
794 			return EINVAL;
795 		}
796 	}
797 #if NECP
798 #if CONTENT_FILTER
799 	error = cfil_sock_attach(so, NULL, nam, CFS_CONNECTION_DIR_OUT);
800 	if (error != 0) {
801 		return error;
802 	}
803 #endif /* CONTENT_FILTER */
804 #if FLOW_DIVERT
805 	if (necp_socket_should_use_flow_divert(inp)) {
806 		error = flow_divert_pcb_init(so);
807 		if (error == 0) {
808 			error = flow_divert_connect_out(so, nam, p);
809 		}
810 		return error;
811 	}
812 #endif /* FLOW_DIVERT */
813 #endif /* NECP */
814 
815 	tp = intotcpcb(inp);
816 	TCPDEBUG1();
817 
818 	calculate_tcp_clock();
819 
820 	error = tcp_usr_connect_common(so, tp, nam, p, true, true);
821 	if (error != 0) {
822 		route_clear(&inp->inp_route);
823 		goto out;
824 	}
825 
826 	COMMON_END(PRU_CONNECT);
827 }
828 
829 static int
tcp6_usr_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)830 tcp6_usr_connectx(struct socket *so, struct sockaddr*src,
831     struct sockaddr *dst, struct proc *p, uint32_t ifscope,
832     sae_associd_t aid, sae_connid_t *pcid, uint32_t flags, void *arg,
833     uint32_t arglen, struct uio *uio, user_ssize_t *bytes_written)
834 {
835 	return tcp_usr_connectx_common(so, AF_INET6, src, dst, p, ifscope, aid,
836 	           pcid, flags, arg, arglen, uio, bytes_written);
837 }
838 
839 /*
840  * Initiate disconnect from peer.
841  * If connection never passed embryonic stage, just drop;
842  * else if don't need to let data drain, then can just drop anyways,
843  * else have to begin TCP shutdown process: mark socket disconnecting,
844  * drain unread data, state switch to reflect user close, and
845  * send segment (e.g. FIN) to peer.  Socket will be really disconnected
846  * when peer sends FIN and acks ours.
847  *
848  * SHOULD IMPLEMENT LATER PRU_CONNECT VIA REALLOC TCPCB.
849  */
850 static int
tcp_usr_disconnect(struct socket * so)851 tcp_usr_disconnect(struct socket *so)
852 {
853 	int error = 0;
854 	struct inpcb *inp = sotoinpcb(so);
855 	struct tcpcb *tp;
856 
857 	socket_lock_assert_owned(so);
858 	COMMON_START();
859 	/* In case we got disconnected from the peer */
860 	if (tp == NULL) {
861 		goto out;
862 	}
863 	tp = tcp_disconnect(tp);
864 	COMMON_END(PRU_DISCONNECT);
865 }
866 
867 /*
868  * User-protocol pru_disconnectx callback.
869  */
870 static int
tcp_usr_disconnectx(struct socket * so,sae_associd_t aid,sae_connid_t cid)871 tcp_usr_disconnectx(struct socket *so, sae_associd_t aid, sae_connid_t cid)
872 {
873 #pragma unused(cid)
874 	if (aid != SAE_ASSOCID_ANY && aid != SAE_ASSOCID_ALL) {
875 		return EINVAL;
876 	}
877 
878 	return tcp_usr_disconnect(so);
879 }
880 
881 /*
882  * Accept a connection.  Essentially all the work is
883  * done at higher levels; just return the address
884  * of the peer, storing through addr.
885  */
886 static int
tcp_usr_accept(struct socket * so,struct sockaddr ** nam)887 tcp_usr_accept(struct socket *so, struct sockaddr **nam)
888 {
889 	int error = 0;
890 	struct inpcb *inp = sotoinpcb(so);
891 	struct tcpcb *tp = NULL;
892 	TCPDEBUG0;
893 
894 	in_getpeeraddr(so, nam);
895 
896 	if (so->so_state & SS_ISDISCONNECTED) {
897 		error = ECONNABORTED;
898 		goto out;
899 	}
900 	if (inp == NULL || inp->inp_state == INPCB_STATE_DEAD) {
901 		return EINVAL;
902 	}
903 #if NECP
904 	else if (necp_socket_should_use_flow_divert(inp)) {
905 		return EPROTOTYPE;
906 	}
907 
908 #endif /* NECP */
909 
910 	tp = intotcpcb(inp);
911 	TCPDEBUG1();
912 
913 	TCP_LOG_ACCEPT(tp, 0);
914 
915 	calculate_tcp_clock();
916 
917 	COMMON_END(PRU_ACCEPT);
918 }
919 
920 static int
tcp6_usr_accept(struct socket * so,struct sockaddr ** nam)921 tcp6_usr_accept(struct socket *so, struct sockaddr **nam)
922 {
923 	int error = 0;
924 	struct inpcb *inp = sotoinpcb(so);
925 	struct tcpcb *tp = NULL;
926 	TCPDEBUG0;
927 
928 	if (so->so_state & SS_ISDISCONNECTED) {
929 		error = ECONNABORTED;
930 		goto out;
931 	}
932 	if (inp == NULL || inp->inp_state == INPCB_STATE_DEAD) {
933 		return EINVAL;
934 	}
935 #if NECP
936 	else if (necp_socket_should_use_flow_divert(inp)) {
937 		return EPROTOTYPE;
938 	}
939 
940 #endif /* NECP */
941 
942 	tp = intotcpcb(inp);
943 	TCPDEBUG1();
944 
945 	TCP_LOG_ACCEPT(tp, 0);
946 
947 	calculate_tcp_clock();
948 
949 	in6_mapped_peeraddr(so, nam);
950 	COMMON_END(PRU_ACCEPT);
951 }
952 
953 /*
954  * Mark the connection as being incapable of further output.
955  *
956  * Returns:	0			Success
957  *		EINVAL [COMMON_START]
958  *	tcp_output:EADDRNOTAVAIL
959  *	tcp_output:ENOBUFS
960  *	tcp_output:EMSGSIZE
961  *	tcp_output:EHOSTUNREACH
962  *	tcp_output:ENETUNREACH
963  *	tcp_output:ENETDOWN
964  *	tcp_output:ENOMEM
965  *	tcp_output:EACCES
966  *	tcp_output:EMSGSIZE
967  *	tcp_output:ENOBUFS
968  *	tcp_output:???			[ignorable: mostly IPSEC/firewall/DLIL]
969  */
970 static int
tcp_usr_shutdown(struct socket * so)971 tcp_usr_shutdown(struct socket *so)
972 {
973 	int error = 0;
974 	struct inpcb *inp = sotoinpcb(so);
975 	struct tcpcb *tp;
976 
977 	TCPDEBUG0;
978 	if (inp == NULL || inp->inp_state == INPCB_STATE_DEAD) {
979 		return EINVAL;
980 	}
981 
982 	socantsendmore(so);
983 
984 	/*
985 	 * In case we got disconnected from the peer, or if this is
986 	 * a socket that is to be flow-diverted (but not yet).
987 	 */
988 	tp = intotcpcb(inp);
989 	TCPDEBUG1();
990 
991 	if (tp == NULL
992 #if NECP
993 	    || (necp_socket_should_use_flow_divert(inp))
994 #endif /* NECP */
995 	    ) {
996 		if (tp != NULL) {
997 			error = EPROTOTYPE;
998 		}
999 		goto out;
1000 	}
1001 
1002 	calculate_tcp_clock();
1003 
1004 	tp = tcp_usrclosed(tp);
1005 #if MPTCP
1006 	/* A reset has been sent but socket exists, do not send FIN */
1007 	if ((so->so_flags & SOF_MP_SUBFLOW) &&
1008 	    (tp) && (tp->t_mpflags & TMPF_RESET)) {
1009 		goto out;
1010 	}
1011 #endif
1012 #if CONTENT_FILTER
1013 	/* Don't send a FIN yet */
1014 	if (tp && !(so->so_state & SS_ISDISCONNECTED) &&
1015 	    cfil_sock_data_pending(&so->so_snd)) {
1016 		goto out;
1017 	}
1018 #endif /* CONTENT_FILTER */
1019 	if (tp) {
1020 		error = tcp_output(tp);
1021 	}
1022 	COMMON_END(PRU_SHUTDOWN);
1023 }
1024 
1025 /*
1026  * After a receive, possibly send window update to peer.
1027  */
1028 static int
tcp_usr_rcvd(struct socket * so,int flags)1029 tcp_usr_rcvd(struct socket *so, int flags)
1030 {
1031 	int error = 0;
1032 	struct inpcb *inp = sotoinpcb(so);
1033 	struct tcpcb *tp;
1034 
1035 	COMMON_START();
1036 	/* In case we got disconnected from the peer */
1037 	if (tp == NULL) {
1038 		goto out;
1039 	}
1040 	tcp_sbrcv_trim(tp, &so->so_rcv);
1041 
1042 	if ((flags & MSG_WAITALL) && SEQ_LT(tp->last_ack_sent, tp->rcv_nxt)) {
1043 		tp->t_flags |= TF_ACKNOW;
1044 	}
1045 
1046 	/*
1047 	 * This tcp_output is solely there to trigger window-updates.
1048 	 * However, we really do not want these window-updates while we
1049 	 * are still in SYN_SENT or SYN_RECEIVED.
1050 	 */
1051 	if (TCPS_HAVEESTABLISHED(tp->t_state)) {
1052 		tcp_output(tp);
1053 	}
1054 
1055 #if CONTENT_FILTER
1056 	cfil_sock_buf_update(&so->so_rcv);
1057 #endif /* CONTENT_FILTER */
1058 
1059 	COMMON_END(PRU_RCVD);
1060 }
1061 
1062 __attribute__((noinline))
1063 static int
tcp_send_implied_connect(struct socket * so,struct tcpcb * tp,struct sockaddr * nam,struct proc * p,bool isipv6)1064 tcp_send_implied_connect(struct socket *so, struct tcpcb *tp, struct sockaddr *nam,
1065     struct proc *p, bool isipv6)
1066 {
1067 	int error = 0;
1068 
1069 	error = tcp_usr_connect_common(so, tp, nam, p, isipv6, false);
1070 	if (error != 0) {
1071 		goto out;
1072 	}
1073 	/*
1074 	 * initialize window to default value, and
1075 	 * initialize maxseg/maxopd using peer's cached
1076 	 * MSS.
1077 	 */
1078 	tp->snd_wnd = TTCP_CLIENT_SND_WND;
1079 	tp->max_sndwnd = tp->snd_wnd;
1080 	tcp_mss(tp, -1, IFSCOPE_NONE);
1081 out:
1082 	return error;
1083 }
1084 
1085 __attribute__((noinline))
1086 static void
mpkl_tcp_send(struct socket * so,struct tcpcb * tp,uint32_t mpkl_seq,uint32_t mpkl_len,struct so_mpkl_send_info * mpkl_send_info)1087 mpkl_tcp_send(struct socket *so, struct tcpcb *tp, uint32_t mpkl_seq, uint32_t mpkl_len,
1088     struct so_mpkl_send_info *mpkl_send_info)
1089 {
1090 	struct inpcb *inp = tp->t_inpcb;
1091 
1092 	if (inp == NULL) {
1093 		return;
1094 	}
1095 
1096 	if ((inp->inp_last_outifp != NULL &&
1097 	    (inp->inp_last_outifp->if_xflags & IFXF_MPK_LOG)) ||
1098 	    (inp->inp_boundifp != NULL &&
1099 	    (inp->inp_boundifp->if_xflags & IFXF_MPK_LOG))) {
1100 		MPKL_TCP_SEND(tcp_mpkl_log_object,
1101 		    mpkl_send_info->mpkl_proto,
1102 		    mpkl_send_info->mpkl_uuid,
1103 		    ntohs(inp->inp_lport),
1104 		    ntohs(inp->inp_fport),
1105 		    mpkl_seq,
1106 		    mpkl_len,
1107 		    so->last_pid,
1108 		    so->so_log_seqn++);
1109 	}
1110 }
1111 
1112 /*
1113  * Do a send by putting data in output queue and updating urgent
1114  * marker if URG set.  Possibly send more data.  Unlike the other
1115  * pru_*() routines, the mbuf chains are our responsibility.  We
1116  * must either enqueue them or free them.  The other pru_* routines
1117  * generally are caller-frees.
1118  *
1119  * Returns:	0			Success
1120  *		ECONNRESET
1121  *		EINVAL
1122  *		ENOBUFS
1123  *	tcp_connect:EADDRINUSE		Address in use
1124  *	tcp_connect:EADDRNOTAVAIL	Address not available.
1125  *	tcp_connect:EINVAL		Invalid argument
1126  *	tcp_connect:EAFNOSUPPORT	Address family not supported [notdef]
1127  *	tcp_connect:EACCES		Permission denied
1128  *	tcp_connect:EAGAIN		Resource unavailable, try again
1129  *	tcp_connect:EPERM		Operation not permitted
1130  *	tcp_output:EADDRNOTAVAIL
1131  *	tcp_output:ENOBUFS
1132  *	tcp_output:EMSGSIZE
1133  *	tcp_output:EHOSTUNREACH
1134  *	tcp_output:ENETUNREACH
1135  *	tcp_output:ENETDOWN
1136  *	tcp_output:ENOMEM
1137  *	tcp_output:EACCES
1138  *	tcp_output:EMSGSIZE
1139  *	tcp_output:ENOBUFS
1140  *	tcp_output:???			[ignorable: mostly IPSEC/firewall/DLIL]
1141  *	tcp6_connect:???		[IPV6 only]
1142  */
1143 static int
tcp_usr_send(struct socket * so,int flags,struct mbuf * m,struct sockaddr * nam,struct mbuf * control,struct proc * p)1144 tcp_usr_send(struct socket *so, int flags, struct mbuf *m,
1145     struct sockaddr *nam, struct mbuf *control, struct proc *p)
1146 {
1147 	int error = 0;
1148 	struct inpcb *inp = sotoinpcb(so);
1149 	struct tcpcb *tp;
1150 	uint32_t mpkl_len = 0; /* length of mbuf chain */
1151 	uint32_t mpkl_seq = 0; /* sequence number where new data is added */
1152 	struct so_mpkl_send_info mpkl_send_info = {};
1153 	bool isipv6;
1154 
1155 	TCPDEBUG0;
1156 
1157 	if (inp == NULL || inp->inp_state == INPCB_STATE_DEAD
1158 #if NECP
1159 	    || (necp_socket_should_use_flow_divert(inp))
1160 #endif /* NECP */
1161 	    ) {
1162 		/*
1163 		 * OOPS! we lost a race, the TCP session got reset after
1164 		 * we checked SS_CANTSENDMORE, eg: while doing uiomove or a
1165 		 * network interrupt in the non-splnet() section of sosend().
1166 		 */
1167 		if (m != NULL) {
1168 			m_freem(m);
1169 		}
1170 		if (control != NULL) {
1171 			m_freem(control);
1172 			control = NULL;
1173 		}
1174 
1175 		if (inp == NULL || inp->inp_state == INPCB_STATE_DEAD) {
1176 			error = ECONNRESET;     /* XXX EPIPE? */
1177 		} else {
1178 			error = EPROTOTYPE;
1179 		}
1180 		tp = NULL;
1181 		TCPDEBUG1();
1182 		goto out;
1183 	}
1184 	isipv6 = nam && nam->sa_family == AF_INET6 ? true : false;
1185 	tp = intotcpcb(inp);
1186 	TCPDEBUG1();
1187 
1188 	calculate_tcp_clock();
1189 
1190 	if (net_mpklog_enabled) {
1191 		mpkl_seq = tp->snd_una + so->so_snd.sb_cc;
1192 		if (m) {
1193 			mpkl_len = m_length(m);
1194 		}
1195 		if (so->so_flags1 & SOF1_MPKL_SEND_INFO) {
1196 			uuid_copy(mpkl_send_info.mpkl_uuid, so->so_mpkl_send_uuid);
1197 			mpkl_send_info.mpkl_proto = so->so_mpkl_send_proto;
1198 		}
1199 	}
1200 
1201 	if (control != NULL) {
1202 		if (control->m_len > 0 && net_mpklog_enabled) {
1203 			error = tcp_get_mpkl_send_info(control, &mpkl_send_info);
1204 			/*
1205 			 * Intepretation of the returned code:
1206 			 *  0: client wants us to use value passed in SCM_MPKL_SEND_INFO
1207 			 *  1: SCM_MPKL_SEND_INFO was not present
1208 			 *  other: failure
1209 			 */
1210 			if (error != 0 && error != ENOMSG) {
1211 				m_freem(control);
1212 				if (m != NULL) {
1213 					m_freem(m);
1214 				}
1215 				control = NULL;
1216 				m = NULL;
1217 				goto out;
1218 			}
1219 		}
1220 		/*
1221 		 * Silently drop unsupported ancillary data messages
1222 		 */
1223 		m_freem(control);
1224 		control = NULL;
1225 	}
1226 
1227 	/* MPTCP sublow socket buffers must not be compressed */
1228 	VERIFY(!(so->so_flags & SOF_MP_SUBFLOW) ||
1229 	    (so->so_snd.sb_flags & SB_NOCOMPRESS));
1230 
1231 	if (!(flags & PRUS_OOB) || (so->so_flags1 & SOF1_PRECONNECT_DATA)) {
1232 		sbappendstream(&so->so_snd, m);
1233 
1234 		if (nam && tp->t_state < TCPS_SYN_SENT) {
1235 			/*
1236 			 * Do implied connect if not yet connected,
1237 			 */
1238 			error = tcp_send_implied_connect(so, tp, nam, p, isipv6);
1239 			if (error != 0) {
1240 				goto out;
1241 			}
1242 			/* The sequence number of the data is past the SYN */
1243 			mpkl_seq = tp->iss + 1;
1244 		}
1245 
1246 		if (flags & PRUS_EOF) {
1247 			/*
1248 			 * Close the send side of the connection after
1249 			 * the data is sent.
1250 			 */
1251 			socantsendmore(so);
1252 			tp = tcp_usrclosed(tp);
1253 		}
1254 		if (tp != NULL) {
1255 			if (flags & PRUS_MORETOCOME) {
1256 				tp->t_flags |= TF_MORETOCOME;
1257 			}
1258 			tp->t_flagsext |= TF_USR_OUTPUT;
1259 			error = tcp_output(tp);
1260 			tp->t_flagsext &= ~TF_USR_OUTPUT;
1261 			if (flags & PRUS_MORETOCOME) {
1262 				tp->t_flags &= ~TF_MORETOCOME;
1263 			}
1264 		}
1265 	} else {
1266 		if (sbspace(&so->so_snd) == 0) {
1267 			/* if no space is left in sockbuf,
1268 			 * do not try to squeeze in OOB traffic */
1269 			m_freem(m);
1270 			error = ENOBUFS;
1271 			goto out;
1272 		}
1273 		/*
1274 		 * According to RFC961 (Assigned Protocols),
1275 		 * the urgent pointer points to the last octet
1276 		 * of urgent data.  We continue, however,
1277 		 * to consider it to indicate the first octet
1278 		 * of data past the urgent section.
1279 		 * Otherwise, snd_up should be one lower.
1280 		 */
1281 		sbappendstream(&so->so_snd, m);
1282 		if (nam && tp->t_state < TCPS_SYN_SENT) {
1283 			/*
1284 			 * Do implied connect if not yet connected,
1285 			 * initialize window to default value, and
1286 			 * initialize maxseg/maxopd using peer's cached
1287 			 * MSS.
1288 			 */
1289 			error = tcp_send_implied_connect(so, tp, nam, p, isipv6);
1290 			if (error != 0) {
1291 				goto out;
1292 			}
1293 		}
1294 		tp->snd_up = tp->snd_una + so->so_snd.sb_cc;
1295 		tp->t_flagsext |= TF_FORCE;
1296 		tp->t_flagsext |= TF_USR_OUTPUT;
1297 		error = tcp_output(tp);
1298 		tp->t_flagsext &= ~TF_USR_OUTPUT;
1299 		tp->t_flagsext &= ~TF_FORCE;
1300 	}
1301 
1302 	if (net_mpklog_enabled) {
1303 		mpkl_tcp_send(so, tp, mpkl_seq, mpkl_len, &mpkl_send_info);
1304 	}
1305 
1306 	/*
1307 	 * We wait for the socket to successfully connect before returning.
1308 	 * This allows us to signal a timeout to the application.
1309 	 */
1310 	if (so->so_state & SS_ISCONNECTING) {
1311 		if (so->so_state & SS_NBIO) {
1312 			error = EWOULDBLOCK;
1313 		} else {
1314 			error = sbwait(&so->so_snd);
1315 		}
1316 	}
1317 
1318 	COMMON_END((flags & PRUS_OOB) ? PRU_SENDOOB :
1319 	    ((flags & PRUS_EOF) ? PRU_SEND_EOF : PRU_SEND));
1320 }
1321 
1322 /*
1323  * Abort the TCP.
1324  */
1325 static int
tcp_usr_abort(struct socket * so)1326 tcp_usr_abort(struct socket *so)
1327 {
1328 	int error = 0;
1329 	struct inpcb *inp = sotoinpcb(so);
1330 	struct tcpcb *tp;
1331 
1332 	COMMON_START();
1333 	/* In case we got disconnected from the peer */
1334 	if (tp == NULL) {
1335 		goto out;
1336 	}
1337 	tp = tcp_drop(tp, ECONNABORTED);
1338 	VERIFY(so->so_usecount > 0);
1339 	so->so_usecount--;
1340 	COMMON_END(PRU_ABORT);
1341 }
1342 
1343 /*
1344  * Receive out-of-band data.
1345  *
1346  * Returns:	0			Success
1347  *		EINVAL [COMMON_START]
1348  *		EINVAL
1349  *		EWOULDBLOCK
1350  */
1351 static int
tcp_usr_rcvoob(struct socket * so,struct mbuf * m,int flags)1352 tcp_usr_rcvoob(struct socket *so, struct mbuf *m, int flags)
1353 {
1354 	int error = 0;
1355 	struct inpcb *inp = sotoinpcb(so);
1356 	struct tcpcb *tp;
1357 
1358 	COMMON_START();
1359 	if ((so->so_oobmark == 0 &&
1360 	    (so->so_state & SS_RCVATMARK) == 0) ||
1361 	    so->so_options & SO_OOBINLINE ||
1362 	    tp->t_oobflags & TCPOOB_HADDATA) {
1363 		error = EINVAL;
1364 		goto out;
1365 	}
1366 	if ((tp->t_oobflags & TCPOOB_HAVEDATA) == 0) {
1367 		error = EWOULDBLOCK;
1368 		goto out;
1369 	}
1370 	m->m_len = 1;
1371 	*mtod(m, caddr_t) = tp->t_iobc;
1372 	so->so_state &= ~SS_RCVATMARK;
1373 	if ((flags & MSG_PEEK) == 0) {
1374 		tp->t_oobflags ^= (TCPOOB_HAVEDATA | TCPOOB_HADDATA);
1375 	}
1376 	COMMON_END(PRU_RCVOOB);
1377 }
1378 
1379 static int
tcp_usr_preconnect(struct socket * so)1380 tcp_usr_preconnect(struct socket *so)
1381 {
1382 	struct inpcb *inp = sotoinpcb(so);
1383 	int error = 0;
1384 
1385 #if NECP
1386 	if (necp_socket_should_use_flow_divert(inp)) {
1387 		/* May happen, if in tcp_usr_connect we did not had a chance
1388 		 * to set the usrreqs (due to some error). So, let's get out
1389 		 * of here.
1390 		 */
1391 		goto out;
1392 	}
1393 #endif /* NECP */
1394 
1395 	error = tcp_output(sototcpcb(so));
1396 
1397 	soclearfastopen(so);
1398 
1399 	COMMON_END(PRU_PRECONNECT);
1400 }
1401 
1402 /* xxx - should be const */
1403 struct pr_usrreqs tcp_usrreqs = {
1404 	.pru_abort =            tcp_usr_abort,
1405 	.pru_accept =           tcp_usr_accept,
1406 	.pru_attach =           tcp_usr_attach,
1407 	.pru_bind =             tcp_usr_bind,
1408 	.pru_connect =          tcp_usr_connect,
1409 	.pru_connectx =         tcp_usr_connectx,
1410 	.pru_control =          in_control,
1411 	.pru_detach =           tcp_usr_detach,
1412 	.pru_disconnect =       tcp_usr_disconnect,
1413 	.pru_disconnectx =      tcp_usr_disconnectx,
1414 	.pru_listen =           tcp_usr_listen,
1415 	.pru_peeraddr =         in_getpeeraddr,
1416 	.pru_rcvd =             tcp_usr_rcvd,
1417 	.pru_rcvoob =           tcp_usr_rcvoob,
1418 	.pru_send =             tcp_usr_send,
1419 	.pru_shutdown =         tcp_usr_shutdown,
1420 	.pru_sockaddr =         in_getsockaddr,
1421 	.pru_sosend =           sosend,
1422 	.pru_soreceive =        soreceive,
1423 	.pru_preconnect =       tcp_usr_preconnect,
1424 };
1425 
1426 struct pr_usrreqs tcp6_usrreqs = {
1427 	.pru_abort =            tcp_usr_abort,
1428 	.pru_accept =           tcp6_usr_accept,
1429 	.pru_attach =           tcp_usr_attach,
1430 	.pru_bind =             tcp6_usr_bind,
1431 	.pru_connect =          tcp6_usr_connect,
1432 	.pru_connectx =         tcp6_usr_connectx,
1433 	.pru_control =          in6_control,
1434 	.pru_detach =           tcp_usr_detach,
1435 	.pru_disconnect =       tcp_usr_disconnect,
1436 	.pru_disconnectx =      tcp_usr_disconnectx,
1437 	.pru_listen =           tcp6_usr_listen,
1438 	.pru_peeraddr =         in6_mapped_peeraddr,
1439 	.pru_rcvd =             tcp_usr_rcvd,
1440 	.pru_rcvoob =           tcp_usr_rcvoob,
1441 	.pru_send =             tcp_usr_send,
1442 	.pru_shutdown =         tcp_usr_shutdown,
1443 	.pru_sockaddr =         in6_mapped_sockaddr,
1444 	.pru_sosend =           sosend,
1445 	.pru_soreceive =        soreceive,
1446 	.pru_preconnect =       tcp_usr_preconnect,
1447 };
1448 
1449 /*
1450  * Common subroutine to open a TCP connection to remote host specified
1451  * by struct sockaddr_in in mbuf *nam.  Call in_pcbbind to assign a local
1452  * port number if needed.  Call in_pcbladdr to do the routing and to choose
1453  * a local host address (interface).  If there is an existing incarnation
1454  * of the same connection in TIME-WAIT state and if the remote host was
1455  * sending CC options and if the connection duration was < MSL, then
1456  * truncate the previous TIME-WAIT state and proceed.
1457  * Initialize connection parameters and enter SYN-SENT state.
1458  *
1459  * Returns:	0			Success
1460  *		EADDRINUSE
1461  *		EINVAL
1462  *	in_pcbbind:EADDRNOTAVAIL	Address not available.
1463  *	in_pcbbind:EINVAL		Invalid argument
1464  *	in_pcbbind:EAFNOSUPPORT		Address family not supported [notdef]
1465  *	in_pcbbind:EACCES		Permission denied
1466  *	in_pcbbind:EADDRINUSE		Address in use
1467  *	in_pcbbind:EAGAIN		Resource unavailable, try again
1468  *	in_pcbbind:EPERM		Operation not permitted
1469  *	in_pcbladdr:EINVAL		Invalid argument
1470  *	in_pcbladdr:EAFNOSUPPORT	Address family not supported
1471  *	in_pcbladdr:EADDRNOTAVAIL	Address not available
1472  */
1473 static int
tcp_connect(struct tcpcb * tp,struct sockaddr * nam,struct proc * p)1474 tcp_connect(struct tcpcb *tp, struct sockaddr *nam, struct proc *p)
1475 {
1476 	struct inpcb *inp = tp->t_inpcb, *oinp;
1477 	struct socket *so = inp->inp_socket;
1478 	struct tcpcb *otp;
1479 	struct sockaddr_in *sin = (struct sockaddr_in *)(void *)nam;
1480 	struct in_addr laddr;
1481 	int error = 0;
1482 	struct ifnet *outif = NULL;
1483 
1484 	if (inp->inp_lport == 0) {
1485 		error = in_pcbbind(inp, NULL, p);
1486 		if (error) {
1487 			goto done;
1488 		}
1489 	}
1490 
1491 	/*
1492 	 * Cannot simply call in_pcbconnect, because there might be an
1493 	 * earlier incarnation of this same connection still in
1494 	 * TIME_WAIT state, creating an ADDRINUSE error.
1495 	 */
1496 	error = in_pcbladdr(inp, nam, &laddr, IFSCOPE_NONE, &outif, 0);
1497 	if (error) {
1498 		goto done;
1499 	}
1500 
1501 	socket_unlock(inp->inp_socket, 0);
1502 	oinp = in_pcblookup_hash(inp->inp_pcbinfo,
1503 	    sin->sin_addr, sin->sin_port,
1504 	    inp->inp_laddr.s_addr != INADDR_ANY ? inp->inp_laddr : laddr,
1505 	    inp->inp_lport, 0, NULL);
1506 
1507 	socket_lock(inp->inp_socket, 0);
1508 	if (oinp) {
1509 		if (oinp != inp) { /* 4143933: avoid deadlock if inp == oinp */
1510 			socket_lock(oinp->inp_socket, 1);
1511 		}
1512 		if (in_pcb_checkstate(oinp, WNT_RELEASE, 1) == WNT_STOPUSING) {
1513 			if (oinp != inp) {
1514 				socket_unlock(oinp->inp_socket, 1);
1515 			}
1516 			goto skip_oinp;
1517 		}
1518 
1519 		if (oinp != inp && (otp = intotcpcb(oinp)) != NULL &&
1520 		    otp->t_state == TCPS_TIME_WAIT &&
1521 		    ((int)(tcp_now - otp->t_starttime)) < tcp_msl &&
1522 		    (otp->t_flags & TF_RCVD_CC)) {
1523 			otp = tcp_close(otp);
1524 		} else {
1525 			printf("tcp_connect: inp=0x%llx err=EADDRINUSE\n",
1526 			    (uint64_t)VM_KERNEL_ADDRPERM(inp));
1527 			if (oinp != inp) {
1528 				socket_unlock(oinp->inp_socket, 1);
1529 			}
1530 			error = EADDRINUSE;
1531 			goto done;
1532 		}
1533 		if (oinp != inp) {
1534 			socket_unlock(oinp->inp_socket, 1);
1535 		}
1536 	}
1537 skip_oinp:
1538 	if ((inp->inp_laddr.s_addr == INADDR_ANY ? laddr.s_addr :
1539 	    inp->inp_laddr.s_addr) == sin->sin_addr.s_addr &&
1540 	    inp->inp_lport == sin->sin_port) {
1541 		error = EINVAL;
1542 		goto done;
1543 	}
1544 #if SKYWALK
1545 	if (!NETNS_TOKEN_VALID(&inp->inp_netns_token)) {
1546 		error = netns_reserve_in(&inp->inp_netns_token,
1547 		    inp->inp_laddr.s_addr != INADDR_ANY ?
1548 		    inp->inp_laddr : laddr,
1549 		    IPPROTO_TCP, inp->inp_lport, NETNS_BSD, NULL);
1550 		if (error) {
1551 			goto done;
1552 		}
1553 	}
1554 #endif /* SKYWALK */
1555 	if (!lck_rw_try_lock_exclusive(&inp->inp_pcbinfo->ipi_lock)) {
1556 		/*lock inversion issue, mostly with udp multicast packets */
1557 		socket_unlock(inp->inp_socket, 0);
1558 		lck_rw_lock_exclusive(&inp->inp_pcbinfo->ipi_lock);
1559 		socket_lock(inp->inp_socket, 0);
1560 	}
1561 	if (inp->inp_laddr.s_addr == INADDR_ANY) {
1562 		inp->inp_laddr = laddr;
1563 		/* no reference needed */
1564 		inp->inp_last_outifp = outif;
1565 #if SKYWALK
1566 		if (NETNS_TOKEN_VALID(&inp->inp_netns_token)) {
1567 			netns_set_ifnet(&inp->inp_netns_token, inp->inp_last_outifp);
1568 		}
1569 #endif /* SKYWALK */
1570 
1571 		inp->inp_flags |= INP_INADDR_ANY;
1572 	}
1573 	inp->inp_faddr = sin->sin_addr;
1574 	inp->inp_fport = sin->sin_port;
1575 	in_pcbrehash(inp);
1576 	lck_rw_done(&inp->inp_pcbinfo->ipi_lock);
1577 
1578 	if (inp->inp_flowhash == 0) {
1579 		inp_calc_flowhash(inp);
1580 		ASSERT(inp->inp_flowhash != 0);
1581 	}
1582 
1583 	tcp_set_max_rwinscale(tp, so);
1584 
1585 	soisconnecting(so);
1586 	tcpstat.tcps_connattempt++;
1587 	TCP_LOG_STATE(tp, TCPS_SYN_SENT);
1588 	tp->t_state = TCPS_SYN_SENT;
1589 	tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp, TCP_CONN_KEEPINIT(tp));
1590 	tp->iss = tcp_new_isn(tp);
1591 	tcp_sendseqinit(tp);
1592 	tp->t_connect_time = tcp_now;
1593 	if (nstat_collect) {
1594 		nstat_pcb_event(inp, NSTAT_EVENT_SRC_FLOW_STATE_OUTBOUND);
1595 		nstat_route_connect_attempt(inp->inp_route.ro_rt);
1596 	}
1597 
1598 	tcp_add_fsw_flow(tp, outif);
1599 
1600 done:
1601 	if (outif != NULL) {
1602 		ifnet_release(outif);
1603 	}
1604 
1605 	return error;
1606 }
1607 
1608 static int
tcp6_connect(struct tcpcb * tp,struct sockaddr * nam,struct proc * p)1609 tcp6_connect(struct tcpcb *tp, struct sockaddr *nam, struct proc *p)
1610 {
1611 	struct inpcb *inp = tp->t_inpcb, *oinp;
1612 	struct socket *so = inp->inp_socket;
1613 	struct tcpcb *otp;
1614 	struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)(void *)nam;
1615 	struct in6_addr addr6;
1616 	int error = 0;
1617 	struct ifnet *outif = NULL;
1618 
1619 	if (inp->inp_lport == 0) {
1620 		error = in6_pcbbind(inp, NULL, p);
1621 		if (error) {
1622 			goto done;
1623 		}
1624 	}
1625 
1626 	/*
1627 	 * Cannot simply call in_pcbconnect, because there might be an
1628 	 * earlier incarnation of this same connection still in
1629 	 * TIME_WAIT state, creating an ADDRINUSE error.
1630 	 *
1631 	 * in6_pcbladdr() might return an ifp with its reference held
1632 	 * even in the error case, so make sure that it's released
1633 	 * whenever it's non-NULL.
1634 	 */
1635 	error = in6_pcbladdr(inp, nam, &addr6, &outif);
1636 	if (error) {
1637 		goto done;
1638 	}
1639 	socket_unlock(inp->inp_socket, 0);
1640 
1641 	uint32_t lifscope = IFSCOPE_NONE;
1642 	if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) {
1643 		lifscope = inp->inp_lifscope;
1644 	} else if (sin6->sin6_scope_id != IFSCOPE_NONE) {
1645 		lifscope = sin6->sin6_scope_id;
1646 	} else if (outif != NULL) {
1647 		lifscope = outif->if_index;
1648 	}
1649 	oinp = in6_pcblookup_hash(inp->inp_pcbinfo,
1650 	    &sin6->sin6_addr, sin6->sin6_port, sin6->sin6_scope_id,
1651 	    IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)
1652 	    ? &addr6
1653 	    : &inp->in6p_laddr,
1654 	    inp->inp_lport, lifscope, 0, NULL);
1655 	socket_lock(inp->inp_socket, 0);
1656 	if (oinp) {
1657 		if (oinp != inp && (otp = intotcpcb(oinp)) != NULL &&
1658 		    otp->t_state == TCPS_TIME_WAIT &&
1659 		    ((int)(tcp_now - otp->t_starttime)) < tcp_msl &&
1660 		    (otp->t_flags & TF_RCVD_CC)) {
1661 			otp = tcp_close(otp);
1662 		} else {
1663 			error = EADDRINUSE;
1664 			goto done;
1665 		}
1666 	}
1667 #if SKYWALK
1668 	if (!NETNS_TOKEN_VALID(&inp->inp_netns_token)) {
1669 		error = netns_reserve_in6(&inp->inp_netns_token,
1670 		    IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr) ?
1671 		    addr6 : inp->in6p_laddr,
1672 		    IPPROTO_TCP, inp->inp_lport, NETNS_BSD, NULL);
1673 		if (error) {
1674 			goto done;
1675 		}
1676 	}
1677 #endif /* SKYWALK */
1678 	if (!lck_rw_try_lock_exclusive(&inp->inp_pcbinfo->ipi_lock)) {
1679 		/*lock inversion issue, mostly with udp multicast packets */
1680 		socket_unlock(inp->inp_socket, 0);
1681 		lck_rw_lock_exclusive(&inp->inp_pcbinfo->ipi_lock);
1682 		socket_lock(inp->inp_socket, 0);
1683 	}
1684 	if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) {
1685 		inp->in6p_laddr = addr6;
1686 		inp->in6p_last_outifp = outif;  /* no reference needed */
1687 		inp->inp_lifscope = lifscope;
1688 		in6_verify_ifscope(&inp->in6p_laddr, inp->inp_lifscope);
1689 #if SKYWALK
1690 		if (NETNS_TOKEN_VALID(&inp->inp_netns_token)) {
1691 			netns_set_ifnet(&inp->inp_netns_token, inp->in6p_last_outifp);
1692 		}
1693 #endif /* SKYWALK */
1694 		inp->in6p_flags |= INP_IN6ADDR_ANY;
1695 	}
1696 	inp->in6p_faddr = sin6->sin6_addr;
1697 	inp->inp_fport = sin6->sin6_port;
1698 	inp->inp_fifscope = sin6->sin6_scope_id;
1699 	in6_verify_ifscope(&inp->in6p_faddr, inp->inp_fifscope);
1700 	if ((sin6->sin6_flowinfo & IPV6_FLOWINFO_MASK) != 0) {
1701 		inp->inp_flow = sin6->sin6_flowinfo;
1702 	}
1703 	in_pcbrehash(inp);
1704 	lck_rw_done(&inp->inp_pcbinfo->ipi_lock);
1705 
1706 	if (inp->inp_flowhash == 0) {
1707 		inp_calc_flowhash(inp);
1708 		ASSERT(inp->inp_flowhash != 0);
1709 	}
1710 	/* update flowinfo - RFC 6437 */
1711 	if (inp->inp_flow == 0 && inp->in6p_flags & IN6P_AUTOFLOWLABEL) {
1712 		inp->inp_flow &= ~IPV6_FLOWLABEL_MASK;
1713 		inp->inp_flow |=
1714 		    (htonl(ip6_randomflowlabel()) & IPV6_FLOWLABEL_MASK);
1715 	}
1716 
1717 	tcp_set_max_rwinscale(tp, so);
1718 
1719 	soisconnecting(so);
1720 	tcpstat.tcps_connattempt++;
1721 	TCP_LOG_STATE(tp, TCPS_SYN_SENT);
1722 	tp->t_state = TCPS_SYN_SENT;
1723 	tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp,
1724 	    TCP_CONN_KEEPINIT(tp));
1725 	tp->iss = tcp_new_isn(tp);
1726 	tcp_sendseqinit(tp);
1727 	tp->t_connect_time = tcp_now;
1728 	if (nstat_collect) {
1729 		nstat_pcb_event(inp, NSTAT_EVENT_SRC_FLOW_STATE_OUTBOUND);
1730 		nstat_route_connect_attempt(inp->inp_route.ro_rt);
1731 	}
1732 
1733 	tcp_add_fsw_flow(tp, outif);
1734 
1735 done:
1736 	if (outif != NULL) {
1737 		ifnet_release(outif);
1738 	}
1739 
1740 	return error;
1741 }
1742 
1743 /*
1744  * Export TCP internal state information via a struct tcp_info
1745  */
1746 void
tcp_fill_info(struct tcpcb * tp,struct tcp_info * ti)1747 tcp_fill_info(struct tcpcb *tp, struct tcp_info *ti)
1748 {
1749 	struct inpcb *inp = tp->t_inpcb;
1750 
1751 	bzero(ti, sizeof(*ti));
1752 
1753 	ti->tcpi_state = (uint8_t)tp->t_state;
1754 	ti->tcpi_flowhash = inp != NULL ? inp->inp_flowhash: 0;
1755 
1756 	if (TSTMP_SUPPORTED(tp)) {
1757 		ti->tcpi_options |= TCPI_OPT_TIMESTAMPS;
1758 	}
1759 	if (SACK_ENABLED(tp)) {
1760 		ti->tcpi_options |= TCPI_OPT_SACK;
1761 	}
1762 	if (TCP_WINDOW_SCALE_ENABLED(tp)) {
1763 		ti->tcpi_options |= TCPI_OPT_WSCALE;
1764 		ti->tcpi_snd_wscale = tp->snd_scale;
1765 		ti->tcpi_rcv_wscale = tp->rcv_scale;
1766 	}
1767 	if (TCP_ECN_ENABLED(tp)) {
1768 		ti->tcpi_options |= TCPI_OPT_ECN;
1769 	}
1770 
1771 	/* Are we in retranmission episode */
1772 	if (IN_FASTRECOVERY(tp) || tp->t_rxtshift > 0) {
1773 		ti->tcpi_flags |= TCPI_FLAG_LOSSRECOVERY;
1774 	}
1775 
1776 	if (tp->t_flags & TF_STREAMING_ON) {
1777 		ti->tcpi_flags |= TCPI_FLAG_STREAMING_ON;
1778 	}
1779 
1780 	ti->tcpi_rto = tp->t_timer[TCPT_REXMT] ? tp->t_rxtcur : 0;
1781 	ti->tcpi_snd_mss = tp->t_maxseg;
1782 	ti->tcpi_rcv_mss = tp->t_maxseg;
1783 
1784 	ti->tcpi_rttcur = tp->t_rttcur;
1785 	ti->tcpi_srtt = tp->t_srtt >> TCP_RTT_SHIFT;
1786 	ti->tcpi_rcv_srtt = tp->rcv_srtt >> TCP_RTT_SHIFT;
1787 	ti->tcpi_rttvar = tp->t_rttvar >> TCP_RTTVAR_SHIFT;
1788 	ti->tcpi_rttbest = tp->t_rttbest >> TCP_RTT_SHIFT;
1789 
1790 	ti->tcpi_snd_ssthresh = tp->snd_ssthresh;
1791 	ti->tcpi_snd_cwnd = tp->snd_cwnd;
1792 	if (inp != NULL && inp->inp_socket != NULL) {
1793 		ti->tcpi_snd_sbbytes = inp->inp_socket->so_snd.sb_cc;
1794 	}
1795 
1796 	ti->tcpi_rcv_space = tp->rcv_adv > tp->rcv_nxt ?
1797 	    tp->rcv_adv - tp->rcv_nxt : 0;
1798 
1799 	ti->tcpi_snd_wnd = tp->snd_wnd;
1800 	ti->tcpi_snd_nxt = tp->snd_nxt;
1801 	ti->tcpi_rcv_nxt = tp->rcv_nxt;
1802 
1803 	/* convert bytes/msec to bits/sec */
1804 	if ((tp->t_flagsext & TF_MEASURESNDBW) != 0 &&
1805 	    tp->t_bwmeas != NULL) {
1806 		ti->tcpi_snd_bw = (tp->t_bwmeas->bw_sndbw * 8000);
1807 	}
1808 
1809 	ti->tcpi_txpackets = inp != NULL ? inp->inp_stat->txpackets : 0;
1810 	ti->tcpi_txbytes = inp != NULL ? inp->inp_stat->txbytes : 0;
1811 	ti->tcpi_txretransmitbytes = tp->t_stat.txretransmitbytes;
1812 	ti->tcpi_txretransmitpackets = tp->t_stat.rxmitpkts;
1813 	ti->tcpi_txunacked = tp->snd_max - tp->snd_una;
1814 
1815 	ti->tcpi_rxpackets = inp != NULL ? inp->inp_stat->rxpackets : 0;
1816 	ti->tcpi_rxbytes = inp != NULL ? inp->inp_stat->rxbytes : 0;
1817 	ti->tcpi_rxduplicatebytes = tp->t_stat.rxduplicatebytes;
1818 	ti->tcpi_rxoutoforderbytes = tp->t_stat.rxoutoforderbytes;
1819 
1820 	if (tp->t_state > TCPS_LISTEN) {
1821 		ti->tcpi_synrexmits = (uint8_t)tp->t_stat.rxmitsyns;
1822 	}
1823 	if (inp != NULL) {
1824 		ti->tcpi_cell_rxpackets = inp->inp_cstat->rxpackets;
1825 		ti->tcpi_cell_rxbytes = inp->inp_cstat->rxbytes;
1826 		ti->tcpi_cell_txpackets = inp->inp_cstat->txpackets;
1827 		ti->tcpi_cell_txbytes = inp->inp_cstat->txbytes;
1828 
1829 		ti->tcpi_wifi_rxpackets = inp->inp_wstat->rxpackets;
1830 		ti->tcpi_wifi_rxbytes = inp->inp_wstat->rxbytes;
1831 		ti->tcpi_wifi_txpackets = inp->inp_wstat->txpackets;
1832 		ti->tcpi_wifi_txbytes = inp->inp_wstat->txbytes;
1833 
1834 		ti->tcpi_wired_rxpackets = inp->inp_Wstat->rxpackets;
1835 		ti->tcpi_wired_rxbytes = inp->inp_Wstat->rxbytes;
1836 		ti->tcpi_wired_txpackets = inp->inp_Wstat->txpackets;
1837 		ti->tcpi_wired_txbytes = inp->inp_Wstat->txbytes;
1838 	}
1839 	tcp_get_connectivity_status(tp, &ti->tcpi_connstatus);
1840 
1841 	ti->tcpi_tfo_syn_data_rcv = !!(tp->t_tfo_stats & TFO_S_SYNDATA_RCV);
1842 	ti->tcpi_tfo_cookie_req_rcv = !!(tp->t_tfo_stats & TFO_S_COOKIEREQ_RECV);
1843 	ti->tcpi_tfo_cookie_sent = !!(tp->t_tfo_stats & TFO_S_COOKIE_SENT);
1844 	ti->tcpi_tfo_cookie_invalid = !!(tp->t_tfo_stats & TFO_S_COOKIE_INVALID);
1845 
1846 	ti->tcpi_tfo_cookie_req = !!(tp->t_tfo_stats & TFO_S_COOKIE_REQ);
1847 	ti->tcpi_tfo_cookie_rcv = !!(tp->t_tfo_stats & TFO_S_COOKIE_RCV);
1848 	ti->tcpi_tfo_syn_data_sent = !!(tp->t_tfo_stats & TFO_S_SYN_DATA_SENT);
1849 	ti->tcpi_tfo_syn_data_acked = !!(tp->t_tfo_stats & TFO_S_SYN_DATA_ACKED);
1850 	ti->tcpi_tfo_syn_loss = !!(tp->t_tfo_stats & TFO_S_SYN_LOSS);
1851 	ti->tcpi_tfo_cookie_wrong = !!(tp->t_tfo_stats & TFO_S_COOKIE_WRONG);
1852 	ti->tcpi_tfo_no_cookie_rcv = !!(tp->t_tfo_stats & TFO_S_NO_COOKIE_RCV);
1853 	ti->tcpi_tfo_heuristics_disable = !!(tp->t_tfo_stats & TFO_S_HEURISTICS_DISABLE);
1854 	ti->tcpi_tfo_send_blackhole = !!(tp->t_tfo_stats & TFO_S_SEND_BLACKHOLE);
1855 	ti->tcpi_tfo_recv_blackhole = !!(tp->t_tfo_stats & TFO_S_RECV_BLACKHOLE);
1856 	ti->tcpi_tfo_onebyte_proxy = !!(tp->t_tfo_stats & TFO_S_ONE_BYTE_PROXY);
1857 
1858 	ti->tcpi_ecn_client_setup = !!(tp->ecn_flags & (TE_SETUPSENT | TE_ACE_SETUPSENT));
1859 	ti->tcpi_ecn_server_setup = !!(tp->ecn_flags & (TE_SETUPRECEIVED | TE_ACE_SETUPRECEIVED));
1860 	ti->tcpi_ecn_success = (TCP_ECN_ENABLED(tp) || TCP_ACC_ECN_ON(tp)) ? 1 : 0;
1861 	ti->tcpi_ecn_lost_syn = !!(tp->ecn_flags & TE_LOST_SYN);
1862 	ti->tcpi_ecn_lost_synack = !!(tp->ecn_flags & TE_LOST_SYNACK);
1863 
1864 	ti->tcpi_local_peer = !!(tp->t_flags & TF_LOCAL);
1865 
1866 	if (inp != NULL && inp->inp_last_outifp != NULL) {
1867 		ti->tcpi_last_outif = inp->inp_last_outifp->if_index;
1868 
1869 		if (IFNET_IS_CELLULAR(inp->inp_last_outifp)) {
1870 			ti->tcpi_if_cell = 1;
1871 		}
1872 		if (IFNET_IS_WIFI(inp->inp_last_outifp)) {
1873 			ti->tcpi_if_wifi = 1;
1874 		}
1875 		if (IFNET_IS_WIRED(inp->inp_last_outifp)) {
1876 			ti->tcpi_if_wired = 1;
1877 		}
1878 		if (IFNET_IS_WIFI_INFRA(inp->inp_last_outifp)) {
1879 			ti->tcpi_if_wifi_infra = 1;
1880 		}
1881 		if (inp->inp_last_outifp->if_eflags & IFEF_AWDL) {
1882 			ti->tcpi_if_wifi_awdl = 1;
1883 		}
1884 	}
1885 	if (tp->tcp_cc_index == TCP_CC_ALGO_BACKGROUND_INDEX) {
1886 		ti->tcpi_snd_background = 1;
1887 	}
1888 	if (tcp_recv_bg == 1 || (inp != NULL && inp->inp_socket != NULL &&
1889 	    IS_TCP_RECV_BG(inp->inp_socket))) {
1890 		ti->tcpi_rcv_background = 1;
1891 	}
1892 
1893 	ti->tcpi_ecn_recv_ce = tp->t_ecn_recv_ce;
1894 	ti->tcpi_ecn_recv_cwr = tp->t_ecn_recv_cwr;
1895 
1896 	ti->tcpi_rcvoopack = tp->t_rcvoopack;
1897 	ti->tcpi_pawsdrop = tp->t_pawsdrop;
1898 	ti->tcpi_sack_recovery_episode = tp->t_sack_recovery_episode;
1899 	ti->tcpi_reordered_pkts = tp->t_reordered_pkts;
1900 	ti->tcpi_dsack_sent = tp->t_dsack_sent;
1901 	ti->tcpi_dsack_recvd = tp->t_dsack_recvd;
1902 
1903 	ti->tcpi_client_accecn_state = tp->t_client_accecn_state;
1904 	ti->tcpi_server_accecn_state = tp->t_server_accecn_state;
1905 	ti->tcpi_ecn_capable_packets_sent = tp->t_ecn_capable_packets_sent;
1906 	ti->tcpi_ecn_capable_packets_acked = tp->t_ecn_capable_packets_acked;
1907 	ti->tcpi_ecn_capable_packets_marked = tp->t_ecn_capable_packets_marked;
1908 	ti->tcpi_ecn_capable_packets_lost = tp->t_ecn_capable_packets_lost;
1909 }
1910 
1911 __private_extern__ errno_t
tcp_fill_info_for_info_tuple(struct info_tuple * itpl,struct tcp_info * ti)1912 tcp_fill_info_for_info_tuple(struct info_tuple *itpl, struct tcp_info *ti)
1913 {
1914 	struct inpcbinfo *pcbinfo = NULL;
1915 	struct inpcb *inp = NULL;
1916 	struct socket *so;
1917 	struct tcpcb *tp;
1918 
1919 	if (itpl->itpl_proto == IPPROTO_TCP) {
1920 		pcbinfo = &tcbinfo;
1921 	} else {
1922 		return EINVAL;
1923 	}
1924 
1925 	if (itpl->itpl_local_sa.sa_family == AF_INET &&
1926 	    itpl->itpl_remote_sa.sa_family == AF_INET) {
1927 		inp = in_pcblookup_hash(pcbinfo,
1928 		    itpl->itpl_remote_sin.sin_addr,
1929 		    itpl->itpl_remote_sin.sin_port,
1930 		    itpl->itpl_local_sin.sin_addr,
1931 		    itpl->itpl_local_sin.sin_port,
1932 		    0, NULL);
1933 	} else if (itpl->itpl_local_sa.sa_family == AF_INET6 &&
1934 	    itpl->itpl_remote_sa.sa_family == AF_INET6) {
1935 		struct in6_addr ina6_local;
1936 		struct in6_addr ina6_remote;
1937 
1938 		ina6_local = itpl->itpl_local_sin6.sin6_addr;
1939 		if (in6_embedded_scope && IN6_IS_SCOPE_LINKLOCAL(&ina6_local) &&
1940 		    itpl->itpl_local_sin6.sin6_scope_id) {
1941 			ina6_local.s6_addr16[1] = htons((uint16_t)itpl->itpl_local_sin6.sin6_scope_id);
1942 		}
1943 
1944 		ina6_remote = itpl->itpl_remote_sin6.sin6_addr;
1945 		if (in6_embedded_scope && IN6_IS_SCOPE_LINKLOCAL(&ina6_remote) &&
1946 		    itpl->itpl_remote_sin6.sin6_scope_id) {
1947 			ina6_remote.s6_addr16[1] = htons((uint16_t)itpl->itpl_remote_sin6.sin6_scope_id);
1948 		}
1949 
1950 		inp = in6_pcblookup_hash(pcbinfo,
1951 		    &ina6_remote,
1952 		    itpl->itpl_remote_sin6.sin6_port,
1953 		    itpl->itpl_remote_sin6.sin6_scope_id,
1954 		    &ina6_local,
1955 		    itpl->itpl_local_sin6.sin6_port,
1956 		    itpl->itpl_local_sin6.sin6_scope_id,
1957 		    0, NULL);
1958 	} else {
1959 		return EINVAL;
1960 	}
1961 
1962 	if (inp != NULL) {
1963 		if ((so = inp->inp_socket) == NULL) {
1964 			return ENOENT;
1965 		}
1966 		socket_lock(so, 0);
1967 		if (in_pcb_checkstate(inp, WNT_RELEASE, 1) == WNT_STOPUSING) {
1968 			socket_unlock(so, 0);
1969 			return ENOENT;
1970 		}
1971 		tp = intotcpcb(inp);
1972 
1973 		tcp_fill_info(tp, ti);
1974 		socket_unlock(so, 0);
1975 
1976 		return 0;
1977 	}
1978 #if SKYWALK
1979 	else {
1980 		/* if no pcb found, check for flowswitch for uTCP flow */
1981 		int error;
1982 		struct nexus_mib_filter nmf = {
1983 			.nmf_type = NXMIB_FLOW,
1984 			.nmf_bitmap = NXMIB_FILTER_INFO_TUPLE,
1985 			.nmf_info_tuple = *itpl,
1986 		};
1987 		struct sk_stats_flow sf;
1988 		size_t len = sizeof(sf);
1989 		error = kernel_sysctlbyname(SK_STATS_FLOW, &sf, &len, &nmf, sizeof(nmf));
1990 		if (error != 0) {
1991 			printf("kernel_sysctlbyname err %d\n", error);
1992 			return error;
1993 		}
1994 		if (len != sizeof(sf)) {
1995 			printf("kernel_sysctlbyname invalid len %zu\n", len);
1996 			return ENOENT;
1997 		}
1998 
1999 		/*
2000 		 * This is what flow tracker can offer right now, which is good
2001 		 * for mDNS TCP keep alive offload.
2002 		 */
2003 		ti->tcpi_snd_nxt = sf.sf_lseq;
2004 		ti->tcpi_rcv_nxt = sf.sf_rseq;
2005 		ti->tcpi_rcv_space = (uint32_t)(sf.sf_lmax_win << sf.sf_lwscale);
2006 		ti->tcpi_rcv_wscale = sf.sf_lwscale;
2007 		ti->tcpi_last_outif = (int32_t)sf.sf_if_index;
2008 
2009 		return 0;
2010 	}
2011 #endif /* SKYWALK */
2012 
2013 	return ENOENT;
2014 }
2015 
2016 static void
tcp_connection_fill_info(struct tcpcb * tp,struct tcp_connection_info * tci)2017 tcp_connection_fill_info(struct tcpcb *tp, struct tcp_connection_info *tci)
2018 {
2019 	struct inpcb *inp = tp->t_inpcb;
2020 
2021 	bzero(tci, sizeof(*tci));
2022 	tci->tcpi_state = (uint8_t)tp->t_state;
2023 
2024 	if (TSTMP_SUPPORTED(tp)) {
2025 		tci->tcpi_options |= TCPCI_OPT_TIMESTAMPS;
2026 	}
2027 	if (SACK_ENABLED(tp)) {
2028 		tci->tcpi_options |= TCPCI_OPT_SACK;
2029 	}
2030 	if (TCP_WINDOW_SCALE_ENABLED(tp)) {
2031 		tci->tcpi_options |= TCPCI_OPT_WSCALE;
2032 		tci->tcpi_snd_wscale = tp->snd_scale;
2033 		tci->tcpi_rcv_wscale = tp->rcv_scale;
2034 	}
2035 	if (TCP_ECN_ENABLED(tp)) {
2036 		tci->tcpi_options |= TCPCI_OPT_ECN;
2037 	}
2038 	if (IN_FASTRECOVERY(tp) || tp->t_rxtshift > 0) {
2039 		tci->tcpi_flags |= TCPCI_FLAG_LOSSRECOVERY;
2040 	}
2041 	if (tp->t_flagsext & TF_PKTS_REORDERED) {
2042 		tci->tcpi_flags |= TCPCI_FLAG_REORDERING_DETECTED;
2043 	}
2044 	tci->tcpi_rto = tp->t_timer[TCPT_REXMT] > 0 ? tp->t_rxtcur : 0;
2045 	tci->tcpi_maxseg = tp->t_maxseg;
2046 	tci->tcpi_snd_ssthresh = tp->snd_ssthresh;
2047 	tci->tcpi_snd_cwnd = tp->snd_cwnd;
2048 	tci->tcpi_snd_wnd = tp->snd_wnd;
2049 	if (inp != NULL && inp->inp_socket != NULL) {
2050 		tci->tcpi_snd_sbbytes = inp->inp_socket->so_snd.sb_cc;
2051 	}
2052 	tci->tcpi_rcv_wnd = tp->rcv_adv > tp->rcv_nxt ? tp->rcv_adv - tp->rcv_nxt : 0;
2053 	tci->tcpi_rttcur = tp->t_rttcur;
2054 	tci->tcpi_srtt = (tp->t_srtt >> TCP_RTT_SHIFT);
2055 	tci->tcpi_rttvar = (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
2056 	tci->tcpi_txpackets = inp != NULL ? inp->inp_stat->txpackets : 0;
2057 	tci->tcpi_txbytes = inp != NULL ? inp->inp_stat->txbytes : 0;
2058 	tci->tcpi_txretransmitbytes = tp->t_stat.txretransmitbytes;
2059 	tci->tcpi_txretransmitpackets = tp->t_stat.rxmitpkts;
2060 	tci->tcpi_rxpackets = inp != NULL ? inp->inp_stat->rxpackets : 0;
2061 	tci->tcpi_rxbytes = inp != NULL ? inp->inp_stat->rxbytes : 0;
2062 	tci->tcpi_rxoutoforderbytes = tp->t_stat.rxoutoforderbytes;
2063 
2064 	tci->tcpi_tfo_syn_data_rcv = !!(tp->t_tfo_stats & TFO_S_SYNDATA_RCV);
2065 	tci->tcpi_tfo_cookie_req_rcv = !!(tp->t_tfo_stats & TFO_S_COOKIEREQ_RECV);
2066 	tci->tcpi_tfo_cookie_sent = !!(tp->t_tfo_stats & TFO_S_COOKIE_SENT);
2067 	tci->tcpi_tfo_cookie_invalid = !!(tp->t_tfo_stats & TFO_S_COOKIE_INVALID);
2068 	tci->tcpi_tfo_cookie_req = !!(tp->t_tfo_stats & TFO_S_COOKIE_REQ);
2069 	tci->tcpi_tfo_cookie_rcv = !!(tp->t_tfo_stats & TFO_S_COOKIE_RCV);
2070 	tci->tcpi_tfo_syn_data_sent = !!(tp->t_tfo_stats & TFO_S_SYN_DATA_SENT);
2071 	tci->tcpi_tfo_syn_data_acked = !!(tp->t_tfo_stats & TFO_S_SYN_DATA_ACKED);
2072 	tci->tcpi_tfo_syn_loss = !!(tp->t_tfo_stats & TFO_S_SYN_LOSS);
2073 	tci->tcpi_tfo_cookie_wrong = !!(tp->t_tfo_stats & TFO_S_COOKIE_WRONG);
2074 	tci->tcpi_tfo_no_cookie_rcv = !!(tp->t_tfo_stats & TFO_S_NO_COOKIE_RCV);
2075 	tci->tcpi_tfo_heuristics_disable = !!(tp->t_tfo_stats & TFO_S_HEURISTICS_DISABLE);
2076 	tci->tcpi_tfo_send_blackhole = !!(tp->t_tfo_stats & TFO_S_SEND_BLACKHOLE);
2077 	tci->tcpi_tfo_recv_blackhole = !!(tp->t_tfo_stats & TFO_S_RECV_BLACKHOLE);
2078 	tci->tcpi_tfo_onebyte_proxy = !!(tp->t_tfo_stats & TFO_S_ONE_BYTE_PROXY);
2079 }
2080 
2081 
2082 __private_extern__ int
tcp_sysctl_info(__unused struct sysctl_oid * oidp,__unused void * arg1,__unused int arg2,struct sysctl_req * req)2083 tcp_sysctl_info(__unused struct sysctl_oid *oidp, __unused void *arg1, __unused int arg2, struct sysctl_req *req)
2084 {
2085 	int error;
2086 	struct tcp_info ti = {};
2087 	struct info_tuple itpl;
2088 
2089 	if (req->newptr == USER_ADDR_NULL) {
2090 		return EINVAL;
2091 	}
2092 	if (req->newlen < sizeof(struct info_tuple)) {
2093 		return EINVAL;
2094 	}
2095 	error = SYSCTL_IN(req, &itpl, sizeof(struct info_tuple));
2096 	if (error != 0) {
2097 		return error;
2098 	}
2099 	error = tcp_fill_info_for_info_tuple(&itpl, &ti);
2100 	if (error != 0) {
2101 		return error;
2102 	}
2103 	error = SYSCTL_OUT(req, &ti, sizeof(struct tcp_info));
2104 	if (error != 0) {
2105 		return error;
2106 	}
2107 
2108 	return 0;
2109 }
2110 
2111 static int
tcp_lookup_peer_pid_locked(struct socket * so,pid_t * out_pid)2112 tcp_lookup_peer_pid_locked(struct socket *so, pid_t *out_pid)
2113 {
2114 	int error = EHOSTUNREACH;
2115 	*out_pid = -1;
2116 	if ((so->so_state & SS_ISCONNECTED) == 0) {
2117 		return ENOTCONN;
2118 	}
2119 
2120 	struct inpcb    *inp = (struct inpcb*)so->so_pcb;
2121 	uint16_t                lport = inp->inp_lport;
2122 	uint16_t                fport = inp->inp_fport;
2123 	uint32_t                                fifscope = inp->inp_fifscope;
2124 	uint32_t                                lifscope = inp->inp_lifscope;
2125 
2126 	struct inpcb    *finp = NULL;
2127 	struct  in6_addr laddr6, faddr6;
2128 	struct in_addr laddr4, faddr4;
2129 
2130 	if (inp->inp_vflag & INP_IPV6) {
2131 		laddr6 = inp->in6p_laddr;
2132 		faddr6 = inp->in6p_faddr;
2133 	} else if (inp->inp_vflag & INP_IPV4) {
2134 		laddr4 = inp->inp_laddr;
2135 		faddr4 = inp->inp_faddr;
2136 	}
2137 
2138 	socket_unlock(so, 0);
2139 	if (inp->inp_vflag & INP_IPV6) {
2140 		finp = in6_pcblookup_hash(&tcbinfo, &laddr6, lport, lifscope, &faddr6, fport, fifscope, 0, NULL);
2141 	} else if (inp->inp_vflag & INP_IPV4) {
2142 		finp = in_pcblookup_hash(&tcbinfo, laddr4, lport, faddr4, fport, 0, NULL);
2143 	}
2144 
2145 	if (finp) {
2146 		*out_pid = finp->inp_socket->last_pid;
2147 		error = 0;
2148 		in_pcb_checkstate(finp, WNT_RELEASE, 0);
2149 	}
2150 	socket_lock(so, 0);
2151 
2152 	return error;
2153 }
2154 
2155 void
tcp_getconninfo(struct socket * so,struct conninfo_tcp * tcp_ci)2156 tcp_getconninfo(struct socket *so, struct conninfo_tcp *tcp_ci)
2157 {
2158 	tcp_fill_info(sototcpcb(so), &tcp_ci->tcpci_tcp_info);
2159 }
2160 
2161 void
tcp_clear_keep_alive_offload(struct socket * so)2162 tcp_clear_keep_alive_offload(struct socket *so)
2163 {
2164 	struct inpcb *inp;
2165 	struct ifnet *ifp;
2166 
2167 	inp = sotoinpcb(so);
2168 	if (inp == NULL) {
2169 		return;
2170 	}
2171 
2172 	if ((inp->inp_flags2 & INP2_KEEPALIVE_OFFLOAD) == 0) {
2173 		return;
2174 	}
2175 
2176 	ifp = inp->inp_boundifp != NULL ? inp->inp_boundifp :
2177 	    inp->inp_last_outifp;
2178 	if (ifp == NULL) {
2179 		panic("%s: so %p inp %p ifp NULL",
2180 		    __func__, so, inp);
2181 	}
2182 
2183 	ifnet_lock_exclusive(ifp);
2184 
2185 	if (ifp->if_tcp_kao_cnt == 0) {
2186 		panic("%s: so %p inp %p ifp %p if_tcp_kao_cnt == 0",
2187 		    __func__, so, inp, ifp);
2188 	}
2189 	ifp->if_tcp_kao_cnt--;
2190 	inp->inp_flags2 &= ~INP2_KEEPALIVE_OFFLOAD;
2191 
2192 	ifnet_lock_done(ifp);
2193 }
2194 
2195 static int
tcp_set_keep_alive_offload(struct socket * so,struct proc * proc)2196 tcp_set_keep_alive_offload(struct socket *so, struct proc *proc)
2197 {
2198 	int error = 0;
2199 	struct inpcb *inp;
2200 	struct ifnet *ifp;
2201 
2202 	inp = sotoinpcb(so);
2203 	if (inp == NULL) {
2204 		return ECONNRESET;
2205 	}
2206 	if ((inp->inp_flags2 & INP2_KEEPALIVE_OFFLOAD) != 0) {
2207 		return 0;
2208 	}
2209 
2210 	ifp = inp->inp_boundifp != NULL ? inp->inp_boundifp :
2211 	    inp->inp_last_outifp;
2212 	if (ifp == NULL) {
2213 		error = ENXIO;
2214 		os_log_info(OS_LOG_DEFAULT,
2215 		    "%s: error %d for proc %s[%u] out ifp is not set\n",
2216 		    __func__, error,
2217 		    proc != NULL ? proc->p_comm : "kernel",
2218 		    proc != NULL ? proc_getpid(proc) : 0);
2219 		return ENXIO;
2220 	}
2221 
2222 	error = if_get_tcp_kao_max(ifp);
2223 	if (error != 0) {
2224 		return error;
2225 	}
2226 
2227 	ifnet_lock_exclusive(ifp);
2228 	if (ifp->if_tcp_kao_cnt < ifp->if_tcp_kao_max) {
2229 		ifp->if_tcp_kao_cnt++;
2230 		inp->inp_flags2 |= INP2_KEEPALIVE_OFFLOAD;
2231 	} else {
2232 		error = ETOOMANYREFS;
2233 		os_log_info(OS_LOG_DEFAULT,
2234 		    "%s: error %d for proc %s[%u] if_tcp_kao_max %u\n",
2235 		    __func__, error,
2236 		    proc != NULL ? proc->p_comm : "kernel",
2237 		    proc != NULL ? proc_getpid(proc) : 0,
2238 		    ifp->if_tcp_kao_max);
2239 	}
2240 	ifnet_lock_done(ifp);
2241 
2242 	return error;
2243 }
2244 
2245 /*
2246  * The new sockopt interface makes it possible for us to block in the
2247  * copyin/out step (if we take a page fault).  Taking a page fault at
2248  * splnet() is probably a Bad Thing.  (Since sockets and pcbs both now
2249  * use TSM, there probably isn't any need for this function to run at
2250  * splnet() any more.  This needs more examination.)
2251  */
2252 int
tcp_ctloutput(struct socket * so,struct sockopt * sopt)2253 tcp_ctloutput(struct socket *so, struct sockopt *sopt)
2254 {
2255 	int     error = 0, opt = 0, optval = 0;
2256 	struct  inpcb *inp;
2257 	struct  tcpcb *tp;
2258 
2259 	inp = sotoinpcb(so);
2260 	if (inp == NULL) {
2261 		return ECONNRESET;
2262 	}
2263 	/* Allow <SOL_SOCKET,SO_FLUSH/SO_TRAFFIC_MGT_BACKGROUND> at this level */
2264 	if (sopt->sopt_level != IPPROTO_TCP &&
2265 	    !(sopt->sopt_level == SOL_SOCKET && (sopt->sopt_name == SO_FLUSH ||
2266 	    sopt->sopt_name == SO_TRAFFIC_MGT_BACKGROUND))) {
2267 		if (SOCK_CHECK_DOM(so, PF_INET6)) {
2268 			error = ip6_ctloutput(so, sopt);
2269 		} else {
2270 			error = ip_ctloutput(so, sopt);
2271 		}
2272 		return error;
2273 	}
2274 	tp = intotcpcb(inp);
2275 	if (tp == NULL) {
2276 		return ECONNRESET;
2277 	}
2278 
2279 	calculate_tcp_clock();
2280 
2281 	switch (sopt->sopt_dir) {
2282 	case SOPT_SET:
2283 		switch (sopt->sopt_name) {
2284 		case TCP_NODELAY:
2285 		case TCP_NOOPT:
2286 		case TCP_NOPUSH:
2287 			error = sooptcopyin(sopt, &optval, sizeof optval,
2288 			    sizeof optval);
2289 			if (error) {
2290 				break;
2291 			}
2292 
2293 			switch (sopt->sopt_name) {
2294 			case TCP_NODELAY:
2295 				opt = TF_NODELAY;
2296 				break;
2297 			case TCP_NOOPT:
2298 				opt = TF_NOOPT;
2299 				break;
2300 			case TCP_NOPUSH:
2301 				opt = TF_NOPUSH;
2302 				break;
2303 			default:
2304 				opt = 0; /* dead code to fool gcc */
2305 				break;
2306 			}
2307 
2308 			if (optval) {
2309 				tp->t_flags |= opt;
2310 			} else {
2311 				tp->t_flags &= ~opt;
2312 			}
2313 			break;
2314 		case TCP_RXT_FINDROP:
2315 		case TCP_NOTIMEWAIT:
2316 			error = sooptcopyin(sopt, &optval, sizeof optval,
2317 			    sizeof optval);
2318 			if (error) {
2319 				break;
2320 			}
2321 			switch (sopt->sopt_name) {
2322 			case TCP_RXT_FINDROP:
2323 				opt = TF_RXTFINDROP;
2324 				break;
2325 			case TCP_NOTIMEWAIT:
2326 				opt = TF_NOTIMEWAIT;
2327 				break;
2328 			default:
2329 				opt = 0;
2330 				break;
2331 			}
2332 			if (optval) {
2333 				tp->t_flagsext |= opt;
2334 			} else {
2335 				tp->t_flagsext &= ~opt;
2336 			}
2337 			break;
2338 		case TCP_MEASURE_SND_BW:
2339 			error = sooptcopyin(sopt, &optval, sizeof optval,
2340 			    sizeof optval);
2341 			if (error) {
2342 				break;
2343 			}
2344 			opt = TF_MEASURESNDBW;
2345 			if (optval) {
2346 				if (tp->t_bwmeas == NULL) {
2347 					tp->t_bwmeas = tcp_bwmeas_alloc(tp);
2348 					if (tp->t_bwmeas == NULL) {
2349 						error = ENOMEM;
2350 						break;
2351 					}
2352 				}
2353 				tp->t_flagsext |= opt;
2354 			} else {
2355 				tp->t_flagsext &= ~opt;
2356 				/* Reset snd bw measurement state */
2357 				tp->t_flagsext &= ~(TF_BWMEAS_INPROGRESS);
2358 				if (tp->t_bwmeas != NULL) {
2359 					tcp_bwmeas_free(tp);
2360 				}
2361 			}
2362 			break;
2363 		case TCP_MEASURE_BW_BURST: {
2364 			struct tcp_measure_bw_burst in;
2365 			uint32_t minpkts, maxpkts;
2366 			bzero(&in, sizeof(in));
2367 
2368 			error = sooptcopyin(sopt, &in, sizeof(in),
2369 			    sizeof(in));
2370 			if (error) {
2371 				break;
2372 			}
2373 			if ((tp->t_flagsext & TF_MEASURESNDBW) == 0 ||
2374 			    tp->t_bwmeas == NULL) {
2375 				error = EINVAL;
2376 				break;
2377 			}
2378 			minpkts = (in.min_burst_size != 0) ? in.min_burst_size :
2379 			    tp->t_bwmeas->bw_minsizepkts;
2380 			maxpkts = (in.max_burst_size != 0) ? in.max_burst_size :
2381 			    tp->t_bwmeas->bw_maxsizepkts;
2382 			if (minpkts > maxpkts) {
2383 				error = EINVAL;
2384 				break;
2385 			}
2386 			tp->t_bwmeas->bw_minsizepkts = minpkts;
2387 			tp->t_bwmeas->bw_maxsizepkts = maxpkts;
2388 			tp->t_bwmeas->bw_minsize = (minpkts * tp->t_maxseg);
2389 			tp->t_bwmeas->bw_maxsize = (maxpkts * tp->t_maxseg);
2390 			break;
2391 		}
2392 		case TCP_MAXSEG:
2393 			error = sooptcopyin(sopt, &optval, sizeof optval,
2394 			    sizeof optval);
2395 			if (error) {
2396 				break;
2397 			}
2398 
2399 			if (optval > 0 && optval <= tp->t_maxseg &&
2400 			    optval + 40 >= tcp_minmss) {
2401 				tp->t_maxseg = optval;
2402 			} else {
2403 				error = EINVAL;
2404 			}
2405 			break;
2406 
2407 		case TCP_KEEPALIVE:
2408 			error = sooptcopyin(sopt, &optval, sizeof optval,
2409 			    sizeof optval);
2410 			if (error) {
2411 				break;
2412 			}
2413 			if (optval < 0 || optval > UINT32_MAX / TCP_RETRANSHZ) {
2414 				error = EINVAL;
2415 			} else {
2416 				tp->t_keepidle = optval * TCP_RETRANSHZ;
2417 				/* reset the timer to new value */
2418 				if (TCPS_HAVEESTABLISHED(tp->t_state)) {
2419 					tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp,
2420 					    TCP_CONN_KEEPIDLE(tp));
2421 					tcp_check_timer_state(tp);
2422 				}
2423 			}
2424 			break;
2425 
2426 		case TCP_CONNECTIONTIMEOUT:
2427 			error = sooptcopyin(sopt, &optval, sizeof optval,
2428 			    sizeof optval);
2429 			if (error) {
2430 				break;
2431 			}
2432 			if (optval < 0 || optval > UINT32_MAX / TCP_RETRANSHZ) {
2433 				error = EINVAL;
2434 			} else {
2435 				tp->t_keepinit = optval * TCP_RETRANSHZ;
2436 				if (tp->t_state == TCPS_SYN_RECEIVED ||
2437 				    tp->t_state == TCPS_SYN_SENT) {
2438 					tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp,
2439 					    TCP_CONN_KEEPINIT(tp));
2440 					tcp_check_timer_state(tp);
2441 				}
2442 			}
2443 			break;
2444 
2445 		case TCP_KEEPINTVL:
2446 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2447 			    sizeof(optval));
2448 			if (error) {
2449 				break;
2450 			}
2451 			if (optval < 0 || optval > UINT32_MAX / TCP_RETRANSHZ) {
2452 				error = EINVAL;
2453 			} else {
2454 				tp->t_keepintvl = optval * TCP_RETRANSHZ;
2455 				if (tp->t_state == TCPS_FIN_WAIT_2 &&
2456 				    TCP_CONN_MAXIDLE(tp) > 0) {
2457 					tp->t_timer[TCPT_2MSL] = OFFSET_FROM_START(tp,
2458 					    TCP_CONN_MAXIDLE(tp));
2459 					tcp_check_timer_state(tp);
2460 				}
2461 			}
2462 			break;
2463 
2464 		case TCP_KEEPCNT:
2465 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2466 			    sizeof(optval));
2467 			if (error) {
2468 				break;
2469 			}
2470 			if (optval < 0 || optval > INT32_MAX) {
2471 				error = EINVAL;
2472 			} else {
2473 				tp->t_keepcnt = optval;
2474 				if (tp->t_state == TCPS_FIN_WAIT_2 &&
2475 				    TCP_CONN_MAXIDLE(tp) > 0) {
2476 					tp->t_timer[TCPT_2MSL] = OFFSET_FROM_START(tp,
2477 					    TCP_CONN_MAXIDLE(tp));
2478 					tcp_check_timer_state(tp);
2479 				}
2480 			}
2481 			break;
2482 
2483 		case TCP_KEEPALIVE_OFFLOAD:
2484 			if ((error = priv_check_cred(kauth_cred_get(),
2485 			    PRIV_NETINET_TCP_KA_OFFLOAD, 0)) != 0) {
2486 				break;
2487 			}
2488 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2489 			    sizeof(optval));
2490 			if (error) {
2491 				break;
2492 			}
2493 			if (optval < 0 || optval > INT32_MAX) {
2494 				error = EINVAL;
2495 				break;
2496 			}
2497 			if (optval != 0) {
2498 				error = tcp_set_keep_alive_offload(so,
2499 				    sopt->sopt_p);
2500 			} else {
2501 				tcp_clear_keep_alive_offload(so);
2502 			}
2503 			break;
2504 
2505 		case PERSIST_TIMEOUT:
2506 			error = sooptcopyin(sopt, &optval, sizeof optval,
2507 			    sizeof optval);
2508 			if (error) {
2509 				break;
2510 			}
2511 			if (optval < 0) {
2512 				error = EINVAL;
2513 			} else {
2514 				tp->t_persist_timeout = optval * TCP_RETRANSHZ;
2515 			}
2516 			break;
2517 		case TCP_RXT_CONNDROPTIME:
2518 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2519 			    sizeof(optval));
2520 			if (error) {
2521 				break;
2522 			}
2523 			if (optval < 0) {
2524 				error = EINVAL;
2525 			} else {
2526 				tp->t_rxt_conndroptime = optval * TCP_RETRANSHZ;
2527 			}
2528 			break;
2529 		case TCP_NOTSENT_LOWAT:
2530 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2531 			    sizeof(optval));
2532 			if (error) {
2533 				break;
2534 			}
2535 			if (optval < 0) {
2536 				error = EINVAL;
2537 				break;
2538 			} else {
2539 				if (optval == 0) {
2540 					so->so_flags &= ~(SOF_NOTSENT_LOWAT);
2541 					tp->t_notsent_lowat = 0;
2542 				} else {
2543 					so->so_flags |= SOF_NOTSENT_LOWAT;
2544 					tp->t_notsent_lowat = optval;
2545 				}
2546 			}
2547 			break;
2548 		case TCP_ADAPTIVE_READ_TIMEOUT:
2549 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2550 			    sizeof(optval));
2551 			if (error) {
2552 				break;
2553 			}
2554 			if (optval < 0 ||
2555 			    optval > TCP_ADAPTIVE_TIMEOUT_MAX) {
2556 				error = EINVAL;
2557 				break;
2558 			} else if (optval == 0) {
2559 				tp->t_adaptive_rtimo = 0;
2560 				tcp_keepalive_reset(tp);
2561 
2562 				if (tp->t_mpsub) {
2563 					mptcp_reset_keepalive(tp);
2564 				}
2565 			} else {
2566 				tp->t_adaptive_rtimo = (uint8_t)optval;
2567 			}
2568 			break;
2569 		case TCP_ADAPTIVE_WRITE_TIMEOUT:
2570 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2571 			    sizeof(optval));
2572 			if (error) {
2573 				break;
2574 			}
2575 			if (optval < 0 ||
2576 			    optval > TCP_ADAPTIVE_TIMEOUT_MAX) {
2577 				error = EINVAL;
2578 				break;
2579 			} else {
2580 				tp->t_adaptive_wtimo = (uint8_t)optval;
2581 			}
2582 			break;
2583 		case TCP_SENDMOREACKS:
2584 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2585 			    sizeof(optval));
2586 			if (error) {
2587 				break;
2588 			}
2589 			if (optval < 0 || optval > 1) {
2590 				error = EINVAL;
2591 			} else if (optval == 0) {
2592 				tp->t_flagsext &= ~(TF_NOSTRETCHACK);
2593 			} else {
2594 				tp->t_flagsext |= TF_NOSTRETCHACK;
2595 			}
2596 			break;
2597 		case TCP_DISABLE_BLACKHOLE_DETECTION:
2598 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2599 			    sizeof(optval));
2600 			if (error) {
2601 				break;
2602 			}
2603 			if (optval < 0 || optval > 1) {
2604 				error = EINVAL;
2605 			} else if (optval == 0) {
2606 				tp->t_flagsext &= ~TF_NOBLACKHOLE_DETECTION;
2607 			} else {
2608 				tp->t_flagsext |= TF_NOBLACKHOLE_DETECTION;
2609 				if ((tp->t_flags & TF_BLACKHOLE) &&
2610 				    tp->t_pmtud_saved_maxopd > 0) {
2611 					tcp_pmtud_revert_segment_size(tp);
2612 				}
2613 			}
2614 			break;
2615 		case TCP_FASTOPEN:
2616 			if (!(tcp_fastopen & TCP_FASTOPEN_SERVER)) {
2617 				error = ENOTSUP;
2618 				break;
2619 			}
2620 
2621 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2622 			    sizeof(optval));
2623 			if (error) {
2624 				break;
2625 			}
2626 			if (optval < 0 || optval > 1) {
2627 				error = EINVAL;
2628 				break;
2629 			}
2630 			if (tp->t_state != TCPS_LISTEN) {
2631 				error =  EINVAL;
2632 				break;
2633 			}
2634 			if (optval) {
2635 				tp->t_flagsext |= TF_FASTOPEN;
2636 			} else {
2637 				tcp_disable_tfo(tp);
2638 			}
2639 			break;
2640 		case TCP_FASTOPEN_FORCE_HEURISTICS:
2641 
2642 			break;
2643 		case TCP_FASTOPEN_FORCE_ENABLE:
2644 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2645 			    sizeof(optval));
2646 
2647 			if (error) {
2648 				break;
2649 			}
2650 			if (optval < 0 || optval > 1) {
2651 				error = EINVAL;
2652 				break;
2653 			}
2654 
2655 			if (tp->t_state != TCPS_CLOSED) {
2656 				error =  EINVAL;
2657 				break;
2658 			}
2659 			if (optval) {
2660 				tp->t_flagsext |= TF_FASTOPEN_FORCE_ENABLE;
2661 			} else {
2662 				tp->t_flagsext &= ~TF_FASTOPEN_FORCE_ENABLE;
2663 			}
2664 
2665 			break;
2666 		case TCP_ENABLE_ECN:
2667 			error = sooptcopyin(sopt, &optval, sizeof optval,
2668 			    sizeof optval);
2669 			if (error) {
2670 				break;
2671 			}
2672 			if (optval) {
2673 				tp->ecn_flags |= TE_ECN_MODE_ENABLE;
2674 				tp->ecn_flags &= ~TE_ECN_MODE_DISABLE;
2675 			} else {
2676 				tp->ecn_flags &= ~TE_ECN_MODE_ENABLE;
2677 				tp->ecn_flags |= TE_ECN_MODE_DISABLE;
2678 			}
2679 			break;
2680 		case TCP_ECN_MODE:
2681 			error = sooptcopyin(sopt, &optval, sizeof optval,
2682 			    sizeof optval);
2683 			if (error) {
2684 				break;
2685 			}
2686 			if (optval == ECN_MODE_DEFAULT) {
2687 				tp->ecn_flags &= ~TE_ECN_MODE_ENABLE;
2688 				tp->ecn_flags &= ~TE_ECN_MODE_DISABLE;
2689 			} else if (optval == ECN_MODE_ENABLE) {
2690 				tp->ecn_flags |= TE_ECN_MODE_ENABLE;
2691 				tp->ecn_flags &= ~TE_ECN_MODE_DISABLE;
2692 			} else if (optval == ECN_MODE_DISABLE) {
2693 				tp->ecn_flags &= ~TE_ECN_MODE_ENABLE;
2694 				tp->ecn_flags |= TE_ECN_MODE_DISABLE;
2695 			} else {
2696 				error = EINVAL;
2697 			}
2698 			break;
2699 		case TCP_ENABLE_L4S:
2700 			error = sooptcopyin(sopt, &optval, sizeof optval,
2701 			    sizeof optval);
2702 			if (error) {
2703 				break;
2704 			}
2705 			if (optval < 0 || optval > 1) {
2706 				error = EINVAL;
2707 				break;
2708 			}
2709 			if (tp->t_state != TCPS_CLOSED) {
2710 				error =  EINVAL;
2711 				break;
2712 			}
2713 			if (optval == 1) {
2714 				tp->t_flagsext |= TF_L4S_ENABLED;
2715 				tp->t_flagsext &= ~TF_L4S_DISABLED;
2716 			} else {
2717 				tp->t_flagsext &= ~TF_L4S_ENABLED;
2718 				tp->t_flagsext |= TF_L4S_DISABLED;
2719 			}
2720 			break;
2721 		case TCP_NOTIFY_ACKNOWLEDGEMENT:
2722 			error = sooptcopyin(sopt, &optval,
2723 			    sizeof(optval), sizeof(optval));
2724 			if (error) {
2725 				break;
2726 			}
2727 			if (optval <= 0) {
2728 				error = EINVAL;
2729 				break;
2730 			}
2731 			if (tp->t_notify_ack_count >= TCP_MAX_NOTIFY_ACK) {
2732 				error = ETOOMANYREFS;
2733 				break;
2734 			}
2735 
2736 			/*
2737 			 * validate that the given marker id is not
2738 			 * a duplicate to avoid ambiguity
2739 			 */
2740 			if ((error = tcp_notify_ack_id_valid(tp, so,
2741 			    optval)) != 0) {
2742 				break;
2743 			}
2744 			error = tcp_add_notify_ack_marker(tp, optval);
2745 			break;
2746 		case SO_FLUSH:
2747 			if ((error = sooptcopyin(sopt, &optval, sizeof(optval),
2748 			    sizeof(optval))) != 0) {
2749 				break;
2750 			}
2751 
2752 			error = inp_flush(inp, optval);
2753 			break;
2754 
2755 		case SO_TRAFFIC_MGT_BACKGROUND:
2756 			if ((error = sooptcopyin(sopt, &optval, sizeof(optval),
2757 			    sizeof(optval))) != 0) {
2758 				break;
2759 			}
2760 
2761 			if (optval) {
2762 				socket_set_traffic_mgt_flags_locked(so,
2763 				    TRAFFIC_MGT_SO_BACKGROUND);
2764 			} else {
2765 				socket_clear_traffic_mgt_flags_locked(so,
2766 				    TRAFFIC_MGT_SO_BACKGROUND);
2767 			}
2768 			break;
2769 		case TCP_RXT_MINIMUM_TIMEOUT:
2770 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2771 			    sizeof(optval));
2772 			if (error) {
2773 				break;
2774 			}
2775 			if (optval < 0) {
2776 				error = EINVAL;
2777 				break;
2778 			}
2779 			if (optval == 0) {
2780 				tp->t_rxt_minimum_timeout = 0;
2781 			} else {
2782 				tp->t_rxt_minimum_timeout = min(optval,
2783 				    TCP_RXT_MINIMUM_TIMEOUT_LIMIT);
2784 				/* convert to milliseconds */
2785 				tp->t_rxt_minimum_timeout *= TCP_RETRANSHZ;
2786 			}
2787 			break;
2788 		default:
2789 			error = ENOPROTOOPT;
2790 			break;
2791 		}
2792 		break;
2793 
2794 	case SOPT_GET:
2795 		switch (sopt->sopt_name) {
2796 		case TCP_NODELAY:
2797 			optval = tp->t_flags & TF_NODELAY;
2798 			break;
2799 		case TCP_MAXSEG:
2800 			optval = tp->t_maxseg;
2801 			break;
2802 		case TCP_KEEPALIVE:
2803 			if (tp->t_keepidle > 0) {
2804 				optval = tp->t_keepidle / TCP_RETRANSHZ;
2805 			} else {
2806 				optval = tcp_keepidle  / TCP_RETRANSHZ;
2807 			}
2808 			break;
2809 		case TCP_KEEPINTVL:
2810 			if (tp->t_keepintvl > 0) {
2811 				optval = tp->t_keepintvl / TCP_RETRANSHZ;
2812 			} else {
2813 				optval = tcp_keepintvl / TCP_RETRANSHZ;
2814 			}
2815 			break;
2816 		case TCP_KEEPCNT:
2817 			if (tp->t_keepcnt > 0) {
2818 				optval = tp->t_keepcnt;
2819 			} else {
2820 				optval = tcp_keepcnt;
2821 			}
2822 			break;
2823 		case TCP_KEEPALIVE_OFFLOAD:
2824 			optval = !!(inp->inp_flags2 & INP2_KEEPALIVE_OFFLOAD);
2825 			break;
2826 		case TCP_NOOPT:
2827 			optval = tp->t_flags & TF_NOOPT;
2828 			break;
2829 		case TCP_NOPUSH:
2830 			optval = tp->t_flags & TF_NOPUSH;
2831 			break;
2832 		case TCP_ENABLE_ECN:
2833 			optval = (tp->ecn_flags & TE_ECN_MODE_ENABLE) ? 1 : 0;
2834 			break;
2835 		case TCP_ECN_MODE:
2836 			if (tp->ecn_flags & TE_ECN_MODE_ENABLE) {
2837 				optval = ECN_MODE_ENABLE;
2838 			} else if (tp->ecn_flags & TE_ECN_MODE_DISABLE) {
2839 				optval = ECN_MODE_DISABLE;
2840 			} else {
2841 				optval = ECN_MODE_DEFAULT;
2842 			}
2843 			break;
2844 		case TCP_ENABLE_L4S:
2845 			optval = (tp->t_flagsext & TF_L4S_ENABLED) ? 1 : 0;
2846 			break;
2847 		case TCP_CONNECTIONTIMEOUT:
2848 			optval = tp->t_keepinit / TCP_RETRANSHZ;
2849 			break;
2850 		case PERSIST_TIMEOUT:
2851 			optval = tp->t_persist_timeout / TCP_RETRANSHZ;
2852 			break;
2853 		case TCP_RXT_CONNDROPTIME:
2854 			optval = tp->t_rxt_conndroptime / TCP_RETRANSHZ;
2855 			break;
2856 		case TCP_RXT_FINDROP:
2857 			optval = tp->t_flagsext & TF_RXTFINDROP;
2858 			break;
2859 		case TCP_NOTIMEWAIT:
2860 			optval = (tp->t_flagsext & TF_NOTIMEWAIT) ? 1 : 0;
2861 			break;
2862 		case TCP_FASTOPEN:
2863 			if (tp->t_state != TCPS_LISTEN ||
2864 			    !(tcp_fastopen & TCP_FASTOPEN_SERVER)) {
2865 				error = ENOTSUP;
2866 				break;
2867 			}
2868 			optval = tfo_enabled(tp);
2869 			break;
2870 		case TCP_FASTOPEN_FORCE_HEURISTICS:
2871 			optval = 0;
2872 			break;
2873 		case TCP_FASTOPEN_FORCE_ENABLE:
2874 			optval = (tp->t_flagsext & TF_FASTOPEN_FORCE_ENABLE) ? 1 : 0;
2875 			break;
2876 		case TCP_MEASURE_SND_BW:
2877 			optval = tp->t_flagsext & TF_MEASURESNDBW;
2878 			break;
2879 		case TCP_INFO: {
2880 			struct tcp_info ti;
2881 
2882 			tcp_fill_info(tp, &ti);
2883 			error = sooptcopyout(sopt, &ti, sizeof(struct tcp_info));
2884 			goto done;
2885 			/* NOT REACHED */
2886 		}
2887 		case TCP_CONNECTION_INFO: {
2888 			struct tcp_connection_info tci;
2889 			tcp_connection_fill_info(tp, &tci);
2890 			error = sooptcopyout(sopt, &tci,
2891 			    sizeof(struct tcp_connection_info));
2892 			goto done;
2893 		}
2894 		case TCP_MEASURE_BW_BURST: {
2895 			struct tcp_measure_bw_burst out = {};
2896 			if ((tp->t_flagsext & TF_MEASURESNDBW) == 0 ||
2897 			    tp->t_bwmeas == NULL) {
2898 				error = EINVAL;
2899 				break;
2900 			}
2901 			out.min_burst_size = tp->t_bwmeas->bw_minsizepkts;
2902 			out.max_burst_size = tp->t_bwmeas->bw_maxsizepkts;
2903 			error = sooptcopyout(sopt, &out, sizeof(out));
2904 			goto done;
2905 		}
2906 		case TCP_NOTSENT_LOWAT:
2907 			if ((so->so_flags & SOF_NOTSENT_LOWAT) != 0) {
2908 				optval = tp->t_notsent_lowat;
2909 			} else {
2910 				optval = 0;
2911 			}
2912 			break;
2913 		case TCP_SENDMOREACKS:
2914 			if (tp->t_flagsext & TF_NOSTRETCHACK) {
2915 				optval = 1;
2916 			} else {
2917 				optval = 0;
2918 			}
2919 			break;
2920 		case TCP_DISABLE_BLACKHOLE_DETECTION:
2921 			if (tp->t_flagsext & TF_NOBLACKHOLE_DETECTION) {
2922 				optval = 1;
2923 			} else {
2924 				optval = 0;
2925 			}
2926 			break;
2927 		case TCP_PEER_PID: {
2928 			pid_t   pid;
2929 			error = tcp_lookup_peer_pid_locked(so, &pid);
2930 			if (error == 0) {
2931 				error = sooptcopyout(sopt, &pid, sizeof(pid));
2932 			}
2933 			goto done;
2934 		}
2935 		case TCP_ADAPTIVE_READ_TIMEOUT:
2936 			optval = tp->t_adaptive_rtimo;
2937 			break;
2938 		case TCP_ADAPTIVE_WRITE_TIMEOUT:
2939 			optval = tp->t_adaptive_wtimo;
2940 			break;
2941 		case SO_TRAFFIC_MGT_BACKGROUND:
2942 			optval = (so->so_flags1 &
2943 			    SOF1_TRAFFIC_MGT_SO_BACKGROUND) ? 1 : 0;
2944 			break;
2945 		case TCP_NOTIFY_ACKNOWLEDGEMENT: {
2946 			struct tcp_notify_ack_complete retid;
2947 
2948 			if (sopt->sopt_valsize != sizeof(retid)) {
2949 				error = EINVAL;
2950 				break;
2951 			}
2952 			bzero(&retid, sizeof(retid));
2953 			tcp_get_notify_ack_count(tp, &retid);
2954 			if (retid.notify_complete_count > 0) {
2955 				tcp_get_notify_ack_ids(tp, &retid);
2956 			}
2957 
2958 			error = sooptcopyout(sopt, &retid, sizeof(retid));
2959 			goto done;
2960 		}
2961 		case TCP_RXT_MINIMUM_TIMEOUT:
2962 			optval = tp->t_rxt_minimum_timeout / TCP_RETRANSHZ;
2963 			break;
2964 		default:
2965 			error = ENOPROTOOPT;
2966 			break;
2967 		}
2968 		if (error == 0) {
2969 			error = sooptcopyout(sopt, &optval, sizeof optval);
2970 		}
2971 		break;
2972 	}
2973 done:
2974 	return error;
2975 }
2976 
2977 /*
2978  * tcp_sendspace and tcp_recvspace are the default send and receive window
2979  * sizes, respectively.  These are obsolescent (this information should
2980  * be set by the route).
2981  */
2982 uint32_t       tcp_sendspace = 1448 * 256;
2983 uint32_t       tcp_recvspace = 1448 * 384;
2984 
2985 /* During attach, the size of socket buffer allocated is limited to
2986  * sb_max in sbreserve. Disallow setting the tcp send and recv space
2987  * to be more than sb_max because that will cause tcp_attach to fail
2988  * (see radar 5713060)
2989  */
2990 static int
sysctl_tcp_sospace(struct sysctl_oid * oidp,__unused void * arg1,int arg2,struct sysctl_req * req)2991 sysctl_tcp_sospace(struct sysctl_oid *oidp, __unused void *arg1,
2992     int arg2, struct sysctl_req *req)
2993 {
2994 #pragma unused(arg2)
2995 	u_int32_t new_value = 0, *space_p = NULL;
2996 	int changed = 0, error = 0;
2997 	u_quad_t sb_effective_max = (sb_max / (SB_MSIZE_ADJ + MCLBYTES)) * MCLBYTES;
2998 
2999 	switch (oidp->oid_number) {
3000 	case TCPCTL_SENDSPACE:
3001 		space_p = &tcp_sendspace;
3002 		break;
3003 	case TCPCTL_RECVSPACE:
3004 		space_p = &tcp_recvspace;
3005 		break;
3006 	default:
3007 		return EINVAL;
3008 	}
3009 	error = sysctl_io_number(req, *space_p, sizeof(u_int32_t),
3010 	    &new_value, &changed);
3011 	if (changed) {
3012 		if (new_value > 0 && new_value <= sb_effective_max) {
3013 			*space_p = new_value;
3014 			SYSCTL_SKMEM_UPDATE_AT_OFFSET(arg2, new_value);
3015 		} else {
3016 			error = ERANGE;
3017 		}
3018 	}
3019 	return error;
3020 }
3021 
3022 #if SYSCTL_SKMEM
3023 SYSCTL_PROC(_net_inet_tcp, TCPCTL_SENDSPACE, sendspace,
3024     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED | CTLFLAG_KERN, &tcp_sendspace,
3025     offsetof(skmem_sysctl, tcp.sendspace), sysctl_tcp_sospace,
3026     "IU", "Maximum outgoing TCP datagram size");
3027 SYSCTL_PROC(_net_inet_tcp, TCPCTL_RECVSPACE, recvspace,
3028     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED | CTLFLAG_KERN, &tcp_recvspace,
3029     offsetof(skmem_sysctl, tcp.recvspace), sysctl_tcp_sospace,
3030     "IU", "Maximum incoming TCP datagram size");
3031 #else /* SYSCTL_SKMEM */
3032 SYSCTL_PROC(_net_inet_tcp, TCPCTL_SENDSPACE, sendspace,
3033     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED | CTLFLAG_KERN,
3034     &tcp_sendspace, 0, &sysctl_tcp_sospace, "IU", "Maximum outgoing TCP datagram size");
3035 SYSCTL_PROC(_net_inet_tcp, TCPCTL_RECVSPACE, recvspace,
3036     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED | CTLFLAG_KERN,
3037     &tcp_recvspace, 0, &sysctl_tcp_sospace, "IU", "Maximum incoming TCP datagram size");
3038 #endif /* SYSCTL_SKMEM */
3039 
3040 /*
3041  * Attach TCP protocol to socket, allocating
3042  * internet protocol control block, tcp control block,
3043  * bufer space, and entering LISTEN state if to accept connections.
3044  *
3045  * Returns:	0			Success
3046  *	in_pcballoc:ENOBUFS
3047  *	in_pcballoc:ENOMEM
3048  *	in_pcballoc:???			[IPSEC specific]
3049  *	soreserve:ENOBUFS
3050  */
3051 static int
tcp_attach(struct socket * so,struct proc * p)3052 tcp_attach(struct socket *so, struct proc *p)
3053 {
3054 	struct tcpcb *tp;
3055 	struct inpcb *inp;
3056 	int error;
3057 	int isipv6 = SOCK_CHECK_DOM(so, PF_INET6) != 0;
3058 
3059 	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
3060 		error = soreserve(so, tcp_sendspace, tcp_recvspace);
3061 		if (error) {
3062 			return error;
3063 		}
3064 	}
3065 
3066 	error = in_pcballoc(so, &tcbinfo, p);
3067 	if (error) {
3068 		return error;
3069 	}
3070 
3071 	inp = sotoinpcb(so);
3072 
3073 	if (so->so_snd.sb_preconn_hiwat == 0) {
3074 		soreserve_preconnect(so, 2048);
3075 	}
3076 
3077 	if ((so->so_rcv.sb_flags & SB_USRSIZE) == 0) {
3078 		so->so_rcv.sb_flags |= SB_AUTOSIZE;
3079 	}
3080 	if ((so->so_snd.sb_flags & SB_USRSIZE) == 0) {
3081 		so->so_snd.sb_flags |= SB_AUTOSIZE;
3082 	}
3083 
3084 	if (isipv6) {
3085 		inp->inp_vflag |= INP_IPV6;
3086 		inp->in6p_hops = -1;    /* use kernel default */
3087 	} else {
3088 		inp->inp_vflag |= INP_IPV4;
3089 	}
3090 	tp = tcp_newtcpcb(inp);
3091 	if (tp == NULL) {
3092 		int nofd = so->so_state & SS_NOFDREF;   /* XXX */
3093 
3094 		so->so_state &= ~SS_NOFDREF;    /* don't free the socket yet */
3095 		if (isipv6) {
3096 			in6_pcbdetach(inp);
3097 		} else {
3098 			in_pcbdetach(inp);
3099 		}
3100 		so->so_state |= nofd;
3101 		return ENOBUFS;
3102 	}
3103 	if (nstat_collect) {
3104 		nstat_tcp_new_pcb(inp);
3105 	}
3106 	TCP_LOG_STATE(tp, TCPS_CLOSED);
3107 	tp->t_state = TCPS_CLOSED;
3108 	return 0;
3109 }
3110 
3111 /*
3112  * Initiate (or continue) disconnect.
3113  * If embryonic state, just send reset (once).
3114  * If in ``let data drain'' option and linger null, just drop.
3115  * Otherwise (hard), mark socket disconnecting and drop
3116  * current input data; switch states based on user close, and
3117  * send segment to peer (with FIN).
3118  */
3119 static struct tcpcb *
tcp_disconnect(struct tcpcb * tp)3120 tcp_disconnect(struct tcpcb *tp)
3121 {
3122 	struct socket *so = tp->t_inpcb->inp_socket;
3123 
3124 	if (so->so_rcv.sb_cc != 0 || tp->t_reassqlen != 0 ||
3125 	    so->so_flags1 & SOF1_DEFUNCTINPROG) {
3126 		return tcp_drop(tp, 0);
3127 	}
3128 
3129 	if (tp->t_state < TCPS_ESTABLISHED) {
3130 		tp = tcp_close(tp);
3131 	} else if ((so->so_options & SO_LINGER) && so->so_linger == 0) {
3132 		tp = tcp_drop(tp, 0);
3133 	} else {
3134 		soisdisconnecting(so);
3135 		sbflush(&so->so_rcv);
3136 		tp = tcp_usrclosed(tp);
3137 #if MPTCP
3138 		/* A reset has been sent but socket exists, do not send FIN */
3139 		if ((so->so_flags & SOF_MP_SUBFLOW) &&
3140 		    (tp) && (tp->t_mpflags & TMPF_RESET)) {
3141 			return tp;
3142 		}
3143 #endif
3144 		if (tp) {
3145 			(void) tcp_output(tp);
3146 		}
3147 	}
3148 	return tp;
3149 }
3150 
3151 /*
3152  * User issued close, and wish to trail through shutdown states:
3153  * if never received SYN, just forget it.  If got a SYN from peer,
3154  * but haven't sent FIN, then go to FIN_WAIT_1 state to send peer a FIN.
3155  * If already got a FIN from peer, then almost done; go to LAST_ACK
3156  * state.  In all other cases, have already sent FIN to peer (e.g.
3157  * after PRU_SHUTDOWN), and just have to play tedious game waiting
3158  * for peer to send FIN or not respond to keep-alives, etc.
3159  * We can let the user exit from the close as soon as the FIN is acked.
3160  */
3161 static struct tcpcb *
tcp_usrclosed(struct tcpcb * tp)3162 tcp_usrclosed(struct tcpcb *tp)
3163 {
3164 	switch (tp->t_state) {
3165 	case TCPS_CLOSED:
3166 	case TCPS_LISTEN:
3167 	case TCPS_SYN_SENT:
3168 		tp = tcp_close(tp);
3169 		break;
3170 
3171 	case TCPS_SYN_RECEIVED:
3172 		tp->t_flags |= TF_NEEDFIN;
3173 		break;
3174 
3175 	case TCPS_ESTABLISHED:
3176 		DTRACE_TCP4(state__change, void, NULL,
3177 		    struct inpcb *, tp->t_inpcb,
3178 		    struct tcpcb *, tp,
3179 		    int32_t, TCPS_FIN_WAIT_1);
3180 		TCP_LOG_STATE(tp, TCPS_FIN_WAIT_1);
3181 		tp->t_state = TCPS_FIN_WAIT_1;
3182 		TCP_LOG_CONNECTION_SUMMARY(tp);
3183 		break;
3184 
3185 	case TCPS_CLOSE_WAIT:
3186 		DTRACE_TCP4(state__change, void, NULL,
3187 		    struct inpcb *, tp->t_inpcb,
3188 		    struct tcpcb *, tp,
3189 		    int32_t, TCPS_LAST_ACK);
3190 		TCP_LOG_STATE(tp, TCPS_LAST_ACK);
3191 		tp->t_state = TCPS_LAST_ACK;
3192 		TCP_LOG_CONNECTION_SUMMARY(tp);
3193 		break;
3194 	}
3195 	if (tp && tp->t_state >= TCPS_FIN_WAIT_2) {
3196 		soisdisconnected(tp->t_inpcb->inp_socket);
3197 		/* To prevent the connection hanging in FIN_WAIT_2 forever. */
3198 		if (tp->t_state == TCPS_FIN_WAIT_2) {
3199 			tcp_set_finwait_timeout(tp);
3200 		}
3201 	}
3202 	return tp;
3203 }
3204 
3205 void
tcp_in_cksum_stats(u_int32_t len)3206 tcp_in_cksum_stats(u_int32_t len)
3207 {
3208 	tcpstat.tcps_rcv_swcsum++;
3209 	tcpstat.tcps_rcv_swcsum_bytes += len;
3210 }
3211 
3212 void
tcp_out_cksum_stats(u_int32_t len)3213 tcp_out_cksum_stats(u_int32_t len)
3214 {
3215 	tcpstat.tcps_snd_swcsum++;
3216 	tcpstat.tcps_snd_swcsum_bytes += len;
3217 }
3218 
3219 void
tcp_in6_cksum_stats(u_int32_t len)3220 tcp_in6_cksum_stats(u_int32_t len)
3221 {
3222 	tcpstat.tcps_rcv6_swcsum++;
3223 	tcpstat.tcps_rcv6_swcsum_bytes += len;
3224 }
3225 
3226 void
tcp_out6_cksum_stats(u_int32_t len)3227 tcp_out6_cksum_stats(u_int32_t len)
3228 {
3229 	tcpstat.tcps_snd6_swcsum++;
3230 	tcpstat.tcps_snd6_swcsum_bytes += len;
3231 }
3232 
3233 int
tcp_get_mpkl_send_info(struct mbuf * control,struct so_mpkl_send_info * mpkl_send_info)3234 tcp_get_mpkl_send_info(struct mbuf *control,
3235     struct so_mpkl_send_info *mpkl_send_info)
3236 {
3237 	struct cmsghdr *cm;
3238 
3239 	if (control == NULL || mpkl_send_info == NULL) {
3240 		return EINVAL;
3241 	}
3242 
3243 	for (cm = M_FIRST_CMSGHDR(control); cm;
3244 	    cm = M_NXT_CMSGHDR(control, cm)) {
3245 		if (cm->cmsg_len < sizeof(struct cmsghdr) ||
3246 		    cm->cmsg_len > control->m_len) {
3247 			return EINVAL;
3248 		}
3249 		if (cm->cmsg_level != SOL_SOCKET ||
3250 		    cm->cmsg_type != SCM_MPKL_SEND_INFO) {
3251 			continue;
3252 		}
3253 		if (cm->cmsg_len != CMSG_LEN(sizeof(struct so_mpkl_send_info))) {
3254 			return EINVAL;
3255 		}
3256 		memcpy(mpkl_send_info, CMSG_DATA(cm),
3257 		    sizeof(struct so_mpkl_send_info));
3258 		return 0;
3259 	}
3260 	return ENOMSG;
3261 }
3262 
3263 /*
3264  * tcp socket options.
3265  *
3266  * The switch statement below does nothing at runtime, as it serves as a
3267  * compile time check to ensure that all of the tcp socket options are
3268  * unique.  This works as long as this routine gets updated each time a
3269  * new tcp socket option gets added.
3270  *
3271  * Any failures at compile time indicates duplicated tcp socket option
3272  * values.
3273  */
3274 static __attribute__((unused)) void
tcpsockopt_cassert(void)3275 tcpsockopt_cassert(void)
3276 {
3277 	/*
3278 	 * This is equivalent to _CASSERT() and the compiler wouldn't
3279 	 * generate any instructions, thus for compile time only.
3280 	 */
3281 	switch ((int)0) {
3282 	case 0:
3283 
3284 	/* bsd/netinet/tcp.h */
3285 	case TCP_NODELAY:
3286 	case TCP_MAXSEG:
3287 	case TCP_NOPUSH:
3288 	case TCP_NOOPT:
3289 	case TCP_KEEPALIVE:
3290 	case TCP_CONNECTIONTIMEOUT:
3291 	case PERSIST_TIMEOUT:
3292 	case TCP_RXT_CONNDROPTIME:
3293 	case TCP_RXT_FINDROP:
3294 	case TCP_KEEPINTVL:
3295 	case TCP_KEEPCNT:
3296 	case TCP_SENDMOREACKS:
3297 	case TCP_ENABLE_ECN:
3298 	case TCP_FASTOPEN:
3299 	case TCP_CONNECTION_INFO:
3300 	case TCP_NOTSENT_LOWAT:
3301 
3302 	/* bsd/netinet/tcp_private.h */
3303 	case TCP_INFO:
3304 	case TCP_MEASURE_SND_BW:
3305 	case TCP_MEASURE_BW_BURST:
3306 	case TCP_PEER_PID:
3307 	case TCP_ADAPTIVE_READ_TIMEOUT:
3308 	case TCP_OPTION_UNUSED_0:
3309 	case TCP_ADAPTIVE_WRITE_TIMEOUT:
3310 	case TCP_NOTIMEWAIT:
3311 	case TCP_DISABLE_BLACKHOLE_DETECTION:
3312 	case TCP_ECN_MODE:
3313 	case TCP_KEEPALIVE_OFFLOAD:
3314 		;
3315 	}
3316 }
3317