1 /*- 2 * SPDX-License-Identifier: BSD-3-Clause 3 * 4 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995 5 * The Regents of the University of California. All rights reserved. 6 * Copyright (c) 2007-2008,2010 7 * Swinburne University of Technology, Melbourne, Australia. 8 * Copyright (c) 2009-2010 Lawrence Stewart <lstewart@freebsd.org> 9 * Copyright (c) 2010 The FreeBSD Foundation 10 * Copyright (c) 2010-2011 Juniper Networks, Inc. 11 * All rights reserved. 12 * 13 * Portions of this software were developed at the Centre for Advanced Internet 14 * Architectures, Swinburne University of Technology, by Lawrence Stewart, 15 * James Healy and David Hayes, made possible in part by a grant from the Cisco 16 * University Research Program Fund at Community Foundation Silicon Valley. 17 * 18 * Portions of this software were developed at the Centre for Advanced 19 * Internet Architectures, Swinburne University of Technology, Melbourne, 20 * Australia by David Hayes under sponsorship from the FreeBSD Foundation. 21 * 22 * Portions of this software were developed by Robert N. M. Watson under 23 * contract to Juniper Networks, Inc. 24 * 25 * Redistribution and use in source and binary forms, with or without 26 * modification, are permitted provided that the following conditions 27 * are met: 28 * 1. Redistributions of source code must retain the above copyright 29 * notice, this list of conditions and the following disclaimer. 30 * 2. Redistributions in binary form must reproduce the above copyright 31 * notice, this list of conditions and the following disclaimer in the 32 * documentation and/or other materials provided with the distribution. 33 * 3. Neither the name of the University nor the names of its contributors 34 * may be used to endorse or promote products derived from this software 35 * without specific prior written permission. 36 * 37 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 38 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 39 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 40 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 41 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 42 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 43 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 44 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 45 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 46 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 47 * SUCH DAMAGE. 48 * 49 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95 50 */ 51 52 #include <sys/cdefs.h> 53 __FBSDID("$FreeBSD$"); 54 55 #include "opt_inet.h" 56 #include "opt_inet6.h" 57 #include "opt_ipsec.h" 58 #include "opt_tcpdebug.h" 59 60 #include <sys/param.h> 61 #include <sys/arb.h> 62 #include <sys/kernel.h> 63 #ifdef TCP_HHOOK 64 #include <sys/hhook.h> 65 #endif 66 #include <sys/malloc.h> 67 #include <sys/mbuf.h> 68 #include <sys/proc.h> /* for proc0 declaration */ 69 #include <sys/protosw.h> 70 #include <sys/qmath.h> 71 #include <sys/sdt.h> 72 #include <sys/signalvar.h> 73 #include <sys/socket.h> 74 #include <sys/socketvar.h> 75 #include <sys/sysctl.h> 76 #include <sys/syslog.h> 77 #include <sys/systm.h> 78 #include <sys/stats.h> 79 80 #include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */ 81 82 #include <vm/uma.h> 83 84 #include <net/if.h> 85 #include <net/if_var.h> 86 #include <net/route.h> 87 #include <net/vnet.h> 88 89 #define TCPSTATES /* for logging */ 90 91 #include <netinet/in.h> 92 #include <netinet/in_kdtrace.h> 93 #include <netinet/in_pcb.h> 94 #include <netinet/in_systm.h> 95 #include <netinet/ip.h> 96 #include <netinet/ip_icmp.h> /* required for icmp_var.h */ 97 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */ 98 #include <netinet/ip_var.h> 99 #include <netinet/ip_options.h> 100 #include <netinet/ip6.h> 101 #include <netinet/icmp6.h> 102 #include <netinet6/in6_pcb.h> 103 #include <netinet6/in6_var.h> 104 #include <netinet6/ip6_var.h> 105 #include <netinet6/nd6.h> 106 #include <netinet/tcp.h> 107 #include <netinet/tcp_fsm.h> 108 #include <netinet/tcp_log_buf.h> 109 #include <netinet/tcp_seq.h> 110 #include <netinet/tcp_timer.h> 111 #include <netinet/tcp_var.h> 112 #include <netinet6/tcp6_var.h> 113 #include <netinet/tcpip.h> 114 #include <netinet/cc/cc.h> 115 #include <netinet/tcp_fastopen.h> 116 #ifdef TCPPCAP 117 #include <netinet/tcp_pcap.h> 118 #endif 119 #include <netinet/tcp_syncache.h> 120 #ifdef TCPDEBUG 121 #include <netinet/tcp_debug.h> 122 #endif /* TCPDEBUG */ 123 #ifdef TCP_OFFLOAD 124 #include <netinet/tcp_offload.h> 125 #endif 126 127 #include <netipsec/ipsec_support.h> 128 129 #include <machine/in_cksum.h> 130 131 #include <security/mac/mac_framework.h> 132 133 const int tcprexmtthresh = 3; 134 135 VNET_DEFINE(int, tcp_log_in_vain) = 0; 136 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_VNET | CTLFLAG_RW, 137 &VNET_NAME(tcp_log_in_vain), 0, 138 "Log all incoming TCP segments to closed ports"); 139 140 VNET_DEFINE(int, blackhole) = 0; 141 #define V_blackhole VNET(blackhole) 142 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_VNET | CTLFLAG_RW, 143 &VNET_NAME(blackhole), 0, 144 "Do not send RST on segments to closed ports"); 145 146 VNET_DEFINE(int, tcp_delack_enabled) = 1; 147 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_VNET | CTLFLAG_RW, 148 &VNET_NAME(tcp_delack_enabled), 0, 149 "Delay ACK to try and piggyback it onto a data packet"); 150 151 VNET_DEFINE(int, drop_synfin) = 0; 152 SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_VNET | CTLFLAG_RW, 153 &VNET_NAME(drop_synfin), 0, 154 "Drop TCP packets with SYN+FIN set"); 155 156 VNET_DEFINE(int, tcp_do_newcwv) = 0; 157 SYSCTL_INT(_net_inet_tcp, OID_AUTO, newcwv, CTLFLAG_VNET | CTLFLAG_RW, 158 &VNET_NAME(tcp_do_newcwv), 0, 159 "Enable New Congestion Window Validation per RFC7661"); 160 161 VNET_DEFINE(int, tcp_do_rfc6675_pipe) = 0; 162 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc6675_pipe, CTLFLAG_VNET | CTLFLAG_RW, 163 &VNET_NAME(tcp_do_rfc6675_pipe), 0, 164 "Use calculated pipe/in-flight bytes per RFC 6675"); 165 166 VNET_DEFINE(int, tcp_do_rfc3042) = 1; 167 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3042, CTLFLAG_VNET | CTLFLAG_RW, 168 &VNET_NAME(tcp_do_rfc3042), 0, 169 "Enable RFC 3042 (Limited Transmit)"); 170 171 VNET_DEFINE(int, tcp_do_rfc3390) = 1; 172 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_VNET | CTLFLAG_RW, 173 &VNET_NAME(tcp_do_rfc3390), 0, 174 "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)"); 175 176 VNET_DEFINE(int, tcp_initcwnd_segments) = 10; 177 SYSCTL_INT(_net_inet_tcp, OID_AUTO, initcwnd_segments, 178 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(tcp_initcwnd_segments), 0, 179 "Slow-start flight size (initial congestion window) in number of segments"); 180 181 VNET_DEFINE(int, tcp_do_rfc3465) = 1; 182 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3465, CTLFLAG_VNET | CTLFLAG_RW, 183 &VNET_NAME(tcp_do_rfc3465), 0, 184 "Enable RFC 3465 (Appropriate Byte Counting)"); 185 186 VNET_DEFINE(int, tcp_abc_l_var) = 2; 187 SYSCTL_INT(_net_inet_tcp, OID_AUTO, abc_l_var, CTLFLAG_VNET | CTLFLAG_RW, 188 &VNET_NAME(tcp_abc_l_var), 2, 189 "Cap the max cwnd increment during slow-start to this number of segments"); 190 191 static SYSCTL_NODE(_net_inet_tcp, OID_AUTO, ecn, 192 CTLFLAG_RW | CTLFLAG_MPSAFE, 0, 193 "TCP ECN"); 194 195 VNET_DEFINE(int, tcp_do_ecn) = 2; 196 SYSCTL_INT(_net_inet_tcp_ecn, OID_AUTO, enable, CTLFLAG_VNET | CTLFLAG_RW, 197 &VNET_NAME(tcp_do_ecn), 0, 198 "TCP ECN support"); 199 200 VNET_DEFINE(int, tcp_ecn_maxretries) = 1; 201 SYSCTL_INT(_net_inet_tcp_ecn, OID_AUTO, maxretries, CTLFLAG_VNET | CTLFLAG_RW, 202 &VNET_NAME(tcp_ecn_maxretries), 0, 203 "Max retries before giving up on ECN"); 204 205 VNET_DEFINE(int, tcp_insecure_syn) = 0; 206 SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_syn, CTLFLAG_VNET | CTLFLAG_RW, 207 &VNET_NAME(tcp_insecure_syn), 0, 208 "Follow RFC793 instead of RFC5961 criteria for accepting SYN packets"); 209 210 VNET_DEFINE(int, tcp_insecure_rst) = 0; 211 SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_rst, CTLFLAG_VNET | CTLFLAG_RW, 212 &VNET_NAME(tcp_insecure_rst), 0, 213 "Follow RFC793 instead of RFC5961 criteria for accepting RST packets"); 214 215 VNET_DEFINE(int, tcp_recvspace) = 1024*64; 216 #define V_tcp_recvspace VNET(tcp_recvspace) 217 SYSCTL_INT(_net_inet_tcp, TCPCTL_RECVSPACE, recvspace, CTLFLAG_VNET | CTLFLAG_RW, 218 &VNET_NAME(tcp_recvspace), 0, "Initial receive socket buffer size"); 219 220 VNET_DEFINE(int, tcp_do_autorcvbuf) = 1; 221 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_VNET | CTLFLAG_RW, 222 &VNET_NAME(tcp_do_autorcvbuf), 0, 223 "Enable automatic receive buffer sizing"); 224 225 VNET_DEFINE(int, tcp_autorcvbuf_max) = 2*1024*1024; 226 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_VNET | CTLFLAG_RW, 227 &VNET_NAME(tcp_autorcvbuf_max), 0, 228 "Max size of automatic receive buffer"); 229 230 VNET_DEFINE(struct inpcbhead, tcb); 231 #define tcb6 tcb /* for KAME src sync over BSD*'s */ 232 VNET_DEFINE(struct inpcbinfo, tcbinfo); 233 234 /* 235 * TCP statistics are stored in an array of counter(9)s, which size matches 236 * size of struct tcpstat. TCP running connection count is a regular array. 237 */ 238 VNET_PCPUSTAT_DEFINE(struct tcpstat, tcpstat); 239 SYSCTL_VNET_PCPUSTAT(_net_inet_tcp, TCPCTL_STATS, stats, struct tcpstat, 240 tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)"); 241 VNET_DEFINE(counter_u64_t, tcps_states[TCP_NSTATES]); 242 SYSCTL_COUNTER_U64_ARRAY(_net_inet_tcp, TCPCTL_STATES, states, CTLFLAG_RD | 243 CTLFLAG_VNET, &VNET_NAME(tcps_states)[0], TCP_NSTATES, 244 "TCP connection counts by TCP state"); 245 246 static void 247 tcp_vnet_init(const void *unused) 248 { 249 250 COUNTER_ARRAY_ALLOC(V_tcps_states, TCP_NSTATES, M_WAITOK); 251 VNET_PCPUSTAT_ALLOC(tcpstat, M_WAITOK); 252 } 253 VNET_SYSINIT(tcp_vnet_init, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY, 254 tcp_vnet_init, NULL); 255 256 #ifdef VIMAGE 257 static void 258 tcp_vnet_uninit(const void *unused) 259 { 260 261 COUNTER_ARRAY_FREE(V_tcps_states, TCP_NSTATES); 262 VNET_PCPUSTAT_FREE(tcpstat); 263 } 264 VNET_SYSUNINIT(tcp_vnet_uninit, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY, 265 tcp_vnet_uninit, NULL); 266 #endif /* VIMAGE */ 267 268 /* 269 * Kernel module interface for updating tcpstat. The first argument is an index 270 * into tcpstat treated as an array. 271 */ 272 void 273 kmod_tcpstat_add(int statnum, int val) 274 { 275 276 counter_u64_add(VNET(tcpstat)[statnum], val); 277 } 278 279 #ifdef TCP_HHOOK 280 /* 281 * Wrapper for the TCP established input helper hook. 282 */ 283 void 284 hhook_run_tcp_est_in(struct tcpcb *tp, struct tcphdr *th, struct tcpopt *to) 285 { 286 struct tcp_hhook_data hhook_data; 287 288 if (V_tcp_hhh[HHOOK_TCP_EST_IN]->hhh_nhooks > 0) { 289 hhook_data.tp = tp; 290 hhook_data.th = th; 291 hhook_data.to = to; 292 293 hhook_run_hooks(V_tcp_hhh[HHOOK_TCP_EST_IN], &hhook_data, 294 tp->osd); 295 } 296 } 297 #endif 298 299 /* 300 * CC wrapper hook functions 301 */ 302 void 303 cc_ack_received(struct tcpcb *tp, struct tcphdr *th, uint16_t nsegs, 304 uint16_t type) 305 { 306 #ifdef STATS 307 int32_t gput; 308 #endif 309 310 INP_WLOCK_ASSERT(tp->t_inpcb); 311 312 tp->ccv->nsegs = nsegs; 313 tp->ccv->bytes_this_ack = BYTES_THIS_ACK(tp, th); 314 if ((!V_tcp_do_newcwv && (tp->snd_cwnd <= tp->snd_wnd)) || 315 (V_tcp_do_newcwv && (tp->snd_cwnd <= tp->snd_wnd) && 316 (tp->snd_cwnd < (tcp_compute_pipe(tp) * 2)))) 317 tp->ccv->flags |= CCF_CWND_LIMITED; 318 else 319 tp->ccv->flags &= ~CCF_CWND_LIMITED; 320 321 if (type == CC_ACK) { 322 #ifdef STATS 323 stats_voi_update_abs_s32(tp->t_stats, VOI_TCP_CALCFRWINDIFF, 324 ((int32_t)tp->snd_cwnd) - tp->snd_wnd); 325 if (!IN_RECOVERY(tp->t_flags)) 326 stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_ACKLEN, 327 tp->ccv->bytes_this_ack / (tcp_maxseg(tp) * nsegs)); 328 if ((tp->t_flags & TF_GPUTINPROG) && 329 SEQ_GEQ(th->th_ack, tp->gput_ack)) { 330 /* 331 * Compute goodput in bits per millisecond. 332 */ 333 gput = (((int64_t)(th->th_ack - tp->gput_seq)) << 3) / 334 max(1, tcp_ts_getticks() - tp->gput_ts); 335 stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_GPUT, 336 gput); 337 /* 338 * XXXLAS: This is a temporary hack, and should be 339 * chained off VOI_TCP_GPUT when stats(9) grows an API 340 * to deal with chained VOIs. 341 */ 342 if (tp->t_stats_gput_prev > 0) 343 stats_voi_update_abs_s32(tp->t_stats, 344 VOI_TCP_GPUT_ND, 345 ((gput - tp->t_stats_gput_prev) * 100) / 346 tp->t_stats_gput_prev); 347 tp->t_flags &= ~TF_GPUTINPROG; 348 tp->t_stats_gput_prev = gput; 349 } 350 #endif /* STATS */ 351 if (tp->snd_cwnd > tp->snd_ssthresh) { 352 tp->t_bytes_acked += min(tp->ccv->bytes_this_ack, 353 nsegs * V_tcp_abc_l_var * tcp_maxseg(tp)); 354 if (tp->t_bytes_acked >= tp->snd_cwnd) { 355 tp->t_bytes_acked -= tp->snd_cwnd; 356 tp->ccv->flags |= CCF_ABC_SENTAWND; 357 } 358 } else { 359 tp->ccv->flags &= ~CCF_ABC_SENTAWND; 360 tp->t_bytes_acked = 0; 361 } 362 } 363 364 if (CC_ALGO(tp)->ack_received != NULL) { 365 /* XXXLAS: Find a way to live without this */ 366 tp->ccv->curack = th->th_ack; 367 CC_ALGO(tp)->ack_received(tp->ccv, type); 368 } 369 #ifdef STATS 370 stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_LCWIN, tp->snd_cwnd); 371 #endif 372 } 373 374 void 375 cc_conn_init(struct tcpcb *tp) 376 { 377 struct hc_metrics_lite metrics; 378 struct inpcb *inp = tp->t_inpcb; 379 u_int maxseg; 380 int rtt; 381 382 INP_WLOCK_ASSERT(tp->t_inpcb); 383 384 tcp_hc_get(&inp->inp_inc, &metrics); 385 maxseg = tcp_maxseg(tp); 386 387 if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) { 388 tp->t_srtt = rtt; 389 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE; 390 TCPSTAT_INC(tcps_usedrtt); 391 if (metrics.rmx_rttvar) { 392 tp->t_rttvar = metrics.rmx_rttvar; 393 TCPSTAT_INC(tcps_usedrttvar); 394 } else { 395 /* default variation is +- 1 rtt */ 396 tp->t_rttvar = 397 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE; 398 } 399 TCPT_RANGESET(tp->t_rxtcur, 400 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1, 401 tp->t_rttmin, TCPTV_REXMTMAX); 402 } 403 if (metrics.rmx_ssthresh) { 404 /* 405 * There's some sort of gateway or interface 406 * buffer limit on the path. Use this to set 407 * the slow start threshold, but set the 408 * threshold to no less than 2*mss. 409 */ 410 tp->snd_ssthresh = max(2 * maxseg, metrics.rmx_ssthresh); 411 TCPSTAT_INC(tcps_usedssthresh); 412 } 413 414 /* 415 * Set the initial slow-start flight size. 416 * 417 * If a SYN or SYN/ACK was lost and retransmitted, we have to 418 * reduce the initial CWND to one segment as congestion is likely 419 * requiring us to be cautious. 420 */ 421 if (tp->snd_cwnd == 1) 422 tp->snd_cwnd = maxseg; /* SYN(-ACK) lost */ 423 else 424 tp->snd_cwnd = tcp_compute_initwnd(maxseg); 425 426 if (CC_ALGO(tp)->conn_init != NULL) 427 CC_ALGO(tp)->conn_init(tp->ccv); 428 } 429 430 void inline 431 cc_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type) 432 { 433 u_int maxseg; 434 435 INP_WLOCK_ASSERT(tp->t_inpcb); 436 437 #ifdef STATS 438 stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_CSIG, type); 439 #endif 440 441 switch(type) { 442 case CC_NDUPACK: 443 if (!IN_FASTRECOVERY(tp->t_flags)) { 444 tp->snd_recover = tp->snd_max; 445 if (tp->t_flags2 & TF2_ECN_PERMIT) 446 tp->t_flags2 |= TF2_ECN_SND_CWR; 447 } 448 break; 449 case CC_ECN: 450 if (!IN_CONGRECOVERY(tp->t_flags)) { 451 TCPSTAT_INC(tcps_ecn_rcwnd); 452 tp->snd_recover = tp->snd_max; 453 if (tp->t_flags2 & TF2_ECN_PERMIT) 454 tp->t_flags2 |= TF2_ECN_SND_CWR; 455 } 456 break; 457 case CC_RTO: 458 maxseg = tcp_maxseg(tp); 459 tp->t_dupacks = 0; 460 tp->t_bytes_acked = 0; 461 EXIT_RECOVERY(tp->t_flags); 462 tp->snd_ssthresh = max(2, min(tp->snd_wnd, tp->snd_cwnd) / 2 / 463 maxseg) * maxseg; 464 tp->snd_cwnd = maxseg; 465 if (tp->t_flags2 & TF2_ECN_PERMIT) 466 tp->t_flags2 |= TF2_ECN_SND_CWR; 467 break; 468 case CC_RTO_ERR: 469 TCPSTAT_INC(tcps_sndrexmitbad); 470 /* RTO was unnecessary, so reset everything. */ 471 tp->snd_cwnd = tp->snd_cwnd_prev; 472 tp->snd_ssthresh = tp->snd_ssthresh_prev; 473 tp->snd_recover = tp->snd_recover_prev; 474 if (tp->t_flags & TF_WASFRECOVERY) 475 ENTER_FASTRECOVERY(tp->t_flags); 476 if (tp->t_flags & TF_WASCRECOVERY) 477 ENTER_CONGRECOVERY(tp->t_flags); 478 tp->snd_nxt = tp->snd_max; 479 tp->t_flags &= ~TF_PREVVALID; 480 tp->t_badrxtwin = 0; 481 break; 482 } 483 484 if (CC_ALGO(tp)->cong_signal != NULL) { 485 if (th != NULL) 486 tp->ccv->curack = th->th_ack; 487 CC_ALGO(tp)->cong_signal(tp->ccv, type); 488 } 489 } 490 491 void inline 492 cc_post_recovery(struct tcpcb *tp, struct tcphdr *th) 493 { 494 INP_WLOCK_ASSERT(tp->t_inpcb); 495 496 /* XXXLAS: KASSERT that we're in recovery? */ 497 498 if (CC_ALGO(tp)->post_recovery != NULL) { 499 tp->ccv->curack = th->th_ack; 500 CC_ALGO(tp)->post_recovery(tp->ccv); 501 } 502 /* XXXLAS: EXIT_RECOVERY ? */ 503 tp->t_bytes_acked = 0; 504 } 505 506 /* 507 * Indicate whether this ack should be delayed. We can delay the ack if 508 * following conditions are met: 509 * - There is no delayed ack timer in progress. 510 * - Our last ack wasn't a 0-sized window. We never want to delay 511 * the ack that opens up a 0-sized window. 512 * - LRO wasn't used for this segment. We make sure by checking that the 513 * segment size is not larger than the MSS. 514 */ 515 #define DELAY_ACK(tp, tlen) \ 516 ((!tcp_timer_active(tp, TT_DELACK) && \ 517 (tp->t_flags & TF_RXWIN0SENT) == 0) && \ 518 (tlen <= tp->t_maxseg) && \ 519 (V_tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN))) 520 521 void inline 522 cc_ecnpkt_handler(struct tcpcb *tp, struct tcphdr *th, uint8_t iptos) 523 { 524 INP_WLOCK_ASSERT(tp->t_inpcb); 525 526 if (CC_ALGO(tp)->ecnpkt_handler != NULL) { 527 switch (iptos & IPTOS_ECN_MASK) { 528 case IPTOS_ECN_CE: 529 tp->ccv->flags |= CCF_IPHDR_CE; 530 break; 531 case IPTOS_ECN_ECT0: 532 /* FALLTHROUGH */ 533 case IPTOS_ECN_ECT1: 534 /* FALLTHROUGH */ 535 case IPTOS_ECN_NOTECT: 536 tp->ccv->flags &= ~CCF_IPHDR_CE; 537 break; 538 } 539 540 if (th->th_flags & TH_CWR) 541 tp->ccv->flags |= CCF_TCPHDR_CWR; 542 else 543 tp->ccv->flags &= ~CCF_TCPHDR_CWR; 544 545 CC_ALGO(tp)->ecnpkt_handler(tp->ccv); 546 547 if (tp->ccv->flags & CCF_ACKNOW) { 548 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime); 549 tp->t_flags |= TF_ACKNOW; 550 } 551 } 552 } 553 554 /* 555 * TCP input handling is split into multiple parts: 556 * tcp6_input is a thin wrapper around tcp_input for the extended 557 * ip6_protox[] call format in ip6_input 558 * tcp_input handles primary segment validation, inpcb lookup and 559 * SYN processing on listen sockets 560 * tcp_do_segment processes the ACK and text of the segment for 561 * establishing, established and closing connections 562 */ 563 #ifdef INET6 564 int 565 tcp6_input(struct mbuf **mp, int *offp, int proto) 566 { 567 struct mbuf *m; 568 struct in6_ifaddr *ia6; 569 struct ip6_hdr *ip6; 570 571 m = *mp; 572 if (m->m_len < *offp + sizeof(struct tcphdr)) { 573 m = m_pullup(m, *offp + sizeof(struct tcphdr)); 574 if (m == NULL) { 575 *mp = m; 576 TCPSTAT_INC(tcps_rcvshort); 577 return (IPPROTO_DONE); 578 } 579 } 580 581 /* 582 * draft-itojun-ipv6-tcp-to-anycast 583 * better place to put this in? 584 */ 585 ip6 = mtod(m, struct ip6_hdr *); 586 ia6 = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */); 587 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) { 588 589 ifa_free(&ia6->ia_ifa); 590 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR, 591 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6); 592 *mp = NULL; 593 return (IPPROTO_DONE); 594 } 595 if (ia6) 596 ifa_free(&ia6->ia_ifa); 597 598 *mp = m; 599 return (tcp_input(mp, offp, proto)); 600 } 601 #endif /* INET6 */ 602 603 int 604 tcp_input(struct mbuf **mp, int *offp, int proto) 605 { 606 struct mbuf *m = *mp; 607 struct tcphdr *th = NULL; 608 struct ip *ip = NULL; 609 struct inpcb *inp = NULL; 610 struct tcpcb *tp = NULL; 611 struct socket *so = NULL; 612 u_char *optp = NULL; 613 int off0; 614 int optlen = 0; 615 #ifdef INET 616 int len; 617 uint8_t ipttl; 618 #endif 619 int tlen = 0, off; 620 int drop_hdrlen; 621 int thflags; 622 int rstreason = 0; /* For badport_bandlim accounting purposes */ 623 uint8_t iptos; 624 struct m_tag *fwd_tag = NULL; 625 #ifdef INET6 626 struct ip6_hdr *ip6 = NULL; 627 int isipv6; 628 #else 629 const void *ip6 = NULL; 630 #endif /* INET6 */ 631 struct tcpopt to; /* options in this segment */ 632 char *s = NULL; /* address and port logging */ 633 #ifdef TCPDEBUG 634 /* 635 * The size of tcp_saveipgen must be the size of the max ip header, 636 * now IPv6. 637 */ 638 u_char tcp_saveipgen[IP6_HDR_LEN]; 639 struct tcphdr tcp_savetcp; 640 short ostate = 0; 641 #endif 642 643 NET_EPOCH_ASSERT(); 644 645 #ifdef INET6 646 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0; 647 #endif 648 649 off0 = *offp; 650 m = *mp; 651 *mp = NULL; 652 to.to_flags = 0; 653 TCPSTAT_INC(tcps_rcvtotal); 654 655 #ifdef INET6 656 if (isipv6) { 657 658 ip6 = mtod(m, struct ip6_hdr *); 659 th = (struct tcphdr *)((caddr_t)ip6 + off0); 660 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0; 661 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID_IPV6) { 662 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) 663 th->th_sum = m->m_pkthdr.csum_data; 664 else 665 th->th_sum = in6_cksum_pseudo(ip6, tlen, 666 IPPROTO_TCP, m->m_pkthdr.csum_data); 667 th->th_sum ^= 0xffff; 668 } else 669 th->th_sum = in6_cksum(m, IPPROTO_TCP, off0, tlen); 670 if (th->th_sum) { 671 TCPSTAT_INC(tcps_rcvbadsum); 672 goto drop; 673 } 674 675 /* 676 * Be proactive about unspecified IPv6 address in source. 677 * As we use all-zero to indicate unbounded/unconnected pcb, 678 * unspecified IPv6 address can be used to confuse us. 679 * 680 * Note that packets with unspecified IPv6 destination is 681 * already dropped in ip6_input. 682 */ 683 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) { 684 /* XXX stat */ 685 goto drop; 686 } 687 iptos = (ntohl(ip6->ip6_flow) >> 20) & 0xff; 688 } 689 #endif 690 #if defined(INET) && defined(INET6) 691 else 692 #endif 693 #ifdef INET 694 { 695 /* 696 * Get IP and TCP header together in first mbuf. 697 * Note: IP leaves IP header in first mbuf. 698 */ 699 if (off0 > sizeof (struct ip)) { 700 ip_stripoptions(m); 701 off0 = sizeof(struct ip); 702 } 703 if (m->m_len < sizeof (struct tcpiphdr)) { 704 if ((m = m_pullup(m, sizeof (struct tcpiphdr))) 705 == NULL) { 706 TCPSTAT_INC(tcps_rcvshort); 707 return (IPPROTO_DONE); 708 } 709 } 710 ip = mtod(m, struct ip *); 711 th = (struct tcphdr *)((caddr_t)ip + off0); 712 tlen = ntohs(ip->ip_len) - off0; 713 714 iptos = ip->ip_tos; 715 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) { 716 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) 717 th->th_sum = m->m_pkthdr.csum_data; 718 else 719 th->th_sum = in_pseudo(ip->ip_src.s_addr, 720 ip->ip_dst.s_addr, 721 htonl(m->m_pkthdr.csum_data + tlen + 722 IPPROTO_TCP)); 723 th->th_sum ^= 0xffff; 724 } else { 725 struct ipovly *ipov = (struct ipovly *)ip; 726 727 /* 728 * Checksum extended TCP header and data. 729 */ 730 len = off0 + tlen; 731 ipttl = ip->ip_ttl; 732 bzero(ipov->ih_x1, sizeof(ipov->ih_x1)); 733 ipov->ih_len = htons(tlen); 734 th->th_sum = in_cksum(m, len); 735 /* Reset length for SDT probes. */ 736 ip->ip_len = htons(len); 737 /* Reset TOS bits */ 738 ip->ip_tos = iptos; 739 /* Re-initialization for later version check */ 740 ip->ip_ttl = ipttl; 741 ip->ip_v = IPVERSION; 742 ip->ip_hl = off0 >> 2; 743 } 744 745 if (th->th_sum) { 746 TCPSTAT_INC(tcps_rcvbadsum); 747 goto drop; 748 } 749 } 750 #endif /* INET */ 751 752 /* 753 * Check that TCP offset makes sense, 754 * pull out TCP options and adjust length. XXX 755 */ 756 off = th->th_off << 2; 757 if (off < sizeof (struct tcphdr) || off > tlen) { 758 TCPSTAT_INC(tcps_rcvbadoff); 759 goto drop; 760 } 761 tlen -= off; /* tlen is used instead of ti->ti_len */ 762 if (off > sizeof (struct tcphdr)) { 763 #ifdef INET6 764 if (isipv6) { 765 if (m->m_len < off0 + off) { 766 m = m_pullup(m, off0 + off); 767 if (m == NULL) { 768 TCPSTAT_INC(tcps_rcvshort); 769 return (IPPROTO_DONE); 770 } 771 } 772 ip6 = mtod(m, struct ip6_hdr *); 773 th = (struct tcphdr *)((caddr_t)ip6 + off0); 774 } 775 #endif 776 #if defined(INET) && defined(INET6) 777 else 778 #endif 779 #ifdef INET 780 { 781 if (m->m_len < sizeof(struct ip) + off) { 782 if ((m = m_pullup(m, sizeof (struct ip) + off)) 783 == NULL) { 784 TCPSTAT_INC(tcps_rcvshort); 785 return (IPPROTO_DONE); 786 } 787 ip = mtod(m, struct ip *); 788 th = (struct tcphdr *)((caddr_t)ip + off0); 789 } 790 } 791 #endif 792 optlen = off - sizeof (struct tcphdr); 793 optp = (u_char *)(th + 1); 794 } 795 thflags = th->th_flags; 796 797 /* 798 * Convert TCP protocol specific fields to host format. 799 */ 800 tcp_fields_to_host(th); 801 802 /* 803 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options. 804 */ 805 drop_hdrlen = off0 + off; 806 807 /* 808 * Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain. 809 */ 810 if ( 811 #ifdef INET6 812 (isipv6 && (m->m_flags & M_IP6_NEXTHOP)) 813 #ifdef INET 814 || (!isipv6 && (m->m_flags & M_IP_NEXTHOP)) 815 #endif 816 #endif 817 #if defined(INET) && !defined(INET6) 818 (m->m_flags & M_IP_NEXTHOP) 819 #endif 820 ) 821 fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL); 822 823 findpcb: 824 #ifdef INET6 825 if (isipv6 && fwd_tag != NULL) { 826 struct sockaddr_in6 *next_hop6; 827 828 next_hop6 = (struct sockaddr_in6 *)(fwd_tag + 1); 829 /* 830 * Transparently forwarded. Pretend to be the destination. 831 * Already got one like this? 832 */ 833 inp = in6_pcblookup_mbuf(&V_tcbinfo, 834 &ip6->ip6_src, th->th_sport, &ip6->ip6_dst, th->th_dport, 835 INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif, m); 836 if (!inp) { 837 /* 838 * It's new. Try to find the ambushing socket. 839 * Because we've rewritten the destination address, 840 * any hardware-generated hash is ignored. 841 */ 842 inp = in6_pcblookup(&V_tcbinfo, &ip6->ip6_src, 843 th->th_sport, &next_hop6->sin6_addr, 844 next_hop6->sin6_port ? ntohs(next_hop6->sin6_port) : 845 th->th_dport, INPLOOKUP_WILDCARD | 846 INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif); 847 } 848 } else if (isipv6) { 849 inp = in6_pcblookup_mbuf(&V_tcbinfo, &ip6->ip6_src, 850 th->th_sport, &ip6->ip6_dst, th->th_dport, 851 INPLOOKUP_WILDCARD | INPLOOKUP_WLOCKPCB, 852 m->m_pkthdr.rcvif, m); 853 } 854 #endif /* INET6 */ 855 #if defined(INET6) && defined(INET) 856 else 857 #endif 858 #ifdef INET 859 if (fwd_tag != NULL) { 860 struct sockaddr_in *next_hop; 861 862 next_hop = (struct sockaddr_in *)(fwd_tag+1); 863 /* 864 * Transparently forwarded. Pretend to be the destination. 865 * already got one like this? 866 */ 867 inp = in_pcblookup_mbuf(&V_tcbinfo, ip->ip_src, th->th_sport, 868 ip->ip_dst, th->th_dport, INPLOOKUP_WLOCKPCB, 869 m->m_pkthdr.rcvif, m); 870 if (!inp) { 871 /* 872 * It's new. Try to find the ambushing socket. 873 * Because we've rewritten the destination address, 874 * any hardware-generated hash is ignored. 875 */ 876 inp = in_pcblookup(&V_tcbinfo, ip->ip_src, 877 th->th_sport, next_hop->sin_addr, 878 next_hop->sin_port ? ntohs(next_hop->sin_port) : 879 th->th_dport, INPLOOKUP_WILDCARD | 880 INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif); 881 } 882 } else 883 inp = in_pcblookup_mbuf(&V_tcbinfo, ip->ip_src, 884 th->th_sport, ip->ip_dst, th->th_dport, 885 INPLOOKUP_WILDCARD | INPLOOKUP_WLOCKPCB, 886 m->m_pkthdr.rcvif, m); 887 #endif /* INET */ 888 889 /* 890 * If the INPCB does not exist then all data in the incoming 891 * segment is discarded and an appropriate RST is sent back. 892 * XXX MRT Send RST using which routing table? 893 */ 894 if (inp == NULL) { 895 /* 896 * Log communication attempts to ports that are not 897 * in use. 898 */ 899 if ((V_tcp_log_in_vain == 1 && (thflags & TH_SYN)) || 900 V_tcp_log_in_vain == 2) { 901 if ((s = tcp_log_vain(NULL, th, (void *)ip, ip6))) 902 log(LOG_INFO, "%s; %s: Connection attempt " 903 "to closed port\n", s, __func__); 904 } 905 /* 906 * When blackholing do not respond with a RST but 907 * completely ignore the segment and drop it. 908 */ 909 if ((V_blackhole == 1 && (thflags & TH_SYN)) || 910 V_blackhole == 2) 911 goto dropunlock; 912 913 rstreason = BANDLIM_RST_CLOSEDPORT; 914 goto dropwithreset; 915 } 916 INP_WLOCK_ASSERT(inp); 917 /* 918 * While waiting for inp lock during the lookup, another thread 919 * can have dropped the inpcb, in which case we need to loop back 920 * and try to find a new inpcb to deliver to. 921 */ 922 if (inp->inp_flags & INP_DROPPED) { 923 INP_WUNLOCK(inp); 924 inp = NULL; 925 goto findpcb; 926 } 927 if ((inp->inp_flowtype == M_HASHTYPE_NONE) && 928 (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE) && 929 ((inp->inp_socket == NULL) || 930 (inp->inp_socket->so_options & SO_ACCEPTCONN) == 0)) { 931 inp->inp_flowid = m->m_pkthdr.flowid; 932 inp->inp_flowtype = M_HASHTYPE_GET(m); 933 } 934 #if defined(IPSEC) || defined(IPSEC_SUPPORT) 935 #ifdef INET6 936 if (isipv6 && IPSEC_ENABLED(ipv6) && 937 IPSEC_CHECK_POLICY(ipv6, m, inp) != 0) { 938 goto dropunlock; 939 } 940 #ifdef INET 941 else 942 #endif 943 #endif /* INET6 */ 944 #ifdef INET 945 if (IPSEC_ENABLED(ipv4) && 946 IPSEC_CHECK_POLICY(ipv4, m, inp) != 0) { 947 goto dropunlock; 948 } 949 #endif /* INET */ 950 #endif /* IPSEC */ 951 952 /* 953 * Check the minimum TTL for socket. 954 */ 955 if (inp->inp_ip_minttl != 0) { 956 #ifdef INET6 957 if (isipv6) { 958 if (inp->inp_ip_minttl > ip6->ip6_hlim) 959 goto dropunlock; 960 } else 961 #endif 962 if (inp->inp_ip_minttl > ip->ip_ttl) 963 goto dropunlock; 964 } 965 966 /* 967 * A previous connection in TIMEWAIT state is supposed to catch stray 968 * or duplicate segments arriving late. If this segment was a 969 * legitimate new connection attempt, the old INPCB gets removed and 970 * we can try again to find a listening socket. 971 * 972 * At this point, due to earlier optimism, we may hold only an inpcb 973 * lock, and not the inpcbinfo write lock. If so, we need to try to 974 * acquire it, or if that fails, acquire a reference on the inpcb, 975 * drop all locks, acquire a global write lock, and then re-acquire 976 * the inpcb lock. We may at that point discover that another thread 977 * has tried to free the inpcb, in which case we need to loop back 978 * and try to find a new inpcb to deliver to. 979 * 980 * XXXRW: It may be time to rethink timewait locking. 981 */ 982 if (inp->inp_flags & INP_TIMEWAIT) { 983 if (thflags & TH_SYN) 984 tcp_dooptions(&to, optp, optlen, TO_SYN); 985 /* 986 * NB: tcp_twcheck unlocks the INP and frees the mbuf. 987 */ 988 if (tcp_twcheck(inp, &to, th, m, tlen)) 989 goto findpcb; 990 return (IPPROTO_DONE); 991 } 992 /* 993 * The TCPCB may no longer exist if the connection is winding 994 * down or it is in the CLOSED state. Either way we drop the 995 * segment and send an appropriate response. 996 */ 997 tp = intotcpcb(inp); 998 if (tp == NULL || tp->t_state == TCPS_CLOSED) { 999 rstreason = BANDLIM_RST_CLOSEDPORT; 1000 goto dropwithreset; 1001 } 1002 1003 #ifdef TCP_OFFLOAD 1004 if (tp->t_flags & TF_TOE) { 1005 tcp_offload_input(tp, m); 1006 m = NULL; /* consumed by the TOE driver */ 1007 goto dropunlock; 1008 } 1009 #endif 1010 1011 #ifdef MAC 1012 INP_WLOCK_ASSERT(inp); 1013 if (mac_inpcb_check_deliver(inp, m)) 1014 goto dropunlock; 1015 #endif 1016 so = inp->inp_socket; 1017 KASSERT(so != NULL, ("%s: so == NULL", __func__)); 1018 #ifdef TCPDEBUG 1019 if (so->so_options & SO_DEBUG) { 1020 ostate = tp->t_state; 1021 #ifdef INET6 1022 if (isipv6) { 1023 bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6)); 1024 } else 1025 #endif 1026 bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip)); 1027 tcp_savetcp = *th; 1028 } 1029 #endif /* TCPDEBUG */ 1030 /* 1031 * When the socket is accepting connections (the INPCB is in LISTEN 1032 * state) we look into the SYN cache if this is a new connection 1033 * attempt or the completion of a previous one. 1034 */ 1035 KASSERT(tp->t_state == TCPS_LISTEN || !(so->so_options & SO_ACCEPTCONN), 1036 ("%s: so accepting but tp %p not listening", __func__, tp)); 1037 if (tp->t_state == TCPS_LISTEN && (so->so_options & SO_ACCEPTCONN)) { 1038 struct in_conninfo inc; 1039 1040 bzero(&inc, sizeof(inc)); 1041 #ifdef INET6 1042 if (isipv6) { 1043 inc.inc_flags |= INC_ISIPV6; 1044 if (inp->inp_inc.inc_flags & INC_IPV6MINMTU) 1045 inc.inc_flags |= INC_IPV6MINMTU; 1046 inc.inc6_faddr = ip6->ip6_src; 1047 inc.inc6_laddr = ip6->ip6_dst; 1048 } else 1049 #endif 1050 { 1051 inc.inc_faddr = ip->ip_src; 1052 inc.inc_laddr = ip->ip_dst; 1053 } 1054 inc.inc_fport = th->th_sport; 1055 inc.inc_lport = th->th_dport; 1056 inc.inc_fibnum = so->so_fibnum; 1057 1058 /* 1059 * Check for an existing connection attempt in syncache if 1060 * the flag is only ACK. A successful lookup creates a new 1061 * socket appended to the listen queue in SYN_RECEIVED state. 1062 */ 1063 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) { 1064 1065 /* 1066 * Parse the TCP options here because 1067 * syncookies need access to the reflected 1068 * timestamp. 1069 */ 1070 tcp_dooptions(&to, optp, optlen, 0); 1071 /* 1072 * NB: syncache_expand() doesn't unlock 1073 * inp and tcpinfo locks. 1074 */ 1075 rstreason = syncache_expand(&inc, &to, th, &so, m); 1076 if (rstreason < 0) { 1077 /* 1078 * A failing TCP MD5 signature comparison 1079 * must result in the segment being dropped 1080 * and must not produce any response back 1081 * to the sender. 1082 */ 1083 goto dropunlock; 1084 } else if (rstreason == 0) { 1085 /* 1086 * No syncache entry or ACK was not 1087 * for our SYN/ACK. Send a RST. 1088 * NB: syncache did its own logging 1089 * of the failure cause. 1090 */ 1091 rstreason = BANDLIM_RST_OPENPORT; 1092 goto dropwithreset; 1093 } 1094 tfo_socket_result: 1095 if (so == NULL) { 1096 /* 1097 * We completed the 3-way handshake 1098 * but could not allocate a socket 1099 * either due to memory shortage, 1100 * listen queue length limits or 1101 * global socket limits. Send RST 1102 * or wait and have the remote end 1103 * retransmit the ACK for another 1104 * try. 1105 */ 1106 if ((s = tcp_log_addrs(&inc, th, NULL, NULL))) 1107 log(LOG_DEBUG, "%s; %s: Listen socket: " 1108 "Socket allocation failed due to " 1109 "limits or memory shortage, %s\n", 1110 s, __func__, 1111 V_tcp_sc_rst_sock_fail ? 1112 "sending RST" : "try again"); 1113 if (V_tcp_sc_rst_sock_fail) { 1114 rstreason = BANDLIM_UNLIMITED; 1115 goto dropwithreset; 1116 } else 1117 goto dropunlock; 1118 } 1119 /* 1120 * Socket is created in state SYN_RECEIVED. 1121 * Unlock the listen socket, lock the newly 1122 * created socket and update the tp variable. 1123 */ 1124 INP_WUNLOCK(inp); /* listen socket */ 1125 inp = sotoinpcb(so); 1126 /* 1127 * New connection inpcb is already locked by 1128 * syncache_expand(). 1129 */ 1130 INP_WLOCK_ASSERT(inp); 1131 tp = intotcpcb(inp); 1132 KASSERT(tp->t_state == TCPS_SYN_RECEIVED, 1133 ("%s: ", __func__)); 1134 /* 1135 * Process the segment and the data it 1136 * contains. tcp_do_segment() consumes 1137 * the mbuf chain and unlocks the inpcb. 1138 */ 1139 TCP_PROBE5(receive, NULL, tp, m, tp, th); 1140 tp->t_fb->tfb_tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen, 1141 iptos); 1142 return (IPPROTO_DONE); 1143 } 1144 /* 1145 * Segment flag validation for new connection attempts: 1146 * 1147 * Our (SYN|ACK) response was rejected. 1148 * Check with syncache and remove entry to prevent 1149 * retransmits. 1150 * 1151 * NB: syncache_chkrst does its own logging of failure 1152 * causes. 1153 */ 1154 if (thflags & TH_RST) { 1155 syncache_chkrst(&inc, th, m); 1156 goto dropunlock; 1157 } 1158 /* 1159 * We can't do anything without SYN. 1160 */ 1161 if ((thflags & TH_SYN) == 0) { 1162 if ((s = tcp_log_addrs(&inc, th, NULL, NULL))) 1163 log(LOG_DEBUG, "%s; %s: Listen socket: " 1164 "SYN is missing, segment ignored\n", 1165 s, __func__); 1166 TCPSTAT_INC(tcps_badsyn); 1167 goto dropunlock; 1168 } 1169 /* 1170 * (SYN|ACK) is bogus on a listen socket. 1171 */ 1172 if (thflags & TH_ACK) { 1173 if ((s = tcp_log_addrs(&inc, th, NULL, NULL))) 1174 log(LOG_DEBUG, "%s; %s: Listen socket: " 1175 "SYN|ACK invalid, segment rejected\n", 1176 s, __func__); 1177 syncache_badack(&inc); /* XXX: Not needed! */ 1178 TCPSTAT_INC(tcps_badsyn); 1179 rstreason = BANDLIM_RST_OPENPORT; 1180 goto dropwithreset; 1181 } 1182 /* 1183 * If the drop_synfin option is enabled, drop all 1184 * segments with both the SYN and FIN bits set. 1185 * This prevents e.g. nmap from identifying the 1186 * TCP/IP stack. 1187 * XXX: Poor reasoning. nmap has other methods 1188 * and is constantly refining its stack detection 1189 * strategies. 1190 * XXX: This is a violation of the TCP specification 1191 * and was used by RFC1644. 1192 */ 1193 if ((thflags & TH_FIN) && V_drop_synfin) { 1194 if ((s = tcp_log_addrs(&inc, th, NULL, NULL))) 1195 log(LOG_DEBUG, "%s; %s: Listen socket: " 1196 "SYN|FIN segment ignored (based on " 1197 "sysctl setting)\n", s, __func__); 1198 TCPSTAT_INC(tcps_badsyn); 1199 goto dropunlock; 1200 } 1201 /* 1202 * Segment's flags are (SYN) or (SYN|FIN). 1203 * 1204 * TH_PUSH, TH_URG, TH_ECE, TH_CWR are ignored 1205 * as they do not affect the state of the TCP FSM. 1206 * The data pointed to by TH_URG and th_urp is ignored. 1207 */ 1208 KASSERT((thflags & (TH_RST|TH_ACK)) == 0, 1209 ("%s: Listen socket: TH_RST or TH_ACK set", __func__)); 1210 KASSERT(thflags & (TH_SYN), 1211 ("%s: Listen socket: TH_SYN not set", __func__)); 1212 #ifdef INET6 1213 /* 1214 * If deprecated address is forbidden, 1215 * we do not accept SYN to deprecated interface 1216 * address to prevent any new inbound connection from 1217 * getting established. 1218 * When we do not accept SYN, we send a TCP RST, 1219 * with deprecated source address (instead of dropping 1220 * it). We compromise it as it is much better for peer 1221 * to send a RST, and RST will be the final packet 1222 * for the exchange. 1223 * 1224 * If we do not forbid deprecated addresses, we accept 1225 * the SYN packet. RFC2462 does not suggest dropping 1226 * SYN in this case. 1227 * If we decipher RFC2462 5.5.4, it says like this: 1228 * 1. use of deprecated addr with existing 1229 * communication is okay - "SHOULD continue to be 1230 * used" 1231 * 2. use of it with new communication: 1232 * (2a) "SHOULD NOT be used if alternate address 1233 * with sufficient scope is available" 1234 * (2b) nothing mentioned otherwise. 1235 * Here we fall into (2b) case as we have no choice in 1236 * our source address selection - we must obey the peer. 1237 * 1238 * The wording in RFC2462 is confusing, and there are 1239 * multiple description text for deprecated address 1240 * handling - worse, they are not exactly the same. 1241 * I believe 5.5.4 is the best one, so we follow 5.5.4. 1242 */ 1243 if (isipv6 && !V_ip6_use_deprecated) { 1244 struct in6_ifaddr *ia6; 1245 1246 ia6 = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */); 1247 if (ia6 != NULL && 1248 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) { 1249 ifa_free(&ia6->ia_ifa); 1250 if ((s = tcp_log_addrs(&inc, th, NULL, NULL))) 1251 log(LOG_DEBUG, "%s; %s: Listen socket: " 1252 "Connection attempt to deprecated " 1253 "IPv6 address rejected\n", 1254 s, __func__); 1255 rstreason = BANDLIM_RST_OPENPORT; 1256 goto dropwithreset; 1257 } 1258 if (ia6) 1259 ifa_free(&ia6->ia_ifa); 1260 } 1261 #endif /* INET6 */ 1262 /* 1263 * Basic sanity checks on incoming SYN requests: 1264 * Don't respond if the destination is a link layer 1265 * broadcast according to RFC1122 4.2.3.10, p. 104. 1266 * If it is from this socket it must be forged. 1267 * Don't respond if the source or destination is a 1268 * global or subnet broad- or multicast address. 1269 * Note that it is quite possible to receive unicast 1270 * link-layer packets with a broadcast IP address. Use 1271 * in_broadcast() to find them. 1272 */ 1273 if (m->m_flags & (M_BCAST|M_MCAST)) { 1274 if ((s = tcp_log_addrs(&inc, th, NULL, NULL))) 1275 log(LOG_DEBUG, "%s; %s: Listen socket: " 1276 "Connection attempt from broad- or multicast " 1277 "link layer address ignored\n", s, __func__); 1278 goto dropunlock; 1279 } 1280 #ifdef INET6 1281 if (isipv6) { 1282 if (th->th_dport == th->th_sport && 1283 IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &ip6->ip6_src)) { 1284 if ((s = tcp_log_addrs(&inc, th, NULL, NULL))) 1285 log(LOG_DEBUG, "%s; %s: Listen socket: " 1286 "Connection attempt to/from self " 1287 "ignored\n", s, __func__); 1288 goto dropunlock; 1289 } 1290 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) || 1291 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) { 1292 if ((s = tcp_log_addrs(&inc, th, NULL, NULL))) 1293 log(LOG_DEBUG, "%s; %s: Listen socket: " 1294 "Connection attempt from/to multicast " 1295 "address ignored\n", s, __func__); 1296 goto dropunlock; 1297 } 1298 } 1299 #endif 1300 #if defined(INET) && defined(INET6) 1301 else 1302 #endif 1303 #ifdef INET 1304 { 1305 if (th->th_dport == th->th_sport && 1306 ip->ip_dst.s_addr == ip->ip_src.s_addr) { 1307 if ((s = tcp_log_addrs(&inc, th, NULL, NULL))) 1308 log(LOG_DEBUG, "%s; %s: Listen socket: " 1309 "Connection attempt from/to self " 1310 "ignored\n", s, __func__); 1311 goto dropunlock; 1312 } 1313 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) || 1314 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) || 1315 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) || 1316 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) { 1317 if ((s = tcp_log_addrs(&inc, th, NULL, NULL))) 1318 log(LOG_DEBUG, "%s; %s: Listen socket: " 1319 "Connection attempt from/to broad- " 1320 "or multicast address ignored\n", 1321 s, __func__); 1322 goto dropunlock; 1323 } 1324 } 1325 #endif 1326 /* 1327 * SYN appears to be valid. Create compressed TCP state 1328 * for syncache. 1329 */ 1330 #ifdef TCPDEBUG 1331 if (so->so_options & SO_DEBUG) 1332 tcp_trace(TA_INPUT, ostate, tp, 1333 (void *)tcp_saveipgen, &tcp_savetcp, 0); 1334 #endif 1335 TCP_PROBE3(debug__input, tp, th, m); 1336 tcp_dooptions(&to, optp, optlen, TO_SYN); 1337 if (syncache_add(&inc, &to, th, inp, &so, m, NULL, NULL, iptos)) 1338 goto tfo_socket_result; 1339 1340 /* 1341 * Entry added to syncache and mbuf consumed. 1342 * Only the listen socket is unlocked by syncache_add(). 1343 */ 1344 INP_INFO_WUNLOCK_ASSERT(&V_tcbinfo); 1345 return (IPPROTO_DONE); 1346 } else if (tp->t_state == TCPS_LISTEN) { 1347 /* 1348 * When a listen socket is torn down the SO_ACCEPTCONN 1349 * flag is removed first while connections are drained 1350 * from the accept queue in a unlock/lock cycle of the 1351 * ACCEPT_LOCK, opening a race condition allowing a SYN 1352 * attempt go through unhandled. 1353 */ 1354 goto dropunlock; 1355 } 1356 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE) 1357 if (tp->t_flags & TF_SIGNATURE) { 1358 tcp_dooptions(&to, optp, optlen, thflags); 1359 if ((to.to_flags & TOF_SIGNATURE) == 0) { 1360 TCPSTAT_INC(tcps_sig_err_nosigopt); 1361 goto dropunlock; 1362 } 1363 if (!TCPMD5_ENABLED() || 1364 TCPMD5_INPUT(m, th, to.to_signature) != 0) 1365 goto dropunlock; 1366 } 1367 #endif 1368 TCP_PROBE5(receive, NULL, tp, m, tp, th); 1369 1370 /* 1371 * Segment belongs to a connection in SYN_SENT, ESTABLISHED or later 1372 * state. tcp_do_segment() always consumes the mbuf chain, unlocks 1373 * the inpcb, and unlocks pcbinfo. 1374 */ 1375 tp->t_fb->tfb_tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen, iptos); 1376 return (IPPROTO_DONE); 1377 1378 dropwithreset: 1379 TCP_PROBE5(receive, NULL, tp, m, tp, th); 1380 1381 if (inp != NULL) { 1382 tcp_dropwithreset(m, th, tp, tlen, rstreason); 1383 INP_WUNLOCK(inp); 1384 } else 1385 tcp_dropwithreset(m, th, NULL, tlen, rstreason); 1386 m = NULL; /* mbuf chain got consumed. */ 1387 goto drop; 1388 1389 dropunlock: 1390 if (m != NULL) 1391 TCP_PROBE5(receive, NULL, tp, m, tp, th); 1392 1393 if (inp != NULL) 1394 INP_WUNLOCK(inp); 1395 1396 drop: 1397 INP_INFO_WUNLOCK_ASSERT(&V_tcbinfo); 1398 if (s != NULL) 1399 free(s, M_TCPLOG); 1400 if (m != NULL) 1401 m_freem(m); 1402 return (IPPROTO_DONE); 1403 } 1404 1405 /* 1406 * Automatic sizing of receive socket buffer. Often the send 1407 * buffer size is not optimally adjusted to the actual network 1408 * conditions at hand (delay bandwidth product). Setting the 1409 * buffer size too small limits throughput on links with high 1410 * bandwidth and high delay (eg. trans-continental/oceanic links). 1411 * 1412 * On the receive side the socket buffer memory is only rarely 1413 * used to any significant extent. This allows us to be much 1414 * more aggressive in scaling the receive socket buffer. For 1415 * the case that the buffer space is actually used to a large 1416 * extent and we run out of kernel memory we can simply drop 1417 * the new segments; TCP on the sender will just retransmit it 1418 * later. Setting the buffer size too big may only consume too 1419 * much kernel memory if the application doesn't read() from 1420 * the socket or packet loss or reordering makes use of the 1421 * reassembly queue. 1422 * 1423 * The criteria to step up the receive buffer one notch are: 1424 * 1. Application has not set receive buffer size with 1425 * SO_RCVBUF. Setting SO_RCVBUF clears SB_AUTOSIZE. 1426 * 2. the number of bytes received during 1/2 of an sRTT 1427 * is at least 3/8 of the current socket buffer size. 1428 * 3. receive buffer size has not hit maximal automatic size; 1429 * 1430 * If all of the criteria are met we increaset the socket buffer 1431 * by a 1/2 (bounded by the max). This allows us to keep ahead 1432 * of slow-start but also makes it so our peer never gets limited 1433 * by our rwnd which we then open up causing a burst. 1434 * 1435 * This algorithm does two steps per RTT at most and only if 1436 * we receive a bulk stream w/o packet losses or reorderings. 1437 * Shrinking the buffer during idle times is not necessary as 1438 * it doesn't consume any memory when idle. 1439 * 1440 * TODO: Only step up if the application is actually serving 1441 * the buffer to better manage the socket buffer resources. 1442 */ 1443 int 1444 tcp_autorcvbuf(struct mbuf *m, struct tcphdr *th, struct socket *so, 1445 struct tcpcb *tp, int tlen) 1446 { 1447 int newsize = 0; 1448 1449 if (V_tcp_do_autorcvbuf && (so->so_rcv.sb_flags & SB_AUTOSIZE) && 1450 tp->t_srtt != 0 && tp->rfbuf_ts != 0 && 1451 TCP_TS_TO_TICKS(tcp_ts_getticks() - tp->rfbuf_ts) > 1452 ((tp->t_srtt >> TCP_RTT_SHIFT)/2)) { 1453 if (tp->rfbuf_cnt > ((so->so_rcv.sb_hiwat / 2)/ 4 * 3) && 1454 so->so_rcv.sb_hiwat < V_tcp_autorcvbuf_max) { 1455 newsize = min((so->so_rcv.sb_hiwat + (so->so_rcv.sb_hiwat/2)), V_tcp_autorcvbuf_max); 1456 } 1457 TCP_PROBE6(receive__autoresize, NULL, tp, m, tp, th, newsize); 1458 1459 /* Start over with next RTT. */ 1460 tp->rfbuf_ts = 0; 1461 tp->rfbuf_cnt = 0; 1462 } else { 1463 tp->rfbuf_cnt += tlen; /* add up */ 1464 } 1465 return (newsize); 1466 } 1467 1468 void 1469 tcp_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so, 1470 struct tcpcb *tp, int drop_hdrlen, int tlen, uint8_t iptos) 1471 { 1472 int thflags, acked, ourfinisacked, needoutput = 0, sack_changed; 1473 int rstreason, todrop, win, incforsyn = 0; 1474 uint32_t tiwin; 1475 uint16_t nsegs; 1476 char *s; 1477 struct in_conninfo *inc; 1478 struct mbuf *mfree; 1479 struct tcpopt to; 1480 int tfo_syn; 1481 1482 #ifdef TCPDEBUG 1483 /* 1484 * The size of tcp_saveipgen must be the size of the max ip header, 1485 * now IPv6. 1486 */ 1487 u_char tcp_saveipgen[IP6_HDR_LEN]; 1488 struct tcphdr tcp_savetcp; 1489 short ostate = 0; 1490 #endif 1491 thflags = th->th_flags; 1492 inc = &tp->t_inpcb->inp_inc; 1493 tp->sackhint.last_sack_ack = 0; 1494 sack_changed = 0; 1495 nsegs = max(1, m->m_pkthdr.lro_nsegs); 1496 1497 NET_EPOCH_ASSERT(); 1498 INP_WLOCK_ASSERT(tp->t_inpcb); 1499 KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN", 1500 __func__)); 1501 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT", 1502 __func__)); 1503 1504 #ifdef TCPPCAP 1505 /* Save segment, if requested. */ 1506 tcp_pcap_add(th, m, &(tp->t_inpkts)); 1507 #endif 1508 TCP_LOG_EVENT(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_IN, 0, 1509 tlen, NULL, true); 1510 1511 if ((thflags & TH_SYN) && (thflags & TH_FIN) && V_drop_synfin) { 1512 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) { 1513 log(LOG_DEBUG, "%s; %s: " 1514 "SYN|FIN segment ignored (based on " 1515 "sysctl setting)\n", s, __func__); 1516 free(s, M_TCPLOG); 1517 } 1518 goto drop; 1519 } 1520 1521 /* 1522 * If a segment with the ACK-bit set arrives in the SYN-SENT state 1523 * check SEQ.ACK first. 1524 */ 1525 if ((tp->t_state == TCPS_SYN_SENT) && (thflags & TH_ACK) && 1526 (SEQ_LEQ(th->th_ack, tp->iss) || SEQ_GT(th->th_ack, tp->snd_max))) { 1527 rstreason = BANDLIM_UNLIMITED; 1528 goto dropwithreset; 1529 } 1530 1531 /* 1532 * Segment received on connection. 1533 * Reset idle time and keep-alive timer. 1534 * XXX: This should be done after segment 1535 * validation to ignore broken/spoofed segs. 1536 */ 1537 tp->t_rcvtime = ticks; 1538 1539 /* 1540 * Scale up the window into a 32-bit value. 1541 * For the SYN_SENT state the scale is zero. 1542 */ 1543 tiwin = th->th_win << tp->snd_scale; 1544 #ifdef STATS 1545 stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_FRWIN, tiwin); 1546 #endif 1547 1548 /* 1549 * TCP ECN processing. 1550 */ 1551 if (tp->t_flags2 & TF2_ECN_PERMIT) { 1552 if (thflags & TH_CWR) { 1553 tp->t_flags2 &= ~TF2_ECN_SND_ECE; 1554 tp->t_flags |= TF_ACKNOW; 1555 } 1556 switch (iptos & IPTOS_ECN_MASK) { 1557 case IPTOS_ECN_CE: 1558 tp->t_flags2 |= TF2_ECN_SND_ECE; 1559 TCPSTAT_INC(tcps_ecn_ce); 1560 break; 1561 case IPTOS_ECN_ECT0: 1562 TCPSTAT_INC(tcps_ecn_ect0); 1563 break; 1564 case IPTOS_ECN_ECT1: 1565 TCPSTAT_INC(tcps_ecn_ect1); 1566 break; 1567 } 1568 1569 /* Process a packet differently from RFC3168. */ 1570 cc_ecnpkt_handler(tp, th, iptos); 1571 1572 /* Congestion experienced. */ 1573 if (thflags & TH_ECE) { 1574 cc_cong_signal(tp, th, CC_ECN); 1575 } 1576 } 1577 1578 /* 1579 * Parse options on any incoming segment. 1580 */ 1581 tcp_dooptions(&to, (u_char *)(th + 1), 1582 (th->th_off << 2) - sizeof(struct tcphdr), 1583 (thflags & TH_SYN) ? TO_SYN : 0); 1584 1585 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE) 1586 if ((tp->t_flags & TF_SIGNATURE) != 0 && 1587 (to.to_flags & TOF_SIGNATURE) == 0) { 1588 TCPSTAT_INC(tcps_sig_err_sigopt); 1589 /* XXX: should drop? */ 1590 } 1591 #endif 1592 /* 1593 * If echoed timestamp is later than the current time, 1594 * fall back to non RFC1323 RTT calculation. Normalize 1595 * timestamp if syncookies were used when this connection 1596 * was established. 1597 */ 1598 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) { 1599 to.to_tsecr -= tp->ts_offset; 1600 if (TSTMP_GT(to.to_tsecr, tcp_ts_getticks())) 1601 to.to_tsecr = 0; 1602 else if (tp->t_flags & TF_PREVVALID && 1603 tp->t_badrxtwin != 0 && SEQ_LT(to.to_tsecr, tp->t_badrxtwin)) 1604 cc_cong_signal(tp, th, CC_RTO_ERR); 1605 } 1606 /* 1607 * Process options only when we get SYN/ACK back. The SYN case 1608 * for incoming connections is handled in tcp_syncache. 1609 * According to RFC1323 the window field in a SYN (i.e., a <SYN> 1610 * or <SYN,ACK>) segment itself is never scaled. 1611 * XXX this is traditional behavior, may need to be cleaned up. 1612 */ 1613 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) { 1614 if ((to.to_flags & TOF_SCALE) && 1615 (tp->t_flags & TF_REQ_SCALE)) { 1616 tp->t_flags |= TF_RCVD_SCALE; 1617 tp->snd_scale = to.to_wscale; 1618 } 1619 /* 1620 * Initial send window. It will be updated with 1621 * the next incoming segment to the scaled value. 1622 */ 1623 tp->snd_wnd = th->th_win; 1624 if (to.to_flags & TOF_TS) { 1625 tp->t_flags |= TF_RCVD_TSTMP; 1626 tp->ts_recent = to.to_tsval; 1627 tp->ts_recent_age = tcp_ts_getticks(); 1628 } 1629 if (to.to_flags & TOF_MSS) 1630 tcp_mss(tp, to.to_mss); 1631 if ((tp->t_flags & TF_SACK_PERMIT) && 1632 (to.to_flags & TOF_SACKPERM) == 0) 1633 tp->t_flags &= ~TF_SACK_PERMIT; 1634 if (IS_FASTOPEN(tp->t_flags)) { 1635 if (to.to_flags & TOF_FASTOPEN) { 1636 uint16_t mss; 1637 1638 if (to.to_flags & TOF_MSS) 1639 mss = to.to_mss; 1640 else 1641 if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0) 1642 mss = TCP6_MSS; 1643 else 1644 mss = TCP_MSS; 1645 tcp_fastopen_update_cache(tp, mss, 1646 to.to_tfo_len, to.to_tfo_cookie); 1647 } else 1648 tcp_fastopen_disable_path(tp); 1649 } 1650 } 1651 1652 /* 1653 * If timestamps were negotiated during SYN/ACK they should 1654 * appear on every segment during this session and vice versa. 1655 */ 1656 if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS)) { 1657 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) { 1658 log(LOG_DEBUG, "%s; %s: Timestamp missing, " 1659 "no action\n", s, __func__); 1660 free(s, M_TCPLOG); 1661 } 1662 } 1663 if (!(tp->t_flags & TF_RCVD_TSTMP) && (to.to_flags & TOF_TS)) { 1664 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) { 1665 log(LOG_DEBUG, "%s; %s: Timestamp not expected, " 1666 "no action\n", s, __func__); 1667 free(s, M_TCPLOG); 1668 } 1669 } 1670 1671 /* 1672 * Header prediction: check for the two common cases 1673 * of a uni-directional data xfer. If the packet has 1674 * no control flags, is in-sequence, the window didn't 1675 * change and we're not retransmitting, it's a 1676 * candidate. If the length is zero and the ack moved 1677 * forward, we're the sender side of the xfer. Just 1678 * free the data acked & wake any higher level process 1679 * that was blocked waiting for space. If the length 1680 * is non-zero and the ack didn't move, we're the 1681 * receiver side. If we're getting packets in-order 1682 * (the reassembly queue is empty), add the data to 1683 * the socket buffer and note that we need a delayed ack. 1684 * Make sure that the hidden state-flags are also off. 1685 * Since we check for TCPS_ESTABLISHED first, it can only 1686 * be TH_NEEDSYN. 1687 */ 1688 if (tp->t_state == TCPS_ESTABLISHED && 1689 th->th_seq == tp->rcv_nxt && 1690 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK && 1691 tp->snd_nxt == tp->snd_max && 1692 tiwin && tiwin == tp->snd_wnd && 1693 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) && 1694 SEGQ_EMPTY(tp) && 1695 ((to.to_flags & TOF_TS) == 0 || 1696 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) ) { 1697 1698 /* 1699 * If last ACK falls within this segment's sequence numbers, 1700 * record the timestamp. 1701 * NOTE that the test is modified according to the latest 1702 * proposal of the tcplw@cray.com list (Braden 1993/04/26). 1703 */ 1704 if ((to.to_flags & TOF_TS) != 0 && 1705 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) { 1706 tp->ts_recent_age = tcp_ts_getticks(); 1707 tp->ts_recent = to.to_tsval; 1708 } 1709 1710 if (tlen == 0) { 1711 if (SEQ_GT(th->th_ack, tp->snd_una) && 1712 SEQ_LEQ(th->th_ack, tp->snd_max) && 1713 !IN_RECOVERY(tp->t_flags) && 1714 (to.to_flags & TOF_SACK) == 0 && 1715 TAILQ_EMPTY(&tp->snd_holes)) { 1716 /* 1717 * This is a pure ack for outstanding data. 1718 */ 1719 TCPSTAT_INC(tcps_predack); 1720 1721 /* 1722 * "bad retransmit" recovery without timestamps. 1723 */ 1724 if ((to.to_flags & TOF_TS) == 0 && 1725 tp->t_rxtshift == 1 && 1726 tp->t_flags & TF_PREVVALID && 1727 (int)(ticks - tp->t_badrxtwin) < 0) { 1728 cc_cong_signal(tp, th, CC_RTO_ERR); 1729 } 1730 1731 /* 1732 * Recalculate the transmit timer / rtt. 1733 * 1734 * Some boxes send broken timestamp replies 1735 * during the SYN+ACK phase, ignore 1736 * timestamps of 0 or we could calculate a 1737 * huge RTT and blow up the retransmit timer. 1738 */ 1739 if ((to.to_flags & TOF_TS) != 0 && 1740 to.to_tsecr) { 1741 uint32_t t; 1742 1743 t = tcp_ts_getticks() - to.to_tsecr; 1744 if (!tp->t_rttlow || tp->t_rttlow > t) 1745 tp->t_rttlow = t; 1746 tcp_xmit_timer(tp, 1747 TCP_TS_TO_TICKS(t) + 1); 1748 } else if (tp->t_rtttime && 1749 SEQ_GT(th->th_ack, tp->t_rtseq)) { 1750 if (!tp->t_rttlow || 1751 tp->t_rttlow > ticks - tp->t_rtttime) 1752 tp->t_rttlow = ticks - tp->t_rtttime; 1753 tcp_xmit_timer(tp, 1754 ticks - tp->t_rtttime); 1755 } 1756 acked = BYTES_THIS_ACK(tp, th); 1757 1758 #ifdef TCP_HHOOK 1759 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */ 1760 hhook_run_tcp_est_in(tp, th, &to); 1761 #endif 1762 1763 TCPSTAT_ADD(tcps_rcvackpack, nsegs); 1764 TCPSTAT_ADD(tcps_rcvackbyte, acked); 1765 sbdrop(&so->so_snd, acked); 1766 if (SEQ_GT(tp->snd_una, tp->snd_recover) && 1767 SEQ_LEQ(th->th_ack, tp->snd_recover)) 1768 tp->snd_recover = th->th_ack - 1; 1769 1770 /* 1771 * Let the congestion control algorithm update 1772 * congestion control related information. This 1773 * typically means increasing the congestion 1774 * window. 1775 */ 1776 cc_ack_received(tp, th, nsegs, CC_ACK); 1777 1778 tp->snd_una = th->th_ack; 1779 /* 1780 * Pull snd_wl2 up to prevent seq wrap relative 1781 * to th_ack. 1782 */ 1783 tp->snd_wl2 = th->th_ack; 1784 tp->t_dupacks = 0; 1785 m_freem(m); 1786 1787 /* 1788 * If all outstanding data are acked, stop 1789 * retransmit timer, otherwise restart timer 1790 * using current (possibly backed-off) value. 1791 * If process is waiting for space, 1792 * wakeup/selwakeup/signal. If data 1793 * are ready to send, let tcp_output 1794 * decide between more output or persist. 1795 */ 1796 #ifdef TCPDEBUG 1797 if (so->so_options & SO_DEBUG) 1798 tcp_trace(TA_INPUT, ostate, tp, 1799 (void *)tcp_saveipgen, 1800 &tcp_savetcp, 0); 1801 #endif 1802 TCP_PROBE3(debug__input, tp, th, m); 1803 if (tp->snd_una == tp->snd_max) 1804 tcp_timer_activate(tp, TT_REXMT, 0); 1805 else if (!tcp_timer_active(tp, TT_PERSIST)) 1806 tcp_timer_activate(tp, TT_REXMT, 1807 tp->t_rxtcur); 1808 sowwakeup(so); 1809 if (sbavail(&so->so_snd)) 1810 (void) tp->t_fb->tfb_tcp_output(tp); 1811 goto check_delack; 1812 } 1813 } else if (th->th_ack == tp->snd_una && 1814 tlen <= sbspace(&so->so_rcv)) { 1815 int newsize = 0; /* automatic sockbuf scaling */ 1816 1817 /* 1818 * This is a pure, in-sequence data packet with 1819 * nothing on the reassembly queue and we have enough 1820 * buffer space to take it. 1821 */ 1822 /* Clean receiver SACK report if present */ 1823 if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks) 1824 tcp_clean_sackreport(tp); 1825 TCPSTAT_INC(tcps_preddat); 1826 tp->rcv_nxt += tlen; 1827 /* 1828 * Pull snd_wl1 up to prevent seq wrap relative to 1829 * th_seq. 1830 */ 1831 tp->snd_wl1 = th->th_seq; 1832 /* 1833 * Pull rcv_up up to prevent seq wrap relative to 1834 * rcv_nxt. 1835 */ 1836 tp->rcv_up = tp->rcv_nxt; 1837 TCPSTAT_ADD(tcps_rcvpack, nsegs); 1838 TCPSTAT_ADD(tcps_rcvbyte, tlen); 1839 #ifdef TCPDEBUG 1840 if (so->so_options & SO_DEBUG) 1841 tcp_trace(TA_INPUT, ostate, tp, 1842 (void *)tcp_saveipgen, &tcp_savetcp, 0); 1843 #endif 1844 TCP_PROBE3(debug__input, tp, th, m); 1845 1846 newsize = tcp_autorcvbuf(m, th, so, tp, tlen); 1847 1848 /* Add data to socket buffer. */ 1849 SOCKBUF_LOCK(&so->so_rcv); 1850 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) { 1851 m_freem(m); 1852 } else { 1853 /* 1854 * Set new socket buffer size. 1855 * Give up when limit is reached. 1856 */ 1857 if (newsize) 1858 if (!sbreserve_locked(&so->so_rcv, 1859 newsize, so, NULL)) 1860 so->so_rcv.sb_flags &= ~SB_AUTOSIZE; 1861 m_adj(m, drop_hdrlen); /* delayed header drop */ 1862 sbappendstream_locked(&so->so_rcv, m, 0); 1863 } 1864 /* NB: sorwakeup_locked() does an implicit unlock. */ 1865 sorwakeup_locked(so); 1866 if (DELAY_ACK(tp, tlen)) { 1867 tp->t_flags |= TF_DELACK; 1868 } else { 1869 tp->t_flags |= TF_ACKNOW; 1870 tp->t_fb->tfb_tcp_output(tp); 1871 } 1872 goto check_delack; 1873 } 1874 } 1875 1876 /* 1877 * Calculate amount of space in receive window, 1878 * and then do TCP input processing. 1879 * Receive window is amount of space in rcv queue, 1880 * but not less than advertised window. 1881 */ 1882 win = sbspace(&so->so_rcv); 1883 if (win < 0) 1884 win = 0; 1885 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt)); 1886 1887 switch (tp->t_state) { 1888 1889 /* 1890 * If the state is SYN_RECEIVED: 1891 * if seg contains an ACK, but not for our SYN/ACK, send a RST. 1892 */ 1893 case TCPS_SYN_RECEIVED: 1894 if ((thflags & TH_ACK) && 1895 (SEQ_LEQ(th->th_ack, tp->snd_una) || 1896 SEQ_GT(th->th_ack, tp->snd_max))) { 1897 rstreason = BANDLIM_RST_OPENPORT; 1898 goto dropwithreset; 1899 } 1900 if (IS_FASTOPEN(tp->t_flags)) { 1901 /* 1902 * When a TFO connection is in SYN_RECEIVED, the 1903 * only valid packets are the initial SYN, a 1904 * retransmit/copy of the initial SYN (possibly with 1905 * a subset of the original data), a valid ACK, a 1906 * FIN, or a RST. 1907 */ 1908 if ((thflags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) { 1909 rstreason = BANDLIM_RST_OPENPORT; 1910 goto dropwithreset; 1911 } else if (thflags & TH_SYN) { 1912 /* non-initial SYN is ignored */ 1913 if ((tcp_timer_active(tp, TT_DELACK) || 1914 tcp_timer_active(tp, TT_REXMT))) 1915 goto drop; 1916 } else if (!(thflags & (TH_ACK|TH_FIN|TH_RST))) { 1917 goto drop; 1918 } 1919 } 1920 break; 1921 1922 /* 1923 * If the state is SYN_SENT: 1924 * if seg contains a RST with valid ACK (SEQ.ACK has already 1925 * been verified), then drop the connection. 1926 * if seg contains a RST without an ACK, drop the seg. 1927 * if seg does not contain SYN, then drop the seg. 1928 * Otherwise this is an acceptable SYN segment 1929 * initialize tp->rcv_nxt and tp->irs 1930 * if seg contains ack then advance tp->snd_una 1931 * if seg contains an ECE and ECN support is enabled, the stream 1932 * is ECN capable. 1933 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state 1934 * arrange for segment to be acked (eventually) 1935 * continue processing rest of data/controls, beginning with URG 1936 */ 1937 case TCPS_SYN_SENT: 1938 if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) { 1939 TCP_PROBE5(connect__refused, NULL, tp, 1940 m, tp, th); 1941 tp = tcp_drop(tp, ECONNREFUSED); 1942 } 1943 if (thflags & TH_RST) 1944 goto drop; 1945 if (!(thflags & TH_SYN)) 1946 goto drop; 1947 1948 tp->irs = th->th_seq; 1949 tcp_rcvseqinit(tp); 1950 if (thflags & TH_ACK) { 1951 int tfo_partial_ack = 0; 1952 1953 TCPSTAT_INC(tcps_connects); 1954 soisconnected(so); 1955 #ifdef MAC 1956 mac_socketpeer_set_from_mbuf(m, so); 1957 #endif 1958 /* Do window scaling on this connection? */ 1959 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) == 1960 (TF_RCVD_SCALE|TF_REQ_SCALE)) { 1961 tp->rcv_scale = tp->request_r_scale; 1962 } 1963 tp->rcv_adv += min(tp->rcv_wnd, 1964 TCP_MAXWIN << tp->rcv_scale); 1965 tp->snd_una++; /* SYN is acked */ 1966 /* 1967 * If not all the data that was sent in the TFO SYN 1968 * has been acked, resend the remainder right away. 1969 */ 1970 if (IS_FASTOPEN(tp->t_flags) && 1971 (tp->snd_una != tp->snd_max)) { 1972 tp->snd_nxt = th->th_ack; 1973 tfo_partial_ack = 1; 1974 } 1975 /* 1976 * If there's data, delay ACK; if there's also a FIN 1977 * ACKNOW will be turned on later. 1978 */ 1979 if (DELAY_ACK(tp, tlen) && tlen != 0 && !tfo_partial_ack) 1980 tcp_timer_activate(tp, TT_DELACK, 1981 tcp_delacktime); 1982 else 1983 tp->t_flags |= TF_ACKNOW; 1984 1985 if (((thflags & (TH_CWR | TH_ECE)) == TH_ECE) && 1986 (V_tcp_do_ecn == 1)) { 1987 tp->t_flags2 |= TF2_ECN_PERMIT; 1988 TCPSTAT_INC(tcps_ecn_shs); 1989 } 1990 1991 /* 1992 * Received <SYN,ACK> in SYN_SENT[*] state. 1993 * Transitions: 1994 * SYN_SENT --> ESTABLISHED 1995 * SYN_SENT* --> FIN_WAIT_1 1996 */ 1997 tp->t_starttime = ticks; 1998 if (tp->t_flags & TF_NEEDFIN) { 1999 tcp_state_change(tp, TCPS_FIN_WAIT_1); 2000 tp->t_flags &= ~TF_NEEDFIN; 2001 thflags &= ~TH_SYN; 2002 } else { 2003 tcp_state_change(tp, TCPS_ESTABLISHED); 2004 TCP_PROBE5(connect__established, NULL, tp, 2005 m, tp, th); 2006 cc_conn_init(tp); 2007 tcp_timer_activate(tp, TT_KEEP, 2008 TP_KEEPIDLE(tp)); 2009 } 2010 } else { 2011 /* 2012 * Received initial SYN in SYN-SENT[*] state => 2013 * simultaneous open. 2014 * If it succeeds, connection is * half-synchronized. 2015 * Otherwise, do 3-way handshake: 2016 * SYN-SENT -> SYN-RECEIVED 2017 * SYN-SENT* -> SYN-RECEIVED* 2018 */ 2019 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN); 2020 tcp_timer_activate(tp, TT_REXMT, 0); 2021 tcp_state_change(tp, TCPS_SYN_RECEIVED); 2022 } 2023 2024 INP_WLOCK_ASSERT(tp->t_inpcb); 2025 2026 /* 2027 * Advance th->th_seq to correspond to first data byte. 2028 * If data, trim to stay within window, 2029 * dropping FIN if necessary. 2030 */ 2031 th->th_seq++; 2032 if (tlen > tp->rcv_wnd) { 2033 todrop = tlen - tp->rcv_wnd; 2034 m_adj(m, -todrop); 2035 tlen = tp->rcv_wnd; 2036 thflags &= ~TH_FIN; 2037 TCPSTAT_INC(tcps_rcvpackafterwin); 2038 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop); 2039 } 2040 tp->snd_wl1 = th->th_seq - 1; 2041 tp->rcv_up = th->th_seq; 2042 /* 2043 * Client side of transaction: already sent SYN and data. 2044 * If the remote host used T/TCP to validate the SYN, 2045 * our data will be ACK'd; if so, enter normal data segment 2046 * processing in the middle of step 5, ack processing. 2047 * Otherwise, goto step 6. 2048 */ 2049 if (thflags & TH_ACK) 2050 goto process_ACK; 2051 2052 goto step6; 2053 2054 /* 2055 * If the state is LAST_ACK or CLOSING or TIME_WAIT: 2056 * do normal processing. 2057 * 2058 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later. 2059 */ 2060 case TCPS_LAST_ACK: 2061 case TCPS_CLOSING: 2062 break; /* continue normal processing */ 2063 } 2064 2065 /* 2066 * States other than LISTEN or SYN_SENT. 2067 * First check the RST flag and sequence number since reset segments 2068 * are exempt from the timestamp and connection count tests. This 2069 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix 2070 * below which allowed reset segments in half the sequence space 2071 * to fall though and be processed (which gives forged reset 2072 * segments with a random sequence number a 50 percent chance of 2073 * killing a connection). 2074 * Then check timestamp, if present. 2075 * Then check the connection count, if present. 2076 * Then check that at least some bytes of segment are within 2077 * receive window. If segment begins before rcv_nxt, 2078 * drop leading data (and SYN); if nothing left, just ack. 2079 */ 2080 if (thflags & TH_RST) { 2081 /* 2082 * RFC5961 Section 3.2 2083 * 2084 * - RST drops connection only if SEG.SEQ == RCV.NXT. 2085 * - If RST is in window, we send challenge ACK. 2086 * 2087 * Note: to take into account delayed ACKs, we should 2088 * test against last_ack_sent instead of rcv_nxt. 2089 * Note 2: we handle special case of closed window, not 2090 * covered by the RFC. 2091 */ 2092 if ((SEQ_GEQ(th->th_seq, tp->last_ack_sent) && 2093 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) || 2094 (tp->rcv_wnd == 0 && tp->last_ack_sent == th->th_seq)) { 2095 2096 KASSERT(tp->t_state != TCPS_SYN_SENT, 2097 ("%s: TH_RST for TCPS_SYN_SENT th %p tp %p", 2098 __func__, th, tp)); 2099 2100 if (V_tcp_insecure_rst || 2101 tp->last_ack_sent == th->th_seq) { 2102 TCPSTAT_INC(tcps_drops); 2103 /* Drop the connection. */ 2104 switch (tp->t_state) { 2105 case TCPS_SYN_RECEIVED: 2106 so->so_error = ECONNREFUSED; 2107 goto close; 2108 case TCPS_ESTABLISHED: 2109 case TCPS_FIN_WAIT_1: 2110 case TCPS_FIN_WAIT_2: 2111 case TCPS_CLOSE_WAIT: 2112 case TCPS_CLOSING: 2113 case TCPS_LAST_ACK: 2114 so->so_error = ECONNRESET; 2115 close: 2116 /* FALLTHROUGH */ 2117 default: 2118 tp = tcp_close(tp); 2119 } 2120 } else { 2121 TCPSTAT_INC(tcps_badrst); 2122 /* Send challenge ACK. */ 2123 tcp_respond(tp, mtod(m, void *), th, m, 2124 tp->rcv_nxt, tp->snd_nxt, TH_ACK); 2125 tp->last_ack_sent = tp->rcv_nxt; 2126 m = NULL; 2127 } 2128 } 2129 goto drop; 2130 } 2131 2132 /* 2133 * RFC5961 Section 4.2 2134 * Send challenge ACK for any SYN in synchronized state. 2135 */ 2136 if ((thflags & TH_SYN) && tp->t_state != TCPS_SYN_SENT && 2137 tp->t_state != TCPS_SYN_RECEIVED) { 2138 TCPSTAT_INC(tcps_badsyn); 2139 if (V_tcp_insecure_syn && 2140 SEQ_GEQ(th->th_seq, tp->last_ack_sent) && 2141 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) { 2142 tp = tcp_drop(tp, ECONNRESET); 2143 rstreason = BANDLIM_UNLIMITED; 2144 } else { 2145 /* Send challenge ACK. */ 2146 tcp_respond(tp, mtod(m, void *), th, m, tp->rcv_nxt, 2147 tp->snd_nxt, TH_ACK); 2148 tp->last_ack_sent = tp->rcv_nxt; 2149 m = NULL; 2150 } 2151 goto drop; 2152 } 2153 2154 /* 2155 * RFC 1323 PAWS: If we have a timestamp reply on this segment 2156 * and it's less than ts_recent, drop it. 2157 */ 2158 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent && 2159 TSTMP_LT(to.to_tsval, tp->ts_recent)) { 2160 2161 /* Check to see if ts_recent is over 24 days old. */ 2162 if (tcp_ts_getticks() - tp->ts_recent_age > TCP_PAWS_IDLE) { 2163 /* 2164 * Invalidate ts_recent. If this segment updates 2165 * ts_recent, the age will be reset later and ts_recent 2166 * will get a valid value. If it does not, setting 2167 * ts_recent to zero will at least satisfy the 2168 * requirement that zero be placed in the timestamp 2169 * echo reply when ts_recent isn't valid. The 2170 * age isn't reset until we get a valid ts_recent 2171 * because we don't want out-of-order segments to be 2172 * dropped when ts_recent is old. 2173 */ 2174 tp->ts_recent = 0; 2175 } else { 2176 TCPSTAT_INC(tcps_rcvduppack); 2177 TCPSTAT_ADD(tcps_rcvdupbyte, tlen); 2178 TCPSTAT_INC(tcps_pawsdrop); 2179 if (tlen) 2180 goto dropafterack; 2181 goto drop; 2182 } 2183 } 2184 2185 /* 2186 * In the SYN-RECEIVED state, validate that the packet belongs to 2187 * this connection before trimming the data to fit the receive 2188 * window. Check the sequence number versus IRS since we know 2189 * the sequence numbers haven't wrapped. This is a partial fix 2190 * for the "LAND" DoS attack. 2191 */ 2192 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) { 2193 rstreason = BANDLIM_RST_OPENPORT; 2194 goto dropwithreset; 2195 } 2196 2197 todrop = tp->rcv_nxt - th->th_seq; 2198 if (todrop > 0) { 2199 if (thflags & TH_SYN) { 2200 thflags &= ~TH_SYN; 2201 th->th_seq++; 2202 if (th->th_urp > 1) 2203 th->th_urp--; 2204 else 2205 thflags &= ~TH_URG; 2206 todrop--; 2207 } 2208 /* 2209 * Following if statement from Stevens, vol. 2, p. 960. 2210 */ 2211 if (todrop > tlen 2212 || (todrop == tlen && (thflags & TH_FIN) == 0)) { 2213 /* 2214 * Any valid FIN must be to the left of the window. 2215 * At this point the FIN must be a duplicate or out 2216 * of sequence; drop it. 2217 */ 2218 thflags &= ~TH_FIN; 2219 2220 /* 2221 * Send an ACK to resynchronize and drop any data. 2222 * But keep on processing for RST or ACK. 2223 */ 2224 tp->t_flags |= TF_ACKNOW; 2225 todrop = tlen; 2226 TCPSTAT_INC(tcps_rcvduppack); 2227 TCPSTAT_ADD(tcps_rcvdupbyte, todrop); 2228 } else { 2229 TCPSTAT_INC(tcps_rcvpartduppack); 2230 TCPSTAT_ADD(tcps_rcvpartdupbyte, todrop); 2231 } 2232 /* 2233 * DSACK - add SACK block for dropped range 2234 */ 2235 if ((todrop > 0) && (tp->t_flags & TF_SACK_PERMIT)) { 2236 tcp_update_sack_list(tp, th->th_seq, 2237 th->th_seq + todrop); 2238 /* 2239 * ACK now, as the next in-sequence segment 2240 * will clear the DSACK block again 2241 */ 2242 tp->t_flags |= TF_ACKNOW; 2243 } 2244 drop_hdrlen += todrop; /* drop from the top afterwards */ 2245 th->th_seq += todrop; 2246 tlen -= todrop; 2247 if (th->th_urp > todrop) 2248 th->th_urp -= todrop; 2249 else { 2250 thflags &= ~TH_URG; 2251 th->th_urp = 0; 2252 } 2253 } 2254 2255 /* 2256 * If new data are received on a connection after the 2257 * user processes are gone, then RST the other end. 2258 */ 2259 if ((so->so_state & SS_NOFDREF) && 2260 tp->t_state > TCPS_CLOSE_WAIT && tlen) { 2261 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) { 2262 log(LOG_DEBUG, "%s; %s: %s: Received %d bytes of data " 2263 "after socket was closed, " 2264 "sending RST and removing tcpcb\n", 2265 s, __func__, tcpstates[tp->t_state], tlen); 2266 free(s, M_TCPLOG); 2267 } 2268 tp = tcp_close(tp); 2269 TCPSTAT_INC(tcps_rcvafterclose); 2270 rstreason = BANDLIM_UNLIMITED; 2271 goto dropwithreset; 2272 } 2273 2274 /* 2275 * If segment ends after window, drop trailing data 2276 * (and PUSH and FIN); if nothing left, just ACK. 2277 */ 2278 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd); 2279 if (todrop > 0) { 2280 TCPSTAT_INC(tcps_rcvpackafterwin); 2281 if (todrop >= tlen) { 2282 TCPSTAT_ADD(tcps_rcvbyteafterwin, tlen); 2283 /* 2284 * If window is closed can only take segments at 2285 * window edge, and have to drop data and PUSH from 2286 * incoming segments. Continue processing, but 2287 * remember to ack. Otherwise, drop segment 2288 * and ack. 2289 */ 2290 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) { 2291 tp->t_flags |= TF_ACKNOW; 2292 TCPSTAT_INC(tcps_rcvwinprobe); 2293 } else 2294 goto dropafterack; 2295 } else 2296 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop); 2297 m_adj(m, -todrop); 2298 tlen -= todrop; 2299 thflags &= ~(TH_PUSH|TH_FIN); 2300 } 2301 2302 /* 2303 * If last ACK falls within this segment's sequence numbers, 2304 * record its timestamp. 2305 * NOTE: 2306 * 1) That the test incorporates suggestions from the latest 2307 * proposal of the tcplw@cray.com list (Braden 1993/04/26). 2308 * 2) That updating only on newer timestamps interferes with 2309 * our earlier PAWS tests, so this check should be solely 2310 * predicated on the sequence space of this segment. 2311 * 3) That we modify the segment boundary check to be 2312 * Last.ACK.Sent <= SEG.SEQ + SEG.Len 2313 * instead of RFC1323's 2314 * Last.ACK.Sent < SEG.SEQ + SEG.Len, 2315 * This modified check allows us to overcome RFC1323's 2316 * limitations as described in Stevens TCP/IP Illustrated 2317 * Vol. 2 p.869. In such cases, we can still calculate the 2318 * RTT correctly when RCV.NXT == Last.ACK.Sent. 2319 */ 2320 if ((to.to_flags & TOF_TS) != 0 && 2321 SEQ_LEQ(th->th_seq, tp->last_ack_sent) && 2322 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen + 2323 ((thflags & (TH_SYN|TH_FIN)) != 0))) { 2324 tp->ts_recent_age = tcp_ts_getticks(); 2325 tp->ts_recent = to.to_tsval; 2326 } 2327 2328 /* 2329 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN 2330 * flag is on (half-synchronized state), then queue data for 2331 * later processing; else drop segment and return. 2332 */ 2333 if ((thflags & TH_ACK) == 0) { 2334 if (tp->t_state == TCPS_SYN_RECEIVED || 2335 (tp->t_flags & TF_NEEDSYN)) { 2336 if (tp->t_state == TCPS_SYN_RECEIVED && 2337 IS_FASTOPEN(tp->t_flags)) { 2338 tp->snd_wnd = tiwin; 2339 cc_conn_init(tp); 2340 } 2341 goto step6; 2342 } else if (tp->t_flags & TF_ACKNOW) 2343 goto dropafterack; 2344 else 2345 goto drop; 2346 } 2347 2348 /* 2349 * Ack processing. 2350 */ 2351 switch (tp->t_state) { 2352 2353 /* 2354 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter 2355 * ESTABLISHED state and continue processing. 2356 * The ACK was checked above. 2357 */ 2358 case TCPS_SYN_RECEIVED: 2359 2360 TCPSTAT_INC(tcps_connects); 2361 soisconnected(so); 2362 /* Do window scaling? */ 2363 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) == 2364 (TF_RCVD_SCALE|TF_REQ_SCALE)) { 2365 tp->rcv_scale = tp->request_r_scale; 2366 } 2367 tp->snd_wnd = tiwin; 2368 /* 2369 * Make transitions: 2370 * SYN-RECEIVED -> ESTABLISHED 2371 * SYN-RECEIVED* -> FIN-WAIT-1 2372 */ 2373 tp->t_starttime = ticks; 2374 if (IS_FASTOPEN(tp->t_flags) && tp->t_tfo_pending) { 2375 tcp_fastopen_decrement_counter(tp->t_tfo_pending); 2376 tp->t_tfo_pending = NULL; 2377 } 2378 if (tp->t_flags & TF_NEEDFIN) { 2379 tcp_state_change(tp, TCPS_FIN_WAIT_1); 2380 tp->t_flags &= ~TF_NEEDFIN; 2381 } else { 2382 tcp_state_change(tp, TCPS_ESTABLISHED); 2383 TCP_PROBE5(accept__established, NULL, tp, 2384 m, tp, th); 2385 /* 2386 * TFO connections call cc_conn_init() during SYN 2387 * processing. Calling it again here for such 2388 * connections is not harmless as it would undo the 2389 * snd_cwnd reduction that occurs when a TFO SYN|ACK 2390 * is retransmitted. 2391 */ 2392 if (!IS_FASTOPEN(tp->t_flags)) 2393 cc_conn_init(tp); 2394 tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp)); 2395 } 2396 /* 2397 * Account for the ACK of our SYN prior to 2398 * regular ACK processing below, except for 2399 * simultaneous SYN, which is handled later. 2400 */ 2401 if (SEQ_GT(th->th_ack, tp->snd_una) && !(tp->t_flags & TF_NEEDSYN)) 2402 incforsyn = 1; 2403 /* 2404 * If segment contains data or ACK, will call tcp_reass() 2405 * later; if not, do so now to pass queued data to user. 2406 */ 2407 if (tlen == 0 && (thflags & TH_FIN) == 0) 2408 (void) tcp_reass(tp, (struct tcphdr *)0, NULL, 0, 2409 (struct mbuf *)0); 2410 tp->snd_wl1 = th->th_seq - 1; 2411 /* FALLTHROUGH */ 2412 2413 /* 2414 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range 2415 * ACKs. If the ack is in the range 2416 * tp->snd_una < th->th_ack <= tp->snd_max 2417 * then advance tp->snd_una to th->th_ack and drop 2418 * data from the retransmission queue. If this ACK reflects 2419 * more up to date window information we update our window information. 2420 */ 2421 case TCPS_ESTABLISHED: 2422 case TCPS_FIN_WAIT_1: 2423 case TCPS_FIN_WAIT_2: 2424 case TCPS_CLOSE_WAIT: 2425 case TCPS_CLOSING: 2426 case TCPS_LAST_ACK: 2427 if (SEQ_GT(th->th_ack, tp->snd_max)) { 2428 TCPSTAT_INC(tcps_rcvacktoomuch); 2429 goto dropafterack; 2430 } 2431 if ((tp->t_flags & TF_SACK_PERMIT) && 2432 ((to.to_flags & TOF_SACK) || 2433 !TAILQ_EMPTY(&tp->snd_holes))) 2434 sack_changed = tcp_sack_doack(tp, &to, th->th_ack); 2435 else 2436 /* 2437 * Reset the value so that previous (valid) value 2438 * from the last ack with SACK doesn't get used. 2439 */ 2440 tp->sackhint.sacked_bytes = 0; 2441 2442 #ifdef TCP_HHOOK 2443 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */ 2444 hhook_run_tcp_est_in(tp, th, &to); 2445 #endif 2446 2447 if (SEQ_LEQ(th->th_ack, tp->snd_una)) { 2448 u_int maxseg; 2449 2450 maxseg = tcp_maxseg(tp); 2451 if (tlen == 0 && 2452 (tiwin == tp->snd_wnd || 2453 (tp->t_flags & TF_SACK_PERMIT))) { 2454 /* 2455 * If this is the first time we've seen a 2456 * FIN from the remote, this is not a 2457 * duplicate and it needs to be processed 2458 * normally. This happens during a 2459 * simultaneous close. 2460 */ 2461 if ((thflags & TH_FIN) && 2462 (TCPS_HAVERCVDFIN(tp->t_state) == 0)) { 2463 tp->t_dupacks = 0; 2464 break; 2465 } 2466 TCPSTAT_INC(tcps_rcvdupack); 2467 /* 2468 * If we have outstanding data (other than 2469 * a window probe), this is a completely 2470 * duplicate ack (ie, window info didn't 2471 * change and FIN isn't set), 2472 * the ack is the biggest we've 2473 * seen and we've seen exactly our rexmt 2474 * threshold of them, assume a packet 2475 * has been dropped and retransmit it. 2476 * Kludge snd_nxt & the congestion 2477 * window so we send only this one 2478 * packet. 2479 * 2480 * We know we're losing at the current 2481 * window size so do congestion avoidance 2482 * (set ssthresh to half the current window 2483 * and pull our congestion window back to 2484 * the new ssthresh). 2485 * 2486 * Dup acks mean that packets have left the 2487 * network (they're now cached at the receiver) 2488 * so bump cwnd by the amount in the receiver 2489 * to keep a constant cwnd packets in the 2490 * network. 2491 * 2492 * When using TCP ECN, notify the peer that 2493 * we reduced the cwnd. 2494 */ 2495 /* 2496 * Following 2 kinds of acks should not affect 2497 * dupack counting: 2498 * 1) Old acks 2499 * 2) Acks with SACK but without any new SACK 2500 * information in them. These could result from 2501 * any anomaly in the network like a switch 2502 * duplicating packets or a possible DoS attack. 2503 */ 2504 if (th->th_ack != tp->snd_una || 2505 ((tp->t_flags & TF_SACK_PERMIT) && 2506 !sack_changed)) 2507 break; 2508 else if (!tcp_timer_active(tp, TT_REXMT)) 2509 tp->t_dupacks = 0; 2510 else if (++tp->t_dupacks > tcprexmtthresh || 2511 IN_FASTRECOVERY(tp->t_flags)) { 2512 cc_ack_received(tp, th, nsegs, 2513 CC_DUPACK); 2514 if ((tp->t_flags & TF_SACK_PERMIT) && 2515 IN_FASTRECOVERY(tp->t_flags)) { 2516 int awnd; 2517 2518 /* 2519 * Compute the amount of data in flight first. 2520 * We can inject new data into the pipe iff 2521 * we have less than 1/2 the original window's 2522 * worth of data in flight. 2523 */ 2524 if (V_tcp_do_rfc6675_pipe) 2525 awnd = tcp_compute_pipe(tp); 2526 else 2527 awnd = (tp->snd_nxt - tp->snd_fack) + 2528 tp->sackhint.sack_bytes_rexmit; 2529 2530 if (awnd < tp->snd_ssthresh) { 2531 tp->snd_cwnd += maxseg; 2532 if (tp->snd_cwnd > tp->snd_ssthresh) 2533 tp->snd_cwnd = tp->snd_ssthresh; 2534 } 2535 } else 2536 tp->snd_cwnd += maxseg; 2537 (void) tp->t_fb->tfb_tcp_output(tp); 2538 goto drop; 2539 } else if (tp->t_dupacks == tcprexmtthresh) { 2540 tcp_seq onxt = tp->snd_nxt; 2541 2542 /* 2543 * If we're doing sack, check to 2544 * see if we're already in sack 2545 * recovery. If we're not doing sack, 2546 * check to see if we're in newreno 2547 * recovery. 2548 */ 2549 if (tp->t_flags & TF_SACK_PERMIT) { 2550 if (IN_FASTRECOVERY(tp->t_flags)) { 2551 tp->t_dupacks = 0; 2552 break; 2553 } 2554 } else { 2555 if (SEQ_LEQ(th->th_ack, 2556 tp->snd_recover)) { 2557 tp->t_dupacks = 0; 2558 break; 2559 } 2560 } 2561 /* Congestion signal before ack. */ 2562 cc_cong_signal(tp, th, CC_NDUPACK); 2563 cc_ack_received(tp, th, nsegs, 2564 CC_DUPACK); 2565 tcp_timer_activate(tp, TT_REXMT, 0); 2566 tp->t_rtttime = 0; 2567 if (tp->t_flags & TF_SACK_PERMIT) { 2568 TCPSTAT_INC( 2569 tcps_sack_recovery_episode); 2570 tp->snd_recover = tp->snd_nxt; 2571 tp->snd_cwnd = maxseg; 2572 (void) tp->t_fb->tfb_tcp_output(tp); 2573 goto drop; 2574 } 2575 tp->snd_nxt = th->th_ack; 2576 tp->snd_cwnd = maxseg; 2577 (void) tp->t_fb->tfb_tcp_output(tp); 2578 KASSERT(tp->snd_limited <= 2, 2579 ("%s: tp->snd_limited too big", 2580 __func__)); 2581 tp->snd_cwnd = tp->snd_ssthresh + 2582 maxseg * 2583 (tp->t_dupacks - tp->snd_limited); 2584 if (SEQ_GT(onxt, tp->snd_nxt)) 2585 tp->snd_nxt = onxt; 2586 goto drop; 2587 } else if (V_tcp_do_rfc3042) { 2588 /* 2589 * Process first and second duplicate 2590 * ACKs. Each indicates a segment 2591 * leaving the network, creating room 2592 * for more. Make sure we can send a 2593 * packet on reception of each duplicate 2594 * ACK by increasing snd_cwnd by one 2595 * segment. Restore the original 2596 * snd_cwnd after packet transmission. 2597 */ 2598 cc_ack_received(tp, th, nsegs, 2599 CC_DUPACK); 2600 uint32_t oldcwnd = tp->snd_cwnd; 2601 tcp_seq oldsndmax = tp->snd_max; 2602 u_int sent; 2603 int avail; 2604 2605 KASSERT(tp->t_dupacks == 1 || 2606 tp->t_dupacks == 2, 2607 ("%s: dupacks not 1 or 2", 2608 __func__)); 2609 if (tp->t_dupacks == 1) 2610 tp->snd_limited = 0; 2611 tp->snd_cwnd = 2612 (tp->snd_nxt - tp->snd_una) + 2613 (tp->t_dupacks - tp->snd_limited) * 2614 maxseg; 2615 /* 2616 * Only call tcp_output when there 2617 * is new data available to be sent. 2618 * Otherwise we would send pure ACKs. 2619 */ 2620 SOCKBUF_LOCK(&so->so_snd); 2621 avail = sbavail(&so->so_snd) - 2622 (tp->snd_nxt - tp->snd_una); 2623 SOCKBUF_UNLOCK(&so->so_snd); 2624 if (avail > 0) 2625 (void) tp->t_fb->tfb_tcp_output(tp); 2626 sent = tp->snd_max - oldsndmax; 2627 if (sent > maxseg) { 2628 KASSERT((tp->t_dupacks == 2 && 2629 tp->snd_limited == 0) || 2630 (sent == maxseg + 1 && 2631 tp->t_flags & TF_SENTFIN), 2632 ("%s: sent too much", 2633 __func__)); 2634 tp->snd_limited = 2; 2635 } else if (sent > 0) 2636 ++tp->snd_limited; 2637 tp->snd_cwnd = oldcwnd; 2638 goto drop; 2639 } 2640 } 2641 break; 2642 } else { 2643 /* 2644 * This ack is advancing the left edge, reset the 2645 * counter. 2646 */ 2647 tp->t_dupacks = 0; 2648 /* 2649 * If this ack also has new SACK info, increment the 2650 * counter as per rfc6675. 2651 */ 2652 if ((tp->t_flags & TF_SACK_PERMIT) && sack_changed) 2653 tp->t_dupacks++; 2654 } 2655 2656 KASSERT(SEQ_GT(th->th_ack, tp->snd_una), 2657 ("%s: th_ack <= snd_una", __func__)); 2658 2659 /* 2660 * If the congestion window was inflated to account 2661 * for the other side's cached packets, retract it. 2662 */ 2663 if (IN_FASTRECOVERY(tp->t_flags)) { 2664 if (SEQ_LT(th->th_ack, tp->snd_recover)) { 2665 if (tp->t_flags & TF_SACK_PERMIT) 2666 tcp_sack_partialack(tp, th); 2667 else 2668 tcp_newreno_partial_ack(tp, th); 2669 } else 2670 cc_post_recovery(tp, th); 2671 } 2672 /* 2673 * If we reach this point, ACK is not a duplicate, 2674 * i.e., it ACKs something we sent. 2675 */ 2676 if (tp->t_flags & TF_NEEDSYN) { 2677 /* 2678 * T/TCP: Connection was half-synchronized, and our 2679 * SYN has been ACK'd (so connection is now fully 2680 * synchronized). Go to non-starred state, 2681 * increment snd_una for ACK of SYN, and check if 2682 * we can do window scaling. 2683 */ 2684 tp->t_flags &= ~TF_NEEDSYN; 2685 tp->snd_una++; 2686 /* Do window scaling? */ 2687 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) == 2688 (TF_RCVD_SCALE|TF_REQ_SCALE)) { 2689 tp->rcv_scale = tp->request_r_scale; 2690 /* Send window already scaled. */ 2691 } 2692 } 2693 2694 process_ACK: 2695 INP_WLOCK_ASSERT(tp->t_inpcb); 2696 2697 /* 2698 * Adjust for the SYN bit in sequence space, 2699 * but don't account for it in cwnd calculations. 2700 * This is for the SYN_RECEIVED, non-simultaneous 2701 * SYN case. SYN_SENT and simultaneous SYN are 2702 * treated elsewhere. 2703 */ 2704 if (incforsyn) 2705 tp->snd_una++; 2706 acked = BYTES_THIS_ACK(tp, th); 2707 KASSERT(acked >= 0, ("%s: acked unexepectedly negative " 2708 "(tp->snd_una=%u, th->th_ack=%u, tp=%p, m=%p)", __func__, 2709 tp->snd_una, th->th_ack, tp, m)); 2710 TCPSTAT_ADD(tcps_rcvackpack, nsegs); 2711 TCPSTAT_ADD(tcps_rcvackbyte, acked); 2712 2713 /* 2714 * If we just performed our first retransmit, and the ACK 2715 * arrives within our recovery window, then it was a mistake 2716 * to do the retransmit in the first place. Recover our 2717 * original cwnd and ssthresh, and proceed to transmit where 2718 * we left off. 2719 */ 2720 if (tp->t_rxtshift == 1 && 2721 tp->t_flags & TF_PREVVALID && 2722 tp->t_badrxtwin && 2723 SEQ_LT(to.to_tsecr, tp->t_badrxtwin)) 2724 cc_cong_signal(tp, th, CC_RTO_ERR); 2725 2726 /* 2727 * If we have a timestamp reply, update smoothed 2728 * round trip time. If no timestamp is present but 2729 * transmit timer is running and timed sequence 2730 * number was acked, update smoothed round trip time. 2731 * Since we now have an rtt measurement, cancel the 2732 * timer backoff (cf., Phil Karn's retransmit alg.). 2733 * Recompute the initial retransmit timer. 2734 * 2735 * Some boxes send broken timestamp replies 2736 * during the SYN+ACK phase, ignore 2737 * timestamps of 0 or we could calculate a 2738 * huge RTT and blow up the retransmit timer. 2739 */ 2740 if ((to.to_flags & TOF_TS) != 0 && to.to_tsecr) { 2741 uint32_t t; 2742 2743 t = tcp_ts_getticks() - to.to_tsecr; 2744 if (!tp->t_rttlow || tp->t_rttlow > t) 2745 tp->t_rttlow = t; 2746 tcp_xmit_timer(tp, TCP_TS_TO_TICKS(t) + 1); 2747 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) { 2748 if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime) 2749 tp->t_rttlow = ticks - tp->t_rtttime; 2750 tcp_xmit_timer(tp, ticks - tp->t_rtttime); 2751 } 2752 2753 /* 2754 * If all outstanding data is acked, stop retransmit 2755 * timer and remember to restart (more output or persist). 2756 * If there is more data to be acked, restart retransmit 2757 * timer, using current (possibly backed-off) value. 2758 */ 2759 if (th->th_ack == tp->snd_max) { 2760 tcp_timer_activate(tp, TT_REXMT, 0); 2761 needoutput = 1; 2762 } else if (!tcp_timer_active(tp, TT_PERSIST)) 2763 tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur); 2764 2765 /* 2766 * If no data (only SYN) was ACK'd, 2767 * skip rest of ACK processing. 2768 */ 2769 if (acked == 0) 2770 goto step6; 2771 2772 /* 2773 * Let the congestion control algorithm update congestion 2774 * control related information. This typically means increasing 2775 * the congestion window. 2776 */ 2777 cc_ack_received(tp, th, nsegs, CC_ACK); 2778 2779 SOCKBUF_LOCK(&so->so_snd); 2780 if (acked > sbavail(&so->so_snd)) { 2781 if (tp->snd_wnd >= sbavail(&so->so_snd)) 2782 tp->snd_wnd -= sbavail(&so->so_snd); 2783 else 2784 tp->snd_wnd = 0; 2785 mfree = sbcut_locked(&so->so_snd, 2786 (int)sbavail(&so->so_snd)); 2787 ourfinisacked = 1; 2788 } else { 2789 mfree = sbcut_locked(&so->so_snd, acked); 2790 if (tp->snd_wnd >= (uint32_t) acked) 2791 tp->snd_wnd -= acked; 2792 else 2793 tp->snd_wnd = 0; 2794 ourfinisacked = 0; 2795 } 2796 /* NB: sowwakeup_locked() does an implicit unlock. */ 2797 sowwakeup_locked(so); 2798 m_freem(mfree); 2799 /* Detect una wraparound. */ 2800 if (!IN_RECOVERY(tp->t_flags) && 2801 SEQ_GT(tp->snd_una, tp->snd_recover) && 2802 SEQ_LEQ(th->th_ack, tp->snd_recover)) 2803 tp->snd_recover = th->th_ack - 1; 2804 /* XXXLAS: Can this be moved up into cc_post_recovery? */ 2805 if (IN_RECOVERY(tp->t_flags) && 2806 SEQ_GEQ(th->th_ack, tp->snd_recover)) { 2807 EXIT_RECOVERY(tp->t_flags); 2808 } 2809 tp->snd_una = th->th_ack; 2810 if (tp->t_flags & TF_SACK_PERMIT) { 2811 if (SEQ_GT(tp->snd_una, tp->snd_recover)) 2812 tp->snd_recover = tp->snd_una; 2813 } 2814 if (SEQ_LT(tp->snd_nxt, tp->snd_una)) 2815 tp->snd_nxt = tp->snd_una; 2816 2817 switch (tp->t_state) { 2818 2819 /* 2820 * In FIN_WAIT_1 STATE in addition to the processing 2821 * for the ESTABLISHED state if our FIN is now acknowledged 2822 * then enter FIN_WAIT_2. 2823 */ 2824 case TCPS_FIN_WAIT_1: 2825 if (ourfinisacked) { 2826 /* 2827 * If we can't receive any more 2828 * data, then closing user can proceed. 2829 * Starting the timer is contrary to the 2830 * specification, but if we don't get a FIN 2831 * we'll hang forever. 2832 * 2833 * XXXjl: 2834 * we should release the tp also, and use a 2835 * compressed state. 2836 */ 2837 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) { 2838 soisdisconnected(so); 2839 tcp_timer_activate(tp, TT_2MSL, 2840 (tcp_fast_finwait2_recycle ? 2841 tcp_finwait2_timeout : 2842 TP_MAXIDLE(tp))); 2843 } 2844 tcp_state_change(tp, TCPS_FIN_WAIT_2); 2845 } 2846 break; 2847 2848 /* 2849 * In CLOSING STATE in addition to the processing for 2850 * the ESTABLISHED state if the ACK acknowledges our FIN 2851 * then enter the TIME-WAIT state, otherwise ignore 2852 * the segment. 2853 */ 2854 case TCPS_CLOSING: 2855 if (ourfinisacked) { 2856 tcp_twstart(tp); 2857 m_freem(m); 2858 return; 2859 } 2860 break; 2861 2862 /* 2863 * In LAST_ACK, we may still be waiting for data to drain 2864 * and/or to be acked, as well as for the ack of our FIN. 2865 * If our FIN is now acknowledged, delete the TCB, 2866 * enter the closed state and return. 2867 */ 2868 case TCPS_LAST_ACK: 2869 if (ourfinisacked) { 2870 tp = tcp_close(tp); 2871 goto drop; 2872 } 2873 break; 2874 } 2875 } 2876 2877 step6: 2878 INP_WLOCK_ASSERT(tp->t_inpcb); 2879 2880 /* 2881 * Update window information. 2882 * Don't look at window if no ACK: TAC's send garbage on first SYN. 2883 */ 2884 if ((thflags & TH_ACK) && 2885 (SEQ_LT(tp->snd_wl1, th->th_seq) || 2886 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) || 2887 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) { 2888 /* keep track of pure window updates */ 2889 if (tlen == 0 && 2890 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd) 2891 TCPSTAT_INC(tcps_rcvwinupd); 2892 tp->snd_wnd = tiwin; 2893 tp->snd_wl1 = th->th_seq; 2894 tp->snd_wl2 = th->th_ack; 2895 if (tp->snd_wnd > tp->max_sndwnd) 2896 tp->max_sndwnd = tp->snd_wnd; 2897 needoutput = 1; 2898 } 2899 2900 /* 2901 * Process segments with URG. 2902 */ 2903 if ((thflags & TH_URG) && th->th_urp && 2904 TCPS_HAVERCVDFIN(tp->t_state) == 0) { 2905 /* 2906 * This is a kludge, but if we receive and accept 2907 * random urgent pointers, we'll crash in 2908 * soreceive. It's hard to imagine someone 2909 * actually wanting to send this much urgent data. 2910 */ 2911 SOCKBUF_LOCK(&so->so_rcv); 2912 if (th->th_urp + sbavail(&so->so_rcv) > sb_max) { 2913 th->th_urp = 0; /* XXX */ 2914 thflags &= ~TH_URG; /* XXX */ 2915 SOCKBUF_UNLOCK(&so->so_rcv); /* XXX */ 2916 goto dodata; /* XXX */ 2917 } 2918 /* 2919 * If this segment advances the known urgent pointer, 2920 * then mark the data stream. This should not happen 2921 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since 2922 * a FIN has been received from the remote side. 2923 * In these states we ignore the URG. 2924 * 2925 * According to RFC961 (Assigned Protocols), 2926 * the urgent pointer points to the last octet 2927 * of urgent data. We continue, however, 2928 * to consider it to indicate the first octet 2929 * of data past the urgent section as the original 2930 * spec states (in one of two places). 2931 */ 2932 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) { 2933 tp->rcv_up = th->th_seq + th->th_urp; 2934 so->so_oobmark = sbavail(&so->so_rcv) + 2935 (tp->rcv_up - tp->rcv_nxt) - 1; 2936 if (so->so_oobmark == 0) 2937 so->so_rcv.sb_state |= SBS_RCVATMARK; 2938 sohasoutofband(so); 2939 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA); 2940 } 2941 SOCKBUF_UNLOCK(&so->so_rcv); 2942 /* 2943 * Remove out of band data so doesn't get presented to user. 2944 * This can happen independent of advancing the URG pointer, 2945 * but if two URG's are pending at once, some out-of-band 2946 * data may creep in... ick. 2947 */ 2948 if (th->th_urp <= (uint32_t)tlen && 2949 !(so->so_options & SO_OOBINLINE)) { 2950 /* hdr drop is delayed */ 2951 tcp_pulloutofband(so, th, m, drop_hdrlen); 2952 } 2953 } else { 2954 /* 2955 * If no out of band data is expected, 2956 * pull receive urgent pointer along 2957 * with the receive window. 2958 */ 2959 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up)) 2960 tp->rcv_up = tp->rcv_nxt; 2961 } 2962 dodata: /* XXX */ 2963 INP_WLOCK_ASSERT(tp->t_inpcb); 2964 2965 /* 2966 * Process the segment text, merging it into the TCP sequencing queue, 2967 * and arranging for acknowledgment of receipt if necessary. 2968 * This process logically involves adjusting tp->rcv_wnd as data 2969 * is presented to the user (this happens in tcp_usrreq.c, 2970 * case PRU_RCVD). If a FIN has already been received on this 2971 * connection then we just ignore the text. 2972 */ 2973 tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) && 2974 IS_FASTOPEN(tp->t_flags)); 2975 if ((tlen || (thflags & TH_FIN) || tfo_syn) && 2976 TCPS_HAVERCVDFIN(tp->t_state) == 0) { 2977 tcp_seq save_start = th->th_seq; 2978 tcp_seq save_rnxt = tp->rcv_nxt; 2979 int save_tlen = tlen; 2980 m_adj(m, drop_hdrlen); /* delayed header drop */ 2981 /* 2982 * Insert segment which includes th into TCP reassembly queue 2983 * with control block tp. Set thflags to whether reassembly now 2984 * includes a segment with FIN. This handles the common case 2985 * inline (segment is the next to be received on an established 2986 * connection, and the queue is empty), avoiding linkage into 2987 * and removal from the queue and repetition of various 2988 * conversions. 2989 * Set DELACK for segments received in order, but ack 2990 * immediately when segments are out of order (so 2991 * fast retransmit can work). 2992 */ 2993 if (th->th_seq == tp->rcv_nxt && 2994 SEGQ_EMPTY(tp) && 2995 (TCPS_HAVEESTABLISHED(tp->t_state) || 2996 tfo_syn)) { 2997 if (DELAY_ACK(tp, tlen) || tfo_syn) 2998 tp->t_flags |= TF_DELACK; 2999 else 3000 tp->t_flags |= TF_ACKNOW; 3001 tp->rcv_nxt += tlen; 3002 thflags = th->th_flags & TH_FIN; 3003 TCPSTAT_INC(tcps_rcvpack); 3004 TCPSTAT_ADD(tcps_rcvbyte, tlen); 3005 SOCKBUF_LOCK(&so->so_rcv); 3006 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) 3007 m_freem(m); 3008 else 3009 sbappendstream_locked(&so->so_rcv, m, 0); 3010 /* NB: sorwakeup_locked() does an implicit unlock. */ 3011 sorwakeup_locked(so); 3012 } else { 3013 /* 3014 * XXX: Due to the header drop above "th" is 3015 * theoretically invalid by now. Fortunately 3016 * m_adj() doesn't actually frees any mbufs 3017 * when trimming from the head. 3018 */ 3019 tcp_seq temp = save_start; 3020 thflags = tcp_reass(tp, th, &temp, &tlen, m); 3021 tp->t_flags |= TF_ACKNOW; 3022 } 3023 if ((tp->t_flags & TF_SACK_PERMIT) && (save_tlen > 0)) { 3024 if ((tlen == 0) && (SEQ_LT(save_start, save_rnxt))) { 3025 /* 3026 * DSACK actually handled in the fastpath 3027 * above. 3028 */ 3029 tcp_update_sack_list(tp, save_start, 3030 save_start + save_tlen); 3031 } else if ((tlen > 0) && SEQ_GT(tp->rcv_nxt, save_rnxt)) { 3032 if ((tp->rcv_numsacks >= 1) && 3033 (tp->sackblks[0].end == save_start)) { 3034 /* 3035 * Partial overlap, recorded at todrop 3036 * above. 3037 */ 3038 tcp_update_sack_list(tp, 3039 tp->sackblks[0].start, 3040 tp->sackblks[0].end); 3041 } else { 3042 tcp_update_dsack_list(tp, save_start, 3043 save_start + save_tlen); 3044 } 3045 } else if (tlen >= save_tlen) { 3046 /* Update of sackblks. */ 3047 tcp_update_dsack_list(tp, save_start, 3048 save_start + save_tlen); 3049 } else if (tlen > 0) { 3050 tcp_update_dsack_list(tp, save_start, 3051 save_start + tlen); 3052 } 3053 } 3054 #if 0 3055 /* 3056 * Note the amount of data that peer has sent into 3057 * our window, in order to estimate the sender's 3058 * buffer size. 3059 * XXX: Unused. 3060 */ 3061 if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt)) 3062 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt); 3063 else 3064 len = so->so_rcv.sb_hiwat; 3065 #endif 3066 } else { 3067 m_freem(m); 3068 thflags &= ~TH_FIN; 3069 } 3070 3071 /* 3072 * If FIN is received ACK the FIN and let the user know 3073 * that the connection is closing. 3074 */ 3075 if (thflags & TH_FIN) { 3076 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) { 3077 socantrcvmore(so); 3078 /* 3079 * If connection is half-synchronized 3080 * (ie NEEDSYN flag on) then delay ACK, 3081 * so it may be piggybacked when SYN is sent. 3082 * Otherwise, since we received a FIN then no 3083 * more input can be expected, send ACK now. 3084 */ 3085 if (tp->t_flags & TF_NEEDSYN) 3086 tp->t_flags |= TF_DELACK; 3087 else 3088 tp->t_flags |= TF_ACKNOW; 3089 tp->rcv_nxt++; 3090 } 3091 switch (tp->t_state) { 3092 3093 /* 3094 * In SYN_RECEIVED and ESTABLISHED STATES 3095 * enter the CLOSE_WAIT state. 3096 */ 3097 case TCPS_SYN_RECEIVED: 3098 tp->t_starttime = ticks; 3099 /* FALLTHROUGH */ 3100 case TCPS_ESTABLISHED: 3101 tcp_state_change(tp, TCPS_CLOSE_WAIT); 3102 break; 3103 3104 /* 3105 * If still in FIN_WAIT_1 STATE FIN has not been acked so 3106 * enter the CLOSING state. 3107 */ 3108 case TCPS_FIN_WAIT_1: 3109 tcp_state_change(tp, TCPS_CLOSING); 3110 break; 3111 3112 /* 3113 * In FIN_WAIT_2 state enter the TIME_WAIT state, 3114 * starting the time-wait timer, turning off the other 3115 * standard timers. 3116 */ 3117 case TCPS_FIN_WAIT_2: 3118 tcp_twstart(tp); 3119 return; 3120 } 3121 } 3122 #ifdef TCPDEBUG 3123 if (so->so_options & SO_DEBUG) 3124 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen, 3125 &tcp_savetcp, 0); 3126 #endif 3127 TCP_PROBE3(debug__input, tp, th, m); 3128 3129 /* 3130 * Return any desired output. 3131 */ 3132 if (needoutput || (tp->t_flags & TF_ACKNOW)) 3133 (void) tp->t_fb->tfb_tcp_output(tp); 3134 3135 check_delack: 3136 INP_WLOCK_ASSERT(tp->t_inpcb); 3137 3138 if (tp->t_flags & TF_DELACK) { 3139 tp->t_flags &= ~TF_DELACK; 3140 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime); 3141 } 3142 INP_WUNLOCK(tp->t_inpcb); 3143 return; 3144 3145 dropafterack: 3146 /* 3147 * Generate an ACK dropping incoming segment if it occupies 3148 * sequence space, where the ACK reflects our state. 3149 * 3150 * We can now skip the test for the RST flag since all 3151 * paths to this code happen after packets containing 3152 * RST have been dropped. 3153 * 3154 * In the SYN-RECEIVED state, don't send an ACK unless the 3155 * segment we received passes the SYN-RECEIVED ACK test. 3156 * If it fails send a RST. This breaks the loop in the 3157 * "LAND" DoS attack, and also prevents an ACK storm 3158 * between two listening ports that have been sent forged 3159 * SYN segments, each with the source address of the other. 3160 */ 3161 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) && 3162 (SEQ_GT(tp->snd_una, th->th_ack) || 3163 SEQ_GT(th->th_ack, tp->snd_max)) ) { 3164 rstreason = BANDLIM_RST_OPENPORT; 3165 goto dropwithreset; 3166 } 3167 #ifdef TCPDEBUG 3168 if (so->so_options & SO_DEBUG) 3169 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen, 3170 &tcp_savetcp, 0); 3171 #endif 3172 TCP_PROBE3(debug__input, tp, th, m); 3173 tp->t_flags |= TF_ACKNOW; 3174 (void) tp->t_fb->tfb_tcp_output(tp); 3175 INP_WUNLOCK(tp->t_inpcb); 3176 m_freem(m); 3177 return; 3178 3179 dropwithreset: 3180 if (tp != NULL) { 3181 tcp_dropwithreset(m, th, tp, tlen, rstreason); 3182 INP_WUNLOCK(tp->t_inpcb); 3183 } else 3184 tcp_dropwithreset(m, th, NULL, tlen, rstreason); 3185 return; 3186 3187 drop: 3188 /* 3189 * Drop space held by incoming segment and return. 3190 */ 3191 #ifdef TCPDEBUG 3192 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG)) 3193 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen, 3194 &tcp_savetcp, 0); 3195 #endif 3196 TCP_PROBE3(debug__input, tp, th, m); 3197 if (tp != NULL) 3198 INP_WUNLOCK(tp->t_inpcb); 3199 m_freem(m); 3200 } 3201 3202 /* 3203 * Issue RST and make ACK acceptable to originator of segment. 3204 * The mbuf must still include the original packet header. 3205 * tp may be NULL. 3206 */ 3207 void 3208 tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp, 3209 int tlen, int rstreason) 3210 { 3211 #ifdef INET 3212 struct ip *ip; 3213 #endif 3214 #ifdef INET6 3215 struct ip6_hdr *ip6; 3216 #endif 3217 3218 if (tp != NULL) { 3219 INP_WLOCK_ASSERT(tp->t_inpcb); 3220 } 3221 3222 /* Don't bother if destination was broadcast/multicast. */ 3223 if ((th->th_flags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST)) 3224 goto drop; 3225 #ifdef INET6 3226 if (mtod(m, struct ip *)->ip_v == 6) { 3227 ip6 = mtod(m, struct ip6_hdr *); 3228 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) || 3229 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) 3230 goto drop; 3231 /* IPv6 anycast check is done at tcp6_input() */ 3232 } 3233 #endif 3234 #if defined(INET) && defined(INET6) 3235 else 3236 #endif 3237 #ifdef INET 3238 { 3239 ip = mtod(m, struct ip *); 3240 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) || 3241 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) || 3242 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) || 3243 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) 3244 goto drop; 3245 } 3246 #endif 3247 3248 /* Perform bandwidth limiting. */ 3249 if (badport_bandlim(rstreason) < 0) 3250 goto drop; 3251 3252 /* tcp_respond consumes the mbuf chain. */ 3253 if (th->th_flags & TH_ACK) { 3254 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, 3255 th->th_ack, TH_RST); 3256 } else { 3257 if (th->th_flags & TH_SYN) 3258 tlen++; 3259 if (th->th_flags & TH_FIN) 3260 tlen++; 3261 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen, 3262 (tcp_seq)0, TH_RST|TH_ACK); 3263 } 3264 return; 3265 drop: 3266 m_freem(m); 3267 } 3268 3269 /* 3270 * Parse TCP options and place in tcpopt. 3271 */ 3272 void 3273 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags) 3274 { 3275 int opt, optlen; 3276 3277 to->to_flags = 0; 3278 for (; cnt > 0; cnt -= optlen, cp += optlen) { 3279 opt = cp[0]; 3280 if (opt == TCPOPT_EOL) 3281 break; 3282 if (opt == TCPOPT_NOP) 3283 optlen = 1; 3284 else { 3285 if (cnt < 2) 3286 break; 3287 optlen = cp[1]; 3288 if (optlen < 2 || optlen > cnt) 3289 break; 3290 } 3291 switch (opt) { 3292 case TCPOPT_MAXSEG: 3293 if (optlen != TCPOLEN_MAXSEG) 3294 continue; 3295 if (!(flags & TO_SYN)) 3296 continue; 3297 to->to_flags |= TOF_MSS; 3298 bcopy((char *)cp + 2, 3299 (char *)&to->to_mss, sizeof(to->to_mss)); 3300 to->to_mss = ntohs(to->to_mss); 3301 break; 3302 case TCPOPT_WINDOW: 3303 if (optlen != TCPOLEN_WINDOW) 3304 continue; 3305 if (!(flags & TO_SYN)) 3306 continue; 3307 to->to_flags |= TOF_SCALE; 3308 to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT); 3309 break; 3310 case TCPOPT_TIMESTAMP: 3311 if (optlen != TCPOLEN_TIMESTAMP) 3312 continue; 3313 to->to_flags |= TOF_TS; 3314 bcopy((char *)cp + 2, 3315 (char *)&to->to_tsval, sizeof(to->to_tsval)); 3316 to->to_tsval = ntohl(to->to_tsval); 3317 bcopy((char *)cp + 6, 3318 (char *)&to->to_tsecr, sizeof(to->to_tsecr)); 3319 to->to_tsecr = ntohl(to->to_tsecr); 3320 break; 3321 case TCPOPT_SIGNATURE: 3322 /* 3323 * In order to reply to a host which has set the 3324 * TCP_SIGNATURE option in its initial SYN, we have 3325 * to record the fact that the option was observed 3326 * here for the syncache code to perform the correct 3327 * response. 3328 */ 3329 if (optlen != TCPOLEN_SIGNATURE) 3330 continue; 3331 to->to_flags |= TOF_SIGNATURE; 3332 to->to_signature = cp + 2; 3333 break; 3334 case TCPOPT_SACK_PERMITTED: 3335 if (optlen != TCPOLEN_SACK_PERMITTED) 3336 continue; 3337 if (!(flags & TO_SYN)) 3338 continue; 3339 if (!V_tcp_do_sack) 3340 continue; 3341 to->to_flags |= TOF_SACKPERM; 3342 break; 3343 case TCPOPT_SACK: 3344 if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0) 3345 continue; 3346 if (flags & TO_SYN) 3347 continue; 3348 to->to_flags |= TOF_SACK; 3349 to->to_nsacks = (optlen - 2) / TCPOLEN_SACK; 3350 to->to_sacks = cp + 2; 3351 TCPSTAT_INC(tcps_sack_rcv_blocks); 3352 break; 3353 case TCPOPT_FAST_OPEN: 3354 /* 3355 * Cookie length validation is performed by the 3356 * server side cookie checking code or the client 3357 * side cookie cache update code. 3358 */ 3359 if (!(flags & TO_SYN)) 3360 continue; 3361 if (!V_tcp_fastopen_client_enable && 3362 !V_tcp_fastopen_server_enable) 3363 continue; 3364 to->to_flags |= TOF_FASTOPEN; 3365 to->to_tfo_len = optlen - 2; 3366 to->to_tfo_cookie = to->to_tfo_len ? cp + 2 : NULL; 3367 break; 3368 default: 3369 continue; 3370 } 3371 } 3372 } 3373 3374 /* 3375 * Pull out of band byte out of a segment so 3376 * it doesn't appear in the user's data queue. 3377 * It is still reflected in the segment length for 3378 * sequencing purposes. 3379 */ 3380 void 3381 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m, 3382 int off) 3383 { 3384 int cnt = off + th->th_urp - 1; 3385 3386 while (cnt >= 0) { 3387 if (m->m_len > cnt) { 3388 char *cp = mtod(m, caddr_t) + cnt; 3389 struct tcpcb *tp = sototcpcb(so); 3390 3391 INP_WLOCK_ASSERT(tp->t_inpcb); 3392 3393 tp->t_iobc = *cp; 3394 tp->t_oobflags |= TCPOOB_HAVEDATA; 3395 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1)); 3396 m->m_len--; 3397 if (m->m_flags & M_PKTHDR) 3398 m->m_pkthdr.len--; 3399 return; 3400 } 3401 cnt -= m->m_len; 3402 m = m->m_next; 3403 if (m == NULL) 3404 break; 3405 } 3406 panic("tcp_pulloutofband"); 3407 } 3408 3409 /* 3410 * Collect new round-trip time estimate 3411 * and update averages and current timeout. 3412 */ 3413 void 3414 tcp_xmit_timer(struct tcpcb *tp, int rtt) 3415 { 3416 int delta; 3417 3418 INP_WLOCK_ASSERT(tp->t_inpcb); 3419 3420 TCPSTAT_INC(tcps_rttupdated); 3421 tp->t_rttupdated++; 3422 #ifdef STATS 3423 stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT, 3424 imax(0, rtt * 1000 / hz)); 3425 #endif 3426 if ((tp->t_srtt != 0) && (tp->t_rxtshift <= TCP_RTT_INVALIDATE)) { 3427 /* 3428 * srtt is stored as fixed point with 5 bits after the 3429 * binary point (i.e., scaled by 8). The following magic 3430 * is equivalent to the smoothing algorithm in rfc793 with 3431 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed 3432 * point). Adjust rtt to origin 0. 3433 */ 3434 delta = ((rtt - 1) << TCP_DELTA_SHIFT) 3435 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT)); 3436 3437 if ((tp->t_srtt += delta) <= 0) 3438 tp->t_srtt = 1; 3439 3440 /* 3441 * We accumulate a smoothed rtt variance (actually, a 3442 * smoothed mean difference), then set the retransmit 3443 * timer to smoothed rtt + 4 times the smoothed variance. 3444 * rttvar is stored as fixed point with 4 bits after the 3445 * binary point (scaled by 16). The following is 3446 * equivalent to rfc793 smoothing with an alpha of .75 3447 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces 3448 * rfc793's wired-in beta. 3449 */ 3450 if (delta < 0) 3451 delta = -delta; 3452 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT); 3453 if ((tp->t_rttvar += delta) <= 0) 3454 tp->t_rttvar = 1; 3455 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar) 3456 tp->t_rttbest = tp->t_srtt + tp->t_rttvar; 3457 } else { 3458 /* 3459 * No rtt measurement yet - use the unsmoothed rtt. 3460 * Set the variance to half the rtt (so our first 3461 * retransmit happens at 3*rtt). 3462 */ 3463 tp->t_srtt = rtt << TCP_RTT_SHIFT; 3464 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1); 3465 tp->t_rttbest = tp->t_srtt + tp->t_rttvar; 3466 } 3467 tp->t_rtttime = 0; 3468 tp->t_rxtshift = 0; 3469 3470 /* 3471 * the retransmit should happen at rtt + 4 * rttvar. 3472 * Because of the way we do the smoothing, srtt and rttvar 3473 * will each average +1/2 tick of bias. When we compute 3474 * the retransmit timer, we want 1/2 tick of rounding and 3475 * 1 extra tick because of +-1/2 tick uncertainty in the 3476 * firing of the timer. The bias will give us exactly the 3477 * 1.5 tick we need. But, because the bias is 3478 * statistical, we have to test that we don't drop below 3479 * the minimum feasible timer (which is 2 ticks). 3480 */ 3481 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp), 3482 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX); 3483 3484 /* 3485 * We received an ack for a packet that wasn't retransmitted; 3486 * it is probably safe to discard any error indications we've 3487 * received recently. This isn't quite right, but close enough 3488 * for now (a route might have failed after we sent a segment, 3489 * and the return path might not be symmetrical). 3490 */ 3491 tp->t_softerror = 0; 3492 } 3493 3494 /* 3495 * Determine a reasonable value for maxseg size. 3496 * If the route is known, check route for mtu. 3497 * If none, use an mss that can be handled on the outgoing interface 3498 * without forcing IP to fragment. If no route is found, route has no mtu, 3499 * or the destination isn't local, use a default, hopefully conservative 3500 * size (usually 512 or the default IP max size, but no more than the mtu 3501 * of the interface), as we can't discover anything about intervening 3502 * gateways or networks. We also initialize the congestion/slow start 3503 * window to be a single segment if the destination isn't local. 3504 * While looking at the routing entry, we also initialize other path-dependent 3505 * parameters from pre-set or cached values in the routing entry. 3506 * 3507 * NOTE that resulting t_maxseg doesn't include space for TCP options or 3508 * IP options, e.g. IPSEC data, since length of this data may vary, and 3509 * thus it is calculated for every segment separately in tcp_output(). 3510 * 3511 * NOTE that this routine is only called when we process an incoming 3512 * segment, or an ICMP need fragmentation datagram. Outgoing SYN/ACK MSS 3513 * settings are handled in tcp_mssopt(). 3514 */ 3515 void 3516 tcp_mss_update(struct tcpcb *tp, int offer, int mtuoffer, 3517 struct hc_metrics_lite *metricptr, struct tcp_ifcap *cap) 3518 { 3519 int mss = 0; 3520 uint32_t maxmtu = 0; 3521 struct inpcb *inp = tp->t_inpcb; 3522 struct hc_metrics_lite metrics; 3523 #ifdef INET6 3524 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0; 3525 size_t min_protoh = isipv6 ? 3526 sizeof (struct ip6_hdr) + sizeof (struct tcphdr) : 3527 sizeof (struct tcpiphdr); 3528 #else 3529 const size_t min_protoh = sizeof(struct tcpiphdr); 3530 #endif 3531 3532 INP_WLOCK_ASSERT(tp->t_inpcb); 3533 3534 if (mtuoffer != -1) { 3535 KASSERT(offer == -1, ("%s: conflict", __func__)); 3536 offer = mtuoffer - min_protoh; 3537 } 3538 3539 /* Initialize. */ 3540 #ifdef INET6 3541 if (isipv6) { 3542 maxmtu = tcp_maxmtu6(&inp->inp_inc, cap); 3543 tp->t_maxseg = V_tcp_v6mssdflt; 3544 } 3545 #endif 3546 #if defined(INET) && defined(INET6) 3547 else 3548 #endif 3549 #ifdef INET 3550 { 3551 maxmtu = tcp_maxmtu(&inp->inp_inc, cap); 3552 tp->t_maxseg = V_tcp_mssdflt; 3553 } 3554 #endif 3555 3556 /* 3557 * No route to sender, stay with default mss and return. 3558 */ 3559 if (maxmtu == 0) { 3560 /* 3561 * In case we return early we need to initialize metrics 3562 * to a defined state as tcp_hc_get() would do for us 3563 * if there was no cache hit. 3564 */ 3565 if (metricptr != NULL) 3566 bzero(metricptr, sizeof(struct hc_metrics_lite)); 3567 return; 3568 } 3569 3570 /* What have we got? */ 3571 switch (offer) { 3572 case 0: 3573 /* 3574 * Offer == 0 means that there was no MSS on the SYN 3575 * segment, in this case we use tcp_mssdflt as 3576 * already assigned to t_maxseg above. 3577 */ 3578 offer = tp->t_maxseg; 3579 break; 3580 3581 case -1: 3582 /* 3583 * Offer == -1 means that we didn't receive SYN yet. 3584 */ 3585 /* FALLTHROUGH */ 3586 3587 default: 3588 /* 3589 * Prevent DoS attack with too small MSS. Round up 3590 * to at least minmss. 3591 */ 3592 offer = max(offer, V_tcp_minmss); 3593 } 3594 3595 /* 3596 * rmx information is now retrieved from tcp_hostcache. 3597 */ 3598 tcp_hc_get(&inp->inp_inc, &metrics); 3599 if (metricptr != NULL) 3600 bcopy(&metrics, metricptr, sizeof(struct hc_metrics_lite)); 3601 3602 /* 3603 * If there's a discovered mtu in tcp hostcache, use it. 3604 * Else, use the link mtu. 3605 */ 3606 if (metrics.rmx_mtu) 3607 mss = min(metrics.rmx_mtu, maxmtu) - min_protoh; 3608 else { 3609 #ifdef INET6 3610 if (isipv6) { 3611 mss = maxmtu - min_protoh; 3612 if (!V_path_mtu_discovery && 3613 !in6_localaddr(&inp->in6p_faddr)) 3614 mss = min(mss, V_tcp_v6mssdflt); 3615 } 3616 #endif 3617 #if defined(INET) && defined(INET6) 3618 else 3619 #endif 3620 #ifdef INET 3621 { 3622 mss = maxmtu - min_protoh; 3623 if (!V_path_mtu_discovery && 3624 !in_localaddr(inp->inp_faddr)) 3625 mss = min(mss, V_tcp_mssdflt); 3626 } 3627 #endif 3628 /* 3629 * XXX - The above conditional (mss = maxmtu - min_protoh) 3630 * probably violates the TCP spec. 3631 * The problem is that, since we don't know the 3632 * other end's MSS, we are supposed to use a conservative 3633 * default. But, if we do that, then MTU discovery will 3634 * never actually take place, because the conservative 3635 * default is much less than the MTUs typically seen 3636 * on the Internet today. For the moment, we'll sweep 3637 * this under the carpet. 3638 * 3639 * The conservative default might not actually be a problem 3640 * if the only case this occurs is when sending an initial 3641 * SYN with options and data to a host we've never talked 3642 * to before. Then, they will reply with an MSS value which 3643 * will get recorded and the new parameters should get 3644 * recomputed. For Further Study. 3645 */ 3646 } 3647 mss = min(mss, offer); 3648 3649 /* 3650 * Sanity check: make sure that maxseg will be large 3651 * enough to allow some data on segments even if the 3652 * all the option space is used (40bytes). Otherwise 3653 * funny things may happen in tcp_output. 3654 * 3655 * XXXGL: shouldn't we reserve space for IP/IPv6 options? 3656 */ 3657 mss = max(mss, 64); 3658 3659 tp->t_maxseg = mss; 3660 } 3661 3662 void 3663 tcp_mss(struct tcpcb *tp, int offer) 3664 { 3665 int mss; 3666 uint32_t bufsize; 3667 struct inpcb *inp; 3668 struct socket *so; 3669 struct hc_metrics_lite metrics; 3670 struct tcp_ifcap cap; 3671 3672 KASSERT(tp != NULL, ("%s: tp == NULL", __func__)); 3673 3674 bzero(&cap, sizeof(cap)); 3675 tcp_mss_update(tp, offer, -1, &metrics, &cap); 3676 3677 mss = tp->t_maxseg; 3678 inp = tp->t_inpcb; 3679 3680 /* 3681 * If there's a pipesize, change the socket buffer to that size, 3682 * don't change if sb_hiwat is different than default (then it 3683 * has been changed on purpose with setsockopt). 3684 * Make the socket buffers an integral number of mss units; 3685 * if the mss is larger than the socket buffer, decrease the mss. 3686 */ 3687 so = inp->inp_socket; 3688 SOCKBUF_LOCK(&so->so_snd); 3689 if ((so->so_snd.sb_hiwat == V_tcp_sendspace) && metrics.rmx_sendpipe) 3690 bufsize = metrics.rmx_sendpipe; 3691 else 3692 bufsize = so->so_snd.sb_hiwat; 3693 if (bufsize < mss) 3694 mss = bufsize; 3695 else { 3696 bufsize = roundup(bufsize, mss); 3697 if (bufsize > sb_max) 3698 bufsize = sb_max; 3699 if (bufsize > so->so_snd.sb_hiwat) 3700 (void)sbreserve_locked(&so->so_snd, bufsize, so, NULL); 3701 } 3702 SOCKBUF_UNLOCK(&so->so_snd); 3703 /* 3704 * Sanity check: make sure that maxseg will be large 3705 * enough to allow some data on segments even if the 3706 * all the option space is used (40bytes). Otherwise 3707 * funny things may happen in tcp_output. 3708 * 3709 * XXXGL: shouldn't we reserve space for IP/IPv6 options? 3710 */ 3711 tp->t_maxseg = max(mss, 64); 3712 3713 SOCKBUF_LOCK(&so->so_rcv); 3714 if ((so->so_rcv.sb_hiwat == V_tcp_recvspace) && metrics.rmx_recvpipe) 3715 bufsize = metrics.rmx_recvpipe; 3716 else 3717 bufsize = so->so_rcv.sb_hiwat; 3718 if (bufsize > mss) { 3719 bufsize = roundup(bufsize, mss); 3720 if (bufsize > sb_max) 3721 bufsize = sb_max; 3722 if (bufsize > so->so_rcv.sb_hiwat) 3723 (void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL); 3724 } 3725 SOCKBUF_UNLOCK(&so->so_rcv); 3726 3727 /* Check the interface for TSO capabilities. */ 3728 if (cap.ifcap & CSUM_TSO) { 3729 tp->t_flags |= TF_TSO; 3730 tp->t_tsomax = cap.tsomax; 3731 tp->t_tsomaxsegcount = cap.tsomaxsegcount; 3732 tp->t_tsomaxsegsize = cap.tsomaxsegsize; 3733 } 3734 } 3735 3736 /* 3737 * Determine the MSS option to send on an outgoing SYN. 3738 */ 3739 int 3740 tcp_mssopt(struct in_conninfo *inc) 3741 { 3742 int mss = 0; 3743 uint32_t thcmtu = 0; 3744 uint32_t maxmtu = 0; 3745 size_t min_protoh; 3746 3747 KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer")); 3748 3749 #ifdef INET6 3750 if (inc->inc_flags & INC_ISIPV6) { 3751 mss = V_tcp_v6mssdflt; 3752 maxmtu = tcp_maxmtu6(inc, NULL); 3753 min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr); 3754 } 3755 #endif 3756 #if defined(INET) && defined(INET6) 3757 else 3758 #endif 3759 #ifdef INET 3760 { 3761 mss = V_tcp_mssdflt; 3762 maxmtu = tcp_maxmtu(inc, NULL); 3763 min_protoh = sizeof(struct tcpiphdr); 3764 } 3765 #endif 3766 #if defined(INET6) || defined(INET) 3767 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */ 3768 #endif 3769 3770 if (maxmtu && thcmtu) 3771 mss = min(maxmtu, thcmtu) - min_protoh; 3772 else if (maxmtu || thcmtu) 3773 mss = max(maxmtu, thcmtu) - min_protoh; 3774 3775 return (mss); 3776 } 3777 3778 3779 /* 3780 * On a partial ack arrives, force the retransmission of the 3781 * next unacknowledged segment. Do not clear tp->t_dupacks. 3782 * By setting snd_nxt to ti_ack, this forces retransmission timer to 3783 * be started again. 3784 */ 3785 void 3786 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th) 3787 { 3788 tcp_seq onxt = tp->snd_nxt; 3789 uint32_t ocwnd = tp->snd_cwnd; 3790 u_int maxseg = tcp_maxseg(tp); 3791 3792 INP_WLOCK_ASSERT(tp->t_inpcb); 3793 3794 tcp_timer_activate(tp, TT_REXMT, 0); 3795 tp->t_rtttime = 0; 3796 tp->snd_nxt = th->th_ack; 3797 /* 3798 * Set snd_cwnd to one segment beyond acknowledged offset. 3799 * (tp->snd_una has not yet been updated when this function is called.) 3800 */ 3801 tp->snd_cwnd = maxseg + BYTES_THIS_ACK(tp, th); 3802 tp->t_flags |= TF_ACKNOW; 3803 (void) tp->t_fb->tfb_tcp_output(tp); 3804 tp->snd_cwnd = ocwnd; 3805 if (SEQ_GT(onxt, tp->snd_nxt)) 3806 tp->snd_nxt = onxt; 3807 /* 3808 * Partial window deflation. Relies on fact that tp->snd_una 3809 * not updated yet. 3810 */ 3811 if (tp->snd_cwnd > BYTES_THIS_ACK(tp, th)) 3812 tp->snd_cwnd -= BYTES_THIS_ACK(tp, th); 3813 else 3814 tp->snd_cwnd = 0; 3815 tp->snd_cwnd += maxseg; 3816 } 3817 3818 int 3819 tcp_compute_pipe(struct tcpcb *tp) 3820 { 3821 return (tp->snd_max - tp->snd_una + 3822 tp->sackhint.sack_bytes_rexmit - 3823 tp->sackhint.sacked_bytes); 3824 } 3825 3826 uint32_t 3827 tcp_compute_initwnd(uint32_t maxseg) 3828 { 3829 /* 3830 * Calculate the Initial Window, also used as Restart Window 3831 * 3832 * RFC5681 Section 3.1 specifies the default conservative values. 3833 * RFC3390 specifies slightly more aggressive values. 3834 * RFC6928 increases it to ten segments. 3835 * Support for user specified value for initial flight size. 3836 */ 3837 if (V_tcp_initcwnd_segments) 3838 return min(V_tcp_initcwnd_segments * maxseg, 3839 max(2 * maxseg, V_tcp_initcwnd_segments * 1460)); 3840 else if (V_tcp_do_rfc3390) 3841 return min(4 * maxseg, max(2 * maxseg, 4380)); 3842 else { 3843 /* Per RFC5681 Section 3.1 */ 3844 if (maxseg > 2190) 3845 return (2 * maxseg); 3846 else if (maxseg > 1095) 3847 return (3 * maxseg); 3848 else 3849 return (4 * maxseg); 3850 } 3851 } 3852