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 tp->request_r_scale = tcp_get_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] = tcp_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 tp->request_r_scale = tcp_get_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] = tcp_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 ti->tcpi_rto = tp->t_timer[TCPT_REXMT] ? tp->t_rxtcur : 0;
1784 ti->tcpi_snd_mss = tp->t_maxseg;
1785 ti->tcpi_rcv_mss = tp->t_maxseg;
1786
1787 ti->tcpi_rttcur = tp->t_rttcur;
1788 ti->tcpi_srtt = tp->t_srtt >> TCP_RTT_SHIFT;
1789 ti->tcpi_rcv_srtt = tp->rcv_srtt >> TCP_RTT_SHIFT;
1790 ti->tcpi_rttvar = tp->t_rttvar >> TCP_RTTVAR_SHIFT;
1791 ti->tcpi_rttbest = tp->t_rttbest >> TCP_RTT_SHIFT;
1792
1793 ti->tcpi_snd_ssthresh = tp->snd_ssthresh;
1794 ti->tcpi_snd_cwnd = tp->snd_cwnd;
1795 if (inp != NULL && inp->inp_socket != NULL) {
1796 ti->tcpi_snd_sbbytes = inp->inp_socket->so_snd.sb_cc;
1797 }
1798
1799 ti->tcpi_rcv_space = tp->rcv_adv > tp->rcv_nxt ?
1800 tp->rcv_adv - tp->rcv_nxt : 0;
1801
1802 ti->tcpi_snd_wnd = tp->snd_wnd;
1803 ti->tcpi_snd_nxt = tp->snd_nxt;
1804 ti->tcpi_rcv_nxt = tp->rcv_nxt;
1805
1806 /* convert bytes/msec to bits/sec */
1807 if ((tp->t_flagsext & TF_MEASURESNDBW) != 0 &&
1808 tp->t_bwmeas != NULL) {
1809 ti->tcpi_snd_bw = (tp->t_bwmeas->bw_sndbw * 8000);
1810 }
1811
1812 ti->tcpi_txpackets = inp != NULL ? inp->inp_mstat.ms_total.ts_txpackets : 0;
1813 ti->tcpi_txbytes = inp != NULL ? inp->inp_mstat.ms_total.ts_txbytes : 0;
1814 ti->tcpi_txretransmitbytes = tp->t_stat.txretransmitbytes;
1815 ti->tcpi_txretransmitpackets = tp->t_stat.rxmitpkts;
1816 ti->tcpi_txunacked = tp->snd_max - tp->snd_una;
1817
1818 ti->tcpi_rxpackets = inp != NULL ? inp->inp_mstat.ms_total.ts_rxpackets : 0;
1819 ti->tcpi_rxbytes = inp != NULL ? inp->inp_mstat.ms_total.ts_rxbytes : 0;
1820 ti->tcpi_rxduplicatebytes = tp->t_stat.rxduplicatebytes;
1821 ti->tcpi_rxoutoforderbytes = tp->t_stat.rxoutoforderbytes;
1822
1823 if (tp->t_state > TCPS_LISTEN) {
1824 ti->tcpi_synrexmits = (uint8_t)tp->t_stat.rxmitsyns;
1825 }
1826 if (inp != NULL) {
1827 ti->tcpi_cell_rxpackets = inp->inp_mstat.ms_cellular.ts_rxpackets;
1828 ti->tcpi_cell_rxbytes = inp->inp_mstat.ms_cellular.ts_rxbytes;
1829 ti->tcpi_cell_txpackets = inp->inp_mstat.ms_cellular.ts_txpackets;
1830 ti->tcpi_cell_txbytes = inp->inp_mstat.ms_cellular.ts_txbytes;
1831
1832 ti->tcpi_wifi_rxpackets = inp->inp_mstat.ms_wifi_infra.ts_rxpackets +
1833 inp->inp_mstat.ms_wifi_non_infra.ts_rxpackets;
1834 ti->tcpi_wifi_rxbytes = inp->inp_mstat.ms_wifi_infra.ts_rxbytes +
1835 inp->inp_mstat.ms_wifi_non_infra.ts_rxbytes;
1836
1837 ti->tcpi_wifi_txpackets = inp->inp_mstat.ms_wifi_infra.ts_txpackets +
1838 inp->inp_mstat.ms_wifi_non_infra.ts_txpackets;
1839 ti->tcpi_wifi_txbytes = inp->inp_mstat.ms_wifi_infra.ts_txbytes +
1840 inp->inp_mstat.ms_wifi_non_infra.ts_txbytes;
1841
1842 ti->tcpi_wired_rxpackets = inp->inp_mstat.ms_wired.ts_rxpackets;
1843 ti->tcpi_wired_rxbytes = inp->inp_mstat.ms_wired.ts_rxbytes;
1844 ti->tcpi_wired_txpackets = inp->inp_mstat.ms_wired.ts_txpackets;
1845 ti->tcpi_wired_txbytes = inp->inp_mstat.ms_wired.ts_txbytes;
1846 }
1847 tcp_get_connectivity_status(tp, &ti->tcpi_connstatus);
1848
1849 ti->tcpi_tfo_syn_data_rcv = !!(tp->t_tfo_stats & TFO_S_SYNDATA_RCV);
1850 ti->tcpi_tfo_cookie_req_rcv = !!(tp->t_tfo_stats & TFO_S_COOKIEREQ_RECV);
1851 ti->tcpi_tfo_cookie_sent = !!(tp->t_tfo_stats & TFO_S_COOKIE_SENT);
1852 ti->tcpi_tfo_cookie_invalid = !!(tp->t_tfo_stats & TFO_S_COOKIE_INVALID);
1853
1854 ti->tcpi_tfo_cookie_req = !!(tp->t_tfo_stats & TFO_S_COOKIE_REQ);
1855 ti->tcpi_tfo_cookie_rcv = !!(tp->t_tfo_stats & TFO_S_COOKIE_RCV);
1856 ti->tcpi_tfo_syn_data_sent = !!(tp->t_tfo_stats & TFO_S_SYN_DATA_SENT);
1857 ti->tcpi_tfo_syn_data_acked = !!(tp->t_tfo_stats & TFO_S_SYN_DATA_ACKED);
1858 ti->tcpi_tfo_syn_loss = !!(tp->t_tfo_stats & TFO_S_SYN_LOSS);
1859 ti->tcpi_tfo_cookie_wrong = !!(tp->t_tfo_stats & TFO_S_COOKIE_WRONG);
1860 ti->tcpi_tfo_no_cookie_rcv = !!(tp->t_tfo_stats & TFO_S_NO_COOKIE_RCV);
1861 ti->tcpi_tfo_heuristics_disable = !!(tp->t_tfo_stats & TFO_S_HEURISTICS_DISABLE);
1862 ti->tcpi_tfo_send_blackhole = !!(tp->t_tfo_stats & TFO_S_SEND_BLACKHOLE);
1863 ti->tcpi_tfo_recv_blackhole = !!(tp->t_tfo_stats & TFO_S_RECV_BLACKHOLE);
1864 ti->tcpi_tfo_onebyte_proxy = !!(tp->t_tfo_stats & TFO_S_ONE_BYTE_PROXY);
1865
1866 ti->tcpi_ecn_client_setup = !!(tp->ecn_flags & (TE_SETUPSENT | TE_ACE_SETUPSENT));
1867 ti->tcpi_ecn_server_setup = !!(tp->ecn_flags & (TE_SETUPRECEIVED | TE_ACE_SETUPRECEIVED));
1868 ti->tcpi_ecn_success = (TCP_ECN_ENABLED(tp) || tp->accurate_ecn_on) ? 1 : 0;
1869 ti->tcpi_ecn_lost_syn = !!(tp->ecn_flags & TE_LOST_SYN);
1870 ti->tcpi_ecn_lost_synack = !!(tp->ecn_flags & TE_LOST_SYNACK);
1871
1872 ti->tcpi_local_peer = !!(tp->t_flags & TF_LOCAL);
1873
1874 if (inp != NULL && inp->inp_last_outifp != NULL) {
1875 ti->tcpi_last_outif = inp->inp_last_outifp->if_index;
1876
1877 if (IFNET_IS_CELLULAR(inp->inp_last_outifp)) {
1878 ti->tcpi_if_cell = 1;
1879 }
1880 if (IFNET_IS_WIFI(inp->inp_last_outifp)) {
1881 ti->tcpi_if_wifi = 1;
1882 }
1883 if (IFNET_IS_WIRED(inp->inp_last_outifp)) {
1884 ti->tcpi_if_wired = 1;
1885 }
1886 if (IFNET_IS_WIFI_INFRA(inp->inp_last_outifp)) {
1887 ti->tcpi_if_wifi_infra = 1;
1888 }
1889 if (inp->inp_last_outifp->if_eflags & IFEF_AWDL) {
1890 ti->tcpi_if_wifi_awdl = 1;
1891 }
1892 }
1893 if (tp->tcp_cc_index == TCP_CC_ALGO_BACKGROUND_INDEX) {
1894 ti->tcpi_snd_background = 1;
1895 }
1896 if (tcp_recv_bg == 1 || (inp != NULL && inp->inp_socket != NULL &&
1897 IS_TCP_RECV_BG(inp->inp_socket))) {
1898 ti->tcpi_rcv_background = 1;
1899 }
1900
1901 ti->tcpi_ecn_recv_ce = tp->t_ecn_recv_ce;
1902 ti->tcpi_ecn_recv_cwr = tp->t_ecn_recv_cwr;
1903
1904 ti->tcpi_rcvoopack = tp->t_rcvoopack;
1905 ti->tcpi_pawsdrop = tp->t_pawsdrop;
1906 ti->tcpi_sack_recovery_episode = tp->t_sack_recovery_episode;
1907 ti->tcpi_reordered_pkts = tp->t_reordered_pkts;
1908 ti->tcpi_dsack_sent = tp->t_dsack_sent;
1909 ti->tcpi_dsack_recvd = tp->t_dsack_recvd;
1910
1911 ti->tcpi_client_accecn_state = tp->t_client_accecn_state;
1912 ti->tcpi_server_accecn_state = tp->t_server_accecn_state;
1913 ti->tcpi_ecn_capable_packets_sent = tp->t_ecn_capable_packets_sent;
1914 ti->tcpi_ecn_capable_packets_acked = tp->t_ecn_capable_packets_acked;
1915 ti->tcpi_ecn_capable_packets_marked = tp->t_ecn_capable_packets_marked;
1916 ti->tcpi_ecn_capable_packets_lost = tp->t_ecn_capable_packets_lost;
1917
1918 /*
1919 * As some of the AccECN fields are initialized to non-zero
1920 * values, we subtract the initial values.
1921 */
1922 ti->tcpi_received_ce_packets = tp->t_aecn.t_rcv_ce_packets ? tp->t_aecn.t_rcv_ce_packets - 5 : 0;
1923 ti->tcpi_received_ect0_bytes = tp->t_aecn.t_rcv_ect0_bytes ? tp->t_aecn.t_rcv_ect0_bytes - 1 : 0;
1924 ti->tcpi_received_ect1_bytes = tp->t_aecn.t_rcv_ect1_bytes ? tp->t_aecn.t_rcv_ect1_bytes - 1 : 0;
1925 ti->tcpi_received_ce_bytes = tp->t_aecn.t_rcv_ce_bytes;
1926 ti->tcpi_delivered_ect0_bytes = tp->t_aecn.t_snd_ect0_bytes ? tp->t_aecn.t_snd_ect0_bytes - 1 : 0;
1927 ti->tcpi_delivered_ect1_bytes = tp->t_aecn.t_snd_ect1_bytes ? tp->t_aecn.t_snd_ect1_bytes - 1 : 0;
1928 ti->tcpi_delivered_ce_bytes = tp->t_aecn.t_snd_ce_bytes;
1929
1930 ti->tcpi_l4s_enabled = tp->l4s_enabled;
1931
1932 ti->tcpi_flow_control_total_time = inp->inp_fadv_total_time;
1933 ti->tcpi_rcvwnd_limited_total_time = tp->t_rcvwnd_limited_total_time;
1934
1935 ti->tcpi_pacing_rate = tp->t_pacer.rate;
1936 ti->tcpi_max_pacing_rate = inp->inp_max_pacing_rate;
1937 }
1938
1939 __private_extern__ errno_t
tcp_fill_info_for_info_tuple(struct info_tuple * itpl,struct tcp_info * ti)1940 tcp_fill_info_for_info_tuple(struct info_tuple *itpl, struct tcp_info *ti)
1941 {
1942 struct inpcbinfo *pcbinfo = NULL;
1943 struct inpcb *inp = NULL;
1944 struct socket *so;
1945 struct tcpcb *tp;
1946
1947 if (itpl->itpl_proto == IPPROTO_TCP) {
1948 pcbinfo = &tcbinfo;
1949 } else {
1950 return EINVAL;
1951 }
1952
1953 if (itpl->itpl_local_sah.sa_family == AF_INET &&
1954 itpl->itpl_remote_sah.sa_family == AF_INET) {
1955 inp = in_pcblookup_hash(pcbinfo,
1956 itpl->itpl_remote_sin.sin_addr,
1957 itpl->itpl_remote_sin.sin_port,
1958 itpl->itpl_local_sin.sin_addr,
1959 itpl->itpl_local_sin.sin_port,
1960 0, NULL);
1961 } else if (itpl->itpl_local_sah.sa_family == AF_INET6 &&
1962 itpl->itpl_remote_sah.sa_family == AF_INET6) {
1963 struct in6_addr ina6_local;
1964 struct in6_addr ina6_remote;
1965
1966 ina6_local = itpl->itpl_local_sin6.sin6_addr;
1967 if (in6_embedded_scope && IN6_IS_SCOPE_LINKLOCAL(&ina6_local) &&
1968 itpl->itpl_local_sin6.sin6_scope_id) {
1969 ina6_local.s6_addr16[1] = htons((uint16_t)itpl->itpl_local_sin6.sin6_scope_id);
1970 }
1971
1972 ina6_remote = itpl->itpl_remote_sin6.sin6_addr;
1973 if (in6_embedded_scope && IN6_IS_SCOPE_LINKLOCAL(&ina6_remote) &&
1974 itpl->itpl_remote_sin6.sin6_scope_id) {
1975 ina6_remote.s6_addr16[1] = htons((uint16_t)itpl->itpl_remote_sin6.sin6_scope_id);
1976 }
1977
1978 inp = in6_pcblookup_hash(pcbinfo,
1979 &ina6_remote,
1980 itpl->itpl_remote_sin6.sin6_port,
1981 itpl->itpl_remote_sin6.sin6_scope_id,
1982 &ina6_local,
1983 itpl->itpl_local_sin6.sin6_port,
1984 itpl->itpl_local_sin6.sin6_scope_id,
1985 0, NULL);
1986 } else {
1987 return EINVAL;
1988 }
1989
1990 if (inp != NULL) {
1991 if ((so = inp->inp_socket) == NULL) {
1992 return ENOENT;
1993 }
1994 socket_lock(so, 0);
1995 if (in_pcb_checkstate(inp, WNT_RELEASE, 1) == WNT_STOPUSING) {
1996 socket_unlock(so, 0);
1997 return ENOENT;
1998 }
1999 tp = intotcpcb(inp);
2000
2001 tcp_fill_info(tp, ti);
2002 socket_unlock(so, 0);
2003
2004 return 0;
2005 }
2006 #if SKYWALK
2007 else {
2008 /* if no pcb found, check for flowswitch for uTCP flow */
2009 int error;
2010 struct nexus_mib_filter nmf = {
2011 .nmf_type = NXMIB_FLOW,
2012 .nmf_bitmap = NXMIB_FILTER_INFO_TUPLE,
2013 .nmf_info_tuple = *itpl,
2014 };
2015 struct sk_stats_flow sf;
2016 size_t len = sizeof(sf);
2017 error = kernel_sysctlbyname(SK_STATS_FLOW, &sf, &len, &nmf, sizeof(nmf));
2018 if (error != 0) {
2019 printf("kernel_sysctlbyname err %d\n", error);
2020 return error;
2021 }
2022 if (len != sizeof(sf)) {
2023 printf("kernel_sysctlbyname invalid len %zu\n", len);
2024 return ENOENT;
2025 }
2026
2027 /*
2028 * This is what flow tracker can offer right now, which is good
2029 * for mDNS TCP keep alive offload.
2030 */
2031 ti->tcpi_snd_nxt = sf.sf_lseq;
2032 ti->tcpi_rcv_nxt = sf.sf_rseq;
2033 ti->tcpi_rcv_space = (uint32_t)(sf.sf_lmax_win << sf.sf_lwscale);
2034 ti->tcpi_rcv_wscale = sf.sf_lwscale;
2035 ti->tcpi_last_outif = (int32_t)sf.sf_if_index;
2036
2037 return 0;
2038 }
2039 #endif /* SKYWALK */
2040
2041 return ENOENT;
2042 }
2043
2044 static void
tcp_connection_fill_info(struct tcpcb * tp,struct tcp_connection_info * tci)2045 tcp_connection_fill_info(struct tcpcb *tp, struct tcp_connection_info *tci)
2046 {
2047 struct inpcb *inp = tp->t_inpcb;
2048
2049 bzero(tci, sizeof(*tci));
2050 tci->tcpi_state = (uint8_t)tp->t_state;
2051
2052 if (TSTMP_SUPPORTED(tp)) {
2053 tci->tcpi_options |= TCPCI_OPT_TIMESTAMPS;
2054 }
2055 if (SACK_ENABLED(tp)) {
2056 tci->tcpi_options |= TCPCI_OPT_SACK;
2057 }
2058 if (TCP_WINDOW_SCALE_ENABLED(tp)) {
2059 tci->tcpi_options |= TCPCI_OPT_WSCALE;
2060 tci->tcpi_snd_wscale = tp->snd_scale;
2061 tci->tcpi_rcv_wscale = tp->rcv_scale;
2062 }
2063 if (TCP_ECN_ENABLED(tp)) {
2064 tci->tcpi_options |= TCPCI_OPT_ECN;
2065 }
2066 if (IN_FASTRECOVERY(tp) || tp->t_rxtshift > 0) {
2067 tci->tcpi_flags |= TCPCI_FLAG_LOSSRECOVERY;
2068 }
2069 if (tp->t_flagsext & TF_PKTS_REORDERED) {
2070 tci->tcpi_flags |= TCPCI_FLAG_REORDERING_DETECTED;
2071 }
2072 tci->tcpi_rto = tp->t_timer[TCPT_REXMT] > 0 ? tp->t_rxtcur : 0;
2073 tci->tcpi_maxseg = tp->t_maxseg;
2074 tci->tcpi_snd_ssthresh = tp->snd_ssthresh;
2075 tci->tcpi_snd_cwnd = tp->snd_cwnd;
2076 tci->tcpi_snd_wnd = tp->snd_wnd;
2077 if (inp != NULL && inp->inp_socket != NULL) {
2078 tci->tcpi_snd_sbbytes = inp->inp_socket->so_snd.sb_cc;
2079 }
2080 tci->tcpi_rcv_wnd = tp->rcv_adv > tp->rcv_nxt ? tp->rcv_adv - tp->rcv_nxt : 0;
2081 tci->tcpi_rttcur = tp->t_rttcur;
2082 tci->tcpi_srtt = (tp->t_srtt >> TCP_RTT_SHIFT);
2083 tci->tcpi_rttvar = (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
2084 tci->tcpi_txpackets = inp != NULL ? inp->inp_mstat.ms_total.ts_txpackets : 0;
2085 tci->tcpi_txbytes = inp != NULL ? inp->inp_mstat.ms_total.ts_txbytes : 0;
2086 tci->tcpi_txretransmitbytes = tp->t_stat.txretransmitbytes;
2087 tci->tcpi_txretransmitpackets = tp->t_stat.rxmitpkts;
2088 tci->tcpi_rxpackets = inp != NULL ? inp->inp_mstat.ms_total.ts_rxpackets : 0;
2089 tci->tcpi_rxbytes = inp != NULL ? inp->inp_mstat.ms_total.ts_rxbytes : 0;
2090 tci->tcpi_rxoutoforderbytes = tp->t_stat.rxoutoforderbytes;
2091
2092 tci->tcpi_tfo_syn_data_rcv = !!(tp->t_tfo_stats & TFO_S_SYNDATA_RCV);
2093 tci->tcpi_tfo_cookie_req_rcv = !!(tp->t_tfo_stats & TFO_S_COOKIEREQ_RECV);
2094 tci->tcpi_tfo_cookie_sent = !!(tp->t_tfo_stats & TFO_S_COOKIE_SENT);
2095 tci->tcpi_tfo_cookie_invalid = !!(tp->t_tfo_stats & TFO_S_COOKIE_INVALID);
2096 tci->tcpi_tfo_cookie_req = !!(tp->t_tfo_stats & TFO_S_COOKIE_REQ);
2097 tci->tcpi_tfo_cookie_rcv = !!(tp->t_tfo_stats & TFO_S_COOKIE_RCV);
2098 tci->tcpi_tfo_syn_data_sent = !!(tp->t_tfo_stats & TFO_S_SYN_DATA_SENT);
2099 tci->tcpi_tfo_syn_data_acked = !!(tp->t_tfo_stats & TFO_S_SYN_DATA_ACKED);
2100 tci->tcpi_tfo_syn_loss = !!(tp->t_tfo_stats & TFO_S_SYN_LOSS);
2101 tci->tcpi_tfo_cookie_wrong = !!(tp->t_tfo_stats & TFO_S_COOKIE_WRONG);
2102 tci->tcpi_tfo_no_cookie_rcv = !!(tp->t_tfo_stats & TFO_S_NO_COOKIE_RCV);
2103 tci->tcpi_tfo_heuristics_disable = !!(tp->t_tfo_stats & TFO_S_HEURISTICS_DISABLE);
2104 tci->tcpi_tfo_send_blackhole = !!(tp->t_tfo_stats & TFO_S_SEND_BLACKHOLE);
2105 tci->tcpi_tfo_recv_blackhole = !!(tp->t_tfo_stats & TFO_S_RECV_BLACKHOLE);
2106 tci->tcpi_tfo_onebyte_proxy = !!(tp->t_tfo_stats & TFO_S_ONE_BYTE_PROXY);
2107 }
2108
2109
2110 __private_extern__ int
tcp_sysctl_info(__unused struct sysctl_oid * oidp,__unused void * arg1,__unused int arg2,struct sysctl_req * req)2111 tcp_sysctl_info(__unused struct sysctl_oid *oidp, __unused void *arg1, __unused int arg2, struct sysctl_req *req)
2112 {
2113 int error;
2114 struct tcp_info ti = {};
2115 struct info_tuple itpl;
2116
2117 if (req->newptr == USER_ADDR_NULL) {
2118 return EINVAL;
2119 }
2120 if (req->newlen < sizeof(struct info_tuple)) {
2121 return EINVAL;
2122 }
2123 error = SYSCTL_IN(req, &itpl, sizeof(struct info_tuple));
2124 if (error != 0) {
2125 return error;
2126 }
2127 error = tcp_fill_info_for_info_tuple(&itpl, &ti);
2128 if (error != 0) {
2129 return error;
2130 }
2131 error = SYSCTL_OUT(req, &ti, sizeof(struct tcp_info));
2132 if (error != 0) {
2133 return error;
2134 }
2135
2136 return 0;
2137 }
2138
2139 static int
tcp_lookup_peer_pid_locked(struct socket * so,pid_t * out_pid)2140 tcp_lookup_peer_pid_locked(struct socket *so, pid_t *out_pid)
2141 {
2142 int error = EHOSTUNREACH;
2143 *out_pid = -1;
2144 if ((so->so_state & SS_ISCONNECTED) == 0) {
2145 return ENOTCONN;
2146 }
2147
2148 struct inpcb *inp = (struct inpcb*)so->so_pcb;
2149 uint16_t lport = inp->inp_lport;
2150 uint16_t fport = inp->inp_fport;
2151 uint32_t fifscope = inp->inp_fifscope;
2152 uint32_t lifscope = inp->inp_lifscope;
2153
2154 struct inpcb *finp = NULL;
2155 struct in6_addr laddr6, faddr6;
2156 struct in_addr laddr4, faddr4;
2157
2158 if (inp->inp_vflag & INP_IPV6) {
2159 laddr6 = inp->in6p_laddr;
2160 faddr6 = inp->in6p_faddr;
2161 } else if (inp->inp_vflag & INP_IPV4) {
2162 laddr4 = inp->inp_laddr;
2163 faddr4 = inp->inp_faddr;
2164 }
2165
2166 socket_unlock(so, 0);
2167 if (inp->inp_vflag & INP_IPV6) {
2168 finp = in6_pcblookup_hash(&tcbinfo, &laddr6, lport, lifscope, &faddr6, fport, fifscope, 0, NULL);
2169 } else if (inp->inp_vflag & INP_IPV4) {
2170 finp = in_pcblookup_hash(&tcbinfo, laddr4, lport, faddr4, fport, 0, NULL);
2171 }
2172
2173 if (finp) {
2174 *out_pid = finp->inp_socket->last_pid;
2175 error = 0;
2176 in_pcb_checkstate(finp, WNT_RELEASE, 0);
2177 }
2178 socket_lock(so, 0);
2179
2180 return error;
2181 }
2182
2183 void
tcp_getconninfo(struct socket * so,struct conninfo_tcp * tcp_ci)2184 tcp_getconninfo(struct socket *so, struct conninfo_tcp *tcp_ci)
2185 {
2186 tcp_fill_info(sototcpcb(so), &tcp_ci->tcpci_tcp_info);
2187 }
2188
2189 void
tcp_clear_keep_alive_offload(struct socket * so)2190 tcp_clear_keep_alive_offload(struct socket *so)
2191 {
2192 struct inpcb *inp;
2193 struct ifnet *ifp;
2194
2195 inp = sotoinpcb(so);
2196 if (inp == NULL) {
2197 return;
2198 }
2199
2200 if ((inp->inp_flags2 & INP2_KEEPALIVE_OFFLOAD) == 0) {
2201 return;
2202 }
2203
2204 ifp = inp->inp_boundifp != NULL ? inp->inp_boundifp :
2205 inp->inp_last_outifp;
2206 if (ifp == NULL) {
2207 panic("%s: so %p inp %p ifp NULL",
2208 __func__, so, inp);
2209 }
2210
2211 ifnet_lock_exclusive(ifp);
2212
2213 if (ifp->if_tcp_kao_cnt == 0) {
2214 panic("%s: so %p inp %p ifp %p if_tcp_kao_cnt == 0",
2215 __func__, so, inp, ifp);
2216 }
2217 ifp->if_tcp_kao_cnt--;
2218 inp->inp_flags2 &= ~INP2_KEEPALIVE_OFFLOAD;
2219
2220 ifnet_lock_done(ifp);
2221 }
2222
2223 static int
tcp_set_keep_alive_offload(struct socket * so,struct proc * proc)2224 tcp_set_keep_alive_offload(struct socket *so, struct proc *proc)
2225 {
2226 int error = 0;
2227 struct inpcb *inp;
2228 struct ifnet *ifp;
2229
2230 inp = sotoinpcb(so);
2231 if (inp == NULL) {
2232 return ECONNRESET;
2233 }
2234 if ((inp->inp_flags2 & INP2_KEEPALIVE_OFFLOAD) != 0) {
2235 return 0;
2236 }
2237
2238 ifp = inp->inp_boundifp != NULL ? inp->inp_boundifp :
2239 inp->inp_last_outifp;
2240 if (ifp == NULL) {
2241 error = ENXIO;
2242 os_log_info(OS_LOG_DEFAULT,
2243 "%s: error %d for proc %s[%u] out ifp is not set\n",
2244 __func__, error,
2245 proc != NULL ? proc->p_comm : "kernel",
2246 proc != NULL ? proc_getpid(proc) : 0);
2247 return ENXIO;
2248 }
2249
2250 error = if_get_tcp_kao_max(ifp);
2251 if (error != 0) {
2252 return error;
2253 }
2254
2255 ifnet_lock_exclusive(ifp);
2256 if (ifp->if_tcp_kao_cnt < ifp->if_tcp_kao_max) {
2257 ifp->if_tcp_kao_cnt++;
2258 inp->inp_flags2 |= INP2_KEEPALIVE_OFFLOAD;
2259 } else {
2260 error = ETOOMANYREFS;
2261 os_log_info(OS_LOG_DEFAULT,
2262 "%s: error %d for proc %s[%u] if_tcp_kao_max %u\n",
2263 __func__, error,
2264 proc != NULL ? proc->p_comm : "kernel",
2265 proc != NULL ? proc_getpid(proc) : 0,
2266 ifp->if_tcp_kao_max);
2267 }
2268 ifnet_lock_done(ifp);
2269
2270 return error;
2271 }
2272
2273 /*
2274 * The new sockopt interface makes it possible for us to block in the
2275 * copyin/out step (if we take a page fault). Taking a page fault at
2276 * splnet() is probably a Bad Thing. (Since sockets and pcbs both now
2277 * use TSM, there probably isn't any need for this function to run at
2278 * splnet() any more. This needs more examination.)
2279 */
2280 int
tcp_ctloutput(struct socket * so,struct sockopt * sopt)2281 tcp_ctloutput(struct socket *so, struct sockopt *sopt)
2282 {
2283 int error = 0, opt = 0, optval = 0;
2284 struct inpcb *inp;
2285 struct tcpcb *tp;
2286
2287 inp = sotoinpcb(so);
2288 if (inp == NULL) {
2289 return ECONNRESET;
2290 }
2291 tp = intotcpcb(inp);
2292 if (tp == NULL) {
2293 return ECONNRESET;
2294 }
2295
2296 /* Allow <SOL_SOCKET,SO_FLUSH/SO_TRAFFIC_MGT_BACKGROUND/SO_BINDTODEVICE> at this level */
2297 if (sopt->sopt_level == SOL_SOCKET) {
2298 if (sopt->sopt_name == SO_BINDTODEVICE) {
2299 if (SOCK_CHECK_DOM(so, PF_INET6)) {
2300 error = ip6_ctloutput(so, sopt);
2301 } else {
2302 error = ip_ctloutput(so, sopt);
2303 }
2304 return error;
2305 } else if (!(sopt->sopt_name == SO_FLUSH ||
2306 sopt->sopt_name == SO_TRAFFIC_MGT_BACKGROUND)) {
2307 return EINVAL;
2308 }
2309 } else if (sopt->sopt_level != IPPROTO_TCP) {
2310 if (SOCK_CHECK_DOM(so, PF_INET6)) {
2311 error = ip6_ctloutput(so, sopt);
2312 } else {
2313 error = ip_ctloutput(so, sopt);
2314 }
2315 return error;
2316 }
2317
2318 calculate_tcp_clock();
2319
2320 switch (sopt->sopt_dir) {
2321 case SOPT_SET:
2322 switch (sopt->sopt_name) {
2323 case TCP_NODELAY:
2324 case TCP_NOOPT:
2325 case TCP_NOPUSH:
2326 error = sooptcopyin(sopt, &optval, sizeof optval,
2327 sizeof optval);
2328 if (error) {
2329 break;
2330 }
2331
2332 switch (sopt->sopt_name) {
2333 case TCP_NODELAY:
2334 opt = TF_NODELAY;
2335 break;
2336 case TCP_NOOPT:
2337 opt = TF_NOOPT;
2338 break;
2339 case TCP_NOPUSH:
2340 opt = TF_NOPUSH;
2341 break;
2342 default:
2343 opt = 0; /* dead code to fool gcc */
2344 break;
2345 }
2346
2347 if (optval) {
2348 tp->t_flags |= opt;
2349 } else {
2350 tp->t_flags &= ~opt;
2351 }
2352 break;
2353 case TCP_RXT_FINDROP:
2354 case TCP_NOTIMEWAIT:
2355 error = sooptcopyin(sopt, &optval, sizeof optval,
2356 sizeof optval);
2357 if (error) {
2358 break;
2359 }
2360 switch (sopt->sopt_name) {
2361 case TCP_RXT_FINDROP:
2362 opt = TF_RXTFINDROP;
2363 break;
2364 case TCP_NOTIMEWAIT:
2365 opt = TF_NOTIMEWAIT;
2366 break;
2367 default:
2368 opt = 0;
2369 break;
2370 }
2371 if (optval) {
2372 tp->t_flagsext |= opt;
2373 } else {
2374 tp->t_flagsext &= ~opt;
2375 }
2376 break;
2377 case TCP_MEASURE_SND_BW:
2378 error = sooptcopyin(sopt, &optval, sizeof optval,
2379 sizeof optval);
2380 if (error) {
2381 break;
2382 }
2383 opt = TF_MEASURESNDBW;
2384 if (optval) {
2385 if (tp->t_bwmeas == NULL) {
2386 tp->t_bwmeas = tcp_bwmeas_alloc(tp);
2387 if (tp->t_bwmeas == NULL) {
2388 error = ENOMEM;
2389 break;
2390 }
2391 }
2392 tp->t_flagsext |= opt;
2393 } else {
2394 tp->t_flagsext &= ~opt;
2395 /* Reset snd bw measurement state */
2396 tp->t_flagsext &= ~(TF_BWMEAS_INPROGRESS);
2397 if (tp->t_bwmeas != NULL) {
2398 tcp_bwmeas_free(tp);
2399 }
2400 }
2401 break;
2402 case TCP_MEASURE_BW_BURST: {
2403 struct tcp_measure_bw_burst in;
2404 uint32_t minpkts, maxpkts;
2405 bzero(&in, sizeof(in));
2406
2407 error = sooptcopyin(sopt, &in, sizeof(in),
2408 sizeof(in));
2409 if (error) {
2410 break;
2411 }
2412 if ((tp->t_flagsext & TF_MEASURESNDBW) == 0 ||
2413 tp->t_bwmeas == NULL) {
2414 error = EINVAL;
2415 break;
2416 }
2417 minpkts = (in.min_burst_size != 0) ? in.min_burst_size :
2418 tp->t_bwmeas->bw_minsizepkts;
2419 maxpkts = (in.max_burst_size != 0) ? in.max_burst_size :
2420 tp->t_bwmeas->bw_maxsizepkts;
2421 if (minpkts > maxpkts) {
2422 error = EINVAL;
2423 break;
2424 }
2425 tp->t_bwmeas->bw_minsizepkts = minpkts;
2426 tp->t_bwmeas->bw_maxsizepkts = maxpkts;
2427 tp->t_bwmeas->bw_minsize = (minpkts * tp->t_maxseg);
2428 tp->t_bwmeas->bw_maxsize = (maxpkts * tp->t_maxseg);
2429 break;
2430 }
2431 case TCP_MAXSEG:
2432 error = sooptcopyin(sopt, &optval, sizeof optval,
2433 sizeof optval);
2434 if (error) {
2435 break;
2436 }
2437
2438 if (optval > 0 && optval <= tp->t_maxseg &&
2439 optval + 40 >= tcp_minmss) {
2440 tp->t_maxseg = optval;
2441 } else {
2442 error = EINVAL;
2443 }
2444 break;
2445
2446 case TCP_KEEPALIVE:
2447 error = sooptcopyin(sopt, &optval, sizeof optval,
2448 sizeof optval);
2449 if (error) {
2450 break;
2451 }
2452 if (optval < 0 || optval > UINT32_MAX / TCP_RETRANSHZ) {
2453 error = EINVAL;
2454 } else {
2455 tp->t_keepidle = optval * TCP_RETRANSHZ;
2456 /* reset the timer to new value */
2457 if (TCPS_HAVEESTABLISHED(tp->t_state)) {
2458 tp->t_timer[TCPT_KEEP] = tcp_offset_from_start(tp,
2459 TCP_CONN_KEEPIDLE(tp));
2460 tcp_check_timer_state(tp);
2461 }
2462 }
2463 break;
2464
2465 case TCP_CONNECTIONTIMEOUT:
2466 error = sooptcopyin(sopt, &optval, sizeof optval,
2467 sizeof optval);
2468 if (error) {
2469 break;
2470 }
2471 if (optval < 0 || optval > UINT32_MAX / TCP_RETRANSHZ) {
2472 error = EINVAL;
2473 } else {
2474 tp->t_keepinit = optval * TCP_RETRANSHZ;
2475 if (tp->t_state == TCPS_SYN_RECEIVED ||
2476 tp->t_state == TCPS_SYN_SENT) {
2477 tp->t_timer[TCPT_KEEP] = tcp_offset_from_start(tp,
2478 TCP_CONN_KEEPINIT(tp));
2479 tcp_check_timer_state(tp);
2480 }
2481 }
2482 break;
2483
2484 case TCP_KEEPINTVL:
2485 error = sooptcopyin(sopt, &optval, sizeof(optval),
2486 sizeof(optval));
2487 if (error) {
2488 break;
2489 }
2490 if (optval < 0 || optval > UINT32_MAX / TCP_RETRANSHZ) {
2491 error = EINVAL;
2492 } else {
2493 tp->t_keepintvl = optval * TCP_RETRANSHZ;
2494 if (tp->t_state == TCPS_FIN_WAIT_2 &&
2495 TCP_CONN_MAXIDLE(tp) > 0) {
2496 tp->t_timer[TCPT_2MSL] = tcp_offset_from_start(tp,
2497 TCP_CONN_MAXIDLE(tp));
2498 tcp_check_timer_state(tp);
2499 }
2500 }
2501 break;
2502
2503 case TCP_KEEPCNT:
2504 error = sooptcopyin(sopt, &optval, sizeof(optval),
2505 sizeof(optval));
2506 if (error) {
2507 break;
2508 }
2509 if (optval < 0 || optval > INT32_MAX) {
2510 error = EINVAL;
2511 } else {
2512 tp->t_keepcnt = optval;
2513 if (tp->t_state == TCPS_FIN_WAIT_2 &&
2514 TCP_CONN_MAXIDLE(tp) > 0) {
2515 tp->t_timer[TCPT_2MSL] = tcp_offset_from_start(tp,
2516 TCP_CONN_MAXIDLE(tp));
2517 tcp_check_timer_state(tp);
2518 }
2519 }
2520 break;
2521
2522 case TCP_KEEPALIVE_OFFLOAD:
2523 if ((error = priv_check_cred(kauth_cred_get(),
2524 PRIV_NETINET_TCP_KA_OFFLOAD, 0)) != 0) {
2525 break;
2526 }
2527 error = sooptcopyin(sopt, &optval, sizeof(optval),
2528 sizeof(optval));
2529 if (error) {
2530 break;
2531 }
2532 if (optval < 0 || optval > INT32_MAX) {
2533 error = EINVAL;
2534 break;
2535 }
2536 if (optval != 0) {
2537 error = tcp_set_keep_alive_offload(so,
2538 sopt->sopt_p);
2539 } else {
2540 tcp_clear_keep_alive_offload(so);
2541 }
2542 break;
2543
2544 case PERSIST_TIMEOUT:
2545 error = sooptcopyin(sopt, &optval, sizeof optval,
2546 sizeof optval);
2547 if (error) {
2548 break;
2549 }
2550 if (optval < 0) {
2551 error = EINVAL;
2552 } else {
2553 tp->t_persist_timeout = optval * TCP_RETRANSHZ;
2554 }
2555 break;
2556 case TCP_RXT_CONNDROPTIME:
2557 error = sooptcopyin(sopt, &optval, sizeof(optval),
2558 sizeof(optval));
2559 if (error) {
2560 break;
2561 }
2562 if (optval < 0) {
2563 error = EINVAL;
2564 } else {
2565 tp->t_rxt_conndroptime = optval * TCP_RETRANSHZ;
2566 }
2567 break;
2568 case TCP_NOTSENT_LOWAT:
2569 error = sooptcopyin(sopt, &optval, sizeof(optval),
2570 sizeof(optval));
2571 if (error) {
2572 break;
2573 }
2574 if (optval < 0) {
2575 error = EINVAL;
2576 break;
2577 } else {
2578 if (optval == 0) {
2579 so->so_flags &= ~(SOF_NOTSENT_LOWAT);
2580 tp->t_notsent_lowat = 0;
2581 } else {
2582 so->so_flags |= SOF_NOTSENT_LOWAT;
2583 tp->t_notsent_lowat = optval;
2584 }
2585 }
2586 break;
2587 case TCP_ADAPTIVE_READ_TIMEOUT:
2588 error = sooptcopyin(sopt, &optval, sizeof(optval),
2589 sizeof(optval));
2590 if (error) {
2591 break;
2592 }
2593 if (optval < 0 ||
2594 optval > TCP_ADAPTIVE_TIMEOUT_MAX) {
2595 error = EINVAL;
2596 break;
2597 } else if (optval == 0) {
2598 tp->t_adaptive_rtimo = 0;
2599 tcp_keepalive_reset(tp);
2600
2601 if (tp->t_mpsub) {
2602 mptcp_reset_keepalive(tp);
2603 }
2604 } else {
2605 tp->t_adaptive_rtimo = (uint8_t)optval;
2606 }
2607 break;
2608 case TCP_ADAPTIVE_WRITE_TIMEOUT:
2609 error = sooptcopyin(sopt, &optval, sizeof(optval),
2610 sizeof(optval));
2611 if (error) {
2612 break;
2613 }
2614 if (optval < 0 ||
2615 optval > TCP_ADAPTIVE_TIMEOUT_MAX) {
2616 error = EINVAL;
2617 break;
2618 } else {
2619 tp->t_adaptive_wtimo = (uint8_t)optval;
2620 }
2621 break;
2622 case TCP_SENDMOREACKS:
2623 error = sooptcopyin(sopt, &optval, sizeof(optval),
2624 sizeof(optval));
2625 if (error) {
2626 break;
2627 }
2628 if (optval < 0 || optval > 1) {
2629 error = EINVAL;
2630 } else if (optval == 0) {
2631 tp->t_flagsext &= ~(TF_QUICKACK);
2632 } else {
2633 tp->t_flagsext |= TF_QUICKACK;
2634 }
2635 break;
2636 case TCP_DISABLE_BLACKHOLE_DETECTION:
2637 error = sooptcopyin(sopt, &optval, sizeof(optval),
2638 sizeof(optval));
2639 if (error) {
2640 break;
2641 }
2642 if (optval < 0 || optval > 1) {
2643 error = EINVAL;
2644 } else if (optval == 0) {
2645 tp->t_flagsext &= ~TF_NOBLACKHOLE_DETECTION;
2646 } else {
2647 tp->t_flagsext |= TF_NOBLACKHOLE_DETECTION;
2648 if ((tp->t_flags & TF_BLACKHOLE) &&
2649 tp->t_pmtud_saved_maxopd > 0) {
2650 tcp_pmtud_revert_segment_size(tp);
2651 }
2652 }
2653 break;
2654 case TCP_FASTOPEN:
2655 if (!(tcp_fastopen & TCP_FASTOPEN_SERVER)) {
2656 error = ENOTSUP;
2657 break;
2658 }
2659
2660 error = sooptcopyin(sopt, &optval, sizeof(optval),
2661 sizeof(optval));
2662 if (error) {
2663 break;
2664 }
2665 if (optval < 0 || optval > 1) {
2666 error = EINVAL;
2667 break;
2668 }
2669 if (tp->t_state != TCPS_LISTEN) {
2670 error = EINVAL;
2671 break;
2672 }
2673 if (optval) {
2674 tp->t_flagsext |= TF_FASTOPEN;
2675 } else {
2676 tcp_disable_tfo(tp);
2677 }
2678 break;
2679 case TCP_FASTOPEN_FORCE_ENABLE:
2680 error = sooptcopyin(sopt, &optval, sizeof(optval),
2681 sizeof(optval));
2682
2683 if (error) {
2684 break;
2685 }
2686 if (optval < 0 || optval > 1) {
2687 error = EINVAL;
2688 break;
2689 }
2690
2691 if (tp->t_state != TCPS_CLOSED) {
2692 error = EINVAL;
2693 break;
2694 }
2695 if (optval) {
2696 tp->t_flagsext |= TF_FASTOPEN_FORCE_ENABLE;
2697 } else {
2698 tp->t_flagsext &= ~TF_FASTOPEN_FORCE_ENABLE;
2699 }
2700
2701 break;
2702 case TCP_ENABLE_ECN:
2703 error = sooptcopyin(sopt, &optval, sizeof optval,
2704 sizeof optval);
2705 if (error) {
2706 break;
2707 }
2708 if (optval) {
2709 tp->ecn_flags |= TE_ECN_MODE_ENABLE;
2710 tp->ecn_flags &= ~TE_ECN_MODE_DISABLE;
2711 } else {
2712 tp->ecn_flags &= ~TE_ECN_MODE_ENABLE;
2713 tp->ecn_flags |= TE_ECN_MODE_DISABLE;
2714 }
2715 break;
2716 case TCP_ECN_MODE:
2717 error = sooptcopyin(sopt, &optval, sizeof optval,
2718 sizeof optval);
2719 if (error) {
2720 break;
2721 }
2722 if (optval == ECN_MODE_DEFAULT) {
2723 tp->ecn_flags &= ~TE_ECN_MODE_ENABLE;
2724 tp->ecn_flags &= ~TE_ECN_MODE_DISABLE;
2725 } else if (optval == ECN_MODE_ENABLE) {
2726 tp->ecn_flags |= TE_ECN_MODE_ENABLE;
2727 tp->ecn_flags &= ~TE_ECN_MODE_DISABLE;
2728 } else if (optval == ECN_MODE_DISABLE) {
2729 tp->ecn_flags &= ~TE_ECN_MODE_ENABLE;
2730 tp->ecn_flags |= TE_ECN_MODE_DISABLE;
2731 } else {
2732 error = EINVAL;
2733 }
2734 break;
2735 case TCP_ENABLE_L4S:
2736 error = sooptcopyin(sopt, &optval, sizeof optval,
2737 sizeof optval);
2738 if (error) {
2739 break;
2740 }
2741 if (optval < 0 || optval > 1) {
2742 error = EINVAL;
2743 break;
2744 }
2745 if (optval == 1) {
2746 tp->t_flagsext |= TF_L4S_ENABLED;
2747 tp->t_flagsext &= ~TF_L4S_DISABLED;
2748 } else {
2749 tp->t_flagsext &= ~TF_L4S_ENABLED;
2750 tp->t_flagsext |= TF_L4S_DISABLED;
2751 }
2752 tcp_set_foreground_cc(so);
2753 break;
2754 case TCP_NOTIFY_ACKNOWLEDGEMENT:
2755 error = sooptcopyin(sopt, &optval,
2756 sizeof(optval), sizeof(optval));
2757 if (error) {
2758 break;
2759 }
2760 if (optval <= 0) {
2761 error = EINVAL;
2762 break;
2763 }
2764 if (tp->t_notify_ack_count >= TCP_MAX_NOTIFY_ACK) {
2765 error = ETOOMANYREFS;
2766 break;
2767 }
2768
2769 /*
2770 * validate that the given marker id is not
2771 * a duplicate to avoid ambiguity
2772 */
2773 if ((error = tcp_notify_ack_id_valid(tp, so,
2774 optval)) != 0) {
2775 break;
2776 }
2777 error = tcp_add_notify_ack_marker(tp, optval);
2778 break;
2779 case SO_FLUSH:
2780 if ((error = sooptcopyin(sopt, &optval, sizeof(optval),
2781 sizeof(optval))) != 0) {
2782 break;
2783 }
2784
2785 error = inp_flush(inp, optval);
2786 break;
2787
2788 case SO_TRAFFIC_MGT_BACKGROUND:
2789 if ((error = sooptcopyin(sopt, &optval, sizeof(optval),
2790 sizeof(optval))) != 0) {
2791 break;
2792 }
2793
2794 if (optval) {
2795 socket_set_traffic_mgt_flags_locked(so,
2796 TRAFFIC_MGT_SO_BACKGROUND);
2797 } else {
2798 socket_clear_traffic_mgt_flags_locked(so,
2799 TRAFFIC_MGT_SO_BACKGROUND);
2800 }
2801 break;
2802 case TCP_RXT_MINIMUM_TIMEOUT:
2803 error = sooptcopyin(sopt, &optval, sizeof(optval),
2804 sizeof(optval));
2805 if (error) {
2806 break;
2807 }
2808 if (optval < 0) {
2809 error = EINVAL;
2810 break;
2811 }
2812 if (optval == 0) {
2813 tp->t_rxt_minimum_timeout = 0;
2814 } else {
2815 tp->t_rxt_minimum_timeout = min(optval,
2816 TCP_RXT_MINIMUM_TIMEOUT_LIMIT);
2817 /* convert to milliseconds */
2818 tp->t_rxt_minimum_timeout *= TCP_RETRANSHZ;
2819 }
2820 break;
2821 default:
2822 error = ENOPROTOOPT;
2823 break;
2824 }
2825 break;
2826
2827 case SOPT_GET:
2828 switch (sopt->sopt_name) {
2829 case TCP_NODELAY:
2830 optval = tp->t_flags & TF_NODELAY;
2831 break;
2832 case TCP_MAXSEG:
2833 optval = tp->t_maxseg;
2834 break;
2835 case TCP_KEEPALIVE:
2836 if (tp->t_keepidle > 0) {
2837 optval = tp->t_keepidle / TCP_RETRANSHZ;
2838 } else {
2839 optval = tcp_keepidle / TCP_RETRANSHZ;
2840 }
2841 break;
2842 case TCP_KEEPINTVL:
2843 if (tp->t_keepintvl > 0) {
2844 optval = tp->t_keepintvl / TCP_RETRANSHZ;
2845 } else {
2846 optval = tcp_keepintvl / TCP_RETRANSHZ;
2847 }
2848 break;
2849 case TCP_KEEPCNT:
2850 if (tp->t_keepcnt > 0) {
2851 optval = tp->t_keepcnt;
2852 } else {
2853 optval = tcp_keepcnt;
2854 }
2855 break;
2856 case TCP_KEEPALIVE_OFFLOAD:
2857 optval = !!(inp->inp_flags2 & INP2_KEEPALIVE_OFFLOAD);
2858 break;
2859 case TCP_NOOPT:
2860 optval = tp->t_flags & TF_NOOPT;
2861 break;
2862 case TCP_NOPUSH:
2863 optval = tp->t_flags & TF_NOPUSH;
2864 break;
2865 case TCP_ENABLE_ECN:
2866 optval = (tp->ecn_flags & TE_ECN_MODE_ENABLE) ? 1 : 0;
2867 break;
2868 case TCP_ECN_MODE:
2869 if (tp->ecn_flags & TE_ECN_MODE_ENABLE) {
2870 optval = ECN_MODE_ENABLE;
2871 } else if (tp->ecn_flags & TE_ECN_MODE_DISABLE) {
2872 optval = ECN_MODE_DISABLE;
2873 } else {
2874 optval = ECN_MODE_DEFAULT;
2875 }
2876 break;
2877 case TCP_ENABLE_L4S:
2878 optval = (tp->t_flagsext & TF_L4S_ENABLED) ? 1 : 0;
2879 break;
2880 case TCP_CONNECTIONTIMEOUT:
2881 optval = tp->t_keepinit / TCP_RETRANSHZ;
2882 break;
2883 case PERSIST_TIMEOUT:
2884 optval = tp->t_persist_timeout / TCP_RETRANSHZ;
2885 break;
2886 case TCP_RXT_CONNDROPTIME:
2887 optval = tp->t_rxt_conndroptime / TCP_RETRANSHZ;
2888 break;
2889 case TCP_RXT_FINDROP:
2890 optval = tp->t_flagsext & TF_RXTFINDROP;
2891 break;
2892 case TCP_NOTIMEWAIT:
2893 optval = (tp->t_flagsext & TF_NOTIMEWAIT) ? 1 : 0;
2894 break;
2895 case TCP_FASTOPEN:
2896 if (tp->t_state != TCPS_LISTEN ||
2897 !(tcp_fastopen & TCP_FASTOPEN_SERVER)) {
2898 error = ENOTSUP;
2899 break;
2900 }
2901 optval = !!TFO_ENABLED(tp);
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_QUICKACK) {
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 initial send and receive window
3009 * sizes, respectively.
3010 */
3011 uint32_t tcp_sendspace = 128 * 1024;
3012 uint32_t tcp_recvspace = 128 * 1024;
3013
3014 /* During attach, the size of socket buffer allocated is limited to
3015 * sb_max in sbreserve. Disallow setting the tcp send and recv space
3016 * to be more than sb_max because that will cause tcp_attach to fail
3017 * (see radar 5713060)
3018 */
3019 static int
sysctl_tcp_sospace(struct sysctl_oid * oidp,__unused void * arg1,int arg2,struct sysctl_req * req)3020 sysctl_tcp_sospace(struct sysctl_oid *oidp, __unused void *arg1,
3021 int arg2, struct sysctl_req *req)
3022 {
3023 #pragma unused(arg2)
3024 u_int32_t new_value = 0, *space_p = NULL;
3025 int changed = 0, error = 0;
3026
3027 switch (oidp->oid_number) {
3028 case TCPCTL_SENDSPACE:
3029 space_p = &tcp_sendspace;
3030 break;
3031 case TCPCTL_RECVSPACE:
3032 space_p = &tcp_recvspace;
3033 break;
3034 default:
3035 return EINVAL;
3036 }
3037 error = sysctl_io_number(req, *space_p, sizeof(u_int32_t),
3038 &new_value, &changed);
3039 if (changed) {
3040 if (new_value > 0 && new_value <= sb_max) {
3041 *space_p = new_value;
3042 SYSCTL_SKMEM_UPDATE_AT_OFFSET(arg2, new_value);
3043 } else {
3044 error = ERANGE;
3045 }
3046 }
3047 return error;
3048 }
3049
3050 #if SYSCTL_SKMEM
3051 SYSCTL_PROC(_net_inet_tcp, TCPCTL_SENDSPACE, sendspace,
3052 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED | CTLFLAG_KERN, &tcp_sendspace,
3053 offsetof(skmem_sysctl, tcp.sendspace), sysctl_tcp_sospace,
3054 "IU", "Maximum outgoing TCP datagram size");
3055 SYSCTL_PROC(_net_inet_tcp, TCPCTL_RECVSPACE, recvspace,
3056 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED | CTLFLAG_KERN, &tcp_recvspace,
3057 offsetof(skmem_sysctl, tcp.recvspace), sysctl_tcp_sospace,
3058 "IU", "Maximum incoming TCP datagram size");
3059 #else /* SYSCTL_SKMEM */
3060 SYSCTL_PROC(_net_inet_tcp, TCPCTL_SENDSPACE, sendspace,
3061 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED | CTLFLAG_KERN,
3062 &tcp_sendspace, 0, &sysctl_tcp_sospace, "IU", "Maximum outgoing TCP datagram size");
3063 SYSCTL_PROC(_net_inet_tcp, TCPCTL_RECVSPACE, recvspace,
3064 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED | CTLFLAG_KERN,
3065 &tcp_recvspace, 0, &sysctl_tcp_sospace, "IU", "Maximum incoming TCP datagram size");
3066 #endif /* SYSCTL_SKMEM */
3067
3068 /*
3069 * Attach TCP protocol to socket, allocating
3070 * internet protocol control block, tcp control block,
3071 * bufer space, and entering LISTEN state if to accept connections.
3072 *
3073 * Returns: 0 Success
3074 * in_pcballoc:ENOBUFS
3075 * in_pcballoc:ENOMEM
3076 * in_pcballoc:??? [IPSEC specific]
3077 * soreserve:ENOBUFS
3078 */
3079 static int
tcp_attach(struct socket * so,struct proc * p)3080 tcp_attach(struct socket *so, struct proc *p)
3081 {
3082 struct tcpcb *tp;
3083 struct inpcb *inp;
3084 int error;
3085 int isipv6 = SOCK_CHECK_DOM(so, PF_INET6) != 0;
3086
3087 if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
3088 error = soreserve(so, tcp_sendspace, tcp_recvspace);
3089 if (error) {
3090 return error;
3091 }
3092 }
3093
3094 error = in_pcballoc(so, &tcbinfo, p);
3095 if (error) {
3096 return error;
3097 }
3098
3099 inp = sotoinpcb(so);
3100
3101 if (so->so_snd.sb_preconn_hiwat == 0) {
3102 soreserve_preconnect(so, 2048);
3103 }
3104
3105 if ((so->so_rcv.sb_flags & SB_USRSIZE) == 0) {
3106 so->so_rcv.sb_flags |= SB_AUTOSIZE;
3107 }
3108 if ((so->so_snd.sb_flags & SB_USRSIZE) == 0) {
3109 so->so_snd.sb_flags |= SB_AUTOSIZE;
3110 }
3111
3112 if (isipv6) {
3113 inp->inp_vflag |= INP_IPV6;
3114 inp->in6p_hops = -1; /* use kernel default */
3115 } else {
3116 inp->inp_vflag |= INP_IPV4;
3117 }
3118 tp = tcp_newtcpcb(inp);
3119 if (tp == NULL) {
3120 short nofd = so->so_state & SS_NOFDREF; /* XXX */
3121
3122 so->so_state &= ~SS_NOFDREF; /* don't free the socket yet */
3123 if (isipv6) {
3124 in6_pcbdetach(inp);
3125 } else {
3126 in_pcbdetach(inp);
3127 }
3128 so->so_state |= nofd;
3129 return ENOBUFS;
3130 }
3131 if (nstat_collect) {
3132 nstat_tcp_new_pcb(inp);
3133 }
3134 TCP_LOG_STATE(tp, TCPS_CLOSED);
3135 tp->t_state = TCPS_CLOSED;
3136 return 0;
3137 }
3138
3139 /*
3140 * Initiate (or continue) disconnect.
3141 * If embryonic state, just send reset (once).
3142 * If in ``let data drain'' option and linger null, just drop.
3143 * Otherwise (hard), mark socket disconnecting and drop
3144 * current input data; switch states based on user close, and
3145 * send segment to peer (with FIN).
3146 */
3147 static struct tcpcb *
tcp_disconnect(struct tcpcb * tp)3148 tcp_disconnect(struct tcpcb *tp)
3149 {
3150 struct socket *so = tp->t_inpcb->inp_socket;
3151
3152 if (so->so_rcv.sb_cc != 0 || tp->t_reassqlen != 0 ||
3153 so->so_flags1 & SOF1_DEFUNCTINPROG) {
3154 return tcp_drop(tp, 0);
3155 }
3156
3157 if (tp->t_state < TCPS_ESTABLISHED) {
3158 tp = tcp_close(tp);
3159 } else if ((so->so_options & SO_LINGER) && so->so_linger == 0) {
3160 tp = tcp_drop(tp, 0);
3161 } else {
3162 soisdisconnecting(so);
3163 sbflush(&so->so_rcv);
3164 tp = tcp_usrclosed(tp);
3165 #if MPTCP
3166 /* A reset has been sent but socket exists, do not send FIN */
3167 if ((so->so_flags & SOF_MP_SUBFLOW) &&
3168 (tp) && (tp->t_mpflags & TMPF_RESET)) {
3169 return tp;
3170 }
3171 #endif
3172 if (tp) {
3173 (void) tcp_output(tp);
3174 }
3175 }
3176 return tp;
3177 }
3178
3179 /*
3180 * User issued close, and wish to trail through shutdown states:
3181 * if never received SYN, just forget it. If got a SYN from peer,
3182 * but haven't sent FIN, then go to FIN_WAIT_1 state to send peer a FIN.
3183 * If already got a FIN from peer, then almost done; go to LAST_ACK
3184 * state. In all other cases, have already sent FIN to peer (e.g.
3185 * after PRU_SHUTDOWN), and just have to play tedious game waiting
3186 * for peer to send FIN or not respond to keep-alives, etc.
3187 * We can let the user exit from the close as soon as the FIN is acked.
3188 */
3189 static struct tcpcb *
tcp_usrclosed(struct tcpcb * tp)3190 tcp_usrclosed(struct tcpcb *tp)
3191 {
3192 switch (tp->t_state) {
3193 case TCPS_CLOSED:
3194 case TCPS_LISTEN:
3195 case TCPS_SYN_SENT:
3196 tp = tcp_close(tp);
3197 break;
3198
3199 case TCPS_SYN_RECEIVED:
3200 tp->t_flags |= TF_NEEDFIN;
3201 break;
3202
3203 case TCPS_ESTABLISHED:
3204 DTRACE_TCP4(state__change, void, NULL,
3205 struct inpcb *, tp->t_inpcb,
3206 struct tcpcb *, tp,
3207 int32_t, TCPS_FIN_WAIT_1);
3208 TCP_LOG_STATE(tp, TCPS_FIN_WAIT_1);
3209 tp->t_state = TCPS_FIN_WAIT_1;
3210 TCP_LOG_CONNECTION_SUMMARY(tp);
3211 break;
3212
3213 case TCPS_CLOSE_WAIT:
3214 DTRACE_TCP4(state__change, void, NULL,
3215 struct inpcb *, tp->t_inpcb,
3216 struct tcpcb *, tp,
3217 int32_t, TCPS_LAST_ACK);
3218 TCP_LOG_STATE(tp, TCPS_LAST_ACK);
3219 tp->t_state = TCPS_LAST_ACK;
3220 TCP_LOG_CONNECTION_SUMMARY(tp);
3221 break;
3222 }
3223 if (tp && tp->t_state >= TCPS_FIN_WAIT_2) {
3224 soisdisconnected(tp->t_inpcb->inp_socket);
3225 /* To prevent the connection hanging in FIN_WAIT_2 forever. */
3226 if (tp->t_state == TCPS_FIN_WAIT_2) {
3227 tcp_set_finwait_timeout(tp);
3228 }
3229 }
3230 return tp;
3231 }
3232
3233 void
tcp_in_cksum_stats(u_int32_t len)3234 tcp_in_cksum_stats(u_int32_t len)
3235 {
3236 tcpstat.tcps_rcv_swcsum++;
3237 tcpstat.tcps_rcv_swcsum_bytes += len;
3238 }
3239
3240 void
tcp_out_cksum_stats(u_int32_t len)3241 tcp_out_cksum_stats(u_int32_t len)
3242 {
3243 tcpstat.tcps_snd_swcsum++;
3244 tcpstat.tcps_snd_swcsum_bytes += len;
3245 }
3246
3247 void
tcp_in6_cksum_stats(u_int32_t len)3248 tcp_in6_cksum_stats(u_int32_t len)
3249 {
3250 tcpstat.tcps_rcv6_swcsum++;
3251 tcpstat.tcps_rcv6_swcsum_bytes += len;
3252 }
3253
3254 void
tcp_out6_cksum_stats(u_int32_t len)3255 tcp_out6_cksum_stats(u_int32_t len)
3256 {
3257 tcpstat.tcps_snd6_swcsum++;
3258 tcpstat.tcps_snd6_swcsum_bytes += len;
3259 }
3260
3261 int
tcp_get_mpkl_send_info(struct mbuf * control,struct so_mpkl_send_info * mpkl_send_info)3262 tcp_get_mpkl_send_info(struct mbuf *control,
3263 struct so_mpkl_send_info *mpkl_send_info)
3264 {
3265 struct cmsghdr *cm;
3266
3267 if (control == NULL || mpkl_send_info == NULL) {
3268 return EINVAL;
3269 }
3270
3271 for (cm = M_FIRST_CMSGHDR(control); cm;
3272 cm = M_NXT_CMSGHDR(control, cm)) {
3273 if (cm->cmsg_len < sizeof(struct cmsghdr) ||
3274 cm->cmsg_len > control->m_len) {
3275 return EINVAL;
3276 }
3277 if (cm->cmsg_level != SOL_SOCKET ||
3278 cm->cmsg_type != SCM_MPKL_SEND_INFO) {
3279 continue;
3280 }
3281 if (cm->cmsg_len != CMSG_LEN(sizeof(struct so_mpkl_send_info))) {
3282 return EINVAL;
3283 }
3284 memcpy(mpkl_send_info, CMSG_DATA(cm),
3285 sizeof(struct so_mpkl_send_info));
3286 return 0;
3287 }
3288 return ENOMSG;
3289 }
3290
3291 /*
3292 * tcp socket options.
3293 *
3294 * The switch statement below does nothing at runtime, as it serves as a
3295 * compile time check to ensure that all of the tcp socket options are
3296 * unique. This works as long as this routine gets updated each time a
3297 * new tcp socket option gets added.
3298 *
3299 * Any failures at compile time indicates duplicated tcp socket option
3300 * values.
3301 */
3302 static __attribute__((unused)) void
tcpsockopt_cassert(void)3303 tcpsockopt_cassert(void)
3304 {
3305 /*
3306 * This is equivalent to static_assert() and the compiler wouldn't
3307 * generate any instructions, thus for compile time only.
3308 */
3309 switch ((int)0) {
3310 case 0:
3311
3312 /* bsd/netinet/tcp.h */
3313 case TCP_NODELAY:
3314 case TCP_MAXSEG:
3315 case TCP_NOPUSH:
3316 case TCP_NOOPT:
3317 case TCP_KEEPALIVE:
3318 case TCP_CONNECTIONTIMEOUT:
3319 case PERSIST_TIMEOUT:
3320 case TCP_RXT_CONNDROPTIME:
3321 case TCP_RXT_FINDROP:
3322 case TCP_KEEPINTVL:
3323 case TCP_KEEPCNT:
3324 case TCP_SENDMOREACKS:
3325 case TCP_ENABLE_ECN:
3326 case TCP_FASTOPEN:
3327 case TCP_CONNECTION_INFO:
3328 case TCP_NOTSENT_LOWAT:
3329
3330 /* bsd/netinet/tcp_private.h */
3331 case TCP_INFO:
3332 case TCP_MEASURE_SND_BW:
3333 case TCP_MEASURE_BW_BURST:
3334 case TCP_PEER_PID:
3335 case TCP_ADAPTIVE_READ_TIMEOUT:
3336 case TCP_OPTION_UNUSED_0:
3337 case TCP_ADAPTIVE_WRITE_TIMEOUT:
3338 case TCP_NOTIMEWAIT:
3339 case TCP_DISABLE_BLACKHOLE_DETECTION:
3340 case TCP_ECN_MODE:
3341 case TCP_KEEPALIVE_OFFLOAD:
3342 ;
3343 }
3344 }
3345