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