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