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