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