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