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