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