xref: /xnu-8019.80.24/bsd/netinet/tcp_usrreq.c (revision a325d9c4a84054e40bbe985afedcb50ab80993ea)
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; /* 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->inp_flowhash;
1667 
1668 	if (tp->t_state > TCPS_LISTEN) {
1669 		if (TSTMP_SUPPORTED(tp)) {
1670 			ti->tcpi_options |= TCPI_OPT_TIMESTAMPS;
1671 		}
1672 		if (SACK_ENABLED(tp)) {
1673 			ti->tcpi_options |= TCPI_OPT_SACK;
1674 		}
1675 		if (TCP_WINDOW_SCALE_ENABLED(tp)) {
1676 			ti->tcpi_options |= TCPI_OPT_WSCALE;
1677 			ti->tcpi_snd_wscale = tp->snd_scale;
1678 			ti->tcpi_rcv_wscale = tp->rcv_scale;
1679 		}
1680 		if (TCP_ECN_ENABLED(tp)) {
1681 			ti->tcpi_options |= TCPI_OPT_ECN;
1682 		}
1683 
1684 		/* Are we in retranmission episode */
1685 		if (IN_FASTRECOVERY(tp) || tp->t_rxtshift > 0) {
1686 			ti->tcpi_flags |= TCPI_FLAG_LOSSRECOVERY;
1687 		}
1688 
1689 		if (tp->t_flags & TF_STREAMING_ON) {
1690 			ti->tcpi_flags |= TCPI_FLAG_STREAMING_ON;
1691 		}
1692 
1693 		ti->tcpi_rto = tp->t_timer[TCPT_REXMT] ? tp->t_rxtcur : 0;
1694 		ti->tcpi_snd_mss = tp->t_maxseg;
1695 		ti->tcpi_rcv_mss = tp->t_maxseg;
1696 
1697 		ti->tcpi_rttcur = tp->t_rttcur;
1698 		ti->tcpi_srtt = tp->t_srtt >> TCP_RTT_SHIFT;
1699 		ti->tcpi_rcv_srtt = tp->rcv_srtt >> TCP_RTT_SHIFT;
1700 		ti->tcpi_rttvar = tp->t_rttvar >> TCP_RTTVAR_SHIFT;
1701 		ti->tcpi_rttbest = tp->t_rttbest >> TCP_RTT_SHIFT;
1702 
1703 		ti->tcpi_snd_ssthresh = tp->snd_ssthresh;
1704 		ti->tcpi_snd_cwnd = tp->snd_cwnd;
1705 		ti->tcpi_snd_sbbytes = inp->inp_socket->so_snd.sb_cc;
1706 
1707 		ti->tcpi_rcv_space = tp->rcv_adv > tp->rcv_nxt ?
1708 		    tp->rcv_adv - tp->rcv_nxt : 0;
1709 
1710 		ti->tcpi_snd_wnd = tp->snd_wnd;
1711 		ti->tcpi_snd_nxt = tp->snd_nxt;
1712 		ti->tcpi_rcv_nxt = tp->rcv_nxt;
1713 
1714 		/* convert bytes/msec to bits/sec */
1715 		if ((tp->t_flagsext & TF_MEASURESNDBW) != 0 &&
1716 		    tp->t_bwmeas != NULL) {
1717 			ti->tcpi_snd_bw = (tp->t_bwmeas->bw_sndbw * 8000);
1718 		}
1719 
1720 		ti->tcpi_last_outif = (tp->t_inpcb->inp_last_outifp == NULL) ? 0 :
1721 		    tp->t_inpcb->inp_last_outifp->if_index;
1722 
1723 		//atomic_get_64(ti->tcpi_txbytes, &inp->inp_stat->txbytes);
1724 		ti->tcpi_txpackets = inp->inp_stat->txpackets;
1725 		ti->tcpi_txbytes = inp->inp_stat->txbytes;
1726 		ti->tcpi_txretransmitbytes = tp->t_stat.txretransmitbytes;
1727 		ti->tcpi_txretransmitpackets = tp->t_stat.rxmitpkts;
1728 		ti->tcpi_txunacked = tp->snd_max - tp->snd_una;
1729 
1730 		//atomic_get_64(ti->tcpi_rxbytes, &inp->inp_stat->rxbytes);
1731 		ti->tcpi_rxpackets = inp->inp_stat->rxpackets;
1732 		ti->tcpi_rxbytes = inp->inp_stat->rxbytes;
1733 		ti->tcpi_rxduplicatebytes = tp->t_stat.rxduplicatebytes;
1734 		ti->tcpi_rxoutoforderbytes = tp->t_stat.rxoutoforderbytes;
1735 
1736 		if (tp->t_state > TCPS_LISTEN) {
1737 			ti->tcpi_synrexmits = (uint8_t)tp->t_stat.rxmitsyns;
1738 		}
1739 		ti->tcpi_cell_rxpackets = inp->inp_cstat->rxpackets;
1740 		ti->tcpi_cell_rxbytes = inp->inp_cstat->rxbytes;
1741 		ti->tcpi_cell_txpackets = inp->inp_cstat->txpackets;
1742 		ti->tcpi_cell_txbytes = inp->inp_cstat->txbytes;
1743 
1744 		ti->tcpi_wifi_rxpackets = inp->inp_wstat->rxpackets;
1745 		ti->tcpi_wifi_rxbytes = inp->inp_wstat->rxbytes;
1746 		ti->tcpi_wifi_txpackets = inp->inp_wstat->txpackets;
1747 		ti->tcpi_wifi_txbytes = inp->inp_wstat->txbytes;
1748 
1749 		ti->tcpi_wired_rxpackets = inp->inp_Wstat->rxpackets;
1750 		ti->tcpi_wired_rxbytes = inp->inp_Wstat->rxbytes;
1751 		ti->tcpi_wired_txpackets = inp->inp_Wstat->txpackets;
1752 		ti->tcpi_wired_txbytes = inp->inp_Wstat->txbytes;
1753 		tcp_get_connectivity_status(tp, &ti->tcpi_connstatus);
1754 
1755 		ti->tcpi_tfo_syn_data_rcv = !!(tp->t_tfo_stats & TFO_S_SYNDATA_RCV);
1756 		ti->tcpi_tfo_cookie_req_rcv = !!(tp->t_tfo_stats & TFO_S_COOKIEREQ_RECV);
1757 		ti->tcpi_tfo_cookie_sent = !!(tp->t_tfo_stats & TFO_S_COOKIE_SENT);
1758 		ti->tcpi_tfo_cookie_invalid = !!(tp->t_tfo_stats & TFO_S_COOKIE_INVALID);
1759 
1760 		ti->tcpi_tfo_cookie_req = !!(tp->t_tfo_stats & TFO_S_COOKIE_REQ);
1761 		ti->tcpi_tfo_cookie_rcv = !!(tp->t_tfo_stats & TFO_S_COOKIE_RCV);
1762 		ti->tcpi_tfo_syn_data_sent = !!(tp->t_tfo_stats & TFO_S_SYN_DATA_SENT);
1763 		ti->tcpi_tfo_syn_data_acked = !!(tp->t_tfo_stats & TFO_S_SYN_DATA_ACKED);
1764 		ti->tcpi_tfo_syn_loss = !!(tp->t_tfo_stats & TFO_S_SYN_LOSS);
1765 		ti->tcpi_tfo_cookie_wrong = !!(tp->t_tfo_stats & TFO_S_COOKIE_WRONG);
1766 		ti->tcpi_tfo_no_cookie_rcv = !!(tp->t_tfo_stats & TFO_S_NO_COOKIE_RCV);
1767 		ti->tcpi_tfo_heuristics_disable = !!(tp->t_tfo_stats & TFO_S_HEURISTICS_DISABLE);
1768 		ti->tcpi_tfo_send_blackhole = !!(tp->t_tfo_stats & TFO_S_SEND_BLACKHOLE);
1769 		ti->tcpi_tfo_recv_blackhole = !!(tp->t_tfo_stats & TFO_S_RECV_BLACKHOLE);
1770 		ti->tcpi_tfo_onebyte_proxy = !!(tp->t_tfo_stats & TFO_S_ONE_BYTE_PROXY);
1771 
1772 		ti->tcpi_ecn_client_setup = !!(tp->ecn_flags & TE_SETUPSENT);
1773 		ti->tcpi_ecn_server_setup = !!(tp->ecn_flags & TE_SETUPRECEIVED);
1774 		ti->tcpi_ecn_success = (tp->ecn_flags & TE_ECN_ON) == TE_ECN_ON ? 1 : 0;
1775 		ti->tcpi_ecn_lost_syn = !!(tp->ecn_flags & TE_LOST_SYN);
1776 		ti->tcpi_ecn_lost_synack = !!(tp->ecn_flags & TE_LOST_SYNACK);
1777 
1778 		ti->tcpi_local_peer = !!(tp->t_flags & TF_LOCAL);
1779 
1780 		if (tp->t_inpcb->inp_last_outifp != NULL) {
1781 			if (IFNET_IS_CELLULAR(tp->t_inpcb->inp_last_outifp)) {
1782 				ti->tcpi_if_cell = 1;
1783 			}
1784 			if (IFNET_IS_WIFI(tp->t_inpcb->inp_last_outifp)) {
1785 				ti->tcpi_if_wifi = 1;
1786 			}
1787 			if (IFNET_IS_WIRED(tp->t_inpcb->inp_last_outifp)) {
1788 				ti->tcpi_if_wired = 1;
1789 			}
1790 			if (IFNET_IS_WIFI_INFRA(tp->t_inpcb->inp_last_outifp)) {
1791 				ti->tcpi_if_wifi_infra = 1;
1792 			}
1793 			if (tp->t_inpcb->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 ||
1801 		    IS_TCP_RECV_BG(tp->t_inpcb->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 
1817 __private_extern__ errno_t
tcp_fill_info_for_info_tuple(struct info_tuple * itpl,struct tcp_info * ti)1818 tcp_fill_info_for_info_tuple(struct info_tuple *itpl, struct tcp_info *ti)
1819 {
1820 	struct inpcbinfo *pcbinfo = NULL;
1821 	struct inpcb *inp = NULL;
1822 	struct socket *so;
1823 	struct tcpcb *tp;
1824 
1825 	if (itpl->itpl_proto == IPPROTO_TCP) {
1826 		pcbinfo = &tcbinfo;
1827 	} else {
1828 		return EINVAL;
1829 	}
1830 
1831 	if (itpl->itpl_local_sa.sa_family == AF_INET &&
1832 	    itpl->itpl_remote_sa.sa_family == AF_INET) {
1833 		inp = in_pcblookup_hash(pcbinfo,
1834 		    itpl->itpl_remote_sin.sin_addr,
1835 		    itpl->itpl_remote_sin.sin_port,
1836 		    itpl->itpl_local_sin.sin_addr,
1837 		    itpl->itpl_local_sin.sin_port,
1838 		    0, NULL);
1839 	} else if (itpl->itpl_local_sa.sa_family == AF_INET6 &&
1840 	    itpl->itpl_remote_sa.sa_family == AF_INET6) {
1841 		struct in6_addr ina6_local;
1842 		struct in6_addr ina6_remote;
1843 
1844 		ina6_local = itpl->itpl_local_sin6.sin6_addr;
1845 		if (in6_embedded_scope && IN6_IS_SCOPE_LINKLOCAL(&ina6_local) &&
1846 		    itpl->itpl_local_sin6.sin6_scope_id) {
1847 			ina6_local.s6_addr16[1] = htons((uint16_t)itpl->itpl_local_sin6.sin6_scope_id);
1848 		}
1849 
1850 		ina6_remote = itpl->itpl_remote_sin6.sin6_addr;
1851 		if (in6_embedded_scope && IN6_IS_SCOPE_LINKLOCAL(&ina6_remote) &&
1852 		    itpl->itpl_remote_sin6.sin6_scope_id) {
1853 			ina6_remote.s6_addr16[1] = htons((uint16_t)itpl->itpl_remote_sin6.sin6_scope_id);
1854 		}
1855 
1856 		inp = in6_pcblookup_hash(pcbinfo,
1857 		    &ina6_remote,
1858 		    itpl->itpl_remote_sin6.sin6_port,
1859 		    itpl->itpl_remote_sin6.sin6_scope_id,
1860 		    &ina6_local,
1861 		    itpl->itpl_local_sin6.sin6_port,
1862 		    itpl->itpl_local_sin6.sin6_scope_id,
1863 		    0, NULL);
1864 	} else {
1865 		return EINVAL;
1866 	}
1867 
1868 	if (inp != NULL) {
1869 		if ((so = inp->inp_socket) == NULL) {
1870 			return ENOENT;
1871 		}
1872 		socket_lock(so, 0);
1873 		if (in_pcb_checkstate(inp, WNT_RELEASE, 1) == WNT_STOPUSING) {
1874 			socket_unlock(so, 0);
1875 			return ENOENT;
1876 		}
1877 		tp = intotcpcb(inp);
1878 
1879 		tcp_fill_info(tp, ti);
1880 		socket_unlock(so, 0);
1881 
1882 		return 0;
1883 	}
1884 #if SKYWALK
1885 	else {
1886 		/* if no pcb found, check for flowswitch for uTCP flow */
1887 		int error;
1888 		struct nexus_mib_filter nmf = {
1889 			.nmf_type = NXMIB_FLOW,
1890 			.nmf_bitmap = NXMIB_FILTER_INFO_TUPLE,
1891 			.nmf_info_tuple = *itpl,
1892 		};
1893 		struct sk_stats_flow sf;
1894 		size_t len = sizeof(sf);
1895 		error = kernel_sysctlbyname(SK_STATS_FLOW, &sf, &len, &nmf, sizeof(nmf));
1896 		if (error != 0) {
1897 			printf("kernel_sysctlbyname err %d\n", error);
1898 			return error;
1899 		}
1900 		if (len != sizeof(sf)) {
1901 			printf("kernel_sysctlbyname invalid len %zu\n", len);
1902 			return ENOENT;
1903 		}
1904 
1905 		/*
1906 		 * This is what flow tracker can offer right now, which is good
1907 		 * for mDNS TCP keep alive offload.
1908 		 */
1909 		ti->tcpi_snd_nxt = sf.sf_lseq;
1910 		ti->tcpi_rcv_nxt = sf.sf_rseq;
1911 		ti->tcpi_rcv_space = (uint32_t)(sf.sf_lmax_win << sf.sf_lwscale);
1912 		ti->tcpi_rcv_wscale = sf.sf_lwscale;
1913 		ti->tcpi_last_outif = (int32_t)sf.sf_if_index;
1914 
1915 		return 0;
1916 	}
1917 #endif /* SKYWALK */
1918 
1919 	return ENOENT;
1920 }
1921 
1922 static void
tcp_connection_fill_info(struct tcpcb * tp,struct tcp_connection_info * tci)1923 tcp_connection_fill_info(struct tcpcb *tp, struct tcp_connection_info *tci)
1924 {
1925 	struct inpcb *inp = tp->t_inpcb;
1926 
1927 	bzero(tci, sizeof(*tci));
1928 	tci->tcpi_state = (uint8_t)tp->t_state;
1929 	if (tp->t_state > TCPS_LISTEN) {
1930 		if (TSTMP_SUPPORTED(tp)) {
1931 			tci->tcpi_options |= TCPCI_OPT_TIMESTAMPS;
1932 		}
1933 		if (SACK_ENABLED(tp)) {
1934 			tci->tcpi_options |= TCPCI_OPT_SACK;
1935 		}
1936 		if (TCP_WINDOW_SCALE_ENABLED(tp)) {
1937 			tci->tcpi_options |= TCPCI_OPT_WSCALE;
1938 			tci->tcpi_snd_wscale = tp->snd_scale;
1939 			tci->tcpi_rcv_wscale = tp->rcv_scale;
1940 		}
1941 		if (TCP_ECN_ENABLED(tp)) {
1942 			tci->tcpi_options |= TCPCI_OPT_ECN;
1943 		}
1944 		if (IN_FASTRECOVERY(tp) || tp->t_rxtshift > 0) {
1945 			tci->tcpi_flags |= TCPCI_FLAG_LOSSRECOVERY;
1946 		}
1947 		if (tp->t_flagsext & TF_PKTS_REORDERED) {
1948 			tci->tcpi_flags |= TCPCI_FLAG_REORDERING_DETECTED;
1949 		}
1950 		tci->tcpi_rto = (tp->t_timer[TCPT_REXMT] > 0) ?
1951 		    tp->t_rxtcur : 0;
1952 		tci->tcpi_maxseg = tp->t_maxseg;
1953 		tci->tcpi_snd_ssthresh = tp->snd_ssthresh;
1954 		tci->tcpi_snd_cwnd = tp->snd_cwnd;
1955 		tci->tcpi_snd_wnd = tp->snd_wnd;
1956 		tci->tcpi_snd_sbbytes = inp->inp_socket->so_snd.sb_cc;
1957 		tci->tcpi_rcv_wnd = tp->rcv_adv > tp->rcv_nxt ?
1958 		    tp->rcv_adv - tp->rcv_nxt : 0;
1959 		tci->tcpi_rttcur = tp->t_rttcur;
1960 		tci->tcpi_srtt = (tp->t_srtt >> TCP_RTT_SHIFT);
1961 		tci->tcpi_rttvar = (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
1962 		tci->tcpi_txpackets = inp->inp_stat->txpackets;
1963 		tci->tcpi_txbytes = inp->inp_stat->txbytes;
1964 		tci->tcpi_txretransmitbytes = tp->t_stat.txretransmitbytes;
1965 		tci->tcpi_txretransmitpackets = tp->t_stat.rxmitpkts;
1966 		tci->tcpi_rxpackets = inp->inp_stat->rxpackets;
1967 		tci->tcpi_rxbytes = inp->inp_stat->rxbytes;
1968 		tci->tcpi_rxoutoforderbytes = tp->t_stat.rxoutoforderbytes;
1969 
1970 		tci->tcpi_tfo_syn_data_rcv = !!(tp->t_tfo_stats & TFO_S_SYNDATA_RCV);
1971 		tci->tcpi_tfo_cookie_req_rcv = !!(tp->t_tfo_stats & TFO_S_COOKIEREQ_RECV);
1972 		tci->tcpi_tfo_cookie_sent = !!(tp->t_tfo_stats & TFO_S_COOKIE_SENT);
1973 		tci->tcpi_tfo_cookie_invalid = !!(tp->t_tfo_stats & TFO_S_COOKIE_INVALID);
1974 		tci->tcpi_tfo_cookie_req = !!(tp->t_tfo_stats & TFO_S_COOKIE_REQ);
1975 		tci->tcpi_tfo_cookie_rcv = !!(tp->t_tfo_stats & TFO_S_COOKIE_RCV);
1976 		tci->tcpi_tfo_syn_data_sent = !!(tp->t_tfo_stats & TFO_S_SYN_DATA_SENT);
1977 		tci->tcpi_tfo_syn_data_acked = !!(tp->t_tfo_stats & TFO_S_SYN_DATA_ACKED);
1978 		tci->tcpi_tfo_syn_loss = !!(tp->t_tfo_stats & TFO_S_SYN_LOSS);
1979 		tci->tcpi_tfo_cookie_wrong = !!(tp->t_tfo_stats & TFO_S_COOKIE_WRONG);
1980 		tci->tcpi_tfo_no_cookie_rcv = !!(tp->t_tfo_stats & TFO_S_NO_COOKIE_RCV);
1981 		tci->tcpi_tfo_heuristics_disable = !!(tp->t_tfo_stats & TFO_S_HEURISTICS_DISABLE);
1982 		tci->tcpi_tfo_send_blackhole = !!(tp->t_tfo_stats & TFO_S_SEND_BLACKHOLE);
1983 		tci->tcpi_tfo_recv_blackhole = !!(tp->t_tfo_stats & TFO_S_RECV_BLACKHOLE);
1984 		tci->tcpi_tfo_onebyte_proxy = !!(tp->t_tfo_stats & TFO_S_ONE_BYTE_PROXY);
1985 	}
1986 }
1987 
1988 
1989 __private_extern__ int
tcp_sysctl_info(__unused struct sysctl_oid * oidp,__unused void * arg1,__unused int arg2,struct sysctl_req * req)1990 tcp_sysctl_info(__unused struct sysctl_oid *oidp, __unused void *arg1, __unused int arg2, struct sysctl_req *req)
1991 {
1992 	int error;
1993 	struct tcp_info ti = {};
1994 	struct info_tuple itpl;
1995 
1996 	if (req->newptr == USER_ADDR_NULL) {
1997 		return EINVAL;
1998 	}
1999 	if (req->newlen < sizeof(struct info_tuple)) {
2000 		return EINVAL;
2001 	}
2002 	error = SYSCTL_IN(req, &itpl, sizeof(struct info_tuple));
2003 	if (error != 0) {
2004 		return error;
2005 	}
2006 	error = tcp_fill_info_for_info_tuple(&itpl, &ti);
2007 	if (error != 0) {
2008 		return error;
2009 	}
2010 	error = SYSCTL_OUT(req, &ti, sizeof(struct tcp_info));
2011 	if (error != 0) {
2012 		return error;
2013 	}
2014 
2015 	return 0;
2016 }
2017 
2018 static int
tcp_lookup_peer_pid_locked(struct socket * so,pid_t * out_pid)2019 tcp_lookup_peer_pid_locked(struct socket *so, pid_t *out_pid)
2020 {
2021 	int error = EHOSTUNREACH;
2022 	*out_pid = -1;
2023 	if ((so->so_state & SS_ISCONNECTED) == 0) {
2024 		return ENOTCONN;
2025 	}
2026 
2027 	struct inpcb    *inp = (struct inpcb*)so->so_pcb;
2028 	uint16_t                lport = inp->inp_lport;
2029 	uint16_t                fport = inp->inp_fport;
2030 	uint32_t                                fifscope = inp->inp_fifscope;
2031 	uint32_t                                lifscope = inp->inp_lifscope;
2032 
2033 	struct inpcb    *finp = NULL;
2034 	struct  in6_addr laddr6, faddr6;
2035 	struct in_addr laddr4, faddr4;
2036 
2037 	if (inp->inp_vflag & INP_IPV6) {
2038 		laddr6 = inp->in6p_laddr;
2039 		faddr6 = inp->in6p_faddr;
2040 	} else if (inp->inp_vflag & INP_IPV4) {
2041 		laddr4 = inp->inp_laddr;
2042 		faddr4 = inp->inp_faddr;
2043 	}
2044 
2045 	socket_unlock(so, 0);
2046 	if (inp->inp_vflag & INP_IPV6) {
2047 		finp = in6_pcblookup_hash(&tcbinfo, &laddr6, lport, lifscope, &faddr6, fport, fifscope, 0, NULL);
2048 	} else if (inp->inp_vflag & INP_IPV4) {
2049 		finp = in_pcblookup_hash(&tcbinfo, laddr4, lport, faddr4, fport, 0, NULL);
2050 	}
2051 
2052 	if (finp) {
2053 		*out_pid = finp->inp_socket->last_pid;
2054 		error = 0;
2055 		in_pcb_checkstate(finp, WNT_RELEASE, 0);
2056 	}
2057 	socket_lock(so, 0);
2058 
2059 	return error;
2060 }
2061 
2062 void
tcp_getconninfo(struct socket * so,struct conninfo_tcp * tcp_ci)2063 tcp_getconninfo(struct socket *so, struct conninfo_tcp *tcp_ci)
2064 {
2065 	(void) tcp_lookup_peer_pid_locked(so, &tcp_ci->tcpci_peer_pid);
2066 	tcp_fill_info(sototcpcb(so), &tcp_ci->tcpci_tcp_info);
2067 }
2068 
2069 void
tcp_clear_keep_alive_offload(struct socket * so)2070 tcp_clear_keep_alive_offload(struct socket *so)
2071 {
2072 	struct inpcb *inp;
2073 	struct ifnet *ifp;
2074 
2075 	inp = sotoinpcb(so);
2076 	if (inp == NULL) {
2077 		return;
2078 	}
2079 
2080 	if ((inp->inp_flags2 & INP2_KEEPALIVE_OFFLOAD) == 0) {
2081 		return;
2082 	}
2083 
2084 	ifp = inp->inp_boundifp != NULL ? inp->inp_boundifp :
2085 	    inp->inp_last_outifp;
2086 	if (ifp == NULL) {
2087 		panic("%s: so %p inp %p ifp NULL",
2088 		    __func__, so, inp);
2089 	}
2090 
2091 	ifnet_lock_exclusive(ifp);
2092 
2093 	if (ifp->if_tcp_kao_cnt == 0) {
2094 		panic("%s: so %p inp %p ifp %p if_tcp_kao_cnt == 0",
2095 		    __func__, so, inp, ifp);
2096 	}
2097 	ifp->if_tcp_kao_cnt--;
2098 	inp->inp_flags2 &= ~INP2_KEEPALIVE_OFFLOAD;
2099 
2100 	ifnet_lock_done(ifp);
2101 }
2102 
2103 static int
tcp_set_keep_alive_offload(struct socket * so,struct proc * proc)2104 tcp_set_keep_alive_offload(struct socket *so, struct proc *proc)
2105 {
2106 	int error = 0;
2107 	struct inpcb *inp;
2108 	struct ifnet *ifp;
2109 
2110 	inp = sotoinpcb(so);
2111 	if (inp == NULL) {
2112 		return ECONNRESET;
2113 	}
2114 	if ((inp->inp_flags2 & INP2_KEEPALIVE_OFFLOAD) != 0) {
2115 		return 0;
2116 	}
2117 
2118 	ifp = inp->inp_boundifp != NULL ? inp->inp_boundifp :
2119 	    inp->inp_last_outifp;
2120 	if (ifp == NULL) {
2121 		error = ENXIO;
2122 		os_log_info(OS_LOG_DEFAULT,
2123 		    "%s: error %d for proc %s[%u] out ifp is not set\n",
2124 		    __func__, error,
2125 		    proc != NULL ? proc->p_comm : "kernel",
2126 		    proc != NULL ? proc_getpid(proc) : 0);
2127 		return ENXIO;
2128 	}
2129 
2130 	error = if_get_tcp_kao_max(ifp);
2131 	if (error != 0) {
2132 		return error;
2133 	}
2134 
2135 	ifnet_lock_exclusive(ifp);
2136 	if (ifp->if_tcp_kao_cnt < ifp->if_tcp_kao_max) {
2137 		ifp->if_tcp_kao_cnt++;
2138 		inp->inp_flags2 |= INP2_KEEPALIVE_OFFLOAD;
2139 	} else {
2140 		error = ETOOMANYREFS;
2141 		os_log_info(OS_LOG_DEFAULT,
2142 		    "%s: error %d for proc %s[%u] if_tcp_kao_max %u\n",
2143 		    __func__, error,
2144 		    proc != NULL ? proc->p_comm : "kernel",
2145 		    proc != NULL ? proc_getpid(proc) : 0,
2146 		    ifp->if_tcp_kao_max);
2147 	}
2148 	ifnet_lock_done(ifp);
2149 
2150 	return error;
2151 }
2152 
2153 /*
2154  * The new sockopt interface makes it possible for us to block in the
2155  * copyin/out step (if we take a page fault).  Taking a page fault at
2156  * splnet() is probably a Bad Thing.  (Since sockets and pcbs both now
2157  * use TSM, there probably isn't any need for this function to run at
2158  * splnet() any more.  This needs more examination.)
2159  */
2160 int
tcp_ctloutput(struct socket * so,struct sockopt * sopt)2161 tcp_ctloutput(struct socket *so, struct sockopt *sopt)
2162 {
2163 	int     error = 0, opt = 0, optval = 0;
2164 	struct  inpcb *inp;
2165 	struct  tcpcb *tp;
2166 
2167 	inp = sotoinpcb(so);
2168 	if (inp == NULL) {
2169 		return ECONNRESET;
2170 	}
2171 	/* Allow <SOL_SOCKET,SO_FLUSH/SO_TRAFFIC_MGT_BACKGROUND> at this level */
2172 	if (sopt->sopt_level != IPPROTO_TCP &&
2173 	    !(sopt->sopt_level == SOL_SOCKET && (sopt->sopt_name == SO_FLUSH ||
2174 	    sopt->sopt_name == SO_TRAFFIC_MGT_BACKGROUND))) {
2175 		if (SOCK_CHECK_DOM(so, PF_INET6)) {
2176 			error = ip6_ctloutput(so, sopt);
2177 		} else {
2178 			error = ip_ctloutput(so, sopt);
2179 		}
2180 		return error;
2181 	}
2182 	tp = intotcpcb(inp);
2183 	if (tp == NULL) {
2184 		return ECONNRESET;
2185 	}
2186 
2187 	calculate_tcp_clock();
2188 
2189 	switch (sopt->sopt_dir) {
2190 	case SOPT_SET:
2191 		switch (sopt->sopt_name) {
2192 		case TCP_NODELAY:
2193 		case TCP_NOOPT:
2194 		case TCP_NOPUSH:
2195 			error = sooptcopyin(sopt, &optval, sizeof optval,
2196 			    sizeof optval);
2197 			if (error) {
2198 				break;
2199 			}
2200 
2201 			switch (sopt->sopt_name) {
2202 			case TCP_NODELAY:
2203 				opt = TF_NODELAY;
2204 				break;
2205 			case TCP_NOOPT:
2206 				opt = TF_NOOPT;
2207 				break;
2208 			case TCP_NOPUSH:
2209 				opt = TF_NOPUSH;
2210 				break;
2211 			default:
2212 				opt = 0; /* dead code to fool gcc */
2213 				break;
2214 			}
2215 
2216 			if (optval) {
2217 				tp->t_flags |= opt;
2218 			} else {
2219 				tp->t_flags &= ~opt;
2220 			}
2221 			break;
2222 		case TCP_RXT_FINDROP:
2223 		case TCP_NOTIMEWAIT:
2224 			error = sooptcopyin(sopt, &optval, sizeof optval,
2225 			    sizeof optval);
2226 			if (error) {
2227 				break;
2228 			}
2229 			switch (sopt->sopt_name) {
2230 			case TCP_RXT_FINDROP:
2231 				opt = TF_RXTFINDROP;
2232 				break;
2233 			case TCP_NOTIMEWAIT:
2234 				opt = TF_NOTIMEWAIT;
2235 				break;
2236 			default:
2237 				opt = 0;
2238 				break;
2239 			}
2240 			if (optval) {
2241 				tp->t_flagsext |= opt;
2242 			} else {
2243 				tp->t_flagsext &= ~opt;
2244 			}
2245 			break;
2246 		case TCP_MEASURE_SND_BW:
2247 			error = sooptcopyin(sopt, &optval, sizeof optval,
2248 			    sizeof optval);
2249 			if (error) {
2250 				break;
2251 			}
2252 			opt = TF_MEASURESNDBW;
2253 			if (optval) {
2254 				if (tp->t_bwmeas == NULL) {
2255 					tp->t_bwmeas = tcp_bwmeas_alloc(tp);
2256 					if (tp->t_bwmeas == NULL) {
2257 						error = ENOMEM;
2258 						break;
2259 					}
2260 				}
2261 				tp->t_flagsext |= opt;
2262 			} else {
2263 				tp->t_flagsext &= ~opt;
2264 				/* Reset snd bw measurement state */
2265 				tp->t_flagsext &= ~(TF_BWMEAS_INPROGRESS);
2266 				if (tp->t_bwmeas != NULL) {
2267 					tcp_bwmeas_free(tp);
2268 				}
2269 			}
2270 			break;
2271 		case TCP_MEASURE_BW_BURST: {
2272 			struct tcp_measure_bw_burst in;
2273 			uint32_t minpkts, maxpkts;
2274 			bzero(&in, sizeof(in));
2275 
2276 			error = sooptcopyin(sopt, &in, sizeof(in),
2277 			    sizeof(in));
2278 			if (error) {
2279 				break;
2280 			}
2281 			if ((tp->t_flagsext & TF_MEASURESNDBW) == 0 ||
2282 			    tp->t_bwmeas == NULL) {
2283 				error = EINVAL;
2284 				break;
2285 			}
2286 			minpkts = (in.min_burst_size != 0) ? in.min_burst_size :
2287 			    tp->t_bwmeas->bw_minsizepkts;
2288 			maxpkts = (in.max_burst_size != 0) ? in.max_burst_size :
2289 			    tp->t_bwmeas->bw_maxsizepkts;
2290 			if (minpkts > maxpkts) {
2291 				error = EINVAL;
2292 				break;
2293 			}
2294 			tp->t_bwmeas->bw_minsizepkts = minpkts;
2295 			tp->t_bwmeas->bw_maxsizepkts = maxpkts;
2296 			tp->t_bwmeas->bw_minsize = (minpkts * tp->t_maxseg);
2297 			tp->t_bwmeas->bw_maxsize = (maxpkts * tp->t_maxseg);
2298 			break;
2299 		}
2300 		case TCP_MAXSEG:
2301 			error = sooptcopyin(sopt, &optval, sizeof optval,
2302 			    sizeof optval);
2303 			if (error) {
2304 				break;
2305 			}
2306 
2307 			if (optval > 0 && optval <= tp->t_maxseg &&
2308 			    optval + 40 >= tcp_minmss) {
2309 				tp->t_maxseg = optval;
2310 			} else {
2311 				error = EINVAL;
2312 			}
2313 			break;
2314 
2315 		case TCP_KEEPALIVE:
2316 			error = sooptcopyin(sopt, &optval, sizeof optval,
2317 			    sizeof optval);
2318 			if (error) {
2319 				break;
2320 			}
2321 			if (optval < 0 || optval > UINT32_MAX / TCP_RETRANSHZ) {
2322 				error = EINVAL;
2323 			} else {
2324 				tp->t_keepidle = optval * TCP_RETRANSHZ;
2325 				/* reset the timer to new value */
2326 				tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp,
2327 				    TCP_CONN_KEEPIDLE(tp));
2328 				tcp_check_timer_state(tp);
2329 			}
2330 			break;
2331 
2332 		case TCP_CONNECTIONTIMEOUT:
2333 			error = sooptcopyin(sopt, &optval, sizeof optval,
2334 			    sizeof optval);
2335 			if (error) {
2336 				break;
2337 			}
2338 			if (optval < 0 || optval > UINT32_MAX / TCP_RETRANSHZ) {
2339 				error = EINVAL;
2340 			} else {
2341 				tp->t_keepinit = optval * TCP_RETRANSHZ;
2342 				if (tp->t_state == TCPS_SYN_RECEIVED ||
2343 				    tp->t_state == TCPS_SYN_SENT) {
2344 					tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp,
2345 					    TCP_CONN_KEEPINIT(tp));
2346 					tcp_check_timer_state(tp);
2347 				}
2348 			}
2349 			break;
2350 
2351 		case TCP_KEEPINTVL:
2352 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2353 			    sizeof(optval));
2354 			if (error) {
2355 				break;
2356 			}
2357 			if (optval < 0 || optval > UINT32_MAX / TCP_RETRANSHZ) {
2358 				error = EINVAL;
2359 			} else {
2360 				tp->t_keepintvl = optval * TCP_RETRANSHZ;
2361 				if (tp->t_state == TCPS_FIN_WAIT_2 &&
2362 				    TCP_CONN_MAXIDLE(tp) > 0) {
2363 					tp->t_timer[TCPT_2MSL] = OFFSET_FROM_START(tp,
2364 					    TCP_CONN_MAXIDLE(tp));
2365 					tcp_check_timer_state(tp);
2366 				}
2367 			}
2368 			break;
2369 
2370 		case TCP_KEEPCNT:
2371 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2372 			    sizeof(optval));
2373 			if (error) {
2374 				break;
2375 			}
2376 			if (optval < 0 || optval > INT32_MAX) {
2377 				error = EINVAL;
2378 			} else {
2379 				tp->t_keepcnt = optval;
2380 				if (tp->t_state == TCPS_FIN_WAIT_2 &&
2381 				    TCP_CONN_MAXIDLE(tp) > 0) {
2382 					tp->t_timer[TCPT_2MSL] = OFFSET_FROM_START(tp,
2383 					    TCP_CONN_MAXIDLE(tp));
2384 					tcp_check_timer_state(tp);
2385 				}
2386 			}
2387 			break;
2388 
2389 		case TCP_KEEPALIVE_OFFLOAD:
2390 			if ((error = priv_check_cred(kauth_cred_get(),
2391 			    PRIV_NETINET_TCP_KA_OFFLOAD, 0)) != 0) {
2392 				break;
2393 			}
2394 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2395 			    sizeof(optval));
2396 			if (error) {
2397 				break;
2398 			}
2399 			if (optval < 0 || optval > INT32_MAX) {
2400 				error = EINVAL;
2401 				break;
2402 			}
2403 			if (optval != 0) {
2404 				error = tcp_set_keep_alive_offload(so,
2405 				    sopt->sopt_p);
2406 			} else {
2407 				tcp_clear_keep_alive_offload(so);
2408 			}
2409 			break;
2410 
2411 		case PERSIST_TIMEOUT:
2412 			error = sooptcopyin(sopt, &optval, sizeof optval,
2413 			    sizeof optval);
2414 			if (error) {
2415 				break;
2416 			}
2417 			if (optval < 0) {
2418 				error = EINVAL;
2419 			} else {
2420 				tp->t_persist_timeout = optval * TCP_RETRANSHZ;
2421 			}
2422 			break;
2423 		case TCP_RXT_CONNDROPTIME:
2424 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2425 			    sizeof(optval));
2426 			if (error) {
2427 				break;
2428 			}
2429 			if (optval < 0) {
2430 				error = EINVAL;
2431 			} else {
2432 				tp->t_rxt_conndroptime = optval * TCP_RETRANSHZ;
2433 			}
2434 			break;
2435 		case TCP_NOTSENT_LOWAT:
2436 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2437 			    sizeof(optval));
2438 			if (error) {
2439 				break;
2440 			}
2441 			if (optval < 0) {
2442 				error = EINVAL;
2443 				break;
2444 			} else {
2445 				if (optval == 0) {
2446 					so->so_flags &= ~(SOF_NOTSENT_LOWAT);
2447 					tp->t_notsent_lowat = 0;
2448 				} else {
2449 					so->so_flags |= SOF_NOTSENT_LOWAT;
2450 					tp->t_notsent_lowat = optval;
2451 				}
2452 			}
2453 			break;
2454 		case TCP_ADAPTIVE_READ_TIMEOUT:
2455 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2456 			    sizeof(optval));
2457 			if (error) {
2458 				break;
2459 			}
2460 			if (optval < 0 ||
2461 			    optval > TCP_ADAPTIVE_TIMEOUT_MAX) {
2462 				error = EINVAL;
2463 				break;
2464 			} else if (optval == 0) {
2465 				tp->t_adaptive_rtimo = 0;
2466 				tcp_keepalive_reset(tp);
2467 
2468 				if (tp->t_mpsub) {
2469 					mptcp_reset_keepalive(tp);
2470 				}
2471 			} else {
2472 				tp->t_adaptive_rtimo = (uint8_t)optval;
2473 			}
2474 			break;
2475 		case TCP_ADAPTIVE_WRITE_TIMEOUT:
2476 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2477 			    sizeof(optval));
2478 			if (error) {
2479 				break;
2480 			}
2481 			if (optval < 0 ||
2482 			    optval > TCP_ADAPTIVE_TIMEOUT_MAX) {
2483 				error = EINVAL;
2484 				break;
2485 			} else {
2486 				tp->t_adaptive_wtimo = (uint8_t)optval;
2487 			}
2488 			break;
2489 		case TCP_SENDMOREACKS:
2490 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2491 			    sizeof(optval));
2492 			if (error) {
2493 				break;
2494 			}
2495 			if (optval < 0 || optval > 1) {
2496 				error = EINVAL;
2497 			} else if (optval == 0) {
2498 				tp->t_flagsext &= ~(TF_NOSTRETCHACK);
2499 			} else {
2500 				tp->t_flagsext |= TF_NOSTRETCHACK;
2501 			}
2502 			break;
2503 		case TCP_DISABLE_BLACKHOLE_DETECTION:
2504 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2505 			    sizeof(optval));
2506 			if (error) {
2507 				break;
2508 			}
2509 			if (optval < 0 || optval > 1) {
2510 				error = EINVAL;
2511 			} else if (optval == 0) {
2512 				tp->t_flagsext &= ~TF_NOBLACKHOLE_DETECTION;
2513 			} else {
2514 				tp->t_flagsext |= TF_NOBLACKHOLE_DETECTION;
2515 				if ((tp->t_flags & TF_BLACKHOLE) &&
2516 				    tp->t_pmtud_saved_maxopd > 0) {
2517 					tcp_pmtud_revert_segment_size(tp);
2518 				}
2519 			}
2520 			break;
2521 		case TCP_FASTOPEN:
2522 			if (!(tcp_fastopen & TCP_FASTOPEN_SERVER)) {
2523 				error = ENOTSUP;
2524 				break;
2525 			}
2526 
2527 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2528 			    sizeof(optval));
2529 			if (error) {
2530 				break;
2531 			}
2532 			if (optval < 0 || optval > 1) {
2533 				error = EINVAL;
2534 				break;
2535 			}
2536 			if (tp->t_state != TCPS_LISTEN) {
2537 				error =  EINVAL;
2538 				break;
2539 			}
2540 			if (optval) {
2541 				tp->t_flagsext |= TF_FASTOPEN;
2542 			} else {
2543 				tcp_disable_tfo(tp);
2544 			}
2545 			break;
2546 		case TCP_FASTOPEN_FORCE_HEURISTICS:
2547 
2548 			break;
2549 		case TCP_FASTOPEN_FORCE_ENABLE:
2550 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2551 			    sizeof(optval));
2552 
2553 			if (error) {
2554 				break;
2555 			}
2556 			if (optval < 0 || optval > 1) {
2557 				error = EINVAL;
2558 				break;
2559 			}
2560 
2561 			if (tp->t_state != TCPS_CLOSED) {
2562 				error =  EINVAL;
2563 				break;
2564 			}
2565 			if (optval) {
2566 				tp->t_flagsext |= TF_FASTOPEN_FORCE_ENABLE;
2567 			} else {
2568 				tp->t_flagsext &= ~TF_FASTOPEN_FORCE_ENABLE;
2569 			}
2570 
2571 			break;
2572 		case TCP_ENABLE_ECN:
2573 			error = sooptcopyin(sopt, &optval, sizeof optval,
2574 			    sizeof optval);
2575 			if (error) {
2576 				break;
2577 			}
2578 			if (optval) {
2579 				tp->ecn_flags |= TE_ECN_MODE_ENABLE;
2580 				tp->ecn_flags &= ~TE_ECN_MODE_DISABLE;
2581 			} else {
2582 				tp->ecn_flags &= ~TE_ECN_MODE_ENABLE;
2583 				tp->ecn_flags |= TE_ECN_MODE_DISABLE;
2584 			}
2585 			break;
2586 		case TCP_ECN_MODE:
2587 			error = sooptcopyin(sopt, &optval, sizeof optval,
2588 			    sizeof optval);
2589 			if (error) {
2590 				break;
2591 			}
2592 			if (optval == ECN_MODE_DEFAULT) {
2593 				tp->ecn_flags &= ~TE_ECN_MODE_ENABLE;
2594 				tp->ecn_flags &= ~TE_ECN_MODE_DISABLE;
2595 			} else if (optval == ECN_MODE_ENABLE) {
2596 				tp->ecn_flags |= TE_ECN_MODE_ENABLE;
2597 				tp->ecn_flags &= ~TE_ECN_MODE_DISABLE;
2598 			} else if (optval == ECN_MODE_DISABLE) {
2599 				tp->ecn_flags &= ~TE_ECN_MODE_ENABLE;
2600 				tp->ecn_flags |= TE_ECN_MODE_DISABLE;
2601 			} else {
2602 				error = EINVAL;
2603 			}
2604 			break;
2605 		case TCP_NOTIFY_ACKNOWLEDGEMENT:
2606 			error = sooptcopyin(sopt, &optval,
2607 			    sizeof(optval), sizeof(optval));
2608 			if (error) {
2609 				break;
2610 			}
2611 			if (optval <= 0) {
2612 				error = EINVAL;
2613 				break;
2614 			}
2615 			if (tp->t_notify_ack_count >= TCP_MAX_NOTIFY_ACK) {
2616 				error = ETOOMANYREFS;
2617 				break;
2618 			}
2619 
2620 			/*
2621 			 * validate that the given marker id is not
2622 			 * a duplicate to avoid ambiguity
2623 			 */
2624 			if ((error = tcp_notify_ack_id_valid(tp, so,
2625 			    optval)) != 0) {
2626 				break;
2627 			}
2628 			error = tcp_add_notify_ack_marker(tp, optval);
2629 			break;
2630 		case SO_FLUSH:
2631 			if ((error = sooptcopyin(sopt, &optval, sizeof(optval),
2632 			    sizeof(optval))) != 0) {
2633 				break;
2634 			}
2635 
2636 			error = inp_flush(inp, optval);
2637 			break;
2638 
2639 		case SO_TRAFFIC_MGT_BACKGROUND:
2640 			if ((error = sooptcopyin(sopt, &optval, sizeof(optval),
2641 			    sizeof(optval))) != 0) {
2642 				break;
2643 			}
2644 
2645 			if (optval) {
2646 				socket_set_traffic_mgt_flags_locked(so,
2647 				    TRAFFIC_MGT_SO_BACKGROUND);
2648 			} else {
2649 				socket_clear_traffic_mgt_flags_locked(so,
2650 				    TRAFFIC_MGT_SO_BACKGROUND);
2651 			}
2652 			break;
2653 		case TCP_RXT_MINIMUM_TIMEOUT:
2654 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2655 			    sizeof(optval));
2656 			if (error) {
2657 				break;
2658 			}
2659 			if (optval < 0) {
2660 				error = EINVAL;
2661 				break;
2662 			}
2663 			if (optval == 0) {
2664 				tp->t_rxt_minimum_timeout = 0;
2665 			} else {
2666 				tp->t_rxt_minimum_timeout = min(optval,
2667 				    TCP_RXT_MINIMUM_TIMEOUT_LIMIT);
2668 				/* convert to milliseconds */
2669 				tp->t_rxt_minimum_timeout *= TCP_RETRANSHZ;
2670 			}
2671 			break;
2672 		default:
2673 			error = ENOPROTOOPT;
2674 			break;
2675 		}
2676 		break;
2677 
2678 	case SOPT_GET:
2679 		switch (sopt->sopt_name) {
2680 		case TCP_NODELAY:
2681 			optval = tp->t_flags & TF_NODELAY;
2682 			break;
2683 		case TCP_MAXSEG:
2684 			optval = tp->t_maxseg;
2685 			break;
2686 		case TCP_KEEPALIVE:
2687 			if (tp->t_keepidle > 0) {
2688 				optval = tp->t_keepidle / TCP_RETRANSHZ;
2689 			} else {
2690 				optval = tcp_keepidle  / TCP_RETRANSHZ;
2691 			}
2692 			break;
2693 		case TCP_KEEPINTVL:
2694 			if (tp->t_keepintvl > 0) {
2695 				optval = tp->t_keepintvl / TCP_RETRANSHZ;
2696 			} else {
2697 				optval = tcp_keepintvl / TCP_RETRANSHZ;
2698 			}
2699 			break;
2700 		case TCP_KEEPCNT:
2701 			if (tp->t_keepcnt > 0) {
2702 				optval = tp->t_keepcnt;
2703 			} else {
2704 				optval = tcp_keepcnt;
2705 			}
2706 			break;
2707 		case TCP_KEEPALIVE_OFFLOAD:
2708 			optval = !!(inp->inp_flags2 & INP2_KEEPALIVE_OFFLOAD);
2709 			break;
2710 		case TCP_NOOPT:
2711 			optval = tp->t_flags & TF_NOOPT;
2712 			break;
2713 		case TCP_NOPUSH:
2714 			optval = tp->t_flags & TF_NOPUSH;
2715 			break;
2716 		case TCP_ENABLE_ECN:
2717 			optval = (tp->ecn_flags & TE_ECN_MODE_ENABLE) ? 1 : 0;
2718 			break;
2719 		case TCP_ECN_MODE:
2720 			if (tp->ecn_flags & TE_ECN_MODE_ENABLE) {
2721 				optval = ECN_MODE_ENABLE;
2722 			} else if (tp->ecn_flags & TE_ECN_MODE_DISABLE) {
2723 				optval = ECN_MODE_DISABLE;
2724 			} else {
2725 				optval = ECN_MODE_DEFAULT;
2726 			}
2727 			break;
2728 		case TCP_CONNECTIONTIMEOUT:
2729 			optval = tp->t_keepinit / TCP_RETRANSHZ;
2730 			break;
2731 		case PERSIST_TIMEOUT:
2732 			optval = tp->t_persist_timeout / TCP_RETRANSHZ;
2733 			break;
2734 		case TCP_RXT_CONNDROPTIME:
2735 			optval = tp->t_rxt_conndroptime / TCP_RETRANSHZ;
2736 			break;
2737 		case TCP_RXT_FINDROP:
2738 			optval = tp->t_flagsext & TF_RXTFINDROP;
2739 			break;
2740 		case TCP_NOTIMEWAIT:
2741 			optval = (tp->t_flagsext & TF_NOTIMEWAIT) ? 1 : 0;
2742 			break;
2743 		case TCP_FASTOPEN:
2744 			if (tp->t_state != TCPS_LISTEN ||
2745 			    !(tcp_fastopen & TCP_FASTOPEN_SERVER)) {
2746 				error = ENOTSUP;
2747 				break;
2748 			}
2749 			optval = tfo_enabled(tp);
2750 			break;
2751 		case TCP_FASTOPEN_FORCE_HEURISTICS:
2752 			optval = 0;
2753 			break;
2754 		case TCP_FASTOPEN_FORCE_ENABLE:
2755 			optval = (tp->t_flagsext & TF_FASTOPEN_FORCE_ENABLE) ? 1 : 0;
2756 			break;
2757 		case TCP_MEASURE_SND_BW:
2758 			optval = tp->t_flagsext & TF_MEASURESNDBW;
2759 			break;
2760 		case TCP_INFO: {
2761 			struct tcp_info ti;
2762 
2763 			tcp_fill_info(tp, &ti);
2764 			error = sooptcopyout(sopt, &ti, sizeof(struct tcp_info));
2765 			goto done;
2766 			/* NOT REACHED */
2767 		}
2768 		case TCP_CONNECTION_INFO: {
2769 			struct tcp_connection_info tci;
2770 			tcp_connection_fill_info(tp, &tci);
2771 			error = sooptcopyout(sopt, &tci,
2772 			    sizeof(struct tcp_connection_info));
2773 			goto done;
2774 		}
2775 		case TCP_MEASURE_BW_BURST: {
2776 			struct tcp_measure_bw_burst out = {};
2777 			if ((tp->t_flagsext & TF_MEASURESNDBW) == 0 ||
2778 			    tp->t_bwmeas == NULL) {
2779 				error = EINVAL;
2780 				break;
2781 			}
2782 			out.min_burst_size = tp->t_bwmeas->bw_minsizepkts;
2783 			out.max_burst_size = tp->t_bwmeas->bw_maxsizepkts;
2784 			error = sooptcopyout(sopt, &out, sizeof(out));
2785 			goto done;
2786 		}
2787 		case TCP_NOTSENT_LOWAT:
2788 			if ((so->so_flags & SOF_NOTSENT_LOWAT) != 0) {
2789 				optval = tp->t_notsent_lowat;
2790 			} else {
2791 				optval = 0;
2792 			}
2793 			break;
2794 		case TCP_SENDMOREACKS:
2795 			if (tp->t_flagsext & TF_NOSTRETCHACK) {
2796 				optval = 1;
2797 			} else {
2798 				optval = 0;
2799 			}
2800 			break;
2801 		case TCP_DISABLE_BLACKHOLE_DETECTION:
2802 			if (tp->t_flagsext & TF_NOBLACKHOLE_DETECTION) {
2803 				optval = 1;
2804 			} else {
2805 				optval = 0;
2806 			}
2807 			break;
2808 		case TCP_PEER_PID: {
2809 			pid_t   pid;
2810 			error = tcp_lookup_peer_pid_locked(so, &pid);
2811 			if (error == 0) {
2812 				error = sooptcopyout(sopt, &pid, sizeof(pid));
2813 			}
2814 			goto done;
2815 		}
2816 		case TCP_ADAPTIVE_READ_TIMEOUT:
2817 			optval = tp->t_adaptive_rtimo;
2818 			break;
2819 		case TCP_ADAPTIVE_WRITE_TIMEOUT:
2820 			optval = tp->t_adaptive_wtimo;
2821 			break;
2822 		case SO_TRAFFIC_MGT_BACKGROUND:
2823 			optval = (so->so_flags1 &
2824 			    SOF1_TRAFFIC_MGT_SO_BACKGROUND) ? 1 : 0;
2825 			break;
2826 		case TCP_NOTIFY_ACKNOWLEDGEMENT: {
2827 			struct tcp_notify_ack_complete retid;
2828 
2829 			if (sopt->sopt_valsize != sizeof(retid)) {
2830 				error = EINVAL;
2831 				break;
2832 			}
2833 			bzero(&retid, sizeof(retid));
2834 			tcp_get_notify_ack_count(tp, &retid);
2835 			if (retid.notify_complete_count > 0) {
2836 				tcp_get_notify_ack_ids(tp, &retid);
2837 			}
2838 
2839 			error = sooptcopyout(sopt, &retid, sizeof(retid));
2840 			goto done;
2841 		}
2842 		case TCP_RXT_MINIMUM_TIMEOUT:
2843 			optval = tp->t_rxt_minimum_timeout / TCP_RETRANSHZ;
2844 			break;
2845 		default:
2846 			error = ENOPROTOOPT;
2847 			break;
2848 		}
2849 		if (error == 0) {
2850 			error = sooptcopyout(sopt, &optval, sizeof optval);
2851 		}
2852 		break;
2853 	}
2854 done:
2855 	return error;
2856 }
2857 
2858 /*
2859  * tcp_sendspace and tcp_recvspace are the default send and receive window
2860  * sizes, respectively.  These are obsolescent (this information should
2861  * be set by the route).
2862  */
2863 u_int32_t       tcp_sendspace = 1448 * 256;
2864 u_int32_t       tcp_recvspace = 1448 * 384;
2865 
2866 /* During attach, the size of socket buffer allocated is limited to
2867  * sb_max in sbreserve. Disallow setting the tcp send and recv space
2868  * to be more than sb_max because that will cause tcp_attach to fail
2869  * (see radar 5713060)
2870  */
2871 static int
sysctl_tcp_sospace(struct sysctl_oid * oidp,__unused void * arg1,int arg2,struct sysctl_req * req)2872 sysctl_tcp_sospace(struct sysctl_oid *oidp, __unused void *arg1,
2873     int arg2, struct sysctl_req *req)
2874 {
2875 #pragma unused(arg2)
2876 	u_int32_t new_value = 0, *space_p = NULL;
2877 	int changed = 0, error = 0;
2878 	u_quad_t sb_effective_max = (sb_max / (MSIZE + MCLBYTES)) * MCLBYTES;
2879 
2880 	switch (oidp->oid_number) {
2881 	case TCPCTL_SENDSPACE:
2882 		space_p = &tcp_sendspace;
2883 		break;
2884 	case TCPCTL_RECVSPACE:
2885 		space_p = &tcp_recvspace;
2886 		break;
2887 	default:
2888 		return EINVAL;
2889 	}
2890 	error = sysctl_io_number(req, *space_p, sizeof(u_int32_t),
2891 	    &new_value, &changed);
2892 	if (changed) {
2893 		if (new_value > 0 && new_value <= sb_effective_max) {
2894 			*space_p = new_value;
2895 			SYSCTL_SKMEM_UPDATE_AT_OFFSET(arg2, new_value);
2896 		} else {
2897 			error = ERANGE;
2898 		}
2899 	}
2900 	return error;
2901 }
2902 
2903 #if SYSCTL_SKMEM
2904 SYSCTL_PROC(_net_inet_tcp, TCPCTL_SENDSPACE, sendspace,
2905     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED, &tcp_sendspace,
2906     offsetof(skmem_sysctl, tcp.sendspace), sysctl_tcp_sospace,
2907     "IU", "Maximum outgoing TCP datagram size");
2908 SYSCTL_PROC(_net_inet_tcp, TCPCTL_RECVSPACE, recvspace,
2909     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED, &tcp_recvspace,
2910     offsetof(skmem_sysctl, tcp.recvspace), sysctl_tcp_sospace,
2911     "IU", "Maximum incoming TCP datagram size");
2912 #else /* SYSCTL_SKMEM */
2913 SYSCTL_PROC(_net_inet_tcp, TCPCTL_SENDSPACE, sendspace, CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
2914     &tcp_sendspace, 0, &sysctl_tcp_sospace, "IU", "Maximum outgoing TCP datagram size");
2915 SYSCTL_PROC(_net_inet_tcp, TCPCTL_RECVSPACE, recvspace, CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
2916     &tcp_recvspace, 0, &sysctl_tcp_sospace, "IU", "Maximum incoming TCP datagram size");
2917 #endif /* SYSCTL_SKMEM */
2918 
2919 /*
2920  * Attach TCP protocol to socket, allocating
2921  * internet protocol control block, tcp control block,
2922  * bufer space, and entering LISTEN state if to accept connections.
2923  *
2924  * Returns:	0			Success
2925  *	in_pcballoc:ENOBUFS
2926  *	in_pcballoc:ENOMEM
2927  *	in_pcballoc:???			[IPSEC specific]
2928  *	soreserve:ENOBUFS
2929  */
2930 static int
tcp_attach(struct socket * so,struct proc * p)2931 tcp_attach(struct socket *so, struct proc *p)
2932 {
2933 	struct tcpcb *tp;
2934 	struct inpcb *inp;
2935 	int error;
2936 	int isipv6 = SOCK_CHECK_DOM(so, PF_INET6) != 0;
2937 
2938 	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
2939 		error = soreserve(so, tcp_sendspace, tcp_recvspace);
2940 		if (error) {
2941 			return error;
2942 		}
2943 	}
2944 
2945 	error = in_pcballoc(so, &tcbinfo, p);
2946 	if (error) {
2947 		return error;
2948 	}
2949 
2950 	inp = sotoinpcb(so);
2951 
2952 	if (so->so_snd.sb_preconn_hiwat == 0) {
2953 		soreserve_preconnect(so, 2048);
2954 	}
2955 
2956 	if ((so->so_rcv.sb_flags & SB_USRSIZE) == 0) {
2957 		so->so_rcv.sb_flags |= SB_AUTOSIZE;
2958 	}
2959 	if ((so->so_snd.sb_flags & SB_USRSIZE) == 0) {
2960 		so->so_snd.sb_flags |= SB_AUTOSIZE;
2961 	}
2962 
2963 	if (isipv6) {
2964 		inp->inp_vflag |= INP_IPV6;
2965 		inp->in6p_hops = -1;    /* use kernel default */
2966 	} else {
2967 		inp->inp_vflag |= INP_IPV4;
2968 	}
2969 	tp = tcp_newtcpcb(inp);
2970 	if (tp == NULL) {
2971 		int nofd = so->so_state & SS_NOFDREF;   /* XXX */
2972 
2973 		so->so_state &= ~SS_NOFDREF;    /* don't free the socket yet */
2974 		if (isipv6) {
2975 			in6_pcbdetach(inp);
2976 		} else {
2977 			in_pcbdetach(inp);
2978 		}
2979 		so->so_state |= nofd;
2980 		return ENOBUFS;
2981 	}
2982 	if (nstat_collect) {
2983 		nstat_tcp_new_pcb(inp);
2984 	}
2985 	tp->t_state = TCPS_CLOSED;
2986 	return 0;
2987 }
2988 
2989 /*
2990  * Initiate (or continue) disconnect.
2991  * If embryonic state, just send reset (once).
2992  * If in ``let data drain'' option and linger null, just drop.
2993  * Otherwise (hard), mark socket disconnecting and drop
2994  * current input data; switch states based on user close, and
2995  * send segment to peer (with FIN).
2996  */
2997 static struct tcpcb *
tcp_disconnect(struct tcpcb * tp)2998 tcp_disconnect(struct tcpcb *tp)
2999 {
3000 	struct socket *so = tp->t_inpcb->inp_socket;
3001 
3002 	if (so->so_rcv.sb_cc != 0 || tp->t_reassqlen != 0) {
3003 		return tcp_drop(tp, 0);
3004 	}
3005 
3006 	if (tp->t_state < TCPS_ESTABLISHED) {
3007 		tp = tcp_close(tp);
3008 	} else if ((so->so_options & SO_LINGER) && so->so_linger == 0) {
3009 		tp = tcp_drop(tp, 0);
3010 	} else {
3011 		soisdisconnecting(so);
3012 		sbflush(&so->so_rcv);
3013 		tp = tcp_usrclosed(tp);
3014 #if MPTCP
3015 		/* A reset has been sent but socket exists, do not send FIN */
3016 		if ((so->so_flags & SOF_MP_SUBFLOW) &&
3017 		    (tp) && (tp->t_mpflags & TMPF_RESET)) {
3018 			return tp;
3019 		}
3020 #endif
3021 		if (tp) {
3022 			(void) tcp_output(tp);
3023 		}
3024 	}
3025 	return tp;
3026 }
3027 
3028 /*
3029  * User issued close, and wish to trail through shutdown states:
3030  * if never received SYN, just forget it.  If got a SYN from peer,
3031  * but haven't sent FIN, then go to FIN_WAIT_1 state to send peer a FIN.
3032  * If already got a FIN from peer, then almost done; go to LAST_ACK
3033  * state.  In all other cases, have already sent FIN to peer (e.g.
3034  * after PRU_SHUTDOWN), and just have to play tedious game waiting
3035  * for peer to send FIN or not respond to keep-alives, etc.
3036  * We can let the user exit from the close as soon as the FIN is acked.
3037  */
3038 static struct tcpcb *
tcp_usrclosed(struct tcpcb * tp)3039 tcp_usrclosed(struct tcpcb *tp)
3040 {
3041 	switch (tp->t_state) {
3042 	case TCPS_CLOSED:
3043 	case TCPS_LISTEN:
3044 	case TCPS_SYN_SENT:
3045 		tp = tcp_close(tp);
3046 		break;
3047 
3048 	case TCPS_SYN_RECEIVED:
3049 		tp->t_flags |= TF_NEEDFIN;
3050 		break;
3051 
3052 	case TCPS_ESTABLISHED:
3053 		DTRACE_TCP4(state__change, void, NULL,
3054 		    struct inpcb *, tp->t_inpcb,
3055 		    struct tcpcb *, tp,
3056 		    int32_t, TCPS_FIN_WAIT_1);
3057 		tp->t_state = TCPS_FIN_WAIT_1;
3058 		TCP_LOG_CONNECTION_SUMMARY(tp);
3059 		break;
3060 
3061 	case TCPS_CLOSE_WAIT:
3062 		DTRACE_TCP4(state__change, void, NULL,
3063 		    struct inpcb *, tp->t_inpcb,
3064 		    struct tcpcb *, tp,
3065 		    int32_t, TCPS_LAST_ACK);
3066 		tp->t_state = TCPS_LAST_ACK;
3067 		TCP_LOG_CONNECTION_SUMMARY(tp);
3068 		break;
3069 	}
3070 	if (tp && tp->t_state >= TCPS_FIN_WAIT_2) {
3071 		soisdisconnected(tp->t_inpcb->inp_socket);
3072 		/* To prevent the connection hanging in FIN_WAIT_2 forever. */
3073 		if (tp->t_state == TCPS_FIN_WAIT_2) {
3074 			tcp_set_finwait_timeout(tp);
3075 		}
3076 	}
3077 	return tp;
3078 }
3079 
3080 void
tcp_in_cksum_stats(u_int32_t len)3081 tcp_in_cksum_stats(u_int32_t len)
3082 {
3083 	tcpstat.tcps_rcv_swcsum++;
3084 	tcpstat.tcps_rcv_swcsum_bytes += len;
3085 }
3086 
3087 void
tcp_out_cksum_stats(u_int32_t len)3088 tcp_out_cksum_stats(u_int32_t len)
3089 {
3090 	tcpstat.tcps_snd_swcsum++;
3091 	tcpstat.tcps_snd_swcsum_bytes += len;
3092 }
3093 
3094 void
tcp_in6_cksum_stats(u_int32_t len)3095 tcp_in6_cksum_stats(u_int32_t len)
3096 {
3097 	tcpstat.tcps_rcv6_swcsum++;
3098 	tcpstat.tcps_rcv6_swcsum_bytes += len;
3099 }
3100 
3101 void
tcp_out6_cksum_stats(u_int32_t len)3102 tcp_out6_cksum_stats(u_int32_t len)
3103 {
3104 	tcpstat.tcps_snd6_swcsum++;
3105 	tcpstat.tcps_snd6_swcsum_bytes += len;
3106 }
3107 
3108 int
tcp_get_mpkl_send_info(struct mbuf * control,struct so_mpkl_send_info * mpkl_send_info)3109 tcp_get_mpkl_send_info(struct mbuf *control,
3110     struct so_mpkl_send_info *mpkl_send_info)
3111 {
3112 	struct cmsghdr *cm;
3113 
3114 	if (control == NULL || mpkl_send_info == NULL) {
3115 		return EINVAL;
3116 	}
3117 
3118 	for (cm = M_FIRST_CMSGHDR(control); cm;
3119 	    cm = M_NXT_CMSGHDR(control, cm)) {
3120 		if (cm->cmsg_len < sizeof(struct cmsghdr) ||
3121 		    cm->cmsg_len > control->m_len) {
3122 			return EINVAL;
3123 		}
3124 		if (cm->cmsg_level != SOL_SOCKET ||
3125 		    cm->cmsg_type != SCM_MPKL_SEND_INFO) {
3126 			continue;
3127 		}
3128 		if (cm->cmsg_len != CMSG_LEN(sizeof(struct so_mpkl_send_info))) {
3129 			return EINVAL;
3130 		}
3131 		memcpy(mpkl_send_info, CMSG_DATA(cm),
3132 		    sizeof(struct so_mpkl_send_info));
3133 		return 0;
3134 	}
3135 	return ENOMSG;
3136 }
3137