1/* 2 * Copyright (c) 2000-2014 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, 1990, 1993, 1995 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 * @(#)tcp_subr.c 8.2 (Berkeley) 5/24/95 61 * $FreeBSD: src/sys/netinet/tcp_subr.c,v 1.73.2.22 2001/08/22 00:59:12 silby Exp $ 62 */ 63/* 64 * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce 65 * support for mandatory and extensible security protections. This notice 66 * is included in support of clause 2.2 (b) of the Apple Public License, 67 * Version 2.0. 68 */ 69 70#include <sys/param.h> 71#include <sys/systm.h> 72#include <sys/callout.h> 73#include <sys/kernel.h> 74#include <sys/sysctl.h> 75#include <sys/malloc.h> 76#include <sys/mbuf.h> 77#include <sys/domain.h> 78#include <sys/proc.h> 79#include <sys/kauth.h> 80#include <sys/socket.h> 81#include <sys/socketvar.h> 82#include <sys/protosw.h> 83#include <sys/random.h> 84#include <sys/syslog.h> 85#include <sys/mcache.h> 86#include <kern/locks.h> 87#include <kern/zalloc.h> 88 89#include <dev/random/randomdev.h> 90 91#include <net/route.h> 92#include <net/if.h> 93#include <net/content_filter.h> 94 95#define tcp_minmssoverload fring 96#define _IP_VHL 97#include <netinet/in.h> 98#include <netinet/in_systm.h> 99#include <netinet/ip.h> 100#include <netinet/ip_icmp.h> 101#if INET6 102#include <netinet/ip6.h> 103#endif 104#include <netinet/in_pcb.h> 105#if INET6 106#include <netinet6/in6_pcb.h> 107#endif 108#include <netinet/in_var.h> 109#include <netinet/ip_var.h> 110#include <netinet/icmp_var.h> 111#if INET6 112#include <netinet6/ip6_var.h> 113#endif 114#include <netinet/tcp.h> 115#include <netinet/tcp_fsm.h> 116#include <netinet/tcp_seq.h> 117#include <netinet/tcp_timer.h> 118#include <netinet/tcp_var.h> 119#include <netinet/tcp_cc.h> 120#include <kern/thread_call.h> 121 122#if INET6 123#include <netinet6/tcp6_var.h> 124#endif 125#include <netinet/tcpip.h> 126#if TCPDEBUG 127#include <netinet/tcp_debug.h> 128#endif 129#include <netinet6/ip6protosw.h> 130 131#if IPSEC 132#include <netinet6/ipsec.h> 133#if INET6 134#include <netinet6/ipsec6.h> 135#endif 136#endif /*IPSEC*/ 137 138#if NECP 139#include <net/necp.h> 140#endif /* NECP */ 141 142#undef tcp_minmssoverload 143 144#if CONFIG_MACF_NET 145#include <security/mac_framework.h> 146#endif /* MAC_NET */ 147 148#include <libkern/crypto/md5.h> 149#include <sys/kdebug.h> 150#include <mach/sdt.h> 151 152#include <netinet/lro_ext.h> 153 154#define DBG_FNC_TCP_CLOSE NETDBG_CODE(DBG_NETTCP, ((5 << 8) | 2)) 155 156extern int tcp_lq_overflow; 157 158extern struct tcptimerlist tcp_timer_list; 159extern struct tcptailq tcp_tw_tailq; 160 161int tcp_mssdflt = TCP_MSS; 162SYSCTL_INT(_net_inet_tcp, TCPCTL_MSSDFLT, mssdflt, CTLFLAG_RW | CTLFLAG_LOCKED, 163 &tcp_mssdflt , 0, "Default TCP Maximum Segment Size"); 164 165#if INET6 166int tcp_v6mssdflt = TCP6_MSS; 167SYSCTL_INT(_net_inet_tcp, TCPCTL_V6MSSDFLT, v6mssdflt, 168 CTLFLAG_RW | CTLFLAG_LOCKED, &tcp_v6mssdflt , 0, 169 "Default TCP Maximum Segment Size for IPv6"); 170#endif 171 172extern int tcp_do_autorcvbuf; 173 174/* 175 * Minimum MSS we accept and use. This prevents DoS attacks where 176 * we are forced to a ridiculous low MSS like 20 and send hundreds 177 * of packets instead of one. The effect scales with the available 178 * bandwidth and quickly saturates the CPU and network interface 179 * with packet generation and sending. Set to zero to disable MINMSS 180 * checking. This setting prevents us from sending too small packets. 181 */ 182int tcp_minmss = TCP_MINMSS; 183SYSCTL_INT(_net_inet_tcp, OID_AUTO, minmss, CTLFLAG_RW | CTLFLAG_LOCKED, 184 &tcp_minmss , 0, "Minmum TCP Maximum Segment Size"); 185 186static int tcp_do_rfc1323 = 1; 187SYSCTL_INT(_net_inet_tcp, TCPCTL_DO_RFC1323, rfc1323, CTLFLAG_RW | CTLFLAG_LOCKED, 188 &tcp_do_rfc1323 , 0, "Enable rfc1323 (high performance TCP) extensions"); 189 190// Not used 191static int tcp_do_rfc1644 = 0; 192SYSCTL_INT(_net_inet_tcp, TCPCTL_DO_RFC1644, rfc1644, CTLFLAG_RW | CTLFLAG_LOCKED, 193 &tcp_do_rfc1644 , 0, "Enable rfc1644 (TTCP) extensions"); 194 195static int do_tcpdrain = 0; 196SYSCTL_INT(_net_inet_tcp, OID_AUTO, do_tcpdrain, CTLFLAG_RW | CTLFLAG_LOCKED, &do_tcpdrain, 0, 197 "Enable tcp_drain routine for extra help when low on mbufs"); 198 199SYSCTL_INT(_net_inet_tcp, OID_AUTO, pcbcount, CTLFLAG_RD | CTLFLAG_LOCKED, 200 &tcbinfo.ipi_count, 0, "Number of active PCBs"); 201 202SYSCTL_INT(_net_inet_tcp, OID_AUTO, tw_pcbcount, 203 CTLFLAG_RD | CTLFLAG_LOCKED, 204 &tcbinfo.ipi_twcount, 0, "Number of pcbs in time-wait state"); 205 206static int icmp_may_rst = 1; 207SYSCTL_INT(_net_inet_tcp, OID_AUTO, icmp_may_rst, CTLFLAG_RW | CTLFLAG_LOCKED, &icmp_may_rst, 0, 208 "Certain ICMP unreachable messages may abort connections in SYN_SENT"); 209 210static int tcp_strict_rfc1948 = 0; 211SYSCTL_INT(_net_inet_tcp, OID_AUTO, strict_rfc1948, CTLFLAG_RW | CTLFLAG_LOCKED, 212 &tcp_strict_rfc1948, 0, "Determines if RFC1948 is followed exactly"); 213 214static int tcp_isn_reseed_interval = 0; 215SYSCTL_INT(_net_inet_tcp, OID_AUTO, isn_reseed_interval, CTLFLAG_RW | CTLFLAG_LOCKED, 216 &tcp_isn_reseed_interval, 0, "Seconds between reseeding of ISN secret"); 217static int tcp_background_io_enabled = 1; 218SYSCTL_INT(_net_inet_tcp, OID_AUTO, background_io_enabled, CTLFLAG_RW | CTLFLAG_LOCKED, 219 &tcp_background_io_enabled, 0, "Background IO Enabled"); 220 221int tcp_TCPTV_MIN = 100; /* 100ms minimum RTT */ 222SYSCTL_INT(_net_inet_tcp, OID_AUTO, rtt_min, CTLFLAG_RW | CTLFLAG_LOCKED, 223 &tcp_TCPTV_MIN, 0, "min rtt value allowed"); 224 225int tcp_rexmt_slop = TCPTV_REXMTSLOP; 226SYSCTL_INT(_net_inet_tcp, OID_AUTO, rexmt_slop, CTLFLAG_RW, 227 &tcp_rexmt_slop, 0, "Slop added to retransmit timeout"); 228 229__private_extern__ int tcp_use_randomport = 0; 230SYSCTL_INT(_net_inet_tcp, OID_AUTO, randomize_ports, CTLFLAG_RW | CTLFLAG_LOCKED, 231 &tcp_use_randomport, 0, "Randomize TCP port numbers"); 232 233__private_extern__ int tcp_win_scale = 3; 234SYSCTL_INT(_net_inet_tcp, OID_AUTO, win_scale_factor, CTLFLAG_RW | CTLFLAG_LOCKED, 235 &tcp_win_scale, 0, "Window scaling factor"); 236 237static void tcp_cleartaocache(void); 238static void tcp_notify(struct inpcb *, int); 239 240struct zone *sack_hole_zone; 241struct zone *tcp_reass_zone; 242struct zone *tcp_bwmeas_zone; 243 244extern int slowlink_wsize; /* window correction for slow links */ 245extern int path_mtu_discovery; 246 247extern u_int32_t tcp_autorcvbuf_max; 248extern u_int32_t tcp_autorcvbuf_inc_shift; 249static void tcp_sbrcv_grow_rwin(struct tcpcb *tp, struct sockbuf *sb); 250 251#define TCP_BWMEAS_BURST_MINSIZE 6 252#define TCP_BWMEAS_BURST_MAXSIZE 25 253 254static uint32_t bwmeas_elm_size; 255 256/* 257 * Target size of TCP PCB hash tables. Must be a power of two. 258 * 259 * Note that this can be overridden by the kernel environment 260 * variable net.inet.tcp.tcbhashsize 261 */ 262#ifndef TCBHASHSIZE 263#define TCBHASHSIZE CONFIG_TCBHASHSIZE 264#endif 265 266__private_extern__ int tcp_tcbhashsize = TCBHASHSIZE; 267SYSCTL_INT(_net_inet_tcp, OID_AUTO, tcbhashsize, CTLFLAG_RD | CTLFLAG_LOCKED, 268 &tcp_tcbhashsize, 0, "Size of TCP control-block hashtable"); 269 270/* 271 * This is the actual shape of what we allocate using the zone 272 * allocator. Doing it this way allows us to protect both structures 273 * using the same generation count, and also eliminates the overhead 274 * of allocating tcpcbs separately. By hiding the structure here, 275 * we avoid changing most of the rest of the code (although it needs 276 * to be changed, eventually, for greater efficiency). 277 */ 278#define ALIGNMENT 32 279struct inp_tp { 280 struct inpcb inp; 281 struct tcpcb tcb __attribute__((aligned(ALIGNMENT))); 282}; 283#undef ALIGNMENT 284 285int get_inpcb_str_size(void); 286int get_tcp_str_size(void); 287 288static void tcpcb_to_otcpcb(struct tcpcb *, struct otcpcb *); 289 290static lck_attr_t *tcp_uptime_mtx_attr = NULL; /* mutex attributes */ 291static lck_grp_t *tcp_uptime_mtx_grp = NULL; /* mutex group definition */ 292static lck_grp_attr_t *tcp_uptime_mtx_grp_attr = NULL; /* mutex group attributes */ 293int tcp_notsent_lowat_check(struct socket *so); 294 295int get_inpcb_str_size(void) 296{ 297 return sizeof(struct inpcb); 298} 299 300int get_tcp_str_size(void) 301{ 302 return sizeof(struct tcpcb); 303} 304 305int tcp_freeq(struct tcpcb *tp); 306 307static int scale_to_powerof2(int size); 308 309/* 310 * This helper routine returns one of the following scaled value of size: 311 * 1. Rounded down power of two value of size if the size value passed as 312 * argument is not a power of two and the rounded up value overflows. 313 * OR 314 * 2. Rounded up power of two value of size if the size value passed as 315 * argument is not a power of two and the rounded up value does not overflow 316 * OR 317 * 3. Same value as argument size if it is already a power of two. 318 */ 319static int scale_to_powerof2(int size) { 320 /* Handle special case of size = 0 */ 321 int ret = size ? size : 1; 322 323 if (!powerof2(ret)) { 324 while(!powerof2(size)) { 325 /* 326 * Clear out least significant 327 * set bit till size is left with 328 * its highest set bit at which point 329 * it is rounded down power of two. 330 */ 331 size = size & (size -1); 332 } 333 334 /* Check for overflow when rounding up */ 335 if (0 == (size << 1)) { 336 ret = size; 337 } else { 338 ret = size << 1; 339 } 340 } 341 342 return ret; 343} 344 345/* 346 * Tcp initialization 347 */ 348void 349tcp_init(struct protosw *pp, struct domain *dp) 350{ 351#pragma unused(dp) 352 static int tcp_initialized = 0; 353 vm_size_t str_size; 354 struct inpcbinfo *pcbinfo; 355 356 VERIFY((pp->pr_flags & (PR_INITIALIZED|PR_ATTACHED)) == PR_ATTACHED); 357 358 if (tcp_initialized) 359 return; 360 tcp_initialized = 1; 361 362 tcp_ccgen = 1; 363 tcp_cleartaocache(); 364 365 tcp_keepinit = TCPTV_KEEP_INIT; 366 tcp_keepidle = TCPTV_KEEP_IDLE; 367 tcp_keepintvl = TCPTV_KEEPINTVL; 368 tcp_keepcnt = TCPTV_KEEPCNT; 369 tcp_maxpersistidle = TCPTV_KEEP_IDLE; 370 tcp_msl = TCPTV_MSL; 371 372 microuptime(&tcp_uptime); 373 read_random(&tcp_now, sizeof(tcp_now)); 374 tcp_now = tcp_now & 0x3fffffff; /* Starts tcp internal clock at a random value */ 375 376 LIST_INIT(&tcb); 377 tcbinfo.ipi_listhead = &tcb; 378 379 pcbinfo = &tcbinfo; 380 /* 381 * allocate lock group attribute and group for tcp pcb mutexes 382 */ 383 pcbinfo->ipi_lock_grp_attr = lck_grp_attr_alloc_init(); 384 pcbinfo->ipi_lock_grp = lck_grp_alloc_init("tcppcb", pcbinfo->ipi_lock_grp_attr); 385 386 /* 387 * allocate the lock attribute for tcp pcb mutexes 388 */ 389 pcbinfo->ipi_lock_attr = lck_attr_alloc_init(); 390 391 if ((pcbinfo->ipi_lock = lck_rw_alloc_init(pcbinfo->ipi_lock_grp, 392 pcbinfo->ipi_lock_attr)) == NULL) { 393 panic("%s: unable to allocate PCB lock\n", __func__); 394 /* NOTREACHED */ 395 } 396 397 if (tcp_tcbhashsize == 0) { 398 /* Set to default */ 399 tcp_tcbhashsize = 512; 400 } 401 402 if (!powerof2(tcp_tcbhashsize)) { 403 int old_hash_size = tcp_tcbhashsize; 404 tcp_tcbhashsize = scale_to_powerof2(tcp_tcbhashsize); 405 /* Lower limit of 16 */ 406 if (tcp_tcbhashsize < 16) { 407 tcp_tcbhashsize = 16; 408 } 409 printf("WARNING: TCB hash size not a power of 2, " 410 "scaled from %d to %d.\n", 411 old_hash_size, 412 tcp_tcbhashsize); 413 } 414 415 tcbinfo.ipi_hashbase = hashinit(tcp_tcbhashsize, M_PCB, &tcbinfo.ipi_hashmask); 416 tcbinfo.ipi_porthashbase = hashinit(tcp_tcbhashsize, M_PCB, 417 &tcbinfo.ipi_porthashmask); 418 str_size = P2ROUNDUP(sizeof(struct inp_tp), sizeof(u_int64_t)); 419 tcbinfo.ipi_zone = zinit(str_size, 120000*str_size, 8192, "tcpcb"); 420 zone_change(tcbinfo.ipi_zone, Z_CALLERACCT, FALSE); 421 zone_change(tcbinfo.ipi_zone, Z_EXPAND, TRUE); 422 423 tcbinfo.ipi_gc = tcp_gc; 424 in_pcbinfo_attach(&tcbinfo); 425 426 str_size = P2ROUNDUP(sizeof(struct sackhole), sizeof(u_int64_t)); 427 sack_hole_zone = zinit(str_size, 120000*str_size, 8192, "sack_hole zone"); 428 zone_change(sack_hole_zone, Z_CALLERACCT, FALSE); 429 zone_change(sack_hole_zone, Z_EXPAND, TRUE); 430 431 str_size = P2ROUNDUP(sizeof(struct tseg_qent), sizeof(u_int64_t)); 432 tcp_reass_zone = zinit(str_size, (nmbclusters >> 4) * str_size, 433 0, "tcp_reass_zone"); 434 if (tcp_reass_zone == NULL) { 435 panic("%s: failed allocating tcp_reass_zone", __func__); 436 /* NOTREACHED */ 437 } 438 zone_change(tcp_reass_zone, Z_CALLERACCT, FALSE); 439 zone_change(tcp_reass_zone, Z_EXPAND, TRUE); 440 441 bwmeas_elm_size = P2ROUNDUP(sizeof(struct bwmeas), sizeof(u_int64_t)); 442 tcp_bwmeas_zone = zinit(bwmeas_elm_size, (100 * bwmeas_elm_size), 0, "tcp_bwmeas_zone"); 443 if (tcp_bwmeas_zone == NULL) { 444 panic("%s: failed allocating tcp_bwmeas_zone", __func__); 445 /* NOTREACHED */ 446 } 447 zone_change(tcp_bwmeas_zone, Z_CALLERACCT, FALSE); 448 zone_change(tcp_bwmeas_zone, Z_EXPAND, TRUE); 449 450 str_size = P2ROUNDUP(sizeof(struct tcp_ccstate), sizeof(u_int64_t)); 451 tcp_cc_zone = zinit(str_size, 20000 * str_size, 0, "tcp_cc_zone"); 452 zone_change(tcp_cc_zone, Z_CALLERACCT, FALSE); 453 zone_change(tcp_cc_zone, Z_EXPAND, TRUE); 454 455#if INET6 456#define TCP_MINPROTOHDR (sizeof(struct ip6_hdr) + sizeof(struct tcphdr)) 457#else /* INET6 */ 458#define TCP_MINPROTOHDR (sizeof(struct tcpiphdr)) 459#endif /* INET6 */ 460 if (max_protohdr < TCP_MINPROTOHDR) { 461 _max_protohdr = TCP_MINPROTOHDR; 462 _max_protohdr = max_protohdr; /* round it up */ 463 } 464 if (max_linkhdr + max_protohdr > MCLBYTES) 465 panic("tcp_init"); 466#undef TCP_MINPROTOHDR 467 468 /* Initialize time wait and timer lists */ 469 TAILQ_INIT(&tcp_tw_tailq); 470 471 bzero(&tcp_timer_list, sizeof(tcp_timer_list)); 472 LIST_INIT(&tcp_timer_list.lhead); 473 /* 474 * allocate lock group attribute, group and attribute for the tcp timer list 475 */ 476 tcp_timer_list.mtx_grp_attr = lck_grp_attr_alloc_init(); 477 tcp_timer_list.mtx_grp = lck_grp_alloc_init("tcptimerlist", tcp_timer_list.mtx_grp_attr); 478 tcp_timer_list.mtx_attr = lck_attr_alloc_init(); 479 if ((tcp_timer_list.mtx = lck_mtx_alloc_init(tcp_timer_list.mtx_grp, tcp_timer_list.mtx_attr)) == NULL) { 480 panic("failed to allocate memory for tcp_timer_list.mtx\n"); 481 }; 482 if ((tcp_timer_list.call = thread_call_allocate(tcp_run_timerlist, NULL)) == NULL) { 483 panic("failed to allocate call entry 1 in tcp_init\n"); 484 } 485 486 /* 487 * allocate lock group attribute, group and attribute for tcp_uptime_lock 488 */ 489 tcp_uptime_mtx_grp_attr = lck_grp_attr_alloc_init(); 490 tcp_uptime_mtx_grp = lck_grp_alloc_init("tcpuptime", tcp_uptime_mtx_grp_attr); 491 tcp_uptime_mtx_attr = lck_attr_alloc_init(); 492 tcp_uptime_lock = lck_spin_alloc_init(tcp_uptime_mtx_grp, tcp_uptime_mtx_attr); 493 494 /* Initialize TCP LRO data structures */ 495 tcp_lro_init(); 496 497 /* 498 * If more than 60 MB of mbuf pool is available, increase the 499 * maximum allowed receive and send socket buffer size. 500 */ 501 if (nmbclusters > 30720) { 502 tcp_autorcvbuf_max = 1024 * 1024; 503 tcp_autosndbuf_max = 1024 * 1024; 504 } 505} 506 507/* 508 * Fill in the IP and TCP headers for an outgoing packet, given the tcpcb. 509 * tcp_template used to store this data in mbufs, but we now recopy it out 510 * of the tcpcb each time to conserve mbufs. 511 */ 512void 513tcp_fillheaders(tp, ip_ptr, tcp_ptr) 514 struct tcpcb *tp; 515 void *ip_ptr; 516 void *tcp_ptr; 517{ 518 struct inpcb *inp = tp->t_inpcb; 519 struct tcphdr *tcp_hdr = (struct tcphdr *)tcp_ptr; 520 521#if INET6 522 if ((inp->inp_vflag & INP_IPV6) != 0) { 523 struct ip6_hdr *ip6; 524 525 ip6 = (struct ip6_hdr *)ip_ptr; 526 ip6->ip6_flow = (ip6->ip6_flow & ~IPV6_FLOWINFO_MASK) | 527 (inp->inp_flow & IPV6_FLOWINFO_MASK); 528 ip6->ip6_vfc = (ip6->ip6_vfc & ~IPV6_VERSION_MASK) | 529 (IPV6_VERSION & IPV6_VERSION_MASK); 530 ip6->ip6_nxt = IPPROTO_TCP; 531 ip6->ip6_plen = sizeof(struct tcphdr); 532 ip6->ip6_src = inp->in6p_laddr; 533 ip6->ip6_dst = inp->in6p_faddr; 534 tcp_hdr->th_sum = in6_pseudo(&inp->in6p_laddr, &inp->in6p_faddr, 535 htonl(sizeof (struct tcphdr) + IPPROTO_TCP)); 536 } else 537#endif 538 { 539 struct ip *ip = (struct ip *) ip_ptr; 540 541 ip->ip_vhl = IP_VHL_BORING; 542 ip->ip_tos = 0; 543 ip->ip_len = 0; 544 ip->ip_id = 0; 545 ip->ip_off = 0; 546 ip->ip_ttl = 0; 547 ip->ip_sum = 0; 548 ip->ip_p = IPPROTO_TCP; 549 ip->ip_src = inp->inp_laddr; 550 ip->ip_dst = inp->inp_faddr; 551 tcp_hdr->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr, 552 htons(sizeof(struct tcphdr) + IPPROTO_TCP)); 553 } 554 555 tcp_hdr->th_sport = inp->inp_lport; 556 tcp_hdr->th_dport = inp->inp_fport; 557 tcp_hdr->th_seq = 0; 558 tcp_hdr->th_ack = 0; 559 tcp_hdr->th_x2 = 0; 560 tcp_hdr->th_off = 5; 561 tcp_hdr->th_flags = 0; 562 tcp_hdr->th_win = 0; 563 tcp_hdr->th_urp = 0; 564} 565 566/* 567 * Create template to be used to send tcp packets on a connection. 568 * Allocates an mbuf and fills in a skeletal tcp/ip header. The only 569 * use for this function is in keepalives, which use tcp_respond. 570 */ 571struct tcptemp * 572tcp_maketemplate(tp) 573 struct tcpcb *tp; 574{ 575 struct mbuf *m; 576 struct tcptemp *n; 577 578 m = m_get(M_DONTWAIT, MT_HEADER); 579 if (m == NULL) 580 return (0); 581 m->m_len = sizeof(struct tcptemp); 582 n = mtod(m, struct tcptemp *); 583 584 tcp_fillheaders(tp, (void *)&n->tt_ipgen, (void *)&n->tt_t); 585 return (n); 586} 587 588/* 589 * Send a single message to the TCP at address specified by 590 * the given TCP/IP header. If m == 0, then we make a copy 591 * of the tcpiphdr at ti and send directly to the addressed host. 592 * This is used to force keep alive messages out using the TCP 593 * template for a connection. If flags are given then we send 594 * a message back to the TCP which originated the * segment ti, 595 * and discard the mbuf containing it and any other attached mbufs. 596 * 597 * In any case the ack and sequence number of the transmitted 598 * segment are as specified by the parameters. 599 * 600 * NOTE: If m != NULL, then ti must point to *inside* the mbuf. 601 */ 602void 603tcp_respond(struct tcpcb *tp, void *ipgen, struct tcphdr *th, struct mbuf *m, 604 tcp_seq ack, tcp_seq seq, int flags, struct tcp_respond_args *tra) 605{ 606 int tlen; 607 int win = 0; 608 struct route *ro = 0; 609 struct route sro; 610 struct ip *ip; 611 struct tcphdr *nth; 612#if INET6 613 struct route_in6 *ro6 = 0; 614 struct route_in6 sro6; 615 struct ip6_hdr *ip6; 616 int isipv6; 617#endif /* INET6 */ 618 struct ifnet *outif; 619 620#if INET6 621 isipv6 = IP_VHL_V(((struct ip *)ipgen)->ip_vhl) == 6; 622 ip6 = ipgen; 623#endif /* INET6 */ 624 ip = ipgen; 625 626 if (tp) { 627 if (!(flags & TH_RST)) { 628 win = tcp_sbspace(tp); 629 if (win > (int32_t)TCP_MAXWIN << tp->rcv_scale) 630 win = (int32_t)TCP_MAXWIN << tp->rcv_scale; 631 } 632#if INET6 633 if (isipv6) 634 ro6 = &tp->t_inpcb->in6p_route; 635 else 636#endif /* INET6 */ 637 ro = &tp->t_inpcb->inp_route; 638 } else { 639#if INET6 640 if (isipv6) { 641 ro6 = &sro6; 642 bzero(ro6, sizeof *ro6); 643 } else 644#endif /* INET6 */ 645 { 646 ro = &sro; 647 bzero(ro, sizeof *ro); 648 } 649 } 650 if (m == 0) { 651 m = m_gethdr(M_DONTWAIT, MT_HEADER); /* MAC-OK */ 652 if (m == NULL) 653 return; 654 tlen = 0; 655 m->m_data += max_linkhdr; 656#if INET6 657 if (isipv6) { 658 VERIFY((MHLEN - max_linkhdr) >= 659 (sizeof (*ip6) + sizeof (*nth))); 660 bcopy((caddr_t)ip6, mtod(m, caddr_t), 661 sizeof(struct ip6_hdr)); 662 ip6 = mtod(m, struct ip6_hdr *); 663 nth = (struct tcphdr *)(void *)(ip6 + 1); 664 } else 665#endif /* INET6 */ 666 { 667 VERIFY((MHLEN - max_linkhdr) >= 668 (sizeof (*ip) + sizeof (*nth))); 669 bcopy((caddr_t)ip, mtod(m, caddr_t), sizeof(struct ip)); 670 ip = mtod(m, struct ip *); 671 nth = (struct tcphdr *)(void *)(ip + 1); 672 } 673 bcopy((caddr_t)th, (caddr_t)nth, sizeof(struct tcphdr)); 674#if MPTCP 675 if ((tp) && (tp->t_mpflags & TMPF_RESET)) 676 flags = (TH_RST | TH_ACK); 677 else 678#endif 679 flags = TH_ACK; 680 } else { 681 m_freem(m->m_next); 682 m->m_next = 0; 683 m->m_data = (caddr_t)ipgen; 684 /* m_len is set later */ 685 tlen = 0; 686#define xchg(a,b,type) { type t; t=a; a=b; b=t; } 687#if INET6 688 if (isipv6) { 689 /* Expect 32-bit aligned IP on strict-align platforms */ 690 IP6_HDR_STRICT_ALIGNMENT_CHECK(ip6); 691 xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr); 692 nth = (struct tcphdr *)(void *)(ip6 + 1); 693 } else 694#endif /* INET6 */ 695 { 696 /* Expect 32-bit aligned IP on strict-align platforms */ 697 IP_HDR_STRICT_ALIGNMENT_CHECK(ip); 698 xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, n_long); 699 nth = (struct tcphdr *)(void *)(ip + 1); 700 } 701 if (th != nth) { 702 /* 703 * this is usually a case when an extension header 704 * exists between the IPv6 header and the 705 * TCP header. 706 */ 707 nth->th_sport = th->th_sport; 708 nth->th_dport = th->th_dport; 709 } 710 xchg(nth->th_dport, nth->th_sport, n_short); 711#undef xchg 712 } 713#if INET6 714 if (isipv6) { 715 ip6->ip6_plen = htons((u_short)(sizeof (struct tcphdr) + 716 tlen)); 717 tlen += sizeof (struct ip6_hdr) + sizeof (struct tcphdr); 718 } else 719#endif 720 { 721 tlen += sizeof (struct tcpiphdr); 722 ip->ip_len = tlen; 723 ip->ip_ttl = ip_defttl; 724 } 725 m->m_len = tlen; 726 m->m_pkthdr.len = tlen; 727 m->m_pkthdr.rcvif = 0; 728#if CONFIG_MACF_NET 729 if (tp != NULL && tp->t_inpcb != NULL) { 730 /* 731 * Packet is associated with a socket, so allow the 732 * label of the response to reflect the socket label. 733 */ 734 mac_mbuf_label_associate_inpcb(tp->t_inpcb, m); 735 } else { 736 /* 737 * Packet is not associated with a socket, so possibly 738 * update the label in place. 739 */ 740 mac_netinet_tcp_reply(m); 741 } 742#endif 743 744 nth->th_seq = htonl(seq); 745 nth->th_ack = htonl(ack); 746 nth->th_x2 = 0; 747 nth->th_off = sizeof (struct tcphdr) >> 2; 748 nth->th_flags = flags; 749 if (tp) 750 nth->th_win = htons((u_short) (win >> tp->rcv_scale)); 751 else 752 nth->th_win = htons((u_short)win); 753 nth->th_urp = 0; 754#if INET6 755 if (isipv6) { 756 nth->th_sum = 0; 757 nth->th_sum = in6_pseudo(&ip6->ip6_src, &ip6->ip6_dst, 758 htonl((tlen - sizeof (struct ip6_hdr)) + IPPROTO_TCP)); 759 m->m_pkthdr.csum_flags = CSUM_TCPIPV6; 760 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum); 761 ip6->ip6_hlim = in6_selecthlim(tp ? tp->t_inpcb : NULL, 762 ro6 && ro6->ro_rt ? 763 ro6->ro_rt->rt_ifp : 764 NULL); 765 } else 766#endif /* INET6 */ 767 { 768 nth->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr, 769 htons((u_short)(tlen - sizeof(struct ip) + ip->ip_p))); 770 m->m_pkthdr.csum_flags = CSUM_TCP; 771 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum); 772 } 773#if TCPDEBUG 774 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG)) 775 tcp_trace(TA_OUTPUT, 0, tp, mtod(m, void *), th, 0); 776#endif 777 778#if NECP 779 necp_mark_packet_from_socket(m, tp ? tp->t_inpcb : NULL, 0); 780#endif /* NECP */ 781 782#if IPSEC 783 if (tp != NULL && tp->t_inpcb->inp_sp != NULL && 784 ipsec_setsocket(m, tp ? tp->t_inpcb->inp_socket : NULL) != 0) { 785 m_freem(m); 786 return; 787 } 788#endif 789 790 if (tp != NULL) { 791 u_int32_t svc_flags = 0; 792 if (isipv6) { 793 svc_flags |= PKT_SCF_IPV6; 794 } 795 set_packet_service_class(m, tp->t_inpcb->inp_socket, 796 MBUF_SC_UNSPEC, svc_flags); 797 798 /* Embed flowhash and flow control flags */ 799 m->m_pkthdr.pkt_flowsrc = FLOWSRC_INPCB; 800 m->m_pkthdr.pkt_flowid = tp->t_inpcb->inp_flowhash; 801 m->m_pkthdr.pkt_flags |= PKTF_FLOW_ID | PKTF_FLOW_LOCALSRC; 802#if MPTCP 803 /* Disable flow advisory when using MPTCP. */ 804 if (!(tp->t_mpflags & TMPF_MPTCP_TRUE)) 805#endif /* MPTCP */ 806 m->m_pkthdr.pkt_flags |= PKTF_FLOW_ADV; 807 m->m_pkthdr.pkt_proto = IPPROTO_TCP; 808 } 809 810#if INET6 811 if (isipv6) { 812 struct ip6_out_args ip6oa = { tra->ifscope, { 0 }, 813 IP6OAF_SELECT_SRCIF | IP6OAF_BOUND_SRCADDR, 0 }; 814 815 if (tra->ifscope != IFSCOPE_NONE) 816 ip6oa.ip6oa_flags |= IP6OAF_BOUND_IF; 817 if (tra->nocell) 818 ip6oa.ip6oa_flags |= IP6OAF_NO_CELLULAR; 819 if (tra->noexpensive) 820 ip6oa.ip6oa_flags |= IP6OAF_NO_EXPENSIVE; 821 if (tra->awdl_unrestricted) 822 ip6oa.ip6oa_flags |= IP6OAF_AWDL_UNRESTRICTED; 823 824 (void) ip6_output(m, NULL, ro6, IPV6_OUTARGS, NULL, 825 NULL, &ip6oa); 826 827 if (tp != NULL && ro6 != NULL && ro6->ro_rt != NULL && 828 (outif = ro6->ro_rt->rt_ifp) != 829 tp->t_inpcb->in6p_last_outifp) 830 tp->t_inpcb->in6p_last_outifp = outif; 831 832 if (ro6 == &sro6) 833 ROUTE_RELEASE(ro6); 834 } else 835#endif /* INET6 */ 836 { 837 struct ip_out_args ipoa = { tra->ifscope, { 0 }, 838 IPOAF_SELECT_SRCIF | IPOAF_BOUND_SRCADDR, 0 }; 839 840 if (tra->ifscope != IFSCOPE_NONE) 841 ipoa.ipoa_flags |= IPOAF_BOUND_IF; 842 if (tra->nocell) 843 ipoa.ipoa_flags |= IPOAF_NO_CELLULAR; 844 if (tra->noexpensive) 845 ipoa.ipoa_flags |= IPOAF_NO_EXPENSIVE; 846 if (tra->awdl_unrestricted) 847 ipoa.ipoa_flags |= IPOAF_AWDL_UNRESTRICTED; 848 849 if (ro != &sro) { 850 /* Copy the cached route and take an extra reference */ 851 inp_route_copyout(tp->t_inpcb, &sro); 852 } 853 /* 854 * For consistency, pass a local route copy. 855 */ 856 (void) ip_output(m, NULL, &sro, IP_OUTARGS, NULL, &ipoa); 857 858 if (tp != NULL && sro.ro_rt != NULL && 859 (outif = sro.ro_rt->rt_ifp) != 860 tp->t_inpcb->inp_last_outifp) 861 tp->t_inpcb->inp_last_outifp = outif; 862 863 if (ro != &sro) { 864 /* Synchronize cached PCB route */ 865 inp_route_copyin(tp->t_inpcb, &sro); 866 } else { 867 ROUTE_RELEASE(&sro); 868 } 869 } 870} 871 872/* 873 * Create a new TCP control block, making an 874 * empty reassembly queue and hooking it to the argument 875 * protocol control block. The `inp' parameter must have 876 * come from the zone allocator set up in tcp_init(). 877 */ 878struct tcpcb * 879tcp_newtcpcb(inp) 880 struct inpcb *inp; 881{ 882 struct inp_tp *it; 883 register struct tcpcb *tp; 884 register struct socket *so = inp->inp_socket; 885#if INET6 886 int isipv6 = (inp->inp_vflag & INP_IPV6) != 0; 887#endif /* INET6 */ 888 889 calculate_tcp_clock(); 890 891 if (!so->cached_in_sock_layer) { 892 it = (struct inp_tp *)(void *)inp; 893 tp = &it->tcb; 894 } else { 895 tp = (struct tcpcb *)(void *)inp->inp_saved_ppcb; 896 } 897 898 bzero((char *) tp, sizeof(struct tcpcb)); 899 LIST_INIT(&tp->t_segq); 900 tp->t_maxseg = tp->t_maxopd = 901#if INET6 902 isipv6 ? tcp_v6mssdflt : 903#endif /* INET6 */ 904 tcp_mssdflt; 905 906 if (tcp_do_rfc1323) 907 tp->t_flags = (TF_REQ_SCALE|TF_REQ_TSTMP); 908 if (tcp_do_sack) 909 tp->t_flagsext |= TF_SACK_ENABLE; 910 911 TAILQ_INIT(&tp->snd_holes); 912 tp->t_inpcb = inp; /* XXX */ 913 /* 914 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no 915 * rtt estimate. Set rttvar so that srtt + 4 * rttvar gives 916 * reasonable initial retransmit time. 917 */ 918 tp->t_srtt = TCPTV_SRTTBASE; 919 tp->t_rttvar = ((TCPTV_RTOBASE - TCPTV_SRTTBASE) << TCP_RTTVAR_SHIFT) / 4; 920 tp->t_rttmin = tcp_TCPTV_MIN; 921 tp->t_rxtcur = TCPTV_RTOBASE; 922 923 if (tcp_use_newreno) 924 /* use newreno by default */ 925 tp->tcp_cc_index = TCP_CC_ALGO_NEWRENO_INDEX; 926 else 927 tp->tcp_cc_index = TCP_CC_ALGO_CUBIC_INDEX; 928 929 tcp_cc_allocate_state(tp); 930 931 if (CC_ALGO(tp)->init != NULL) 932 CC_ALGO(tp)->init(tp); 933 934 tp->snd_cwnd = TCP_CC_CWND_INIT_BYTES; 935 tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT; 936 tp->snd_ssthresh_prev = TCP_MAXWIN << TCP_MAX_WINSHIFT; 937 tp->t_rcvtime = tcp_now; 938 tp->tentry.timer_start = tcp_now; 939 tp->t_persist_timeout = tcp_max_persist_timeout; 940 tp->t_persist_stop = 0; 941 tp->t_flagsext |= TF_RCVUNACK_WAITSS; 942 tp->t_rexmtthresh = tcprexmtthresh; 943 944 /* Clear time wait tailq entry */ 945 tp->t_twentry.tqe_next = NULL; 946 tp->t_twentry.tqe_prev = NULL; 947 948 /* 949 * IPv4 TTL initialization is necessary for an IPv6 socket as well, 950 * because the socket may be bound to an IPv6 wildcard address, 951 * which may match an IPv4-mapped IPv6 address. 952 */ 953 inp->inp_ip_ttl = ip_defttl; 954 inp->inp_ppcb = (caddr_t)tp; 955 return (tp); /* XXX */ 956} 957 958/* 959 * Drop a TCP connection, reporting 960 * the specified error. If connection is synchronized, 961 * then send a RST to peer. 962 */ 963struct tcpcb * 964tcp_drop(tp, errno) 965 register struct tcpcb *tp; 966 int errno; 967{ 968 struct socket *so = tp->t_inpcb->inp_socket; 969#if CONFIG_DTRACE 970 struct inpcb *inp = tp->t_inpcb; 971#endif 972 973 if (TCPS_HAVERCVDSYN(tp->t_state)) { 974 DTRACE_TCP4(state__change, void, NULL, struct inpcb *, inp, 975 struct tcpcb *, tp, int32_t, TCPS_CLOSED); 976 tp->t_state = TCPS_CLOSED; 977 (void) tcp_output(tp); 978 tcpstat.tcps_drops++; 979 } else 980 tcpstat.tcps_conndrops++; 981 if (errno == ETIMEDOUT && tp->t_softerror) 982 errno = tp->t_softerror; 983 so->so_error = errno; 984 return (tcp_close(tp)); 985} 986 987void 988tcp_getrt_rtt(struct tcpcb *tp, struct rtentry *rt) 989{ 990 u_int32_t rtt = rt->rt_rmx.rmx_rtt; 991 int isnetlocal = (tp->t_flags & TF_LOCAL); 992 993 if (rtt != 0) { 994 /* 995 * XXX the lock bit for RTT indicates that the value 996 * is also a minimum value; this is subject to time. 997 */ 998 if (rt->rt_rmx.rmx_locks & RTV_RTT) 999 tp->t_rttmin = rtt / (RTM_RTTUNIT / TCP_RETRANSHZ); 1000 else 1001 tp->t_rttmin = isnetlocal ? tcp_TCPTV_MIN : TCPTV_REXMTMIN; 1002 tp->t_srtt = rtt / (RTM_RTTUNIT / (TCP_RETRANSHZ * TCP_RTT_SCALE)); 1003 tcpstat.tcps_usedrtt++; 1004 if (rt->rt_rmx.rmx_rttvar) { 1005 tp->t_rttvar = rt->rt_rmx.rmx_rttvar / 1006 (RTM_RTTUNIT / (TCP_RETRANSHZ * TCP_RTTVAR_SCALE)); 1007 tcpstat.tcps_usedrttvar++; 1008 } else { 1009 /* default variation is +- 1 rtt */ 1010 tp->t_rttvar = 1011 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE; 1012 } 1013 TCPT_RANGESET(tp->t_rxtcur, 1014 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1, 1015 tp->t_rttmin, TCPTV_REXMTMAX, 1016 TCP_ADD_REXMTSLOP(tp)); 1017 } 1018} 1019 1020/* 1021 * Close a TCP control block: 1022 * discard all space held by the tcp 1023 * discard internet protocol block 1024 * wake up any sleepers 1025 */ 1026struct tcpcb * 1027tcp_close(tp) 1028 register struct tcpcb *tp; 1029{ 1030 struct inpcb *inp = tp->t_inpcb; 1031 struct socket *so = inp->inp_socket; 1032#if INET6 1033 int isipv6 = (inp->inp_vflag & INP_IPV6) != 0; 1034#endif /* INET6 */ 1035 struct route *ro; 1036 struct rtentry *rt; 1037 int dosavessthresh; 1038 1039 /* tcp_close was called previously, bail */ 1040 if (inp->inp_ppcb == NULL) 1041 return(NULL); 1042 1043 tcp_canceltimers(tp); 1044 KERNEL_DEBUG(DBG_FNC_TCP_CLOSE | DBG_FUNC_START, tp,0,0,0,0); 1045 1046 /* 1047 * If another thread for this tcp is currently in ip (indicated by 1048 * the TF_SENDINPROG flag), defer the cleanup until after it returns 1049 * back to tcp. This is done to serialize the close until after all 1050 * pending output is finished, in order to avoid having the PCB be 1051 * detached and the cached route cleaned, only for ip to cache the 1052 * route back into the PCB again. Note that we've cleared all the 1053 * timers at this point. Set TF_CLOSING to indicate to tcp_output() 1054 * that is should call us again once it returns from ip; at that 1055 * point both flags should be cleared and we can proceed further 1056 * with the cleanup. 1057 */ 1058 if ((tp->t_flags & TF_CLOSING) || 1059 inp->inp_sndinprog_cnt > 0) { 1060 tp->t_flags |= TF_CLOSING; 1061 return (NULL); 1062 } 1063 1064 DTRACE_TCP4(state__change, void, NULL, struct inpcb *, inp, 1065 struct tcpcb *, tp, int32_t, TCPS_CLOSED); 1066 1067#if INET6 1068 ro = (isipv6 ? (struct route *)&inp->in6p_route : &inp->inp_route); 1069#else 1070 ro = &inp->inp_route; 1071#endif 1072 rt = ro->ro_rt; 1073 if (rt != NULL) 1074 RT_LOCK_SPIN(rt); 1075 1076 /* 1077 * If we got enough samples through the srtt filter, 1078 * save the rtt and rttvar in the routing entry. 1079 * 'Enough' is arbitrarily defined as the 16 samples. 1080 * 16 samples is enough for the srtt filter to converge 1081 * to within 5% of the correct value; fewer samples and 1082 * we could save a very bogus rtt. 1083 * 1084 * Don't update the default route's characteristics and don't 1085 * update anything that the user "locked". 1086 */ 1087 if (tp->t_rttupdated >= 16) { 1088 register u_int32_t i = 0; 1089 1090#if INET6 1091 if (isipv6) { 1092 struct sockaddr_in6 *sin6; 1093 1094 if (rt == NULL) 1095 goto no_valid_rt; 1096 sin6 = (struct sockaddr_in6 *)(void *)rt_key(rt); 1097 if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) 1098 goto no_valid_rt; 1099 } 1100 else 1101#endif /* INET6 */ 1102 if (ROUTE_UNUSABLE(ro) || 1103 SIN(rt_key(rt))->sin_addr.s_addr == INADDR_ANY) { 1104 DTRACE_TCP4(state__change, void, NULL, 1105 struct inpcb *, inp, struct tcpcb *, tp, 1106 int32_t, TCPS_CLOSED); 1107 tp->t_state = TCPS_CLOSED; 1108 goto no_valid_rt; 1109 } 1110 1111 RT_LOCK_ASSERT_HELD(rt); 1112 if ((rt->rt_rmx.rmx_locks & RTV_RTT) == 0) { 1113 i = tp->t_srtt * 1114 (RTM_RTTUNIT / (TCP_RETRANSHZ * TCP_RTT_SCALE)); 1115 if (rt->rt_rmx.rmx_rtt && i) 1116 /* 1117 * filter this update to half the old & half 1118 * the new values, converting scale. 1119 * See route.h and tcp_var.h for a 1120 * description of the scaling constants. 1121 */ 1122 rt->rt_rmx.rmx_rtt = 1123 (rt->rt_rmx.rmx_rtt + i) / 2; 1124 else 1125 rt->rt_rmx.rmx_rtt = i; 1126 tcpstat.tcps_cachedrtt++; 1127 } 1128 if ((rt->rt_rmx.rmx_locks & RTV_RTTVAR) == 0) { 1129 i = tp->t_rttvar * 1130 (RTM_RTTUNIT / (TCP_RETRANSHZ * TCP_RTTVAR_SCALE)); 1131 if (rt->rt_rmx.rmx_rttvar && i) 1132 rt->rt_rmx.rmx_rttvar = 1133 (rt->rt_rmx.rmx_rttvar + i) / 2; 1134 else 1135 rt->rt_rmx.rmx_rttvar = i; 1136 tcpstat.tcps_cachedrttvar++; 1137 } 1138 /* 1139 * The old comment here said: 1140 * update the pipelimit (ssthresh) if it has been updated 1141 * already or if a pipesize was specified & the threshhold 1142 * got below half the pipesize. I.e., wait for bad news 1143 * before we start updating, then update on both good 1144 * and bad news. 1145 * 1146 * But we want to save the ssthresh even if no pipesize is 1147 * specified explicitly in the route, because such 1148 * connections still have an implicit pipesize specified 1149 * by the global tcp_sendspace. In the absence of a reliable 1150 * way to calculate the pipesize, it will have to do. 1151 */ 1152 i = tp->snd_ssthresh; 1153 if (rt->rt_rmx.rmx_sendpipe != 0) 1154 dosavessthresh = (i < rt->rt_rmx.rmx_sendpipe / 2); 1155 else 1156 dosavessthresh = (i < so->so_snd.sb_hiwat / 2); 1157 if (((rt->rt_rmx.rmx_locks & RTV_SSTHRESH) == 0 && 1158 i != 0 && rt->rt_rmx.rmx_ssthresh != 0) 1159 || dosavessthresh) { 1160 /* 1161 * convert the limit from user data bytes to 1162 * packets then to packet data bytes. 1163 */ 1164 i = (i + tp->t_maxseg / 2) / tp->t_maxseg; 1165 if (i < 2) 1166 i = 2; 1167 i *= (u_int32_t)(tp->t_maxseg + 1168#if INET6 1169 (isipv6 ? sizeof (struct ip6_hdr) + 1170 sizeof (struct tcphdr) : 1171#endif 1172 sizeof (struct tcpiphdr) 1173#if INET6 1174 ) 1175#endif 1176 ); 1177 if (rt->rt_rmx.rmx_ssthresh) 1178 rt->rt_rmx.rmx_ssthresh = 1179 (rt->rt_rmx.rmx_ssthresh + i) / 2; 1180 else 1181 rt->rt_rmx.rmx_ssthresh = i; 1182 tcpstat.tcps_cachedssthresh++; 1183 } 1184 } 1185 1186 /* 1187 * Mark route for deletion if no information is cached. 1188 */ 1189 if (rt != NULL && (so->so_flags & SOF_OVERFLOW) && tcp_lq_overflow) { 1190 if (!(rt->rt_rmx.rmx_locks & RTV_RTT) && 1191 rt->rt_rmx.rmx_rtt == 0) { 1192 rt->rt_flags |= RTF_DELCLONE; 1193 } 1194 } 1195 1196no_valid_rt: 1197 if (rt != NULL) 1198 RT_UNLOCK(rt); 1199 1200 /* free the reassembly queue, if any */ 1201 (void) tcp_freeq(tp); 1202 1203 tcp_free_sackholes(tp); 1204 if (tp->t_bwmeas != NULL) { 1205 tcp_bwmeas_free(tp); 1206 } 1207 1208 /* Free the packet list */ 1209 if (tp->t_pktlist_head != NULL) 1210 m_freem_list(tp->t_pktlist_head); 1211 TCP_PKTLIST_CLEAR(tp); 1212 1213#if MPTCP 1214 /* Clear MPTCP state */ 1215 if ((so->so_flags & SOF_MPTCP_TRUE) || 1216 (so->so_flags & SOF_MP_SUBFLOW)) { 1217 soevent(so, (SO_FILT_HINT_LOCKED | SO_FILT_HINT_DELETEOK)); 1218 } 1219 tp->t_mpflags = 0; 1220 tp->t_mptcb = NULL; 1221#endif /* MPTCP */ 1222 1223 if (so->cached_in_sock_layer) 1224 inp->inp_saved_ppcb = (caddr_t) tp; 1225 1226 tp->t_state = TCPS_CLOSED; 1227 1228 /* Issue a wakeup before detach so that we don't miss 1229 * a wakeup 1230 */ 1231 sodisconnectwakeup(so); 1232 1233 /* 1234 * Clean up any LRO state 1235 */ 1236 if (tp->t_flagsext & TF_LRO_OFFLOADED) { 1237 tcp_lro_remove_state(inp->inp_laddr, inp->inp_faddr, 1238 inp->inp_lport, inp->inp_fport); 1239 tp->t_flagsext &= ~TF_LRO_OFFLOADED; 1240 } 1241 1242 /* 1243 * If this is a socket that does not want to wakeup the device 1244 * for it's traffic, the application might need to know that the 1245 * socket is closed, send a notification. 1246 */ 1247 if ((so->so_options & SO_NOWAKEFROMSLEEP) && 1248 inp->inp_state != INPCB_STATE_DEAD && 1249 !(inp->inp_flags2 & INP2_TIMEWAIT)) 1250 socket_post_kev_msg_closed(so); 1251 1252 if (CC_ALGO(tp)->cleanup != NULL) { 1253 CC_ALGO(tp)->cleanup(tp); 1254 } 1255 1256 if (tp->t_ccstate != NULL) { 1257 zfree(tcp_cc_zone, tp->t_ccstate); 1258 tp->t_ccstate = NULL; 1259 } 1260 tp->tcp_cc_index = TCP_CC_ALGO_NONE; 1261 1262#if INET6 1263 if (SOCK_CHECK_DOM(so, PF_INET6)) 1264 in6_pcbdetach(inp); 1265 else 1266#endif /* INET6 */ 1267 in_pcbdetach(inp); 1268 1269 /* Call soisdisconnected after detach because it might unlock the socket */ 1270 soisdisconnected(so); 1271 tcpstat.tcps_closed++; 1272 KERNEL_DEBUG(DBG_FNC_TCP_CLOSE | DBG_FUNC_END, 1273 tcpstat.tcps_closed, 0, 0, 0, 0); 1274 return(NULL); 1275} 1276 1277int 1278tcp_freeq(tp) 1279 struct tcpcb *tp; 1280{ 1281 1282 register struct tseg_qent *q; 1283 int rv = 0; 1284 1285 while((q = LIST_FIRST(&tp->t_segq)) != NULL) { 1286 LIST_REMOVE(q, tqe_q); 1287 m_freem(q->tqe_m); 1288 zfree(tcp_reass_zone, q); 1289 rv = 1; 1290 } 1291 tp->t_reassqlen = 0; 1292 return (rv); 1293} 1294 1295void 1296tcp_drain() 1297{ 1298 if (do_tcpdrain) 1299 { 1300 struct inpcb *inp; 1301 struct tcpcb *tp; 1302 /* 1303 * Walk the tcpbs, if existing, and flush the reassembly queue, 1304 * if there is one... 1305 * Do it next time if the pcbinfo lock is in use 1306 */ 1307 if (!lck_rw_try_lock_exclusive(tcbinfo.ipi_lock)) 1308 return; 1309 1310 LIST_FOREACH(inp, tcbinfo.ipi_listhead, inp_list) { 1311 if (in_pcb_checkstate(inp, WNT_ACQUIRE, 0) != 1312 WNT_STOPUSING) { 1313 tcp_lock(inp->inp_socket, 1, 0); 1314 if (in_pcb_checkstate(inp, WNT_RELEASE, 1) 1315 == WNT_STOPUSING) { 1316 /* lost a race, try the next one */ 1317 tcp_unlock(inp->inp_socket, 1, 0); 1318 continue; 1319 } 1320 tp = intotcpcb(inp); 1321 tcp_freeq(tp); 1322 tcp_unlock(inp->inp_socket, 1, 0); 1323 } 1324 } 1325 lck_rw_done(tcbinfo.ipi_lock); 1326 1327 } 1328} 1329 1330/* 1331 * Notify a tcp user of an asynchronous error; 1332 * store error as soft error, but wake up user 1333 * (for now, won't do anything until can select for soft error). 1334 * 1335 * Do not wake up user since there currently is no mechanism for 1336 * reporting soft errors (yet - a kqueue filter may be added). 1337 */ 1338static void 1339tcp_notify(inp, error) 1340 struct inpcb *inp; 1341 int error; 1342{ 1343 struct tcpcb *tp; 1344 1345 if (inp == NULL || (inp->inp_state == INPCB_STATE_DEAD)) 1346 return; /* pcb is gone already */ 1347 1348 tp = (struct tcpcb *)inp->inp_ppcb; 1349 1350 /* 1351 * Ignore some errors if we are hooked up. 1352 * If connection hasn't completed, has retransmitted several times, 1353 * and receives a second error, give up now. This is better 1354 * than waiting a long time to establish a connection that 1355 * can never complete. 1356 */ 1357 if (tp->t_state == TCPS_ESTABLISHED && 1358 (error == EHOSTUNREACH || error == ENETUNREACH || 1359 error == EHOSTDOWN)) { 1360 return; 1361 } else if (tp->t_state < TCPS_ESTABLISHED && tp->t_rxtshift > 3 && 1362 tp->t_softerror) 1363 tcp_drop(tp, error); 1364 else 1365 tp->t_softerror = error; 1366#if 0 1367 wakeup((caddr_t) &so->so_timeo); 1368 sorwakeup(so); 1369 sowwakeup(so); 1370#endif 1371} 1372 1373struct bwmeas* 1374tcp_bwmeas_alloc(struct tcpcb *tp) 1375{ 1376 struct bwmeas *elm; 1377 elm = zalloc(tcp_bwmeas_zone); 1378 if (elm == NULL) 1379 return(elm); 1380 1381 bzero(elm, bwmeas_elm_size); 1382 elm->bw_minsizepkts = TCP_BWMEAS_BURST_MINSIZE; 1383 elm->bw_maxsizepkts = TCP_BWMEAS_BURST_MAXSIZE; 1384 elm->bw_minsize = elm->bw_minsizepkts * tp->t_maxseg; 1385 elm->bw_maxsize = elm->bw_maxsizepkts * tp->t_maxseg; 1386 return(elm); 1387} 1388 1389void 1390tcp_bwmeas_free(struct tcpcb* tp) 1391{ 1392 zfree(tcp_bwmeas_zone, tp->t_bwmeas); 1393 tp->t_bwmeas = NULL; 1394 tp->t_flagsext &= ~(TF_MEASURESNDBW); 1395} 1396 1397/* 1398 * tcpcb_to_otcpcb copies specific bits of a tcpcb to a otcpcb format. 1399 * The otcpcb data structure is passed to user space and must not change. 1400 */ 1401static void 1402tcpcb_to_otcpcb(struct tcpcb *tp, struct otcpcb *otp) 1403{ 1404 otp->t_segq = (uint32_t)VM_KERNEL_ADDRPERM(tp->t_segq.lh_first); 1405 otp->t_dupacks = tp->t_dupacks; 1406 otp->t_timer[TCPT_REXMT_EXT] = tp->t_timer[TCPT_REXMT]; 1407 otp->t_timer[TCPT_PERSIST_EXT] = tp->t_timer[TCPT_PERSIST]; 1408 otp->t_timer[TCPT_KEEP_EXT] = tp->t_timer[TCPT_KEEP]; 1409 otp->t_timer[TCPT_2MSL_EXT] = tp->t_timer[TCPT_2MSL]; 1410 otp->t_inpcb = (_TCPCB_PTR(struct inpcb *))VM_KERNEL_ADDRPERM(tp->t_inpcb); 1411 otp->t_state = tp->t_state; 1412 otp->t_flags = tp->t_flags; 1413 otp->t_force = (tp->t_flagsext & TF_FORCE) ? 1 : 0; 1414 otp->snd_una = tp->snd_una; 1415 otp->snd_max = tp->snd_max; 1416 otp->snd_nxt = tp->snd_nxt; 1417 otp->snd_up = tp->snd_up; 1418 otp->snd_wl1 = tp->snd_wl1; 1419 otp->snd_wl2 = tp->snd_wl2; 1420 otp->iss = tp->iss; 1421 otp->irs = tp->irs; 1422 otp->rcv_nxt = tp->rcv_nxt; 1423 otp->rcv_adv = tp->rcv_adv; 1424 otp->rcv_wnd = tp->rcv_wnd; 1425 otp->rcv_up = tp->rcv_up; 1426 otp->snd_wnd = tp->snd_wnd; 1427 otp->snd_cwnd = tp->snd_cwnd; 1428 otp->snd_ssthresh = tp->snd_ssthresh; 1429 otp->t_maxopd = tp->t_maxopd; 1430 otp->t_rcvtime = tp->t_rcvtime; 1431 otp->t_starttime = tp->t_starttime; 1432 otp->t_rtttime = tp->t_rtttime; 1433 otp->t_rtseq = tp->t_rtseq; 1434 otp->t_rxtcur = tp->t_rxtcur; 1435 otp->t_maxseg = tp->t_maxseg; 1436 otp->t_srtt = tp->t_srtt; 1437 otp->t_rttvar = tp->t_rttvar; 1438 otp->t_rxtshift = tp->t_rxtshift; 1439 otp->t_rttmin = tp->t_rttmin; 1440 otp->t_rttupdated = tp->t_rttupdated; 1441 otp->max_sndwnd = tp->max_sndwnd; 1442 otp->t_softerror = tp->t_softerror; 1443 otp->t_oobflags = tp->t_oobflags; 1444 otp->t_iobc = tp->t_iobc; 1445 otp->snd_scale = tp->snd_scale; 1446 otp->rcv_scale = tp->rcv_scale; 1447 otp->request_r_scale = tp->request_r_scale; 1448 otp->requested_s_scale = tp->requested_s_scale; 1449 otp->ts_recent = tp->ts_recent; 1450 otp->ts_recent_age = tp->ts_recent_age; 1451 otp->last_ack_sent = tp->last_ack_sent; 1452 otp->cc_send = tp->cc_send; 1453 otp->cc_recv = tp->cc_recv; 1454 otp->snd_recover = tp->snd_recover; 1455 otp->snd_cwnd_prev = tp->snd_cwnd_prev; 1456 otp->snd_ssthresh_prev = tp->snd_ssthresh_prev; 1457 otp->t_badrxtwin = 0; 1458} 1459 1460static int 1461tcp_pcblist SYSCTL_HANDLER_ARGS 1462{ 1463#pragma unused(oidp, arg1, arg2) 1464 int error, i = 0, n; 1465 struct inpcb *inp, **inp_list; 1466 struct tcpcb *tp; 1467 inp_gen_t gencnt; 1468 struct xinpgen xig; 1469 1470 /* 1471 * The process of preparing the TCB list is too time-consuming and 1472 * resource-intensive to repeat twice on every request. 1473 */ 1474 lck_rw_lock_shared(tcbinfo.ipi_lock); 1475 if (req->oldptr == USER_ADDR_NULL) { 1476 n = tcbinfo.ipi_count; 1477 req->oldidx = 2 * (sizeof xig) 1478 + (n + n/8) * sizeof(struct xtcpcb); 1479 lck_rw_done(tcbinfo.ipi_lock); 1480 return 0; 1481 } 1482 1483 if (req->newptr != USER_ADDR_NULL) { 1484 lck_rw_done(tcbinfo.ipi_lock); 1485 return EPERM; 1486 } 1487 1488 /* 1489 * OK, now we're committed to doing something. 1490 */ 1491 gencnt = tcbinfo.ipi_gencnt; 1492 n = tcbinfo.ipi_count; 1493 1494 bzero(&xig, sizeof(xig)); 1495 xig.xig_len = sizeof xig; 1496 xig.xig_count = n; 1497 xig.xig_gen = gencnt; 1498 xig.xig_sogen = so_gencnt; 1499 error = SYSCTL_OUT(req, &xig, sizeof xig); 1500 if (error) { 1501 lck_rw_done(tcbinfo.ipi_lock); 1502 return error; 1503 } 1504 /* 1505 * We are done if there is no pcb 1506 */ 1507 if (n == 0) { 1508 lck_rw_done(tcbinfo.ipi_lock); 1509 return 0; 1510 } 1511 1512 inp_list = _MALLOC(n * sizeof *inp_list, M_TEMP, M_WAITOK); 1513 if (inp_list == 0) { 1514 lck_rw_done(tcbinfo.ipi_lock); 1515 return ENOMEM; 1516 } 1517 1518 LIST_FOREACH(inp, tcbinfo.ipi_listhead, inp_list) { 1519 if (inp->inp_gencnt <= gencnt && 1520 inp->inp_state != INPCB_STATE_DEAD) 1521 inp_list[i++] = inp; 1522 if (i >= n) break; 1523 } 1524 1525 TAILQ_FOREACH(tp, &tcp_tw_tailq, t_twentry) { 1526 inp = tp->t_inpcb; 1527 if (inp->inp_gencnt <= gencnt && 1528 inp->inp_state != INPCB_STATE_DEAD) 1529 inp_list[i++] = inp; 1530 if (i >= n) break; 1531 } 1532 1533 n = i; 1534 1535 error = 0; 1536 for (i = 0; i < n; i++) { 1537 inp = inp_list[i]; 1538 if (inp->inp_gencnt <= gencnt && 1539 inp->inp_state != INPCB_STATE_DEAD) { 1540 struct xtcpcb xt; 1541 caddr_t inp_ppcb; 1542 1543 bzero(&xt, sizeof(xt)); 1544 xt.xt_len = sizeof xt; 1545 /* XXX should avoid extra copy */ 1546 inpcb_to_compat(inp, &xt.xt_inp); 1547 inp_ppcb = inp->inp_ppcb; 1548 if (inp_ppcb != NULL) { 1549 tcpcb_to_otcpcb( 1550 (struct tcpcb *)(void *)inp_ppcb, 1551 &xt.xt_tp); 1552 } else { 1553 bzero((char *) &xt.xt_tp, sizeof xt.xt_tp); 1554 } 1555 if (inp->inp_socket) 1556 sotoxsocket(inp->inp_socket, &xt.xt_socket); 1557 error = SYSCTL_OUT(req, &xt, sizeof xt); 1558 } 1559 } 1560 if (!error) { 1561 /* 1562 * Give the user an updated idea of our state. 1563 * If the generation differs from what we told 1564 * her before, she knows that something happened 1565 * while we were processing this request, and it 1566 * might be necessary to retry. 1567 */ 1568 bzero(&xig, sizeof(xig)); 1569 xig.xig_len = sizeof xig; 1570 xig.xig_gen = tcbinfo.ipi_gencnt; 1571 xig.xig_sogen = so_gencnt; 1572 xig.xig_count = tcbinfo.ipi_count; 1573 error = SYSCTL_OUT(req, &xig, sizeof xig); 1574 } 1575 FREE(inp_list, M_TEMP); 1576 lck_rw_done(tcbinfo.ipi_lock); 1577 return error; 1578} 1579 1580SYSCTL_PROC(_net_inet_tcp, TCPCTL_PCBLIST, pcblist, 1581 CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0, 1582 tcp_pcblist, "S,xtcpcb", "List of active TCP connections"); 1583 1584 1585static void 1586tcpcb_to_xtcpcb64(struct tcpcb *tp, struct xtcpcb64 *otp) 1587{ 1588 otp->t_segq = (uint32_t)VM_KERNEL_ADDRPERM(tp->t_segq.lh_first); 1589 otp->t_dupacks = tp->t_dupacks; 1590 otp->t_timer[TCPT_REXMT_EXT] = tp->t_timer[TCPT_REXMT]; 1591 otp->t_timer[TCPT_PERSIST_EXT] = tp->t_timer[TCPT_PERSIST]; 1592 otp->t_timer[TCPT_KEEP_EXT] = tp->t_timer[TCPT_KEEP]; 1593 otp->t_timer[TCPT_2MSL_EXT] = tp->t_timer[TCPT_2MSL]; 1594 otp->t_state = tp->t_state; 1595 otp->t_flags = tp->t_flags; 1596 otp->t_force = (tp->t_flagsext & TF_FORCE) ? 1 : 0; 1597 otp->snd_una = tp->snd_una; 1598 otp->snd_max = tp->snd_max; 1599 otp->snd_nxt = tp->snd_nxt; 1600 otp->snd_up = tp->snd_up; 1601 otp->snd_wl1 = tp->snd_wl1; 1602 otp->snd_wl2 = tp->snd_wl2; 1603 otp->iss = tp->iss; 1604 otp->irs = tp->irs; 1605 otp->rcv_nxt = tp->rcv_nxt; 1606 otp->rcv_adv = tp->rcv_adv; 1607 otp->rcv_wnd = tp->rcv_wnd; 1608 otp->rcv_up = tp->rcv_up; 1609 otp->snd_wnd = tp->snd_wnd; 1610 otp->snd_cwnd = tp->snd_cwnd; 1611 otp->snd_ssthresh = tp->snd_ssthresh; 1612 otp->t_maxopd = tp->t_maxopd; 1613 otp->t_rcvtime = tp->t_rcvtime; 1614 otp->t_starttime = tp->t_starttime; 1615 otp->t_rtttime = tp->t_rtttime; 1616 otp->t_rtseq = tp->t_rtseq; 1617 otp->t_rxtcur = tp->t_rxtcur; 1618 otp->t_maxseg = tp->t_maxseg; 1619 otp->t_srtt = tp->t_srtt; 1620 otp->t_rttvar = tp->t_rttvar; 1621 otp->t_rxtshift = tp->t_rxtshift; 1622 otp->t_rttmin = tp->t_rttmin; 1623 otp->t_rttupdated = tp->t_rttupdated; 1624 otp->max_sndwnd = tp->max_sndwnd; 1625 otp->t_softerror = tp->t_softerror; 1626 otp->t_oobflags = tp->t_oobflags; 1627 otp->t_iobc = tp->t_iobc; 1628 otp->snd_scale = tp->snd_scale; 1629 otp->rcv_scale = tp->rcv_scale; 1630 otp->request_r_scale = tp->request_r_scale; 1631 otp->requested_s_scale = tp->requested_s_scale; 1632 otp->ts_recent = tp->ts_recent; 1633 otp->ts_recent_age = tp->ts_recent_age; 1634 otp->last_ack_sent = tp->last_ack_sent; 1635 otp->cc_send = tp->cc_send; 1636 otp->cc_recv = tp->cc_recv; 1637 otp->snd_recover = tp->snd_recover; 1638 otp->snd_cwnd_prev = tp->snd_cwnd_prev; 1639 otp->snd_ssthresh_prev = tp->snd_ssthresh_prev; 1640 otp->t_badrxtwin = 0; 1641} 1642 1643 1644static int 1645tcp_pcblist64 SYSCTL_HANDLER_ARGS 1646{ 1647#pragma unused(oidp, arg1, arg2) 1648 int error, i = 0, n; 1649 struct inpcb *inp, **inp_list; 1650 struct tcpcb *tp; 1651 inp_gen_t gencnt; 1652 struct xinpgen xig; 1653 1654 /* 1655 * The process of preparing the TCB list is too time-consuming and 1656 * resource-intensive to repeat twice on every request. 1657 */ 1658 lck_rw_lock_shared(tcbinfo.ipi_lock); 1659 if (req->oldptr == USER_ADDR_NULL) { 1660 n = tcbinfo.ipi_count; 1661 req->oldidx = 2 * (sizeof xig) 1662 + (n + n/8) * sizeof(struct xtcpcb64); 1663 lck_rw_done(tcbinfo.ipi_lock); 1664 return 0; 1665 } 1666 1667 if (req->newptr != USER_ADDR_NULL) { 1668 lck_rw_done(tcbinfo.ipi_lock); 1669 return EPERM; 1670 } 1671 1672 /* 1673 * OK, now we're committed to doing something. 1674 */ 1675 gencnt = tcbinfo.ipi_gencnt; 1676 n = tcbinfo.ipi_count; 1677 1678 bzero(&xig, sizeof(xig)); 1679 xig.xig_len = sizeof xig; 1680 xig.xig_count = n; 1681 xig.xig_gen = gencnt; 1682 xig.xig_sogen = so_gencnt; 1683 error = SYSCTL_OUT(req, &xig, sizeof xig); 1684 if (error) { 1685 lck_rw_done(tcbinfo.ipi_lock); 1686 return error; 1687 } 1688 /* 1689 * We are done if there is no pcb 1690 */ 1691 if (n == 0) { 1692 lck_rw_done(tcbinfo.ipi_lock); 1693 return 0; 1694 } 1695 1696 inp_list = _MALLOC(n * sizeof *inp_list, M_TEMP, M_WAITOK); 1697 if (inp_list == 0) { 1698 lck_rw_done(tcbinfo.ipi_lock); 1699 return ENOMEM; 1700 } 1701 1702 LIST_FOREACH(inp, tcbinfo.ipi_listhead, inp_list) { 1703 if (inp->inp_gencnt <= gencnt && 1704 inp->inp_state != INPCB_STATE_DEAD) 1705 inp_list[i++] = inp; 1706 if (i >= n) break; 1707 } 1708 1709 TAILQ_FOREACH(tp, &tcp_tw_tailq, t_twentry) { 1710 inp = tp->t_inpcb; 1711 if (inp->inp_gencnt <= gencnt && 1712 inp->inp_state != INPCB_STATE_DEAD) 1713 inp_list[i++] = inp; 1714 if (i >= n) break; 1715 } 1716 1717 n = i; 1718 1719 error = 0; 1720 for (i = 0; i < n; i++) { 1721 inp = inp_list[i]; 1722 if (inp->inp_gencnt <= gencnt && inp->inp_state != INPCB_STATE_DEAD) { 1723 struct xtcpcb64 xt; 1724 1725 bzero(&xt, sizeof(xt)); 1726 xt.xt_len = sizeof xt; 1727 inpcb_to_xinpcb64(inp, &xt.xt_inpcb); 1728 xt.xt_inpcb.inp_ppcb = (uint64_t)VM_KERNEL_ADDRPERM(inp->inp_ppcb); 1729 if (inp->inp_ppcb != NULL) 1730 tcpcb_to_xtcpcb64((struct tcpcb *)inp->inp_ppcb, &xt); 1731 if (inp->inp_socket) 1732 sotoxsocket64(inp->inp_socket, &xt.xt_inpcb.xi_socket); 1733 error = SYSCTL_OUT(req, &xt, sizeof xt); 1734 } 1735 } 1736 if (!error) { 1737 /* 1738 * Give the user an updated idea of our state. 1739 * If the generation differs from what we told 1740 * her before, she knows that something happened 1741 * while we were processing this request, and it 1742 * might be necessary to retry. 1743 */ 1744 bzero(&xig, sizeof(xig)); 1745 xig.xig_len = sizeof xig; 1746 xig.xig_gen = tcbinfo.ipi_gencnt; 1747 xig.xig_sogen = so_gencnt; 1748 xig.xig_count = tcbinfo.ipi_count; 1749 error = SYSCTL_OUT(req, &xig, sizeof xig); 1750 } 1751 FREE(inp_list, M_TEMP); 1752 lck_rw_done(tcbinfo.ipi_lock); 1753 return error; 1754} 1755 1756SYSCTL_PROC(_net_inet_tcp, OID_AUTO, pcblist64, 1757 CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0, 1758 tcp_pcblist64, "S,xtcpcb64", "List of active TCP connections"); 1759 1760 1761static int 1762tcp_pcblist_n SYSCTL_HANDLER_ARGS 1763{ 1764#pragma unused(oidp, arg1, arg2) 1765 int error = 0; 1766 1767 error = get_pcblist_n(IPPROTO_TCP, req, &tcbinfo); 1768 1769 return error; 1770} 1771 1772 1773SYSCTL_PROC(_net_inet_tcp, OID_AUTO, pcblist_n, 1774 CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0, 1775 tcp_pcblist_n, "S,xtcpcb_n", "List of active TCP connections"); 1776 1777 1778__private_extern__ void 1779tcp_get_ports_used(uint32_t ifindex, int protocol, uint32_t flags, 1780 bitstr_t *bitfield) 1781{ 1782 inpcb_get_ports_used(ifindex, protocol, flags, 1783 bitfield, &tcbinfo); 1784} 1785 1786__private_extern__ uint32_t 1787tcp_count_opportunistic(unsigned int ifindex, u_int32_t flags) 1788{ 1789 return inpcb_count_opportunistic(ifindex, &tcbinfo, flags); 1790} 1791 1792__private_extern__ uint32_t 1793tcp_find_anypcb_byaddr(struct ifaddr *ifa) 1794{ 1795 return inpcb_find_anypcb_byaddr(ifa, &tcbinfo); 1796} 1797 1798void 1799tcp_ctlinput(cmd, sa, vip) 1800 int cmd; 1801 struct sockaddr *sa; 1802 void *vip; 1803{ 1804 tcp_seq icmp_tcp_seq; 1805 struct ip *ip = vip; 1806 struct in_addr faddr; 1807 struct inpcb *inp; 1808 struct tcpcb *tp; 1809 1810 void (*notify)(struct inpcb *, int) = tcp_notify; 1811 1812 faddr = ((struct sockaddr_in *)(void *)sa)->sin_addr; 1813 if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY) 1814 return; 1815 1816 if (cmd == PRC_MSGSIZE) 1817 notify = tcp_mtudisc; 1818 else if (icmp_may_rst && (cmd == PRC_UNREACH_ADMIN_PROHIB || 1819 cmd == PRC_UNREACH_PORT) && ip) 1820 notify = tcp_drop_syn_sent; 1821 else if (PRC_IS_REDIRECT(cmd)) { 1822 ip = 0; 1823 notify = in_rtchange; 1824 } else if (cmd == PRC_HOSTDEAD) 1825 ip = 0; 1826 /* Source quench is deprecated */ 1827 else if (cmd == PRC_QUENCH) 1828 return; 1829 else if ((unsigned)cmd > PRC_NCMDS || inetctlerrmap[cmd] == 0) 1830 return; 1831 if (ip) { 1832 struct tcphdr th; 1833 struct icmp *icp; 1834 1835 icp = (struct icmp *)(void *) 1836 ((caddr_t)ip - offsetof(struct icmp, icmp_ip)); 1837 bcopy(((caddr_t)ip + (IP_VHL_HL(ip->ip_vhl) << 2)), 1838 &th, sizeof (th)); 1839 inp = in_pcblookup_hash(&tcbinfo, faddr, th.th_dport, 1840 ip->ip_src, th.th_sport, 0, NULL); 1841 if (inp != NULL && inp->inp_socket != NULL) { 1842 tcp_lock(inp->inp_socket, 1, 0); 1843 if (in_pcb_checkstate(inp, WNT_RELEASE, 1) == WNT_STOPUSING) { 1844 tcp_unlock(inp->inp_socket, 1, 0); 1845 return; 1846 } 1847 icmp_tcp_seq = htonl(th.th_seq); 1848 tp = intotcpcb(inp); 1849 if (SEQ_GEQ(icmp_tcp_seq, tp->snd_una) && 1850 SEQ_LT(icmp_tcp_seq, tp->snd_max)) { 1851 if (cmd == PRC_MSGSIZE) { 1852 1853 /* 1854 * MTU discovery: 1855 * If we got a needfrag and there is a host route to the 1856 * original destination, and the MTU is not locked, then 1857 * set the MTU in the route to the suggested new value 1858 * (if given) and then notify as usual. The ULPs will 1859 * notice that the MTU has changed and adapt accordingly. 1860 * If no new MTU was suggested, then we guess a new one 1861 * less than the current value. If the new MTU is 1862 * unreasonably small (defined by sysctl tcp_minmss), then 1863 * we reset the MTU to the interface value and enable the 1864 * lock bit, indicating that we are no longer doing MTU 1865 * discovery. 1866 */ 1867 struct rtentry *rt; 1868 int mtu; 1869 struct sockaddr_in icmpsrc = { sizeof (struct sockaddr_in), AF_INET, 1870 0 , { 0 }, { 0,0,0,0,0,0,0,0 } }; 1871 icmpsrc.sin_addr = icp->icmp_ip.ip_dst; 1872 1873 rt = rtalloc1((struct sockaddr *)&icmpsrc, 0, 1874 RTF_CLONING | RTF_PRCLONING); 1875 if (rt != NULL) { 1876 RT_LOCK(rt); 1877 if ((rt->rt_flags & RTF_HOST) && 1878 !(rt->rt_rmx.rmx_locks & RTV_MTU)) { 1879 mtu = ntohs(icp->icmp_nextmtu); 1880 if (!mtu) 1881 mtu = ip_next_mtu(rt->rt_rmx. 1882 rmx_mtu, 1); 1883#if DEBUG_MTUDISC 1884 printf("MTU for %s reduced to %d\n", 1885 inet_ntop(AF_INET, 1886 &icmpsrc.sin_addr, ipv4str, 1887 sizeof (ipv4str)), mtu); 1888#endif 1889 if (mtu < max(296, (tcp_minmss + 1890 sizeof (struct tcpiphdr)))) { 1891 /* rt->rt_rmx.rmx_mtu = 1892 rt->rt_ifp->if_mtu; */ 1893 rt->rt_rmx.rmx_locks |= RTV_MTU; 1894 } else if (rt->rt_rmx.rmx_mtu > mtu) { 1895 rt->rt_rmx.rmx_mtu = mtu; 1896 } 1897 } 1898 RT_UNLOCK(rt); 1899 rtfree(rt); 1900 } 1901 } 1902 1903 (*notify)(inp, inetctlerrmap[cmd]); 1904 } 1905 tcp_unlock(inp->inp_socket, 1, 0); 1906 } 1907 } else 1908 in_pcbnotifyall(&tcbinfo, faddr, inetctlerrmap[cmd], notify); 1909} 1910 1911#if INET6 1912void 1913tcp6_ctlinput(cmd, sa, d) 1914 int cmd; 1915 struct sockaddr *sa; 1916 void *d; 1917{ 1918 struct tcphdr th; 1919 void (*notify)(struct inpcb *, int) = tcp_notify; 1920 struct ip6_hdr *ip6; 1921 struct mbuf *m; 1922 struct ip6ctlparam *ip6cp = NULL; 1923 const struct sockaddr_in6 *sa6_src = NULL; 1924 int off; 1925 struct tcp_portonly { 1926 u_int16_t th_sport; 1927 u_int16_t th_dport; 1928 } *thp; 1929 1930 if (sa->sa_family != AF_INET6 || 1931 sa->sa_len != sizeof(struct sockaddr_in6)) 1932 return; 1933 1934 if (cmd == PRC_MSGSIZE) 1935 notify = tcp_mtudisc; 1936 else if (!PRC_IS_REDIRECT(cmd) && 1937 ((unsigned)cmd > PRC_NCMDS || inet6ctlerrmap[cmd] == 0)) 1938 return; 1939 /* Source quench is deprecated */ 1940 else if (cmd == PRC_QUENCH) 1941 return; 1942 1943 /* if the parameter is from icmp6, decode it. */ 1944 if (d != NULL) { 1945 ip6cp = (struct ip6ctlparam *)d; 1946 m = ip6cp->ip6c_m; 1947 ip6 = ip6cp->ip6c_ip6; 1948 off = ip6cp->ip6c_off; 1949 sa6_src = ip6cp->ip6c_src; 1950 } else { 1951 m = NULL; 1952 ip6 = NULL; 1953 off = 0; /* fool gcc */ 1954 sa6_src = &sa6_any; 1955 } 1956 1957 if (ip6) { 1958 /* 1959 * XXX: We assume that when IPV6 is non NULL, 1960 * M and OFF are valid. 1961 */ 1962 1963 /* check if we can safely examine src and dst ports */ 1964 if (m->m_pkthdr.len < off + sizeof(*thp)) 1965 return; 1966 1967 bzero(&th, sizeof(th)); 1968 m_copydata(m, off, sizeof(*thp), (caddr_t)&th); 1969 1970 in6_pcbnotify(&tcbinfo, sa, th.th_dport, 1971 (struct sockaddr *)ip6cp->ip6c_src, 1972 th.th_sport, cmd, NULL, notify); 1973 } else { 1974 in6_pcbnotify(&tcbinfo, sa, 0, 1975 (struct sockaddr *)(size_t)sa6_src, 0, cmd, NULL, notify); 1976 } 1977} 1978#endif /* INET6 */ 1979 1980 1981/* 1982 * Following is where TCP initial sequence number generation occurs. 1983 * 1984 * There are two places where we must use initial sequence numbers: 1985 * 1. In SYN-ACK packets. 1986 * 2. In SYN packets. 1987 * 1988 * The ISNs in SYN-ACK packets have no monotonicity requirement, 1989 * and should be as unpredictable as possible to avoid the possibility 1990 * of spoofing and/or connection hijacking. To satisfy this 1991 * requirement, SYN-ACK ISNs are generated via the arc4random() 1992 * function. If exact RFC 1948 compliance is requested via sysctl, 1993 * these ISNs will be generated just like those in SYN packets. 1994 * 1995 * The ISNs in SYN packets must be monotonic; TIME_WAIT recycling 1996 * depends on this property. In addition, these ISNs should be 1997 * unguessable so as to prevent connection hijacking. To satisfy 1998 * the requirements of this situation, the algorithm outlined in 1999 * RFC 1948 is used to generate sequence numbers. 2000 * 2001 * For more information on the theory of operation, please see 2002 * RFC 1948. 2003 * 2004 * Implementation details: 2005 * 2006 * Time is based off the system timer, and is corrected so that it 2007 * increases by one megabyte per second. This allows for proper 2008 * recycling on high speed LANs while still leaving over an hour 2009 * before rollover. 2010 * 2011 * Two sysctls control the generation of ISNs: 2012 * 2013 * net.inet.tcp.isn_reseed_interval controls the number of seconds 2014 * between seeding of isn_secret. This is normally set to zero, 2015 * as reseeding should not be necessary. 2016 * 2017 * net.inet.tcp.strict_rfc1948 controls whether RFC 1948 is followed 2018 * strictly. When strict compliance is requested, reseeding is 2019 * disabled and SYN-ACKs will be generated in the same manner as 2020 * SYNs. Strict mode is disabled by default. 2021 * 2022 */ 2023 2024#define ISN_BYTES_PER_SECOND 1048576 2025 2026tcp_seq 2027tcp_new_isn(tp) 2028 struct tcpcb *tp; 2029{ 2030 u_int32_t md5_buffer[4]; 2031 tcp_seq new_isn; 2032 struct timeval timenow; 2033 u_char isn_secret[32]; 2034 int isn_last_reseed = 0; 2035 MD5_CTX isn_ctx; 2036 2037 /* Use arc4random for SYN-ACKs when not in exact RFC1948 mode. */ 2038 if (((tp->t_state == TCPS_LISTEN) || (tp->t_state == TCPS_TIME_WAIT)) 2039 && tcp_strict_rfc1948 == 0) 2040#ifdef __APPLE__ 2041 return RandomULong(); 2042#else 2043 return arc4random(); 2044#endif 2045 getmicrotime(&timenow); 2046 2047 /* Seed if this is the first use, reseed if requested. */ 2048 if ((isn_last_reseed == 0) || 2049 ((tcp_strict_rfc1948 == 0) && (tcp_isn_reseed_interval > 0) && 2050 (((u_int)isn_last_reseed + (u_int)tcp_isn_reseed_interval*hz) 2051 < (u_int)timenow.tv_sec))) { 2052#ifdef __APPLE__ 2053 read_random(&isn_secret, sizeof(isn_secret)); 2054#else 2055 read_random_unlimited(&isn_secret, sizeof(isn_secret)); 2056#endif 2057 isn_last_reseed = timenow.tv_sec; 2058 } 2059 2060 /* Compute the md5 hash and return the ISN. */ 2061 MD5Init(&isn_ctx); 2062 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_fport, sizeof(u_short)); 2063 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_lport, sizeof(u_short)); 2064#if INET6 2065 if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0) { 2066 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->in6p_faddr, 2067 sizeof(struct in6_addr)); 2068 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->in6p_laddr, 2069 sizeof(struct in6_addr)); 2070 } else 2071#endif 2072 { 2073 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_faddr, 2074 sizeof(struct in_addr)); 2075 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_laddr, 2076 sizeof(struct in_addr)); 2077 } 2078 MD5Update(&isn_ctx, (u_char *) &isn_secret, sizeof(isn_secret)); 2079 MD5Final((u_char *) &md5_buffer, &isn_ctx); 2080 new_isn = (tcp_seq) md5_buffer[0]; 2081 new_isn += timenow.tv_sec * (ISN_BYTES_PER_SECOND / hz); 2082 return new_isn; 2083} 2084 2085 2086/* 2087 * When a specific ICMP unreachable message is received and the 2088 * connection state is SYN-SENT, drop the connection. This behavior 2089 * is controlled by the icmp_may_rst sysctl. 2090 */ 2091void 2092tcp_drop_syn_sent(inp, errno) 2093 struct inpcb *inp; 2094 int errno; 2095{ 2096 struct tcpcb *tp = intotcpcb(inp); 2097 2098 if (tp && tp->t_state == TCPS_SYN_SENT) 2099 tcp_drop(tp, errno); 2100} 2101 2102/* 2103 * When `need fragmentation' ICMP is received, update our idea of the MSS 2104 * based on the new value in the route. Also nudge TCP to send something, 2105 * since we know the packet we just sent was dropped. 2106 * This duplicates some code in the tcp_mss() function in tcp_input.c. 2107 */ 2108void 2109tcp_mtudisc( 2110 struct inpcb *inp, 2111 __unused int errno 2112) 2113{ 2114 struct tcpcb *tp = intotcpcb(inp); 2115 struct rtentry *rt; 2116 struct rmxp_tao *taop; 2117 struct socket *so = inp->inp_socket; 2118 int offered; 2119 int mss; 2120#if INET6 2121 int isipv6 = (tp->t_inpcb->inp_vflag & INP_IPV6) != 0; 2122#endif /* INET6 */ 2123 2124 if (tp) { 2125#if INET6 2126 if (isipv6) 2127 rt = tcp_rtlookup6(inp, IFSCOPE_NONE); 2128 else 2129#endif /* INET6 */ 2130 rt = tcp_rtlookup(inp, IFSCOPE_NONE); 2131 if (!rt || !rt->rt_rmx.rmx_mtu) { 2132 tp->t_maxopd = tp->t_maxseg = 2133#if INET6 2134 isipv6 ? tcp_v6mssdflt : 2135#endif /* INET6 */ 2136 tcp_mssdflt; 2137 2138 /* Route locked during lookup above */ 2139 if (rt != NULL) 2140 RT_UNLOCK(rt); 2141 return; 2142 } 2143 taop = rmx_taop(rt->rt_rmx); 2144 offered = taop->tao_mssopt; 2145 mss = rt->rt_rmx.rmx_mtu - 2146#if INET6 2147 (isipv6 ? 2148 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) : 2149#endif /* INET6 */ 2150 sizeof(struct tcpiphdr) 2151#if INET6 2152 ) 2153#endif /* INET6 */ 2154 ; 2155 2156 /* Route locked during lookup above */ 2157 RT_UNLOCK(rt); 2158 2159 if (offered) 2160 mss = min(mss, offered); 2161 /* 2162 * XXX - The above conditional probably violates the TCP 2163 * spec. The problem is that, since we don't know the 2164 * other end's MSS, we are supposed to use a conservative 2165 * default. But, if we do that, then MTU discovery will 2166 * never actually take place, because the conservative 2167 * default is much less than the MTUs typically seen 2168 * on the Internet today. For the moment, we'll sweep 2169 * this under the carpet. 2170 * 2171 * The conservative default might not actually be a problem 2172 * if the only case this occurs is when sending an initial 2173 * SYN with options and data to a host we've never talked 2174 * to before. Then, they will reply with an MSS value which 2175 * will get recorded and the new parameters should get 2176 * recomputed. For Further Study. 2177 */ 2178 if (tp->t_maxopd <= mss) 2179 return; 2180 tp->t_maxopd = mss; 2181 2182 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP && 2183 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP) 2184 mss -= TCPOLEN_TSTAMP_APPA; 2185 2186#if MPTCP 2187 mss -= mptcp_adj_mss(tp, TRUE); 2188#endif 2189 if (so->so_snd.sb_hiwat < mss) 2190 mss = so->so_snd.sb_hiwat; 2191 2192 tp->t_maxseg = mss; 2193 2194 /* 2195 * Reset the slow-start flight size as it may depends on the new MSS 2196 */ 2197 if (CC_ALGO(tp)->cwnd_init != NULL) 2198 CC_ALGO(tp)->cwnd_init(tp); 2199 tcpstat.tcps_mturesent++; 2200 tp->t_rtttime = 0; 2201 tp->snd_nxt = tp->snd_una; 2202 tcp_output(tp); 2203 } 2204} 2205 2206/* 2207 * Look-up the routing entry to the peer of this inpcb. If no route 2208 * is found and it cannot be allocated the return NULL. This routine 2209 * is called by TCP routines that access the rmx structure and by tcp_mss 2210 * to get the interface MTU. If a route is found, this routine will 2211 * hold the rtentry lock; the caller is responsible for unlocking. 2212 */ 2213struct rtentry * 2214tcp_rtlookup(inp, input_ifscope) 2215 struct inpcb *inp; 2216 unsigned int input_ifscope; 2217{ 2218 struct route *ro; 2219 struct rtentry *rt; 2220 struct tcpcb *tp; 2221 2222 lck_mtx_assert(rnh_lock, LCK_MTX_ASSERT_NOTOWNED); 2223 2224 ro = &inp->inp_route; 2225 if ((rt = ro->ro_rt) != NULL) 2226 RT_LOCK(rt); 2227 2228 if (ROUTE_UNUSABLE(ro)) { 2229 if (rt != NULL) { 2230 RT_UNLOCK(rt); 2231 rt = NULL; 2232 } 2233 ROUTE_RELEASE(ro); 2234 /* No route yet, so try to acquire one */ 2235 if (inp->inp_faddr.s_addr != INADDR_ANY) { 2236 unsigned int ifscope; 2237 2238 ro->ro_dst.sa_family = AF_INET; 2239 ro->ro_dst.sa_len = sizeof(struct sockaddr_in); 2240 ((struct sockaddr_in *)(void *)&ro->ro_dst)->sin_addr = 2241 inp->inp_faddr; 2242 2243 /* 2244 * If the socket was bound to an interface, then 2245 * the bound-to-interface takes precedence over 2246 * the inbound interface passed in by the caller 2247 * (if we get here as part of the output path then 2248 * input_ifscope is IFSCOPE_NONE). 2249 */ 2250 ifscope = (inp->inp_flags & INP_BOUND_IF) ? 2251 inp->inp_boundifp->if_index : input_ifscope; 2252 2253 rtalloc_scoped(ro, ifscope); 2254 if ((rt = ro->ro_rt) != NULL) 2255 RT_LOCK(rt); 2256 } 2257 } 2258 if (rt != NULL) 2259 RT_LOCK_ASSERT_HELD(rt); 2260 2261 /* 2262 * Update MTU discovery determination. Don't do it if: 2263 * 1) it is disabled via the sysctl 2264 * 2) the route isn't up 2265 * 3) the MTU is locked (if it is, then discovery has been 2266 * disabled) 2267 */ 2268 2269 tp = intotcpcb(inp); 2270 2271 if (!path_mtu_discovery || ((rt != NULL) && 2272 (!(rt->rt_flags & RTF_UP) || (rt->rt_rmx.rmx_locks & RTV_MTU)))) 2273 tp->t_flags &= ~TF_PMTUD; 2274 else 2275 tp->t_flags |= TF_PMTUD; 2276 2277#if CONFIG_IFEF_NOWINDOWSCALE 2278 if (tcp_obey_ifef_nowindowscale && 2279 tp->t_state == TCPS_SYN_SENT && rt != NULL && rt->rt_ifp != NULL && 2280 (rt->rt_ifp->if_eflags & IFEF_NOWINDOWSCALE)) { 2281 /* Window scaling is enabled on this interface */ 2282 tp->t_flags &= ~TF_REQ_SCALE; 2283 } 2284#endif 2285 2286 if (rt != NULL && rt->rt_ifp != NULL) { 2287 somultipages(inp->inp_socket, 2288 (rt->rt_ifp->if_hwassist & IFNET_MULTIPAGES)); 2289 tcp_set_tso(tp, rt->rt_ifp); 2290 soif2kcl(inp->inp_socket, 2291 (rt->rt_ifp->if_eflags & IFEF_2KCL)); 2292 } 2293 2294 /* Note if the peer is local */ 2295 if (rt != NULL && !(rt->rt_ifp->if_flags & IFF_POINTOPOINT) && 2296 (rt->rt_gateway->sa_family == AF_LINK || 2297 rt->rt_ifp->if_flags & IFF_LOOPBACK || 2298 in_localaddr(inp->inp_faddr))) { 2299 tp->t_flags |= TF_LOCAL; 2300 } 2301 2302 /* 2303 * Caller needs to call RT_UNLOCK(rt). 2304 */ 2305 return rt; 2306} 2307 2308#if INET6 2309struct rtentry * 2310tcp_rtlookup6(inp, input_ifscope) 2311 struct inpcb *inp; 2312 unsigned int input_ifscope; 2313{ 2314 struct route_in6 *ro6; 2315 struct rtentry *rt; 2316 struct tcpcb *tp; 2317 2318 lck_mtx_assert(rnh_lock, LCK_MTX_ASSERT_NOTOWNED); 2319 2320 ro6 = &inp->in6p_route; 2321 if ((rt = ro6->ro_rt) != NULL) 2322 RT_LOCK(rt); 2323 2324 if (ROUTE_UNUSABLE(ro6)) { 2325 if (rt != NULL) { 2326 RT_UNLOCK(rt); 2327 rt = NULL; 2328 } 2329 ROUTE_RELEASE(ro6); 2330 /* No route yet, so try to acquire one */ 2331 if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) { 2332 struct sockaddr_in6 *dst6; 2333 unsigned int ifscope; 2334 2335 dst6 = (struct sockaddr_in6 *)&ro6->ro_dst; 2336 dst6->sin6_family = AF_INET6; 2337 dst6->sin6_len = sizeof(*dst6); 2338 dst6->sin6_addr = inp->in6p_faddr; 2339 2340 /* 2341 * If the socket was bound to an interface, then 2342 * the bound-to-interface takes precedence over 2343 * the inbound interface passed in by the caller 2344 * (if we get here as part of the output path then 2345 * input_ifscope is IFSCOPE_NONE). 2346 */ 2347 ifscope = (inp->inp_flags & INP_BOUND_IF) ? 2348 inp->inp_boundifp->if_index : input_ifscope; 2349 2350 rtalloc_scoped((struct route *)ro6, ifscope); 2351 if ((rt = ro6->ro_rt) != NULL) 2352 RT_LOCK(rt); 2353 } 2354 } 2355 if (rt != NULL) 2356 RT_LOCK_ASSERT_HELD(rt); 2357 2358 /* 2359 * Update path MTU Discovery determination 2360 * while looking up the route: 2361 * 1) we have a valid route to the destination 2362 * 2) the MTU is not locked (if it is, then discovery has been 2363 * disabled) 2364 */ 2365 2366 2367 tp = intotcpcb(inp); 2368 2369 /* 2370 * Update MTU discovery determination. Don't do it if: 2371 * 1) it is disabled via the sysctl 2372 * 2) the route isn't up 2373 * 3) the MTU is locked (if it is, then discovery has been 2374 * disabled) 2375 */ 2376 2377 if (!path_mtu_discovery || ((rt != NULL) && 2378 (!(rt->rt_flags & RTF_UP) || (rt->rt_rmx.rmx_locks & RTV_MTU)))) 2379 tp->t_flags &= ~TF_PMTUD; 2380 else 2381 tp->t_flags |= TF_PMTUD; 2382 2383#if CONFIG_IFEF_NOWINDOWSCALE 2384 if (tcp_obey_ifef_nowindowscale && 2385 tp->t_state == TCPS_SYN_SENT && rt != NULL && rt->rt_ifp != NULL && 2386 (rt->rt_ifp->if_eflags & IFEF_NOWINDOWSCALE)) { 2387 /* Window scaling is not enabled on this interface */ 2388 tp->t_flags &= ~TF_REQ_SCALE; 2389 } 2390#endif 2391 2392 if (rt != NULL && rt->rt_ifp != NULL) { 2393 somultipages(inp->inp_socket, 2394 (rt->rt_ifp->if_hwassist & IFNET_MULTIPAGES)); 2395 tcp_set_tso(tp, rt->rt_ifp); 2396 soif2kcl(inp->inp_socket, 2397 (rt->rt_ifp->if_eflags & IFEF_2KCL)); 2398 } 2399 2400 /* Note if the peer is local */ 2401 if (rt != NULL && !(rt->rt_ifp->if_flags & IFF_POINTOPOINT) && 2402 (IN6_IS_ADDR_LOOPBACK(&inp->in6p_faddr) || 2403 IN6_IS_ADDR_LINKLOCAL(&inp->in6p_faddr) || 2404 rt->rt_gateway->sa_family == AF_LINK || 2405 in6_localaddr(&inp->in6p_faddr))) { 2406 tp->t_flags |= TF_LOCAL; 2407 } 2408 2409 /* 2410 * Caller needs to call RT_UNLOCK(rt). 2411 */ 2412 return rt; 2413} 2414#endif /* INET6 */ 2415 2416#if IPSEC 2417/* compute ESP/AH header size for TCP, including outer IP header. */ 2418size_t 2419ipsec_hdrsiz_tcp(tp) 2420 struct tcpcb *tp; 2421{ 2422 struct inpcb *inp; 2423 struct mbuf *m; 2424 size_t hdrsiz; 2425 struct ip *ip; 2426#if INET6 2427 struct ip6_hdr *ip6 = NULL; 2428#endif /* INET6 */ 2429 struct tcphdr *th; 2430 2431 if ((tp == NULL) || ((inp = tp->t_inpcb) == NULL)) 2432 return 0; 2433 MGETHDR(m, M_DONTWAIT, MT_DATA); /* MAC-OK */ 2434 if (!m) 2435 return 0; 2436 2437#if INET6 2438 if ((inp->inp_vflag & INP_IPV6) != 0) { 2439 ip6 = mtod(m, struct ip6_hdr *); 2440 th = (struct tcphdr *)(void *)(ip6 + 1); 2441 m->m_pkthdr.len = m->m_len = 2442 sizeof(struct ip6_hdr) + sizeof(struct tcphdr); 2443 tcp_fillheaders(tp, ip6, th); 2444 hdrsiz = ipsec6_hdrsiz(m, IPSEC_DIR_OUTBOUND, inp); 2445 } else 2446#endif /* INET6 */ 2447 { 2448 ip = mtod(m, struct ip *); 2449 th = (struct tcphdr *)(ip + 1); 2450 m->m_pkthdr.len = m->m_len = sizeof(struct tcpiphdr); 2451 tcp_fillheaders(tp, ip, th); 2452 hdrsiz = ipsec4_hdrsiz(m, IPSEC_DIR_OUTBOUND, inp); 2453 } 2454 m_free(m); 2455 return hdrsiz; 2456} 2457#endif /*IPSEC*/ 2458 2459/* 2460 * Return a pointer to the cached information about the remote host. 2461 * The cached information is stored in the protocol specific part of 2462 * the route metrics. 2463 */ 2464struct rmxp_tao * 2465tcp_gettaocache(inp) 2466 struct inpcb *inp; 2467{ 2468 struct rtentry *rt; 2469 struct rmxp_tao *taop; 2470 2471#if INET6 2472 if ((inp->inp_vflag & INP_IPV6) != 0) 2473 rt = tcp_rtlookup6(inp, IFSCOPE_NONE); 2474 else 2475#endif /* INET6 */ 2476 rt = tcp_rtlookup(inp, IFSCOPE_NONE); 2477 2478 /* Make sure this is a host route and is up. */ 2479 if (rt == NULL || 2480 (rt->rt_flags & (RTF_UP|RTF_HOST)) != (RTF_UP|RTF_HOST)) { 2481 /* Route locked during lookup above */ 2482 if (rt != NULL) 2483 RT_UNLOCK(rt); 2484 return NULL; 2485 } 2486 2487 taop = rmx_taop(rt->rt_rmx); 2488 /* Route locked during lookup above */ 2489 RT_UNLOCK(rt); 2490 return (taop); 2491} 2492 2493/* 2494 * Clear all the TAO cache entries, called from tcp_init. 2495 * 2496 * XXX 2497 * This routine is just an empty one, because we assume that the routing 2498 * routing tables are initialized at the same time when TCP, so there is 2499 * nothing in the cache left over. 2500 */ 2501static void 2502tcp_cleartaocache() 2503{ 2504} 2505 2506int 2507tcp_lock(struct socket *so, int refcount, void *lr) 2508{ 2509 void *lr_saved; 2510 2511 if (lr == NULL) 2512 lr_saved = __builtin_return_address(0); 2513 else 2514 lr_saved = lr; 2515 2516 if (so->so_pcb != NULL) { 2517 lck_mtx_lock(&((struct inpcb *)so->so_pcb)->inpcb_mtx); 2518 } else { 2519 panic("tcp_lock: so=%p NO PCB! lr=%p lrh= %s\n", 2520 so, lr_saved, solockhistory_nr(so)); 2521 /* NOTREACHED */ 2522 } 2523 2524 if (so->so_usecount < 0) { 2525 panic("tcp_lock: so=%p so_pcb=%p lr=%p ref=%x lrh= %s\n", 2526 so, so->so_pcb, lr_saved, so->so_usecount, solockhistory_nr(so)); 2527 /* NOTREACHED */ 2528 } 2529 if (refcount) 2530 so->so_usecount++; 2531 so->lock_lr[so->next_lock_lr] = lr_saved; 2532 so->next_lock_lr = (so->next_lock_lr+1) % SO_LCKDBG_MAX; 2533 return (0); 2534} 2535 2536int 2537tcp_unlock(struct socket *so, int refcount, void *lr) 2538{ 2539 void *lr_saved; 2540 2541 if (lr == NULL) 2542 lr_saved = __builtin_return_address(0); 2543 else 2544 lr_saved = lr; 2545 2546#ifdef MORE_TCPLOCK_DEBUG 2547 printf("tcp_unlock: so=0x%llx sopcb=0x%llx lock=0x%llx ref=%x " 2548 "lr=0x%llx\n", (uint64_t)VM_KERNEL_ADDRPERM(so), 2549 (uint64_t)VM_KERNEL_ADDRPERM(so->so_pcb), 2550 (uint64_t)VM_KERNEL_ADDRPERM(&(sotoinpcb(so)->inpcb_mtx)), 2551 so->so_usecount, (uint64_t)VM_KERNEL_ADDRPERM(lr_saved)); 2552#endif 2553 if (refcount) 2554 so->so_usecount--; 2555 2556 if (so->so_usecount < 0) { 2557 panic("tcp_unlock: so=%p usecount=%x lrh= %s\n", 2558 so, so->so_usecount, solockhistory_nr(so)); 2559 /* NOTREACHED */ 2560 } 2561 if (so->so_pcb == NULL) { 2562 panic("tcp_unlock: so=%p NO PCB usecount=%x lr=%p lrh= %s\n", 2563 so, so->so_usecount, lr_saved, solockhistory_nr(so)); 2564 /* NOTREACHED */ 2565 } else { 2566 lck_mtx_assert(&((struct inpcb *)so->so_pcb)->inpcb_mtx, 2567 LCK_MTX_ASSERT_OWNED); 2568 so->unlock_lr[so->next_unlock_lr] = lr_saved; 2569 so->next_unlock_lr = (so->next_unlock_lr+1) % SO_LCKDBG_MAX; 2570 lck_mtx_unlock(&((struct inpcb *)so->so_pcb)->inpcb_mtx); 2571 } 2572 return (0); 2573} 2574 2575lck_mtx_t * 2576tcp_getlock( 2577 struct socket *so, 2578 __unused int locktype) 2579{ 2580 struct inpcb *inp = sotoinpcb(so); 2581 2582 if (so->so_pcb) { 2583 if (so->so_usecount < 0) 2584 panic("tcp_getlock: so=%p usecount=%x lrh= %s\n", 2585 so, so->so_usecount, solockhistory_nr(so)); 2586 return(&inp->inpcb_mtx); 2587 } 2588 else { 2589 panic("tcp_getlock: so=%p NULL so_pcb %s\n", 2590 so, solockhistory_nr(so)); 2591 return (so->so_proto->pr_domain->dom_mtx); 2592 } 2593} 2594 2595/* Determine if we can grow the recieve socket buffer to avoid sending 2596 * a zero window update to the peer. We allow even socket buffers that 2597 * have fixed size (set by the application) to grow if the resource 2598 * constraints are met. They will also be trimmed after the application 2599 * reads data. 2600 */ 2601static void 2602tcp_sbrcv_grow_rwin(struct tcpcb *tp, struct sockbuf *sb) { 2603 u_int32_t rcvbufinc = tp->t_maxseg << 4; 2604 u_int32_t rcvbuf = sb->sb_hiwat; 2605 struct socket *so = tp->t_inpcb->inp_socket; 2606 2607 /* 2608 * If message delivery is enabled, do not count 2609 * unordered bytes in receive buffer towards hiwat 2610 */ 2611 if (so->so_flags & SOF_ENABLE_MSGS) 2612 rcvbuf = rcvbuf - so->so_msg_state->msg_uno_bytes; 2613 2614 if (tcp_do_autorcvbuf == 1 && 2615 tcp_cansbgrow(sb) && 2616 (tp->t_flags & TF_SLOWLINK) == 0 && 2617 (rcvbuf - sb->sb_cc) < rcvbufinc && 2618 rcvbuf < tcp_autorcvbuf_max && 2619 (sb->sb_idealsize > 0 && 2620 sb->sb_hiwat <= (sb->sb_idealsize + rcvbufinc))) { 2621 sbreserve(sb, 2622 min((sb->sb_hiwat + rcvbufinc), tcp_autorcvbuf_max)); 2623 } 2624} 2625 2626int32_t 2627tcp_sbspace(struct tcpcb *tp) 2628{ 2629 struct sockbuf *sb = &tp->t_inpcb->inp_socket->so_rcv; 2630 u_int32_t rcvbuf = sb->sb_hiwat; 2631 int32_t space; 2632 struct socket *so = tp->t_inpcb->inp_socket; 2633 int32_t pending = 0; 2634 2635 /* 2636 * If message delivery is enabled, do not count 2637 * unordered bytes in receive buffer towards hiwat mark. 2638 * This value is used to return correct rwnd that does 2639 * not reflect the extra unordered bytes added to the 2640 * receive socket buffer. 2641 */ 2642 if (so->so_flags & SOF_ENABLE_MSGS) 2643 rcvbuf = rcvbuf - so->so_msg_state->msg_uno_bytes; 2644 2645 tcp_sbrcv_grow_rwin(tp, sb); 2646 2647 space = ((int32_t) imin((rcvbuf - sb->sb_cc), 2648 (sb->sb_mbmax - sb->sb_mbcnt))); 2649 if (space < 0) 2650 space = 0; 2651 2652#if CONTENT_FILTER 2653 /* Compensate for data being processed by content filters */ 2654 pending = cfil_sock_data_space(sb); 2655#endif /* CONTENT_FILTER */ 2656 if (pending > space) 2657 space = 0; 2658 else 2659 space -= pending; 2660 2661 /* Avoid increasing window size if the current window 2662 * is already very low, we could be in "persist" mode and 2663 * we could break some apps (see rdar://5409343) 2664 */ 2665 2666 if (space < tp->t_maxseg) 2667 return space; 2668 2669 /* Clip window size for slower link */ 2670 2671 if (((tp->t_flags & TF_SLOWLINK) != 0) && slowlink_wsize > 0 ) 2672 return imin(space, slowlink_wsize); 2673 2674 return space; 2675} 2676/* 2677 * Checks TCP Segment Offloading capability for a given connection 2678 * and interface pair. 2679 */ 2680void 2681tcp_set_tso(struct tcpcb *tp, struct ifnet *ifp) 2682{ 2683#if INET6 2684 struct inpcb *inp; 2685 int isipv6; 2686#endif /* INET6 */ 2687#if MPTCP 2688 /* 2689 * We can't use TSO if this tcpcb belongs to an MPTCP session. 2690 */ 2691 if (tp->t_mpflags & TMPF_MPTCP_TRUE) { 2692 tp->t_flags &= ~TF_TSO; 2693 return; 2694 } 2695#endif 2696#if INET6 2697 inp = tp->t_inpcb; 2698 isipv6 = (inp->inp_vflag & INP_IPV6) != 0; 2699 2700 if (isipv6) { 2701 if (ifp && (ifp->if_hwassist & IFNET_TSO_IPV6)) { 2702 tp->t_flags |= TF_TSO; 2703 if (ifp->if_tso_v6_mtu != 0) 2704 tp->tso_max_segment_size = ifp->if_tso_v6_mtu; 2705 else 2706 tp->tso_max_segment_size = TCP_MAXWIN; 2707 } else 2708 tp->t_flags &= ~TF_TSO; 2709 2710 } else 2711#endif /* INET6 */ 2712 2713 { 2714 if (ifp && (ifp->if_hwassist & IFNET_TSO_IPV4)) { 2715 tp->t_flags |= TF_TSO; 2716 if (ifp->if_tso_v4_mtu != 0) 2717 tp->tso_max_segment_size = ifp->if_tso_v4_mtu; 2718 else 2719 tp->tso_max_segment_size = TCP_MAXWIN; 2720 } else 2721 tp->t_flags &= ~TF_TSO; 2722 } 2723} 2724 2725#define TIMEVAL_TO_TCPHZ(_tv_) ((_tv_).tv_sec * TCP_RETRANSHZ + (_tv_).tv_usec / TCP_RETRANSHZ_TO_USEC) 2726 2727/* Function to calculate the tcp clock. The tcp clock will get updated 2728 * at the boundaries of the tcp layer. This is done at 3 places: 2729 * 1. Right before processing an input tcp packet 2730 * 2. Whenever a connection wants to access the network using tcp_usrreqs 2731 * 3. When a tcp timer fires or before tcp slow timeout 2732 * 2733 */ 2734 2735void 2736calculate_tcp_clock() 2737{ 2738 struct timeval tv = tcp_uptime; 2739 struct timeval interval = {0, TCP_RETRANSHZ_TO_USEC}; 2740 struct timeval now, hold_now; 2741 uint32_t incr = 0; 2742 2743 microuptime(&now); 2744 2745 /* 2746 * Update coarse-grained networking timestamp (in sec.); the idea 2747 * is to update the counter returnable via net_uptime() when 2748 * we read time. 2749 */ 2750 net_update_uptime_secs(now.tv_sec); 2751 2752 timevaladd(&tv, &interval); 2753 if (timevalcmp(&now, &tv, >)) { 2754 /* time to update the clock */ 2755 lck_spin_lock(tcp_uptime_lock); 2756 if (timevalcmp(&tcp_uptime, &now, >=)) { 2757 /* clock got updated while waiting for the lock */ 2758 lck_spin_unlock(tcp_uptime_lock); 2759 return; 2760 } 2761 2762 microuptime(&now); 2763 hold_now = now; 2764 tv = tcp_uptime; 2765 timevalsub(&now, &tv); 2766 2767 incr = TIMEVAL_TO_TCPHZ(now); 2768 if (incr > 0) { 2769 tcp_uptime = hold_now; 2770 tcp_now += incr; 2771 } 2772 2773 lck_spin_unlock(tcp_uptime_lock); 2774 } 2775 return; 2776} 2777 2778/* Compute receive window scaling that we are going to request 2779 * for this connection based on sb_hiwat. Try to leave some 2780 * room to potentially increase the window size upto a maximum 2781 * defined by the constant tcp_autorcvbuf_max. 2782 */ 2783void 2784tcp_set_max_rwinscale(struct tcpcb *tp, struct socket *so) { 2785 u_int32_t maxsockbufsize; 2786 2787 tp->request_r_scale = max(tcp_win_scale, tp->request_r_scale); 2788 maxsockbufsize = ((so->so_rcv.sb_flags & SB_USRSIZE) != 0) ? 2789 so->so_rcv.sb_hiwat : tcp_autorcvbuf_max; 2790 2791 while (tp->request_r_scale < TCP_MAX_WINSHIFT && 2792 (TCP_MAXWIN << tp->request_r_scale) < maxsockbufsize) 2793 tp->request_r_scale++; 2794 tp->request_r_scale = min(tp->request_r_scale, TCP_MAX_WINSHIFT); 2795 2796} 2797 2798int 2799tcp_notsent_lowat_check(struct socket *so) { 2800 struct inpcb *inp = sotoinpcb(so); 2801 struct tcpcb *tp = NULL; 2802 int notsent = 0; 2803 if (inp != NULL) { 2804 tp = intotcpcb(inp); 2805 } 2806 2807 notsent = so->so_snd.sb_cc - 2808 (tp->snd_nxt - tp->snd_una); 2809 2810 /* When we send a FIN or SYN, not_sent can be negative. 2811 * In that case also we need to send a write event to the 2812 * process if it is waiting. In the FIN case, it will 2813 * get an error from send because cantsendmore will be set. 2814 */ 2815 if (notsent <= tp->t_notsent_lowat) { 2816 return(1); 2817 } 2818 2819 /* When Nagle's algorithm is not disabled, it is better 2820 * to wakeup the client until there is atleast one 2821 * maxseg of data to write. 2822 */ 2823 if ((tp->t_flags & TF_NODELAY) == 0 && 2824 notsent > 0 && notsent < tp->t_maxseg) { 2825 return(1); 2826 } 2827 return(0); 2828} 2829 2830 2831/* DSEP Review Done pl-20051213-v02 @3253,@3391,@3400 */ 2832