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