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