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; 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 /* 2379 * Account for the ACK of our SYN prior to 2380 * regular ACK processing below. 2381 */ 2382 tp->snd_una++; 2383 } 2384 if (tp->t_flags & TF_NEEDFIN) { 2385 tcp_state_change(tp, TCPS_FIN_WAIT_1); 2386 tp->t_flags &= ~TF_NEEDFIN; 2387 } else { 2388 tcp_state_change(tp, TCPS_ESTABLISHED); 2389 TCP_PROBE5(accept__established, NULL, tp, 2390 m, tp, th); 2391 /* 2392 * TFO connections call cc_conn_init() during SYN 2393 * processing. Calling it again here for such 2394 * connections is not harmless as it would undo the 2395 * snd_cwnd reduction that occurs when a TFO SYN|ACK 2396 * is retransmitted. 2397 */ 2398 if (!IS_FASTOPEN(tp->t_flags)) 2399 cc_conn_init(tp); 2400 tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp)); 2401 } 2402 /* 2403 * If segment contains data or ACK, will call tcp_reass() 2404 * later; if not, do so now to pass queued data to user. 2405 */ 2406 if (tlen == 0 && (thflags & TH_FIN) == 0) 2407 (void) tcp_reass(tp, (struct tcphdr *)0, NULL, 0, 2408 (struct mbuf *)0); 2409 tp->snd_wl1 = th->th_seq - 1; 2410 /* FALLTHROUGH */ 2411 2412 /* 2413 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range 2414 * ACKs. If the ack is in the range 2415 * tp->snd_una < th->th_ack <= tp->snd_max 2416 * then advance tp->snd_una to th->th_ack and drop 2417 * data from the retransmission queue. If this ACK reflects 2418 * more up to date window information we update our window information. 2419 */ 2420 case TCPS_ESTABLISHED: 2421 case TCPS_FIN_WAIT_1: 2422 case TCPS_FIN_WAIT_2: 2423 case TCPS_CLOSE_WAIT: 2424 case TCPS_CLOSING: 2425 case TCPS_LAST_ACK: 2426 if (SEQ_GT(th->th_ack, tp->snd_max)) { 2427 TCPSTAT_INC(tcps_rcvacktoomuch); 2428 goto dropafterack; 2429 } 2430 if ((tp->t_flags & TF_SACK_PERMIT) && 2431 ((to.to_flags & TOF_SACK) || 2432 !TAILQ_EMPTY(&tp->snd_holes))) 2433 sack_changed = tcp_sack_doack(tp, &to, th->th_ack); 2434 else 2435 /* 2436 * Reset the value so that previous (valid) value 2437 * from the last ack with SACK doesn't get used. 2438 */ 2439 tp->sackhint.sacked_bytes = 0; 2440 2441 #ifdef TCP_HHOOK 2442 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */ 2443 hhook_run_tcp_est_in(tp, th, &to); 2444 #endif 2445 2446 if (SEQ_LEQ(th->th_ack, tp->snd_una)) { 2447 u_int maxseg; 2448 2449 maxseg = tcp_maxseg(tp); 2450 if (tlen == 0 && 2451 (tiwin == tp->snd_wnd || 2452 (tp->t_flags & TF_SACK_PERMIT))) { 2453 /* 2454 * If this is the first time we've seen a 2455 * FIN from the remote, this is not a 2456 * duplicate and it needs to be processed 2457 * normally. This happens during a 2458 * simultaneous close. 2459 */ 2460 if ((thflags & TH_FIN) && 2461 (TCPS_HAVERCVDFIN(tp->t_state) == 0)) { 2462 tp->t_dupacks = 0; 2463 break; 2464 } 2465 TCPSTAT_INC(tcps_rcvdupack); 2466 /* 2467 * If we have outstanding data (other than 2468 * a window probe), this is a completely 2469 * duplicate ack (ie, window info didn't 2470 * change and FIN isn't set), 2471 * the ack is the biggest we've 2472 * seen and we've seen exactly our rexmt 2473 * threshold of them, assume a packet 2474 * has been dropped and retransmit it. 2475 * Kludge snd_nxt & the congestion 2476 * window so we send only this one 2477 * packet. 2478 * 2479 * We know we're losing at the current 2480 * window size so do congestion avoidance 2481 * (set ssthresh to half the current window 2482 * and pull our congestion window back to 2483 * the new ssthresh). 2484 * 2485 * Dup acks mean that packets have left the 2486 * network (they're now cached at the receiver) 2487 * so bump cwnd by the amount in the receiver 2488 * to keep a constant cwnd packets in the 2489 * network. 2490 * 2491 * When using TCP ECN, notify the peer that 2492 * we reduced the cwnd. 2493 */ 2494 /* 2495 * Following 2 kinds of acks should not affect 2496 * dupack counting: 2497 * 1) Old acks 2498 * 2) Acks with SACK but without any new SACK 2499 * information in them. These could result from 2500 * any anomaly in the network like a switch 2501 * duplicating packets or a possible DoS attack. 2502 */ 2503 if (th->th_ack != tp->snd_una || 2504 ((tp->t_flags & TF_SACK_PERMIT) && 2505 !sack_changed)) 2506 break; 2507 else if (!tcp_timer_active(tp, TT_REXMT)) 2508 tp->t_dupacks = 0; 2509 else if (++tp->t_dupacks > tcprexmtthresh || 2510 IN_FASTRECOVERY(tp->t_flags)) { 2511 cc_ack_received(tp, th, nsegs, 2512 CC_DUPACK); 2513 if ((tp->t_flags & TF_SACK_PERMIT) && 2514 IN_FASTRECOVERY(tp->t_flags)) { 2515 int awnd; 2516 2517 /* 2518 * Compute the amount of data in flight first. 2519 * We can inject new data into the pipe iff 2520 * we have less than 1/2 the original window's 2521 * worth of data in flight. 2522 */ 2523 if (V_tcp_do_rfc6675_pipe) 2524 awnd = tcp_compute_pipe(tp); 2525 else 2526 awnd = (tp->snd_nxt - tp->snd_fack) + 2527 tp->sackhint.sack_bytes_rexmit; 2528 2529 if (awnd < tp->snd_ssthresh) { 2530 tp->snd_cwnd += maxseg; 2531 if (tp->snd_cwnd > tp->snd_ssthresh) 2532 tp->snd_cwnd = tp->snd_ssthresh; 2533 } 2534 } else 2535 tp->snd_cwnd += maxseg; 2536 (void) tp->t_fb->tfb_tcp_output(tp); 2537 goto drop; 2538 } else if (tp->t_dupacks == tcprexmtthresh) { 2539 tcp_seq onxt = tp->snd_nxt; 2540 2541 /* 2542 * If we're doing sack, check to 2543 * see if we're already in sack 2544 * recovery. If we're not doing sack, 2545 * check to see if we're in newreno 2546 * recovery. 2547 */ 2548 if (tp->t_flags & TF_SACK_PERMIT) { 2549 if (IN_FASTRECOVERY(tp->t_flags)) { 2550 tp->t_dupacks = 0; 2551 break; 2552 } 2553 } else { 2554 if (SEQ_LEQ(th->th_ack, 2555 tp->snd_recover)) { 2556 tp->t_dupacks = 0; 2557 break; 2558 } 2559 } 2560 /* Congestion signal before ack. */ 2561 cc_cong_signal(tp, th, CC_NDUPACK); 2562 cc_ack_received(tp, th, nsegs, 2563 CC_DUPACK); 2564 tcp_timer_activate(tp, TT_REXMT, 0); 2565 tp->t_rtttime = 0; 2566 if (tp->t_flags & TF_SACK_PERMIT) { 2567 TCPSTAT_INC( 2568 tcps_sack_recovery_episode); 2569 tp->snd_recover = tp->snd_nxt; 2570 tp->snd_cwnd = maxseg; 2571 (void) tp->t_fb->tfb_tcp_output(tp); 2572 goto drop; 2573 } 2574 tp->snd_nxt = th->th_ack; 2575 tp->snd_cwnd = maxseg; 2576 (void) tp->t_fb->tfb_tcp_output(tp); 2577 KASSERT(tp->snd_limited <= 2, 2578 ("%s: tp->snd_limited too big", 2579 __func__)); 2580 tp->snd_cwnd = tp->snd_ssthresh + 2581 maxseg * 2582 (tp->t_dupacks - tp->snd_limited); 2583 if (SEQ_GT(onxt, tp->snd_nxt)) 2584 tp->snd_nxt = onxt; 2585 goto drop; 2586 } else if (V_tcp_do_rfc3042) { 2587 /* 2588 * Process first and second duplicate 2589 * ACKs. Each indicates a segment 2590 * leaving the network, creating room 2591 * for more. Make sure we can send a 2592 * packet on reception of each duplicate 2593 * ACK by increasing snd_cwnd by one 2594 * segment. Restore the original 2595 * snd_cwnd after packet transmission. 2596 */ 2597 cc_ack_received(tp, th, nsegs, 2598 CC_DUPACK); 2599 uint32_t oldcwnd = tp->snd_cwnd; 2600 tcp_seq oldsndmax = tp->snd_max; 2601 u_int sent; 2602 int avail; 2603 2604 KASSERT(tp->t_dupacks == 1 || 2605 tp->t_dupacks == 2, 2606 ("%s: dupacks not 1 or 2", 2607 __func__)); 2608 if (tp->t_dupacks == 1) 2609 tp->snd_limited = 0; 2610 tp->snd_cwnd = 2611 (tp->snd_nxt - tp->snd_una) + 2612 (tp->t_dupacks - tp->snd_limited) * 2613 maxseg; 2614 /* 2615 * Only call tcp_output when there 2616 * is new data available to be sent. 2617 * Otherwise we would send pure ACKs. 2618 */ 2619 SOCKBUF_LOCK(&so->so_snd); 2620 avail = sbavail(&so->so_snd) - 2621 (tp->snd_nxt - tp->snd_una); 2622 SOCKBUF_UNLOCK(&so->so_snd); 2623 if (avail > 0) 2624 (void) tp->t_fb->tfb_tcp_output(tp); 2625 sent = tp->snd_max - oldsndmax; 2626 if (sent > maxseg) { 2627 KASSERT((tp->t_dupacks == 2 && 2628 tp->snd_limited == 0) || 2629 (sent == maxseg + 1 && 2630 tp->t_flags & TF_SENTFIN), 2631 ("%s: sent too much", 2632 __func__)); 2633 tp->snd_limited = 2; 2634 } else if (sent > 0) 2635 ++tp->snd_limited; 2636 tp->snd_cwnd = oldcwnd; 2637 goto drop; 2638 } 2639 } 2640 break; 2641 } else { 2642 /* 2643 * This ack is advancing the left edge, reset the 2644 * counter. 2645 */ 2646 tp->t_dupacks = 0; 2647 /* 2648 * If this ack also has new SACK info, increment the 2649 * counter as per rfc6675. 2650 */ 2651 if ((tp->t_flags & TF_SACK_PERMIT) && sack_changed) 2652 tp->t_dupacks++; 2653 } 2654 2655 KASSERT(SEQ_GT(th->th_ack, tp->snd_una), 2656 ("%s: th_ack <= snd_una", __func__)); 2657 2658 /* 2659 * If the congestion window was inflated to account 2660 * for the other side's cached packets, retract it. 2661 */ 2662 if (IN_FASTRECOVERY(tp->t_flags)) { 2663 if (SEQ_LT(th->th_ack, tp->snd_recover)) { 2664 if (tp->t_flags & TF_SACK_PERMIT) 2665 tcp_sack_partialack(tp, th); 2666 else 2667 tcp_newreno_partial_ack(tp, th); 2668 } else 2669 cc_post_recovery(tp, th); 2670 } 2671 /* 2672 * If we reach this point, ACK is not a duplicate, 2673 * i.e., it ACKs something we sent. 2674 */ 2675 if (tp->t_flags & TF_NEEDSYN) { 2676 /* 2677 * T/TCP: Connection was half-synchronized, and our 2678 * SYN has been ACK'd (so connection is now fully 2679 * synchronized). Go to non-starred state, 2680 * increment snd_una for ACK of SYN, and check if 2681 * we can do window scaling. 2682 */ 2683 tp->t_flags &= ~TF_NEEDSYN; 2684 tp->snd_una++; 2685 /* Do window scaling? */ 2686 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) == 2687 (TF_RCVD_SCALE|TF_REQ_SCALE)) { 2688 tp->rcv_scale = tp->request_r_scale; 2689 /* Send window already scaled. */ 2690 } 2691 } 2692 2693 process_ACK: 2694 INP_WLOCK_ASSERT(tp->t_inpcb); 2695 2696 acked = BYTES_THIS_ACK(tp, th); 2697 KASSERT(acked >= 0, ("%s: acked unexepectedly negative " 2698 "(tp->snd_una=%u, th->th_ack=%u, tp=%p, m=%p)", __func__, 2699 tp->snd_una, th->th_ack, tp, m)); 2700 TCPSTAT_ADD(tcps_rcvackpack, nsegs); 2701 TCPSTAT_ADD(tcps_rcvackbyte, acked); 2702 2703 /* 2704 * If we just performed our first retransmit, and the ACK 2705 * arrives within our recovery window, then it was a mistake 2706 * to do the retransmit in the first place. Recover our 2707 * original cwnd and ssthresh, and proceed to transmit where 2708 * we left off. 2709 */ 2710 if (tp->t_rxtshift == 1 && 2711 tp->t_flags & TF_PREVVALID && 2712 tp->t_badrxtwin && 2713 SEQ_LT(to.to_tsecr, tp->t_badrxtwin)) 2714 cc_cong_signal(tp, th, CC_RTO_ERR); 2715 2716 /* 2717 * If we have a timestamp reply, update smoothed 2718 * round trip time. If no timestamp is present but 2719 * transmit timer is running and timed sequence 2720 * number was acked, update smoothed round trip time. 2721 * Since we now have an rtt measurement, cancel the 2722 * timer backoff (cf., Phil Karn's retransmit alg.). 2723 * Recompute the initial retransmit timer. 2724 * 2725 * Some boxes send broken timestamp replies 2726 * during the SYN+ACK phase, ignore 2727 * timestamps of 0 or we could calculate a 2728 * huge RTT and blow up the retransmit timer. 2729 */ 2730 if ((to.to_flags & TOF_TS) != 0 && to.to_tsecr) { 2731 uint32_t t; 2732 2733 t = tcp_ts_getticks() - to.to_tsecr; 2734 if (!tp->t_rttlow || tp->t_rttlow > t) 2735 tp->t_rttlow = t; 2736 tcp_xmit_timer(tp, TCP_TS_TO_TICKS(t) + 1); 2737 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) { 2738 if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime) 2739 tp->t_rttlow = ticks - tp->t_rtttime; 2740 tcp_xmit_timer(tp, ticks - tp->t_rtttime); 2741 } 2742 2743 /* 2744 * If all outstanding data is acked, stop retransmit 2745 * timer and remember to restart (more output or persist). 2746 * If there is more data to be acked, restart retransmit 2747 * timer, using current (possibly backed-off) value. 2748 */ 2749 if (th->th_ack == tp->snd_max) { 2750 tcp_timer_activate(tp, TT_REXMT, 0); 2751 needoutput = 1; 2752 } else if (!tcp_timer_active(tp, TT_PERSIST)) 2753 tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur); 2754 2755 /* 2756 * If no data (only SYN) was ACK'd, 2757 * skip rest of ACK processing. 2758 */ 2759 if (acked == 0) 2760 goto step6; 2761 2762 /* 2763 * Let the congestion control algorithm update congestion 2764 * control related information. This typically means increasing 2765 * the congestion window. 2766 */ 2767 cc_ack_received(tp, th, nsegs, CC_ACK); 2768 2769 SOCKBUF_LOCK(&so->so_snd); 2770 if (acked > sbavail(&so->so_snd)) { 2771 if (tp->snd_wnd >= sbavail(&so->so_snd)) 2772 tp->snd_wnd -= sbavail(&so->so_snd); 2773 else 2774 tp->snd_wnd = 0; 2775 mfree = sbcut_locked(&so->so_snd, 2776 (int)sbavail(&so->so_snd)); 2777 ourfinisacked = 1; 2778 } else { 2779 mfree = sbcut_locked(&so->so_snd, acked); 2780 if (tp->snd_wnd >= (uint32_t) acked) 2781 tp->snd_wnd -= acked; 2782 else 2783 tp->snd_wnd = 0; 2784 ourfinisacked = 0; 2785 } 2786 /* NB: sowwakeup_locked() does an implicit unlock. */ 2787 sowwakeup_locked(so); 2788 m_freem(mfree); 2789 /* Detect una wraparound. */ 2790 if (!IN_RECOVERY(tp->t_flags) && 2791 SEQ_GT(tp->snd_una, tp->snd_recover) && 2792 SEQ_LEQ(th->th_ack, tp->snd_recover)) 2793 tp->snd_recover = th->th_ack - 1; 2794 /* XXXLAS: Can this be moved up into cc_post_recovery? */ 2795 if (IN_RECOVERY(tp->t_flags) && 2796 SEQ_GEQ(th->th_ack, tp->snd_recover)) { 2797 EXIT_RECOVERY(tp->t_flags); 2798 } 2799 tp->snd_una = th->th_ack; 2800 if (tp->t_flags & TF_SACK_PERMIT) { 2801 if (SEQ_GT(tp->snd_una, tp->snd_recover)) 2802 tp->snd_recover = tp->snd_una; 2803 } 2804 if (SEQ_LT(tp->snd_nxt, tp->snd_una)) 2805 tp->snd_nxt = tp->snd_una; 2806 2807 switch (tp->t_state) { 2808 2809 /* 2810 * In FIN_WAIT_1 STATE in addition to the processing 2811 * for the ESTABLISHED state if our FIN is now acknowledged 2812 * then enter FIN_WAIT_2. 2813 */ 2814 case TCPS_FIN_WAIT_1: 2815 if (ourfinisacked) { 2816 /* 2817 * If we can't receive any more 2818 * data, then closing user can proceed. 2819 * Starting the timer is contrary to the 2820 * specification, but if we don't get a FIN 2821 * we'll hang forever. 2822 * 2823 * XXXjl: 2824 * we should release the tp also, and use a 2825 * compressed state. 2826 */ 2827 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) { 2828 soisdisconnected(so); 2829 tcp_timer_activate(tp, TT_2MSL, 2830 (tcp_fast_finwait2_recycle ? 2831 tcp_finwait2_timeout : 2832 TP_MAXIDLE(tp))); 2833 } 2834 tcp_state_change(tp, TCPS_FIN_WAIT_2); 2835 } 2836 break; 2837 2838 /* 2839 * In CLOSING STATE in addition to the processing for 2840 * the ESTABLISHED state if the ACK acknowledges our FIN 2841 * then enter the TIME-WAIT state, otherwise ignore 2842 * the segment. 2843 */ 2844 case TCPS_CLOSING: 2845 if (ourfinisacked) { 2846 tcp_twstart(tp); 2847 m_freem(m); 2848 return; 2849 } 2850 break; 2851 2852 /* 2853 * In LAST_ACK, we may still be waiting for data to drain 2854 * and/or to be acked, as well as for the ack of our FIN. 2855 * If our FIN is now acknowledged, delete the TCB, 2856 * enter the closed state and return. 2857 */ 2858 case TCPS_LAST_ACK: 2859 if (ourfinisacked) { 2860 tp = tcp_close(tp); 2861 goto drop; 2862 } 2863 break; 2864 } 2865 } 2866 2867 step6: 2868 INP_WLOCK_ASSERT(tp->t_inpcb); 2869 2870 /* 2871 * Update window information. 2872 * Don't look at window if no ACK: TAC's send garbage on first SYN. 2873 */ 2874 if ((thflags & TH_ACK) && 2875 (SEQ_LT(tp->snd_wl1, th->th_seq) || 2876 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) || 2877 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) { 2878 /* keep track of pure window updates */ 2879 if (tlen == 0 && 2880 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd) 2881 TCPSTAT_INC(tcps_rcvwinupd); 2882 tp->snd_wnd = tiwin; 2883 tp->snd_wl1 = th->th_seq; 2884 tp->snd_wl2 = th->th_ack; 2885 if (tp->snd_wnd > tp->max_sndwnd) 2886 tp->max_sndwnd = tp->snd_wnd; 2887 needoutput = 1; 2888 } 2889 2890 /* 2891 * Process segments with URG. 2892 */ 2893 if ((thflags & TH_URG) && th->th_urp && 2894 TCPS_HAVERCVDFIN(tp->t_state) == 0) { 2895 /* 2896 * This is a kludge, but if we receive and accept 2897 * random urgent pointers, we'll crash in 2898 * soreceive. It's hard to imagine someone 2899 * actually wanting to send this much urgent data. 2900 */ 2901 SOCKBUF_LOCK(&so->so_rcv); 2902 if (th->th_urp + sbavail(&so->so_rcv) > sb_max) { 2903 th->th_urp = 0; /* XXX */ 2904 thflags &= ~TH_URG; /* XXX */ 2905 SOCKBUF_UNLOCK(&so->so_rcv); /* XXX */ 2906 goto dodata; /* XXX */ 2907 } 2908 /* 2909 * If this segment advances the known urgent pointer, 2910 * then mark the data stream. This should not happen 2911 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since 2912 * a FIN has been received from the remote side. 2913 * In these states we ignore the URG. 2914 * 2915 * According to RFC961 (Assigned Protocols), 2916 * the urgent pointer points to the last octet 2917 * of urgent data. We continue, however, 2918 * to consider it to indicate the first octet 2919 * of data past the urgent section as the original 2920 * spec states (in one of two places). 2921 */ 2922 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) { 2923 tp->rcv_up = th->th_seq + th->th_urp; 2924 so->so_oobmark = sbavail(&so->so_rcv) + 2925 (tp->rcv_up - tp->rcv_nxt) - 1; 2926 if (so->so_oobmark == 0) 2927 so->so_rcv.sb_state |= SBS_RCVATMARK; 2928 sohasoutofband(so); 2929 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA); 2930 } 2931 SOCKBUF_UNLOCK(&so->so_rcv); 2932 /* 2933 * Remove out of band data so doesn't get presented to user. 2934 * This can happen independent of advancing the URG pointer, 2935 * but if two URG's are pending at once, some out-of-band 2936 * data may creep in... ick. 2937 */ 2938 if (th->th_urp <= (uint32_t)tlen && 2939 !(so->so_options & SO_OOBINLINE)) { 2940 /* hdr drop is delayed */ 2941 tcp_pulloutofband(so, th, m, drop_hdrlen); 2942 } 2943 } else { 2944 /* 2945 * If no out of band data is expected, 2946 * pull receive urgent pointer along 2947 * with the receive window. 2948 */ 2949 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up)) 2950 tp->rcv_up = tp->rcv_nxt; 2951 } 2952 dodata: /* XXX */ 2953 INP_WLOCK_ASSERT(tp->t_inpcb); 2954 2955 /* 2956 * Process the segment text, merging it into the TCP sequencing queue, 2957 * and arranging for acknowledgment of receipt if necessary. 2958 * This process logically involves adjusting tp->rcv_wnd as data 2959 * is presented to the user (this happens in tcp_usrreq.c, 2960 * case PRU_RCVD). If a FIN has already been received on this 2961 * connection then we just ignore the text. 2962 */ 2963 tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) && 2964 IS_FASTOPEN(tp->t_flags)); 2965 if ((tlen || (thflags & TH_FIN) || tfo_syn) && 2966 TCPS_HAVERCVDFIN(tp->t_state) == 0) { 2967 tcp_seq save_start = th->th_seq; 2968 tcp_seq save_rnxt = tp->rcv_nxt; 2969 int save_tlen = tlen; 2970 m_adj(m, drop_hdrlen); /* delayed header drop */ 2971 /* 2972 * Insert segment which includes th into TCP reassembly queue 2973 * with control block tp. Set thflags to whether reassembly now 2974 * includes a segment with FIN. This handles the common case 2975 * inline (segment is the next to be received on an established 2976 * connection, and the queue is empty), avoiding linkage into 2977 * and removal from the queue and repetition of various 2978 * conversions. 2979 * Set DELACK for segments received in order, but ack 2980 * immediately when segments are out of order (so 2981 * fast retransmit can work). 2982 */ 2983 if (th->th_seq == tp->rcv_nxt && 2984 SEGQ_EMPTY(tp) && 2985 (TCPS_HAVEESTABLISHED(tp->t_state) || 2986 tfo_syn)) { 2987 if (DELAY_ACK(tp, tlen) || tfo_syn) 2988 tp->t_flags |= TF_DELACK; 2989 else 2990 tp->t_flags |= TF_ACKNOW; 2991 tp->rcv_nxt += tlen; 2992 thflags = th->th_flags & TH_FIN; 2993 TCPSTAT_INC(tcps_rcvpack); 2994 TCPSTAT_ADD(tcps_rcvbyte, tlen); 2995 SOCKBUF_LOCK(&so->so_rcv); 2996 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) 2997 m_freem(m); 2998 else 2999 sbappendstream_locked(&so->so_rcv, m, 0); 3000 /* NB: sorwakeup_locked() does an implicit unlock. */ 3001 sorwakeup_locked(so); 3002 } else { 3003 /* 3004 * XXX: Due to the header drop above "th" is 3005 * theoretically invalid by now. Fortunately 3006 * m_adj() doesn't actually frees any mbufs 3007 * when trimming from the head. 3008 */ 3009 tcp_seq temp = save_start; 3010 thflags = tcp_reass(tp, th, &temp, &tlen, m); 3011 tp->t_flags |= TF_ACKNOW; 3012 } 3013 if ((tp->t_flags & TF_SACK_PERMIT) && (save_tlen > 0)) { 3014 if ((tlen == 0) && (SEQ_LT(save_start, save_rnxt))) { 3015 /* 3016 * DSACK actually handled in the fastpath 3017 * above. 3018 */ 3019 tcp_update_sack_list(tp, save_start, 3020 save_start + save_tlen); 3021 } else if ((tlen > 0) && SEQ_GT(tp->rcv_nxt, save_rnxt)) { 3022 if ((tp->rcv_numsacks >= 1) && 3023 (tp->sackblks[0].end == save_start)) { 3024 /* 3025 * Partial overlap, recorded at todrop 3026 * above. 3027 */ 3028 tcp_update_sack_list(tp, 3029 tp->sackblks[0].start, 3030 tp->sackblks[0].end); 3031 } else { 3032 tcp_update_dsack_list(tp, save_start, 3033 save_start + save_tlen); 3034 } 3035 } else if (tlen >= save_tlen) { 3036 /* Update of sackblks. */ 3037 tcp_update_dsack_list(tp, save_start, 3038 save_start + save_tlen); 3039 } else if (tlen > 0) { 3040 tcp_update_dsack_list(tp, save_start, 3041 save_start + tlen); 3042 } 3043 } 3044 #if 0 3045 /* 3046 * Note the amount of data that peer has sent into 3047 * our window, in order to estimate the sender's 3048 * buffer size. 3049 * XXX: Unused. 3050 */ 3051 if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt)) 3052 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt); 3053 else 3054 len = so->so_rcv.sb_hiwat; 3055 #endif 3056 } else { 3057 m_freem(m); 3058 thflags &= ~TH_FIN; 3059 } 3060 3061 /* 3062 * If FIN is received ACK the FIN and let the user know 3063 * that the connection is closing. 3064 */ 3065 if (thflags & TH_FIN) { 3066 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) { 3067 socantrcvmore(so); 3068 /* 3069 * If connection is half-synchronized 3070 * (ie NEEDSYN flag on) then delay ACK, 3071 * so it may be piggybacked when SYN is sent. 3072 * Otherwise, since we received a FIN then no 3073 * more input can be expected, send ACK now. 3074 */ 3075 if (tp->t_flags & TF_NEEDSYN) 3076 tp->t_flags |= TF_DELACK; 3077 else 3078 tp->t_flags |= TF_ACKNOW; 3079 tp->rcv_nxt++; 3080 } 3081 switch (tp->t_state) { 3082 3083 /* 3084 * In SYN_RECEIVED and ESTABLISHED STATES 3085 * enter the CLOSE_WAIT state. 3086 */ 3087 case TCPS_SYN_RECEIVED: 3088 tp->t_starttime = ticks; 3089 /* FALLTHROUGH */ 3090 case TCPS_ESTABLISHED: 3091 tcp_state_change(tp, TCPS_CLOSE_WAIT); 3092 break; 3093 3094 /* 3095 * If still in FIN_WAIT_1 STATE FIN has not been acked so 3096 * enter the CLOSING state. 3097 */ 3098 case TCPS_FIN_WAIT_1: 3099 tcp_state_change(tp, TCPS_CLOSING); 3100 break; 3101 3102 /* 3103 * In FIN_WAIT_2 state enter the TIME_WAIT state, 3104 * starting the time-wait timer, turning off the other 3105 * standard timers. 3106 */ 3107 case TCPS_FIN_WAIT_2: 3108 tcp_twstart(tp); 3109 return; 3110 } 3111 } 3112 #ifdef TCPDEBUG 3113 if (so->so_options & SO_DEBUG) 3114 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen, 3115 &tcp_savetcp, 0); 3116 #endif 3117 TCP_PROBE3(debug__input, tp, th, m); 3118 3119 /* 3120 * Return any desired output. 3121 */ 3122 if (needoutput || (tp->t_flags & TF_ACKNOW)) 3123 (void) tp->t_fb->tfb_tcp_output(tp); 3124 3125 check_delack: 3126 INP_WLOCK_ASSERT(tp->t_inpcb); 3127 3128 if (tp->t_flags & TF_DELACK) { 3129 tp->t_flags &= ~TF_DELACK; 3130 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime); 3131 } 3132 INP_WUNLOCK(tp->t_inpcb); 3133 return; 3134 3135 dropafterack: 3136 /* 3137 * Generate an ACK dropping incoming segment if it occupies 3138 * sequence space, where the ACK reflects our state. 3139 * 3140 * We can now skip the test for the RST flag since all 3141 * paths to this code happen after packets containing 3142 * RST have been dropped. 3143 * 3144 * In the SYN-RECEIVED state, don't send an ACK unless the 3145 * segment we received passes the SYN-RECEIVED ACK test. 3146 * If it fails send a RST. This breaks the loop in the 3147 * "LAND" DoS attack, and also prevents an ACK storm 3148 * between two listening ports that have been sent forged 3149 * SYN segments, each with the source address of the other. 3150 */ 3151 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) && 3152 (SEQ_GT(tp->snd_una, th->th_ack) || 3153 SEQ_GT(th->th_ack, tp->snd_max)) ) { 3154 rstreason = BANDLIM_RST_OPENPORT; 3155 goto dropwithreset; 3156 } 3157 #ifdef TCPDEBUG 3158 if (so->so_options & SO_DEBUG) 3159 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen, 3160 &tcp_savetcp, 0); 3161 #endif 3162 TCP_PROBE3(debug__input, tp, th, m); 3163 tp->t_flags |= TF_ACKNOW; 3164 (void) tp->t_fb->tfb_tcp_output(tp); 3165 INP_WUNLOCK(tp->t_inpcb); 3166 m_freem(m); 3167 return; 3168 3169 dropwithreset: 3170 if (tp != NULL) { 3171 tcp_dropwithreset(m, th, tp, tlen, rstreason); 3172 INP_WUNLOCK(tp->t_inpcb); 3173 } else 3174 tcp_dropwithreset(m, th, NULL, tlen, rstreason); 3175 return; 3176 3177 drop: 3178 /* 3179 * Drop space held by incoming segment and return. 3180 */ 3181 #ifdef TCPDEBUG 3182 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG)) 3183 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen, 3184 &tcp_savetcp, 0); 3185 #endif 3186 TCP_PROBE3(debug__input, tp, th, m); 3187 if (tp != NULL) 3188 INP_WUNLOCK(tp->t_inpcb); 3189 m_freem(m); 3190 } 3191 3192 /* 3193 * Issue RST and make ACK acceptable to originator of segment. 3194 * The mbuf must still include the original packet header. 3195 * tp may be NULL. 3196 */ 3197 void 3198 tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp, 3199 int tlen, int rstreason) 3200 { 3201 #ifdef INET 3202 struct ip *ip; 3203 #endif 3204 #ifdef INET6 3205 struct ip6_hdr *ip6; 3206 #endif 3207 3208 if (tp != NULL) { 3209 INP_WLOCK_ASSERT(tp->t_inpcb); 3210 } 3211 3212 /* Don't bother if destination was broadcast/multicast. */ 3213 if ((th->th_flags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST)) 3214 goto drop; 3215 #ifdef INET6 3216 if (mtod(m, struct ip *)->ip_v == 6) { 3217 ip6 = mtod(m, struct ip6_hdr *); 3218 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) || 3219 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) 3220 goto drop; 3221 /* IPv6 anycast check is done at tcp6_input() */ 3222 } 3223 #endif 3224 #if defined(INET) && defined(INET6) 3225 else 3226 #endif 3227 #ifdef INET 3228 { 3229 ip = mtod(m, struct ip *); 3230 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) || 3231 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) || 3232 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) || 3233 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) 3234 goto drop; 3235 } 3236 #endif 3237 3238 /* Perform bandwidth limiting. */ 3239 if (badport_bandlim(rstreason) < 0) 3240 goto drop; 3241 3242 /* tcp_respond consumes the mbuf chain. */ 3243 if (th->th_flags & TH_ACK) { 3244 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, 3245 th->th_ack, TH_RST); 3246 } else { 3247 if (th->th_flags & TH_SYN) 3248 tlen++; 3249 if (th->th_flags & TH_FIN) 3250 tlen++; 3251 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen, 3252 (tcp_seq)0, TH_RST|TH_ACK); 3253 } 3254 return; 3255 drop: 3256 m_freem(m); 3257 } 3258 3259 /* 3260 * Parse TCP options and place in tcpopt. 3261 */ 3262 void 3263 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags) 3264 { 3265 int opt, optlen; 3266 3267 to->to_flags = 0; 3268 for (; cnt > 0; cnt -= optlen, cp += optlen) { 3269 opt = cp[0]; 3270 if (opt == TCPOPT_EOL) 3271 break; 3272 if (opt == TCPOPT_NOP) 3273 optlen = 1; 3274 else { 3275 if (cnt < 2) 3276 break; 3277 optlen = cp[1]; 3278 if (optlen < 2 || optlen > cnt) 3279 break; 3280 } 3281 switch (opt) { 3282 case TCPOPT_MAXSEG: 3283 if (optlen != TCPOLEN_MAXSEG) 3284 continue; 3285 if (!(flags & TO_SYN)) 3286 continue; 3287 to->to_flags |= TOF_MSS; 3288 bcopy((char *)cp + 2, 3289 (char *)&to->to_mss, sizeof(to->to_mss)); 3290 to->to_mss = ntohs(to->to_mss); 3291 break; 3292 case TCPOPT_WINDOW: 3293 if (optlen != TCPOLEN_WINDOW) 3294 continue; 3295 if (!(flags & TO_SYN)) 3296 continue; 3297 to->to_flags |= TOF_SCALE; 3298 to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT); 3299 break; 3300 case TCPOPT_TIMESTAMP: 3301 if (optlen != TCPOLEN_TIMESTAMP) 3302 continue; 3303 to->to_flags |= TOF_TS; 3304 bcopy((char *)cp + 2, 3305 (char *)&to->to_tsval, sizeof(to->to_tsval)); 3306 to->to_tsval = ntohl(to->to_tsval); 3307 bcopy((char *)cp + 6, 3308 (char *)&to->to_tsecr, sizeof(to->to_tsecr)); 3309 to->to_tsecr = ntohl(to->to_tsecr); 3310 break; 3311 case TCPOPT_SIGNATURE: 3312 /* 3313 * In order to reply to a host which has set the 3314 * TCP_SIGNATURE option in its initial SYN, we have 3315 * to record the fact that the option was observed 3316 * here for the syncache code to perform the correct 3317 * response. 3318 */ 3319 if (optlen != TCPOLEN_SIGNATURE) 3320 continue; 3321 to->to_flags |= TOF_SIGNATURE; 3322 to->to_signature = cp + 2; 3323 break; 3324 case TCPOPT_SACK_PERMITTED: 3325 if (optlen != TCPOLEN_SACK_PERMITTED) 3326 continue; 3327 if (!(flags & TO_SYN)) 3328 continue; 3329 if (!V_tcp_do_sack) 3330 continue; 3331 to->to_flags |= TOF_SACKPERM; 3332 break; 3333 case TCPOPT_SACK: 3334 if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0) 3335 continue; 3336 if (flags & TO_SYN) 3337 continue; 3338 to->to_flags |= TOF_SACK; 3339 to->to_nsacks = (optlen - 2) / TCPOLEN_SACK; 3340 to->to_sacks = cp + 2; 3341 TCPSTAT_INC(tcps_sack_rcv_blocks); 3342 break; 3343 case TCPOPT_FAST_OPEN: 3344 /* 3345 * Cookie length validation is performed by the 3346 * server side cookie checking code or the client 3347 * side cookie cache update code. 3348 */ 3349 if (!(flags & TO_SYN)) 3350 continue; 3351 if (!V_tcp_fastopen_client_enable && 3352 !V_tcp_fastopen_server_enable) 3353 continue; 3354 to->to_flags |= TOF_FASTOPEN; 3355 to->to_tfo_len = optlen - 2; 3356 to->to_tfo_cookie = to->to_tfo_len ? cp + 2 : NULL; 3357 break; 3358 default: 3359 continue; 3360 } 3361 } 3362 } 3363 3364 /* 3365 * Pull out of band byte out of a segment so 3366 * it doesn't appear in the user's data queue. 3367 * It is still reflected in the segment length for 3368 * sequencing purposes. 3369 */ 3370 void 3371 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m, 3372 int off) 3373 { 3374 int cnt = off + th->th_urp - 1; 3375 3376 while (cnt >= 0) { 3377 if (m->m_len > cnt) { 3378 char *cp = mtod(m, caddr_t) + cnt; 3379 struct tcpcb *tp = sototcpcb(so); 3380 3381 INP_WLOCK_ASSERT(tp->t_inpcb); 3382 3383 tp->t_iobc = *cp; 3384 tp->t_oobflags |= TCPOOB_HAVEDATA; 3385 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1)); 3386 m->m_len--; 3387 if (m->m_flags & M_PKTHDR) 3388 m->m_pkthdr.len--; 3389 return; 3390 } 3391 cnt -= m->m_len; 3392 m = m->m_next; 3393 if (m == NULL) 3394 break; 3395 } 3396 panic("tcp_pulloutofband"); 3397 } 3398 3399 /* 3400 * Collect new round-trip time estimate 3401 * and update averages and current timeout. 3402 */ 3403 void 3404 tcp_xmit_timer(struct tcpcb *tp, int rtt) 3405 { 3406 int delta; 3407 3408 INP_WLOCK_ASSERT(tp->t_inpcb); 3409 3410 TCPSTAT_INC(tcps_rttupdated); 3411 tp->t_rttupdated++; 3412 #ifdef STATS 3413 stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT, 3414 imax(0, rtt * 1000 / hz)); 3415 #endif 3416 if ((tp->t_srtt != 0) && (tp->t_rxtshift <= TCP_RTT_INVALIDATE)) { 3417 /* 3418 * srtt is stored as fixed point with 5 bits after the 3419 * binary point (i.e., scaled by 8). The following magic 3420 * is equivalent to the smoothing algorithm in rfc793 with 3421 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed 3422 * point). Adjust rtt to origin 0. 3423 */ 3424 delta = ((rtt - 1) << TCP_DELTA_SHIFT) 3425 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT)); 3426 3427 if ((tp->t_srtt += delta) <= 0) 3428 tp->t_srtt = 1; 3429 3430 /* 3431 * We accumulate a smoothed rtt variance (actually, a 3432 * smoothed mean difference), then set the retransmit 3433 * timer to smoothed rtt + 4 times the smoothed variance. 3434 * rttvar is stored as fixed point with 4 bits after the 3435 * binary point (scaled by 16). The following is 3436 * equivalent to rfc793 smoothing with an alpha of .75 3437 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces 3438 * rfc793's wired-in beta. 3439 */ 3440 if (delta < 0) 3441 delta = -delta; 3442 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT); 3443 if ((tp->t_rttvar += delta) <= 0) 3444 tp->t_rttvar = 1; 3445 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar) 3446 tp->t_rttbest = tp->t_srtt + tp->t_rttvar; 3447 } else { 3448 /* 3449 * No rtt measurement yet - use the unsmoothed rtt. 3450 * Set the variance to half the rtt (so our first 3451 * retransmit happens at 3*rtt). 3452 */ 3453 tp->t_srtt = rtt << TCP_RTT_SHIFT; 3454 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1); 3455 tp->t_rttbest = tp->t_srtt + tp->t_rttvar; 3456 } 3457 tp->t_rtttime = 0; 3458 tp->t_rxtshift = 0; 3459 3460 /* 3461 * the retransmit should happen at rtt + 4 * rttvar. 3462 * Because of the way we do the smoothing, srtt and rttvar 3463 * will each average +1/2 tick of bias. When we compute 3464 * the retransmit timer, we want 1/2 tick of rounding and 3465 * 1 extra tick because of +-1/2 tick uncertainty in the 3466 * firing of the timer. The bias will give us exactly the 3467 * 1.5 tick we need. But, because the bias is 3468 * statistical, we have to test that we don't drop below 3469 * the minimum feasible timer (which is 2 ticks). 3470 */ 3471 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp), 3472 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX); 3473 3474 /* 3475 * We received an ack for a packet that wasn't retransmitted; 3476 * it is probably safe to discard any error indications we've 3477 * received recently. This isn't quite right, but close enough 3478 * for now (a route might have failed after we sent a segment, 3479 * and the return path might not be symmetrical). 3480 */ 3481 tp->t_softerror = 0; 3482 } 3483 3484 /* 3485 * Determine a reasonable value for maxseg size. 3486 * If the route is known, check route for mtu. 3487 * If none, use an mss that can be handled on the outgoing interface 3488 * without forcing IP to fragment. If no route is found, route has no mtu, 3489 * or the destination isn't local, use a default, hopefully conservative 3490 * size (usually 512 or the default IP max size, but no more than the mtu 3491 * of the interface), as we can't discover anything about intervening 3492 * gateways or networks. We also initialize the congestion/slow start 3493 * window to be a single segment if the destination isn't local. 3494 * While looking at the routing entry, we also initialize other path-dependent 3495 * parameters from pre-set or cached values in the routing entry. 3496 * 3497 * NOTE that resulting t_maxseg doesn't include space for TCP options or 3498 * IP options, e.g. IPSEC data, since length of this data may vary, and 3499 * thus it is calculated for every segment separately in tcp_output(). 3500 * 3501 * NOTE that this routine is only called when we process an incoming 3502 * segment, or an ICMP need fragmentation datagram. Outgoing SYN/ACK MSS 3503 * settings are handled in tcp_mssopt(). 3504 */ 3505 void 3506 tcp_mss_update(struct tcpcb *tp, int offer, int mtuoffer, 3507 struct hc_metrics_lite *metricptr, struct tcp_ifcap *cap) 3508 { 3509 int mss = 0; 3510 uint32_t maxmtu = 0; 3511 struct inpcb *inp = tp->t_inpcb; 3512 struct hc_metrics_lite metrics; 3513 #ifdef INET6 3514 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0; 3515 size_t min_protoh = isipv6 ? 3516 sizeof (struct ip6_hdr) + sizeof (struct tcphdr) : 3517 sizeof (struct tcpiphdr); 3518 #else 3519 const size_t min_protoh = sizeof(struct tcpiphdr); 3520 #endif 3521 3522 INP_WLOCK_ASSERT(tp->t_inpcb); 3523 3524 if (mtuoffer != -1) { 3525 KASSERT(offer == -1, ("%s: conflict", __func__)); 3526 offer = mtuoffer - min_protoh; 3527 } 3528 3529 /* Initialize. */ 3530 #ifdef INET6 3531 if (isipv6) { 3532 maxmtu = tcp_maxmtu6(&inp->inp_inc, cap); 3533 tp->t_maxseg = V_tcp_v6mssdflt; 3534 } 3535 #endif 3536 #if defined(INET) && defined(INET6) 3537 else 3538 #endif 3539 #ifdef INET 3540 { 3541 maxmtu = tcp_maxmtu(&inp->inp_inc, cap); 3542 tp->t_maxseg = V_tcp_mssdflt; 3543 } 3544 #endif 3545 3546 /* 3547 * No route to sender, stay with default mss and return. 3548 */ 3549 if (maxmtu == 0) { 3550 /* 3551 * In case we return early we need to initialize metrics 3552 * to a defined state as tcp_hc_get() would do for us 3553 * if there was no cache hit. 3554 */ 3555 if (metricptr != NULL) 3556 bzero(metricptr, sizeof(struct hc_metrics_lite)); 3557 return; 3558 } 3559 3560 /* What have we got? */ 3561 switch (offer) { 3562 case 0: 3563 /* 3564 * Offer == 0 means that there was no MSS on the SYN 3565 * segment, in this case we use tcp_mssdflt as 3566 * already assigned to t_maxseg above. 3567 */ 3568 offer = tp->t_maxseg; 3569 break; 3570 3571 case -1: 3572 /* 3573 * Offer == -1 means that we didn't receive SYN yet. 3574 */ 3575 /* FALLTHROUGH */ 3576 3577 default: 3578 /* 3579 * Prevent DoS attack with too small MSS. Round up 3580 * to at least minmss. 3581 */ 3582 offer = max(offer, V_tcp_minmss); 3583 } 3584 3585 /* 3586 * rmx information is now retrieved from tcp_hostcache. 3587 */ 3588 tcp_hc_get(&inp->inp_inc, &metrics); 3589 if (metricptr != NULL) 3590 bcopy(&metrics, metricptr, sizeof(struct hc_metrics_lite)); 3591 3592 /* 3593 * If there's a discovered mtu in tcp hostcache, use it. 3594 * Else, use the link mtu. 3595 */ 3596 if (metrics.rmx_mtu) 3597 mss = min(metrics.rmx_mtu, maxmtu) - min_protoh; 3598 else { 3599 #ifdef INET6 3600 if (isipv6) { 3601 mss = maxmtu - min_protoh; 3602 if (!V_path_mtu_discovery && 3603 !in6_localaddr(&inp->in6p_faddr)) 3604 mss = min(mss, V_tcp_v6mssdflt); 3605 } 3606 #endif 3607 #if defined(INET) && defined(INET6) 3608 else 3609 #endif 3610 #ifdef INET 3611 { 3612 mss = maxmtu - min_protoh; 3613 if (!V_path_mtu_discovery && 3614 !in_localaddr(inp->inp_faddr)) 3615 mss = min(mss, V_tcp_mssdflt); 3616 } 3617 #endif 3618 /* 3619 * XXX - The above conditional (mss = maxmtu - min_protoh) 3620 * probably violates the TCP spec. 3621 * The problem is that, since we don't know the 3622 * other end's MSS, we are supposed to use a conservative 3623 * default. But, if we do that, then MTU discovery will 3624 * never actually take place, because the conservative 3625 * default is much less than the MTUs typically seen 3626 * on the Internet today. For the moment, we'll sweep 3627 * this under the carpet. 3628 * 3629 * The conservative default might not actually be a problem 3630 * if the only case this occurs is when sending an initial 3631 * SYN with options and data to a host we've never talked 3632 * to before. Then, they will reply with an MSS value which 3633 * will get recorded and the new parameters should get 3634 * recomputed. For Further Study. 3635 */ 3636 } 3637 mss = min(mss, offer); 3638 3639 /* 3640 * Sanity check: make sure that maxseg will be large 3641 * enough to allow some data on segments even if the 3642 * all the option space is used (40bytes). Otherwise 3643 * funny things may happen in tcp_output. 3644 * 3645 * XXXGL: shouldn't we reserve space for IP/IPv6 options? 3646 */ 3647 mss = max(mss, 64); 3648 3649 tp->t_maxseg = mss; 3650 } 3651 3652 void 3653 tcp_mss(struct tcpcb *tp, int offer) 3654 { 3655 int mss; 3656 uint32_t bufsize; 3657 struct inpcb *inp; 3658 struct socket *so; 3659 struct hc_metrics_lite metrics; 3660 struct tcp_ifcap cap; 3661 3662 KASSERT(tp != NULL, ("%s: tp == NULL", __func__)); 3663 3664 bzero(&cap, sizeof(cap)); 3665 tcp_mss_update(tp, offer, -1, &metrics, &cap); 3666 3667 mss = tp->t_maxseg; 3668 inp = tp->t_inpcb; 3669 3670 /* 3671 * If there's a pipesize, change the socket buffer to that size, 3672 * don't change if sb_hiwat is different than default (then it 3673 * has been changed on purpose with setsockopt). 3674 * Make the socket buffers an integral number of mss units; 3675 * if the mss is larger than the socket buffer, decrease the mss. 3676 */ 3677 so = inp->inp_socket; 3678 SOCKBUF_LOCK(&so->so_snd); 3679 if ((so->so_snd.sb_hiwat == V_tcp_sendspace) && metrics.rmx_sendpipe) 3680 bufsize = metrics.rmx_sendpipe; 3681 else 3682 bufsize = so->so_snd.sb_hiwat; 3683 if (bufsize < mss) 3684 mss = bufsize; 3685 else { 3686 bufsize = roundup(bufsize, mss); 3687 if (bufsize > sb_max) 3688 bufsize = sb_max; 3689 if (bufsize > so->so_snd.sb_hiwat) 3690 (void)sbreserve_locked(&so->so_snd, bufsize, so, NULL); 3691 } 3692 SOCKBUF_UNLOCK(&so->so_snd); 3693 /* 3694 * Sanity check: make sure that maxseg will be large 3695 * enough to allow some data on segments even if the 3696 * all the option space is used (40bytes). Otherwise 3697 * funny things may happen in tcp_output. 3698 * 3699 * XXXGL: shouldn't we reserve space for IP/IPv6 options? 3700 */ 3701 tp->t_maxseg = max(mss, 64); 3702 3703 SOCKBUF_LOCK(&so->so_rcv); 3704 if ((so->so_rcv.sb_hiwat == V_tcp_recvspace) && metrics.rmx_recvpipe) 3705 bufsize = metrics.rmx_recvpipe; 3706 else 3707 bufsize = so->so_rcv.sb_hiwat; 3708 if (bufsize > mss) { 3709 bufsize = roundup(bufsize, mss); 3710 if (bufsize > sb_max) 3711 bufsize = sb_max; 3712 if (bufsize > so->so_rcv.sb_hiwat) 3713 (void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL); 3714 } 3715 SOCKBUF_UNLOCK(&so->so_rcv); 3716 3717 /* Check the interface for TSO capabilities. */ 3718 if (cap.ifcap & CSUM_TSO) { 3719 tp->t_flags |= TF_TSO; 3720 tp->t_tsomax = cap.tsomax; 3721 tp->t_tsomaxsegcount = cap.tsomaxsegcount; 3722 tp->t_tsomaxsegsize = cap.tsomaxsegsize; 3723 } 3724 } 3725 3726 /* 3727 * Determine the MSS option to send on an outgoing SYN. 3728 */ 3729 int 3730 tcp_mssopt(struct in_conninfo *inc) 3731 { 3732 int mss = 0; 3733 uint32_t thcmtu = 0; 3734 uint32_t maxmtu = 0; 3735 size_t min_protoh; 3736 3737 KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer")); 3738 3739 #ifdef INET6 3740 if (inc->inc_flags & INC_ISIPV6) { 3741 mss = V_tcp_v6mssdflt; 3742 maxmtu = tcp_maxmtu6(inc, NULL); 3743 min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr); 3744 } 3745 #endif 3746 #if defined(INET) && defined(INET6) 3747 else 3748 #endif 3749 #ifdef INET 3750 { 3751 mss = V_tcp_mssdflt; 3752 maxmtu = tcp_maxmtu(inc, NULL); 3753 min_protoh = sizeof(struct tcpiphdr); 3754 } 3755 #endif 3756 #if defined(INET6) || defined(INET) 3757 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */ 3758 #endif 3759 3760 if (maxmtu && thcmtu) 3761 mss = min(maxmtu, thcmtu) - min_protoh; 3762 else if (maxmtu || thcmtu) 3763 mss = max(maxmtu, thcmtu) - min_protoh; 3764 3765 return (mss); 3766 } 3767 3768 3769 /* 3770 * On a partial ack arrives, force the retransmission of the 3771 * next unacknowledged segment. Do not clear tp->t_dupacks. 3772 * By setting snd_nxt to ti_ack, this forces retransmission timer to 3773 * be started again. 3774 */ 3775 void 3776 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th) 3777 { 3778 tcp_seq onxt = tp->snd_nxt; 3779 uint32_t ocwnd = tp->snd_cwnd; 3780 u_int maxseg = tcp_maxseg(tp); 3781 3782 INP_WLOCK_ASSERT(tp->t_inpcb); 3783 3784 tcp_timer_activate(tp, TT_REXMT, 0); 3785 tp->t_rtttime = 0; 3786 tp->snd_nxt = th->th_ack; 3787 /* 3788 * Set snd_cwnd to one segment beyond acknowledged offset. 3789 * (tp->snd_una has not yet been updated when this function is called.) 3790 */ 3791 tp->snd_cwnd = maxseg + BYTES_THIS_ACK(tp, th); 3792 tp->t_flags |= TF_ACKNOW; 3793 (void) tp->t_fb->tfb_tcp_output(tp); 3794 tp->snd_cwnd = ocwnd; 3795 if (SEQ_GT(onxt, tp->snd_nxt)) 3796 tp->snd_nxt = onxt; 3797 /* 3798 * Partial window deflation. Relies on fact that tp->snd_una 3799 * not updated yet. 3800 */ 3801 if (tp->snd_cwnd > BYTES_THIS_ACK(tp, th)) 3802 tp->snd_cwnd -= BYTES_THIS_ACK(tp, th); 3803 else 3804 tp->snd_cwnd = 0; 3805 tp->snd_cwnd += maxseg; 3806 } 3807 3808 int 3809 tcp_compute_pipe(struct tcpcb *tp) 3810 { 3811 return (tp->snd_max - tp->snd_una + 3812 tp->sackhint.sack_bytes_rexmit - 3813 tp->sackhint.sacked_bytes); 3814 } 3815 3816 uint32_t 3817 tcp_compute_initwnd(uint32_t maxseg) 3818 { 3819 /* 3820 * Calculate the Initial Window, also used as Restart Window 3821 * 3822 * RFC5681 Section 3.1 specifies the default conservative values. 3823 * RFC3390 specifies slightly more aggressive values. 3824 * RFC6928 increases it to ten segments. 3825 * Support for user specified value for initial flight size. 3826 */ 3827 if (V_tcp_initcwnd_segments) 3828 return min(V_tcp_initcwnd_segments * maxseg, 3829 max(2 * maxseg, V_tcp_initcwnd_segments * 1460)); 3830 else if (V_tcp_do_rfc3390) 3831 return min(4 * maxseg, max(2 * maxseg, 4380)); 3832 else { 3833 /* Per RFC5681 Section 3.1 */ 3834 if (maxseg > 2190) 3835 return (2 * maxseg); 3836 else if (maxseg > 1095) 3837 return (3 * maxseg); 3838 else 3839 return (4 * maxseg); 3840 } 3841 } 3842