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