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) { 923 if (inp->inp_ip_minttl > ip6->ip6_hlim) 924 goto dropunlock; 925 } else 926 #endif 927 if (inp->inp_ip_minttl > ip->ip_ttl) 928 goto dropunlock; 929 } 930 931 /* 932 * A previous connection in TIMEWAIT state is supposed to catch stray 933 * or duplicate segments arriving late. If this segment was a 934 * legitimate new connection attempt, the old INPCB gets removed and 935 * we can try again to find a listening socket. 936 * 937 * At this point, due to earlier optimism, we may hold only an inpcb 938 * lock, and not the inpcbinfo write lock. If so, we need to try to 939 * acquire it, or if that fails, acquire a reference on the inpcb, 940 * drop all locks, acquire a global write lock, and then re-acquire 941 * the inpcb lock. We may at that point discover that another thread 942 * has tried to free the inpcb, in which case we need to loop back 943 * and try to find a new inpcb to deliver to. 944 * 945 * XXXRW: It may be time to rethink timewait locking. 946 */ 947 relocked: 948 if (inp->inp_flags & INP_TIMEWAIT) { 949 if (ti_locked == TI_UNLOCKED) { 950 if (INP_INFO_TRY_RLOCK(&V_tcbinfo) == 0) { 951 in_pcbref(inp); 952 INP_WUNLOCK(inp); 953 INP_INFO_RLOCK(&V_tcbinfo); 954 ti_locked = TI_RLOCKED; 955 INP_WLOCK(inp); 956 if (in_pcbrele_wlocked(inp)) { 957 inp = NULL; 958 goto findpcb; 959 } 960 } else 961 ti_locked = TI_RLOCKED; 962 } 963 INP_INFO_RLOCK_ASSERT(&V_tcbinfo); 964 965 if (thflags & TH_SYN) 966 tcp_dooptions(&to, optp, optlen, TO_SYN); 967 /* 968 * NB: tcp_twcheck unlocks the INP and frees the mbuf. 969 */ 970 if (tcp_twcheck(inp, &to, th, m, tlen)) 971 goto findpcb; 972 INP_INFO_RUNLOCK(&V_tcbinfo); 973 return (IPPROTO_DONE); 974 } 975 /* 976 * The TCPCB may no longer exist if the connection is winding 977 * down or it is in the CLOSED state. Either way we drop the 978 * segment and send an appropriate response. 979 */ 980 tp = intotcpcb(inp); 981 if (tp == NULL || tp->t_state == TCPS_CLOSED) { 982 rstreason = BANDLIM_RST_CLOSEDPORT; 983 goto dropwithreset; 984 } 985 986 #ifdef TCP_OFFLOAD 987 if (tp->t_flags & TF_TOE) { 988 tcp_offload_input(tp, m); 989 m = NULL; /* consumed by the TOE driver */ 990 goto dropunlock; 991 } 992 #endif 993 994 /* 995 * We've identified a valid inpcb, but it could be that we need an 996 * inpcbinfo write lock but don't hold it. In this case, attempt to 997 * acquire using the same strategy as the TIMEWAIT case above. If we 998 * relock, we have to jump back to 'relocked' as the connection might 999 * now be in TIMEWAIT. 1000 */ 1001 #ifdef INVARIANTS 1002 if ((thflags & (TH_FIN | TH_RST)) != 0) 1003 INP_INFO_RLOCK_ASSERT(&V_tcbinfo); 1004 #endif 1005 if (!((tp->t_state == TCPS_ESTABLISHED && (thflags & TH_SYN) == 0) || 1006 (tp->t_state == TCPS_LISTEN && (thflags & TH_SYN) && 1007 !(tp->t_flags & TF_FASTOPEN)))) { 1008 if (ti_locked == TI_UNLOCKED) { 1009 if (INP_INFO_TRY_RLOCK(&V_tcbinfo) == 0) { 1010 in_pcbref(inp); 1011 INP_WUNLOCK(inp); 1012 INP_INFO_RLOCK(&V_tcbinfo); 1013 ti_locked = TI_RLOCKED; 1014 INP_WLOCK(inp); 1015 if (in_pcbrele_wlocked(inp)) { 1016 inp = NULL; 1017 goto findpcb; 1018 } 1019 goto relocked; 1020 } else 1021 ti_locked = TI_RLOCKED; 1022 } 1023 INP_INFO_RLOCK_ASSERT(&V_tcbinfo); 1024 } 1025 1026 #ifdef MAC 1027 INP_WLOCK_ASSERT(inp); 1028 if (mac_inpcb_check_deliver(inp, m)) 1029 goto dropunlock; 1030 #endif 1031 so = inp->inp_socket; 1032 KASSERT(so != NULL, ("%s: so == NULL", __func__)); 1033 #ifdef TCPDEBUG 1034 if (so->so_options & SO_DEBUG) { 1035 ostate = tp->t_state; 1036 #ifdef INET6 1037 if (isipv6) { 1038 bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6)); 1039 } else 1040 #endif 1041 bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip)); 1042 tcp_savetcp = *th; 1043 } 1044 #endif /* TCPDEBUG */ 1045 /* 1046 * When the socket is accepting connections (the INPCB is in LISTEN 1047 * state) we look into the SYN cache if this is a new connection 1048 * attempt or the completion of a previous one. 1049 */ 1050 if (so->so_options & SO_ACCEPTCONN) { 1051 struct in_conninfo inc; 1052 1053 KASSERT(tp->t_state == TCPS_LISTEN, ("%s: so accepting but " 1054 "tp not listening", __func__)); 1055 bzero(&inc, sizeof(inc)); 1056 #ifdef INET6 1057 if (isipv6) { 1058 inc.inc_flags |= INC_ISIPV6; 1059 inc.inc6_faddr = ip6->ip6_src; 1060 inc.inc6_laddr = ip6->ip6_dst; 1061 } else 1062 #endif 1063 { 1064 inc.inc_faddr = ip->ip_src; 1065 inc.inc_laddr = ip->ip_dst; 1066 } 1067 inc.inc_fport = th->th_sport; 1068 inc.inc_lport = th->th_dport; 1069 inc.inc_fibnum = so->so_fibnum; 1070 1071 /* 1072 * Check for an existing connection attempt in syncache if 1073 * the flag is only ACK. A successful lookup creates a new 1074 * socket appended to the listen queue in SYN_RECEIVED state. 1075 */ 1076 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) { 1077 1078 INP_INFO_RLOCK_ASSERT(&V_tcbinfo); 1079 /* 1080 * Parse the TCP options here because 1081 * syncookies need access to the reflected 1082 * timestamp. 1083 */ 1084 tcp_dooptions(&to, optp, optlen, 0); 1085 /* 1086 * NB: syncache_expand() doesn't unlock 1087 * inp and tcpinfo locks. 1088 */ 1089 if (!syncache_expand(&inc, &to, th, &so, m)) { 1090 /* 1091 * No syncache entry or ACK was not 1092 * for our SYN/ACK. Send a RST. 1093 * NB: syncache did its own logging 1094 * of the failure cause. 1095 */ 1096 rstreason = BANDLIM_RST_OPENPORT; 1097 goto dropwithreset; 1098 } 1099 #ifdef TCP_RFC7413 1100 new_tfo_socket: 1101 #endif 1102 if (so == NULL) { 1103 /* 1104 * We completed the 3-way handshake 1105 * but could not allocate a socket 1106 * either due to memory shortage, 1107 * listen queue length limits or 1108 * global socket limits. Send RST 1109 * or wait and have the remote end 1110 * retransmit the ACK for another 1111 * try. 1112 */ 1113 if ((s = tcp_log_addrs(&inc, th, NULL, NULL))) 1114 log(LOG_DEBUG, "%s; %s: Listen socket: " 1115 "Socket allocation failed due to " 1116 "limits or memory shortage, %s\n", 1117 s, __func__, 1118 V_tcp_sc_rst_sock_fail ? 1119 "sending RST" : "try again"); 1120 if (V_tcp_sc_rst_sock_fail) { 1121 rstreason = BANDLIM_UNLIMITED; 1122 goto dropwithreset; 1123 } else 1124 goto dropunlock; 1125 } 1126 /* 1127 * Socket is created in state SYN_RECEIVED. 1128 * Unlock the listen socket, lock the newly 1129 * created socket and update the tp variable. 1130 */ 1131 INP_WUNLOCK(inp); /* listen socket */ 1132 inp = sotoinpcb(so); 1133 /* 1134 * New connection inpcb is already locked by 1135 * syncache_expand(). 1136 */ 1137 INP_WLOCK_ASSERT(inp); 1138 tp = intotcpcb(inp); 1139 KASSERT(tp->t_state == TCPS_SYN_RECEIVED, 1140 ("%s: ", __func__)); 1141 #ifdef TCP_SIGNATURE 1142 if (sig_checked == 0) { 1143 tcp_dooptions(&to, optp, optlen, 1144 (thflags & TH_SYN) ? TO_SYN : 0); 1145 if (!tcp_signature_verify_input(m, off0, tlen, 1146 optlen, &to, th, tp->t_flags)) { 1147 1148 /* 1149 * In SYN_SENT state if it receives an 1150 * RST, it is allowed for further 1151 * processing. 1152 */ 1153 if ((thflags & TH_RST) == 0 || 1154 (tp->t_state == TCPS_SYN_SENT) == 0) 1155 goto dropunlock; 1156 } 1157 sig_checked = 1; 1158 } 1159 #endif 1160 1161 /* 1162 * Process the segment and the data it 1163 * contains. tcp_do_segment() consumes 1164 * the mbuf chain and unlocks the inpcb. 1165 */ 1166 tp->t_fb->tfb_tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen, 1167 iptos, ti_locked); 1168 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo); 1169 return (IPPROTO_DONE); 1170 } 1171 /* 1172 * Segment flag validation for new connection attempts: 1173 * 1174 * Our (SYN|ACK) response was rejected. 1175 * Check with syncache and remove entry to prevent 1176 * retransmits. 1177 * 1178 * NB: syncache_chkrst does its own logging of failure 1179 * causes. 1180 */ 1181 if (thflags & TH_RST) { 1182 syncache_chkrst(&inc, th); 1183 goto dropunlock; 1184 } 1185 /* 1186 * We can't do anything without SYN. 1187 */ 1188 if ((thflags & TH_SYN) == 0) { 1189 if ((s = tcp_log_addrs(&inc, th, NULL, NULL))) 1190 log(LOG_DEBUG, "%s; %s: Listen socket: " 1191 "SYN is missing, segment ignored\n", 1192 s, __func__); 1193 TCPSTAT_INC(tcps_badsyn); 1194 goto dropunlock; 1195 } 1196 /* 1197 * (SYN|ACK) is bogus on a listen socket. 1198 */ 1199 if (thflags & TH_ACK) { 1200 if ((s = tcp_log_addrs(&inc, th, NULL, NULL))) 1201 log(LOG_DEBUG, "%s; %s: Listen socket: " 1202 "SYN|ACK invalid, segment rejected\n", 1203 s, __func__); 1204 syncache_badack(&inc); /* XXX: Not needed! */ 1205 TCPSTAT_INC(tcps_badsyn); 1206 rstreason = BANDLIM_RST_OPENPORT; 1207 goto dropwithreset; 1208 } 1209 /* 1210 * If the drop_synfin option is enabled, drop all 1211 * segments with both the SYN and FIN bits set. 1212 * This prevents e.g. nmap from identifying the 1213 * TCP/IP stack. 1214 * XXX: Poor reasoning. nmap has other methods 1215 * and is constantly refining its stack detection 1216 * strategies. 1217 * XXX: This is a violation of the TCP specification 1218 * and was used by RFC1644. 1219 */ 1220 if ((thflags & TH_FIN) && V_drop_synfin) { 1221 if ((s = tcp_log_addrs(&inc, th, NULL, NULL))) 1222 log(LOG_DEBUG, "%s; %s: Listen socket: " 1223 "SYN|FIN segment ignored (based on " 1224 "sysctl setting)\n", s, __func__); 1225 TCPSTAT_INC(tcps_badsyn); 1226 goto dropunlock; 1227 } 1228 /* 1229 * Segment's flags are (SYN) or (SYN|FIN). 1230 * 1231 * TH_PUSH, TH_URG, TH_ECE, TH_CWR are ignored 1232 * as they do not affect the state of the TCP FSM. 1233 * The data pointed to by TH_URG and th_urp is ignored. 1234 */ 1235 KASSERT((thflags & (TH_RST|TH_ACK)) == 0, 1236 ("%s: Listen socket: TH_RST or TH_ACK set", __func__)); 1237 KASSERT(thflags & (TH_SYN), 1238 ("%s: Listen socket: TH_SYN not set", __func__)); 1239 #ifdef INET6 1240 /* 1241 * If deprecated address is forbidden, 1242 * we do not accept SYN to deprecated interface 1243 * address to prevent any new inbound connection from 1244 * getting established. 1245 * When we do not accept SYN, we send a TCP RST, 1246 * with deprecated source address (instead of dropping 1247 * it). We compromise it as it is much better for peer 1248 * to send a RST, and RST will be the final packet 1249 * for the exchange. 1250 * 1251 * If we do not forbid deprecated addresses, we accept 1252 * the SYN packet. RFC2462 does not suggest dropping 1253 * SYN in this case. 1254 * If we decipher RFC2462 5.5.4, it says like this: 1255 * 1. use of deprecated addr with existing 1256 * communication is okay - "SHOULD continue to be 1257 * used" 1258 * 2. use of it with new communication: 1259 * (2a) "SHOULD NOT be used if alternate address 1260 * with sufficient scope is available" 1261 * (2b) nothing mentioned otherwise. 1262 * Here we fall into (2b) case as we have no choice in 1263 * our source address selection - we must obey the peer. 1264 * 1265 * The wording in RFC2462 is confusing, and there are 1266 * multiple description text for deprecated address 1267 * handling - worse, they are not exactly the same. 1268 * I believe 5.5.4 is the best one, so we follow 5.5.4. 1269 */ 1270 if (isipv6 && !V_ip6_use_deprecated) { 1271 struct in6_ifaddr *ia6; 1272 1273 ia6 = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */); 1274 if (ia6 != NULL && 1275 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) { 1276 ifa_free(&ia6->ia_ifa); 1277 if ((s = tcp_log_addrs(&inc, th, NULL, NULL))) 1278 log(LOG_DEBUG, "%s; %s: Listen socket: " 1279 "Connection attempt to deprecated " 1280 "IPv6 address rejected\n", 1281 s, __func__); 1282 rstreason = BANDLIM_RST_OPENPORT; 1283 goto dropwithreset; 1284 } 1285 if (ia6) 1286 ifa_free(&ia6->ia_ifa); 1287 } 1288 #endif /* INET6 */ 1289 /* 1290 * Basic sanity checks on incoming SYN requests: 1291 * Don't respond if the destination is a link layer 1292 * broadcast according to RFC1122 4.2.3.10, p. 104. 1293 * If it is from this socket it must be forged. 1294 * Don't respond if the source or destination is a 1295 * global or subnet broad- or multicast address. 1296 * Note that it is quite possible to receive unicast 1297 * link-layer packets with a broadcast IP address. Use 1298 * in_broadcast() to find them. 1299 */ 1300 if (m->m_flags & (M_BCAST|M_MCAST)) { 1301 if ((s = tcp_log_addrs(&inc, th, NULL, NULL))) 1302 log(LOG_DEBUG, "%s; %s: Listen socket: " 1303 "Connection attempt from broad- or multicast " 1304 "link layer address ignored\n", s, __func__); 1305 goto dropunlock; 1306 } 1307 #ifdef INET6 1308 if (isipv6) { 1309 if (th->th_dport == th->th_sport && 1310 IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &ip6->ip6_src)) { 1311 if ((s = tcp_log_addrs(&inc, th, NULL, NULL))) 1312 log(LOG_DEBUG, "%s; %s: Listen socket: " 1313 "Connection attempt to/from self " 1314 "ignored\n", s, __func__); 1315 goto dropunlock; 1316 } 1317 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) || 1318 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) { 1319 if ((s = tcp_log_addrs(&inc, th, NULL, NULL))) 1320 log(LOG_DEBUG, "%s; %s: Listen socket: " 1321 "Connection attempt from/to multicast " 1322 "address ignored\n", s, __func__); 1323 goto dropunlock; 1324 } 1325 } 1326 #endif 1327 #if defined(INET) && defined(INET6) 1328 else 1329 #endif 1330 #ifdef INET 1331 { 1332 if (th->th_dport == th->th_sport && 1333 ip->ip_dst.s_addr == ip->ip_src.s_addr) { 1334 if ((s = tcp_log_addrs(&inc, th, NULL, NULL))) 1335 log(LOG_DEBUG, "%s; %s: Listen socket: " 1336 "Connection attempt from/to self " 1337 "ignored\n", s, __func__); 1338 goto dropunlock; 1339 } 1340 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) || 1341 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) || 1342 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) || 1343 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) { 1344 if ((s = tcp_log_addrs(&inc, th, NULL, NULL))) 1345 log(LOG_DEBUG, "%s; %s: Listen socket: " 1346 "Connection attempt from/to broad- " 1347 "or multicast address ignored\n", 1348 s, __func__); 1349 goto dropunlock; 1350 } 1351 } 1352 #endif 1353 /* 1354 * SYN appears to be valid. Create compressed TCP state 1355 * for syncache. 1356 */ 1357 #ifdef TCPDEBUG 1358 if (so->so_options & SO_DEBUG) 1359 tcp_trace(TA_INPUT, ostate, tp, 1360 (void *)tcp_saveipgen, &tcp_savetcp, 0); 1361 #endif 1362 TCP_PROBE3(debug__input, tp, th, mtod(m, const char *)); 1363 tcp_dooptions(&to, optp, optlen, TO_SYN); 1364 #ifdef TCP_RFC7413 1365 if (syncache_add(&inc, &to, th, inp, &so, m, NULL, NULL)) 1366 goto new_tfo_socket; 1367 #else 1368 syncache_add(&inc, &to, th, inp, &so, m, NULL, NULL); 1369 #endif 1370 /* 1371 * Entry added to syncache and mbuf consumed. 1372 * Only the listen socket is unlocked by syncache_add(). 1373 */ 1374 if (ti_locked == TI_RLOCKED) { 1375 INP_INFO_RUNLOCK(&V_tcbinfo); 1376 ti_locked = TI_UNLOCKED; 1377 } 1378 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo); 1379 return (IPPROTO_DONE); 1380 } else if (tp->t_state == TCPS_LISTEN) { 1381 /* 1382 * When a listen socket is torn down the SO_ACCEPTCONN 1383 * flag is removed first while connections are drained 1384 * from the accept queue in a unlock/lock cycle of the 1385 * ACCEPT_LOCK, opening a race condition allowing a SYN 1386 * attempt go through unhandled. 1387 */ 1388 goto dropunlock; 1389 } 1390 1391 #ifdef TCP_SIGNATURE 1392 if (sig_checked == 0) { 1393 tcp_dooptions(&to, optp, optlen, 1394 (thflags & TH_SYN) ? TO_SYN : 0); 1395 if (!tcp_signature_verify_input(m, off0, tlen, optlen, &to, 1396 th, tp->t_flags)) { 1397 1398 /* 1399 * In SYN_SENT state if it receives an RST, it is 1400 * allowed for further processing. 1401 */ 1402 if ((thflags & TH_RST) == 0 || 1403 (tp->t_state == TCPS_SYN_SENT) == 0) 1404 goto dropunlock; 1405 } 1406 sig_checked = 1; 1407 } 1408 #endif 1409 1410 TCP_PROBE5(receive, NULL, tp, mtod(m, const char *), tp, th); 1411 1412 /* 1413 * Segment belongs to a connection in SYN_SENT, ESTABLISHED or later 1414 * state. tcp_do_segment() always consumes the mbuf chain, unlocks 1415 * the inpcb, and unlocks pcbinfo. 1416 */ 1417 tp->t_fb->tfb_tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen, iptos, ti_locked); 1418 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo); 1419 return (IPPROTO_DONE); 1420 1421 dropwithreset: 1422 TCP_PROBE5(receive, NULL, tp, mtod(m, const char *), tp, th); 1423 1424 if (ti_locked == TI_RLOCKED) { 1425 INP_INFO_RUNLOCK(&V_tcbinfo); 1426 ti_locked = TI_UNLOCKED; 1427 } 1428 #ifdef INVARIANTS 1429 else { 1430 KASSERT(ti_locked == TI_UNLOCKED, ("%s: dropwithreset " 1431 "ti_locked: %d", __func__, ti_locked)); 1432 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo); 1433 } 1434 #endif 1435 1436 if (inp != NULL) { 1437 tcp_dropwithreset(m, th, tp, tlen, rstreason); 1438 INP_WUNLOCK(inp); 1439 } else 1440 tcp_dropwithreset(m, th, NULL, tlen, rstreason); 1441 m = NULL; /* mbuf chain got consumed. */ 1442 goto drop; 1443 1444 dropunlock: 1445 if (m != NULL) 1446 TCP_PROBE5(receive, NULL, tp, mtod(m, const char *), tp, th); 1447 1448 if (ti_locked == TI_RLOCKED) { 1449 INP_INFO_RUNLOCK(&V_tcbinfo); 1450 ti_locked = TI_UNLOCKED; 1451 } 1452 #ifdef INVARIANTS 1453 else { 1454 KASSERT(ti_locked == TI_UNLOCKED, ("%s: dropunlock " 1455 "ti_locked: %d", __func__, ti_locked)); 1456 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo); 1457 } 1458 #endif 1459 1460 if (inp != NULL) 1461 INP_WUNLOCK(inp); 1462 1463 drop: 1464 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo); 1465 if (s != NULL) 1466 free(s, M_TCPLOG); 1467 if (m != NULL) 1468 m_freem(m); 1469 return (IPPROTO_DONE); 1470 } 1471 1472 void 1473 tcp_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so, 1474 struct tcpcb *tp, int drop_hdrlen, int tlen, uint8_t iptos, 1475 int ti_locked) 1476 { 1477 int thflags, acked, ourfinisacked, needoutput = 0, sack_changed; 1478 int rstreason, todrop, win; 1479 u_long tiwin; 1480 char *s; 1481 struct in_conninfo *inc; 1482 struct mbuf *mfree; 1483 struct tcpopt to; 1484 int tfo_syn; 1485 1486 #ifdef TCPDEBUG 1487 /* 1488 * The size of tcp_saveipgen must be the size of the max ip header, 1489 * now IPv6. 1490 */ 1491 u_char tcp_saveipgen[IP6_HDR_LEN]; 1492 struct tcphdr tcp_savetcp; 1493 short ostate = 0; 1494 #endif 1495 thflags = th->th_flags; 1496 inc = &tp->t_inpcb->inp_inc; 1497 tp->sackhint.last_sack_ack = 0; 1498 sack_changed = 0; 1499 1500 /* 1501 * If this is either a state-changing packet or current state isn't 1502 * established, we require a write lock on tcbinfo. Otherwise, we 1503 * allow the tcbinfo to be in either alocked or unlocked, as the 1504 * caller may have unnecessarily acquired a write lock due to a race. 1505 */ 1506 if ((thflags & (TH_SYN | TH_FIN | TH_RST)) != 0 || 1507 tp->t_state != TCPS_ESTABLISHED) { 1508 KASSERT(ti_locked == TI_RLOCKED, ("%s ti_locked %d for " 1509 "SYN/FIN/RST/!EST", __func__, ti_locked)); 1510 INP_INFO_RLOCK_ASSERT(&V_tcbinfo); 1511 } else { 1512 #ifdef INVARIANTS 1513 if (ti_locked == TI_RLOCKED) 1514 INP_INFO_RLOCK_ASSERT(&V_tcbinfo); 1515 else { 1516 KASSERT(ti_locked == TI_UNLOCKED, ("%s: EST " 1517 "ti_locked: %d", __func__, ti_locked)); 1518 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo); 1519 } 1520 #endif 1521 } 1522 INP_WLOCK_ASSERT(tp->t_inpcb); 1523 KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN", 1524 __func__)); 1525 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT", 1526 __func__)); 1527 1528 #ifdef TCPPCAP 1529 /* Save segment, if requested. */ 1530 tcp_pcap_add(th, m, &(tp->t_inpkts)); 1531 #endif 1532 1533 /* 1534 * Segment received on connection. 1535 * Reset idle time and keep-alive timer. 1536 * XXX: This should be done after segment 1537 * validation to ignore broken/spoofed segs. 1538 */ 1539 tp->t_rcvtime = ticks; 1540 if (TCPS_HAVEESTABLISHED(tp->t_state)) 1541 tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp)); 1542 1543 /* 1544 * Scale up the window into a 32-bit value. 1545 * For the SYN_SENT state the scale is zero. 1546 */ 1547 tiwin = th->th_win << tp->snd_scale; 1548 1549 /* 1550 * TCP ECN processing. 1551 */ 1552 if (tp->t_flags & TF_ECN_PERMIT) { 1553 if (thflags & TH_CWR) 1554 tp->t_flags &= ~TF_ECN_SND_ECE; 1555 switch (iptos & IPTOS_ECN_MASK) { 1556 case IPTOS_ECN_CE: 1557 tp->t_flags |= TF_ECN_SND_ECE; 1558 TCPSTAT_INC(tcps_ecn_ce); 1559 break; 1560 case IPTOS_ECN_ECT0: 1561 TCPSTAT_INC(tcps_ecn_ect0); 1562 break; 1563 case IPTOS_ECN_ECT1: 1564 TCPSTAT_INC(tcps_ecn_ect1); 1565 break; 1566 } 1567 1568 /* Process a packet differently from RFC3168. */ 1569 cc_ecnpkt_handler(tp, th, iptos); 1570 1571 /* Congestion experienced. */ 1572 if (thflags & TH_ECE) { 1573 cc_cong_signal(tp, th, CC_ECN); 1574 } 1575 } 1576 1577 /* 1578 * Parse options on any incoming segment. 1579 */ 1580 tcp_dooptions(&to, (u_char *)(th + 1), 1581 (th->th_off << 2) - sizeof(struct tcphdr), 1582 (thflags & TH_SYN) ? TO_SYN : 0); 1583 1584 /* 1585 * If echoed timestamp is later than the current time, 1586 * fall back to non RFC1323 RTT calculation. Normalize 1587 * timestamp if syncookies were used when this connection 1588 * was established. 1589 */ 1590 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) { 1591 to.to_tsecr -= tp->ts_offset; 1592 if (TSTMP_GT(to.to_tsecr, tcp_ts_getticks())) 1593 to.to_tsecr = 0; 1594 } 1595 /* 1596 * If timestamps were negotiated during SYN/ACK they should 1597 * appear on every segment during this session and vice versa. 1598 */ 1599 if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS)) { 1600 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) { 1601 log(LOG_DEBUG, "%s; %s: Timestamp missing, " 1602 "no action\n", s, __func__); 1603 free(s, M_TCPLOG); 1604 } 1605 } 1606 if (!(tp->t_flags & TF_RCVD_TSTMP) && (to.to_flags & TOF_TS)) { 1607 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) { 1608 log(LOG_DEBUG, "%s; %s: Timestamp not expected, " 1609 "no action\n", s, __func__); 1610 free(s, M_TCPLOG); 1611 } 1612 } 1613 1614 /* 1615 * Process options only when we get SYN/ACK back. The SYN case 1616 * for incoming connections is handled in tcp_syncache. 1617 * According to RFC1323 the window field in a SYN (i.e., a <SYN> 1618 * or <SYN,ACK>) segment itself is never scaled. 1619 * XXX this is traditional behavior, may need to be cleaned up. 1620 */ 1621 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) { 1622 if ((to.to_flags & TOF_SCALE) && 1623 (tp->t_flags & TF_REQ_SCALE)) { 1624 tp->t_flags |= TF_RCVD_SCALE; 1625 tp->snd_scale = to.to_wscale; 1626 } 1627 /* 1628 * Initial send window. It will be updated with 1629 * the next incoming segment to the scaled value. 1630 */ 1631 tp->snd_wnd = th->th_win; 1632 if (to.to_flags & TOF_TS) { 1633 tp->t_flags |= TF_RCVD_TSTMP; 1634 tp->ts_recent = to.to_tsval; 1635 tp->ts_recent_age = tcp_ts_getticks(); 1636 } 1637 if (to.to_flags & TOF_MSS) 1638 tcp_mss(tp, to.to_mss); 1639 if ((tp->t_flags & TF_SACK_PERMIT) && 1640 (to.to_flags & TOF_SACKPERM) == 0) 1641 tp->t_flags &= ~TF_SACK_PERMIT; 1642 } 1643 1644 /* 1645 * Header prediction: check for the two common cases 1646 * of a uni-directional data xfer. If the packet has 1647 * no control flags, is in-sequence, the window didn't 1648 * change and we're not retransmitting, it's a 1649 * candidate. If the length is zero and the ack moved 1650 * forward, we're the sender side of the xfer. Just 1651 * free the data acked & wake any higher level process 1652 * that was blocked waiting for space. If the length 1653 * is non-zero and the ack didn't move, we're the 1654 * receiver side. If we're getting packets in-order 1655 * (the reassembly queue is empty), add the data to 1656 * the socket buffer and note that we need a delayed ack. 1657 * Make sure that the hidden state-flags are also off. 1658 * Since we check for TCPS_ESTABLISHED first, it can only 1659 * be TH_NEEDSYN. 1660 */ 1661 if (tp->t_state == TCPS_ESTABLISHED && 1662 th->th_seq == tp->rcv_nxt && 1663 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK && 1664 tp->snd_nxt == tp->snd_max && 1665 tiwin && tiwin == tp->snd_wnd && 1666 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) && 1667 LIST_EMPTY(&tp->t_segq) && 1668 ((to.to_flags & TOF_TS) == 0 || 1669 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) ) { 1670 1671 /* 1672 * If last ACK falls within this segment's sequence numbers, 1673 * record the timestamp. 1674 * NOTE that the test is modified according to the latest 1675 * proposal of the tcplw@cray.com list (Braden 1993/04/26). 1676 */ 1677 if ((to.to_flags & TOF_TS) != 0 && 1678 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) { 1679 tp->ts_recent_age = tcp_ts_getticks(); 1680 tp->ts_recent = to.to_tsval; 1681 } 1682 1683 if (tlen == 0) { 1684 if (SEQ_GT(th->th_ack, tp->snd_una) && 1685 SEQ_LEQ(th->th_ack, tp->snd_max) && 1686 !IN_RECOVERY(tp->t_flags) && 1687 (to.to_flags & TOF_SACK) == 0 && 1688 TAILQ_EMPTY(&tp->snd_holes)) { 1689 /* 1690 * This is a pure ack for outstanding data. 1691 */ 1692 if (ti_locked == TI_RLOCKED) 1693 INP_INFO_RUNLOCK(&V_tcbinfo); 1694 ti_locked = TI_UNLOCKED; 1695 1696 TCPSTAT_INC(tcps_predack); 1697 1698 /* 1699 * "bad retransmit" recovery. 1700 */ 1701 if (tp->t_rxtshift == 1 && 1702 tp->t_flags & TF_PREVVALID && 1703 (int)(ticks - tp->t_badrxtwin) < 0) { 1704 cc_cong_signal(tp, th, CC_RTO_ERR); 1705 } 1706 1707 /* 1708 * Recalculate the transmit timer / rtt. 1709 * 1710 * Some boxes send broken timestamp replies 1711 * during the SYN+ACK phase, ignore 1712 * timestamps of 0 or we could calculate a 1713 * huge RTT and blow up the retransmit timer. 1714 */ 1715 if ((to.to_flags & TOF_TS) != 0 && 1716 to.to_tsecr) { 1717 u_int t; 1718 1719 t = tcp_ts_getticks() - to.to_tsecr; 1720 if (!tp->t_rttlow || tp->t_rttlow > t) 1721 tp->t_rttlow = t; 1722 tcp_xmit_timer(tp, 1723 TCP_TS_TO_TICKS(t) + 1); 1724 } else if (tp->t_rtttime && 1725 SEQ_GT(th->th_ack, tp->t_rtseq)) { 1726 if (!tp->t_rttlow || 1727 tp->t_rttlow > ticks - tp->t_rtttime) 1728 tp->t_rttlow = ticks - tp->t_rtttime; 1729 tcp_xmit_timer(tp, 1730 ticks - tp->t_rtttime); 1731 } 1732 acked = BYTES_THIS_ACK(tp, th); 1733 1734 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */ 1735 hhook_run_tcp_est_in(tp, th, &to); 1736 1737 TCPSTAT_INC(tcps_rcvackpack); 1738 TCPSTAT_ADD(tcps_rcvackbyte, acked); 1739 sbdrop(&so->so_snd, acked); 1740 if (SEQ_GT(tp->snd_una, tp->snd_recover) && 1741 SEQ_LEQ(th->th_ack, tp->snd_recover)) 1742 tp->snd_recover = th->th_ack - 1; 1743 1744 /* 1745 * Let the congestion control algorithm update 1746 * congestion control related information. This 1747 * typically means increasing the congestion 1748 * window. 1749 */ 1750 cc_ack_received(tp, th, CC_ACK); 1751 1752 tp->snd_una = th->th_ack; 1753 /* 1754 * Pull snd_wl2 up to prevent seq wrap relative 1755 * to th_ack. 1756 */ 1757 tp->snd_wl2 = th->th_ack; 1758 tp->t_dupacks = 0; 1759 m_freem(m); 1760 1761 /* 1762 * If all outstanding data are acked, stop 1763 * retransmit timer, otherwise restart timer 1764 * using current (possibly backed-off) value. 1765 * If process is waiting for space, 1766 * wakeup/selwakeup/signal. If data 1767 * are ready to send, let tcp_output 1768 * decide between more output or persist. 1769 */ 1770 #ifdef TCPDEBUG 1771 if (so->so_options & SO_DEBUG) 1772 tcp_trace(TA_INPUT, ostate, tp, 1773 (void *)tcp_saveipgen, 1774 &tcp_savetcp, 0); 1775 #endif 1776 TCP_PROBE3(debug__input, tp, th, 1777 mtod(m, const char *)); 1778 if (tp->snd_una == tp->snd_max) 1779 tcp_timer_activate(tp, TT_REXMT, 0); 1780 else if (!tcp_timer_active(tp, TT_PERSIST)) 1781 tcp_timer_activate(tp, TT_REXMT, 1782 tp->t_rxtcur); 1783 sowwakeup(so); 1784 if (sbavail(&so->so_snd)) 1785 (void) tp->t_fb->tfb_tcp_output(tp); 1786 goto check_delack; 1787 } 1788 } else if (th->th_ack == tp->snd_una && 1789 tlen <= sbspace(&so->so_rcv)) { 1790 int newsize = 0; /* automatic sockbuf scaling */ 1791 1792 /* 1793 * This is a pure, in-sequence data packet with 1794 * nothing on the reassembly queue and we have enough 1795 * buffer space to take it. 1796 */ 1797 if (ti_locked == TI_RLOCKED) 1798 INP_INFO_RUNLOCK(&V_tcbinfo); 1799 ti_locked = TI_UNLOCKED; 1800 1801 /* Clean receiver SACK report if present */ 1802 if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks) 1803 tcp_clean_sackreport(tp); 1804 TCPSTAT_INC(tcps_preddat); 1805 tp->rcv_nxt += tlen; 1806 /* 1807 * Pull snd_wl1 up to prevent seq wrap relative to 1808 * th_seq. 1809 */ 1810 tp->snd_wl1 = th->th_seq; 1811 /* 1812 * Pull rcv_up up to prevent seq wrap relative to 1813 * rcv_nxt. 1814 */ 1815 tp->rcv_up = tp->rcv_nxt; 1816 TCPSTAT_INC(tcps_rcvpack); 1817 TCPSTAT_ADD(tcps_rcvbyte, tlen); 1818 #ifdef TCPDEBUG 1819 if (so->so_options & SO_DEBUG) 1820 tcp_trace(TA_INPUT, ostate, tp, 1821 (void *)tcp_saveipgen, &tcp_savetcp, 0); 1822 #endif 1823 TCP_PROBE3(debug__input, tp, th, mtod(m, const char *)); 1824 1825 /* 1826 * Automatic sizing of receive socket buffer. Often the send 1827 * buffer size is not optimally adjusted to the actual network 1828 * conditions at hand (delay bandwidth product). Setting the 1829 * buffer size too small limits throughput on links with high 1830 * bandwidth and high delay (eg. trans-continental/oceanic links). 1831 * 1832 * On the receive side the socket buffer memory is only rarely 1833 * used to any significant extent. This allows us to be much 1834 * more aggressive in scaling the receive socket buffer. For 1835 * the case that the buffer space is actually used to a large 1836 * extent and we run out of kernel memory we can simply drop 1837 * the new segments; TCP on the sender will just retransmit it 1838 * later. Setting the buffer size too big may only consume too 1839 * much kernel memory if the application doesn't read() from 1840 * the socket or packet loss or reordering makes use of the 1841 * reassembly queue. 1842 * 1843 * The criteria to step up the receive buffer one notch are: 1844 * 1. Application has not set receive buffer size with 1845 * SO_RCVBUF. Setting SO_RCVBUF clears SB_AUTOSIZE. 1846 * 2. the number of bytes received during the time it takes 1847 * one timestamp to be reflected back to us (the RTT); 1848 * 3. received bytes per RTT is within seven eighth of the 1849 * current socket buffer size; 1850 * 4. receive buffer size has not hit maximal automatic size; 1851 * 1852 * This algorithm does one step per RTT at most and only if 1853 * we receive a bulk stream w/o packet losses or reorderings. 1854 * Shrinking the buffer during idle times is not necessary as 1855 * it doesn't consume any memory when idle. 1856 * 1857 * TODO: Only step up if the application is actually serving 1858 * the buffer to better manage the socket buffer resources. 1859 */ 1860 if (V_tcp_do_autorcvbuf && 1861 (to.to_flags & TOF_TS) && 1862 to.to_tsecr && 1863 (so->so_rcv.sb_flags & SB_AUTOSIZE)) { 1864 if (TSTMP_GT(to.to_tsecr, tp->rfbuf_ts) && 1865 to.to_tsecr - tp->rfbuf_ts < hz) { 1866 if (tp->rfbuf_cnt > 1867 (so->so_rcv.sb_hiwat / 8 * 7) && 1868 so->so_rcv.sb_hiwat < 1869 V_tcp_autorcvbuf_max) { 1870 newsize = 1871 min(so->so_rcv.sb_hiwat + 1872 V_tcp_autorcvbuf_inc, 1873 V_tcp_autorcvbuf_max); 1874 } 1875 /* Start over with next RTT. */ 1876 tp->rfbuf_ts = 0; 1877 tp->rfbuf_cnt = 0; 1878 } else 1879 tp->rfbuf_cnt += tlen; /* add up */ 1880 } 1881 1882 /* Add data to socket buffer. */ 1883 SOCKBUF_LOCK(&so->so_rcv); 1884 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) { 1885 m_freem(m); 1886 } else { 1887 /* 1888 * Set new socket buffer size. 1889 * Give up when limit is reached. 1890 */ 1891 if (newsize) 1892 if (!sbreserve_locked(&so->so_rcv, 1893 newsize, so, NULL)) 1894 so->so_rcv.sb_flags &= ~SB_AUTOSIZE; 1895 m_adj(m, drop_hdrlen); /* delayed header drop */ 1896 sbappendstream_locked(&so->so_rcv, m, 0); 1897 } 1898 /* NB: sorwakeup_locked() does an implicit unlock. */ 1899 sorwakeup_locked(so); 1900 if (DELAY_ACK(tp, tlen)) { 1901 tp->t_flags |= TF_DELACK; 1902 } else { 1903 tp->t_flags |= TF_ACKNOW; 1904 tp->t_fb->tfb_tcp_output(tp); 1905 } 1906 goto check_delack; 1907 } 1908 } 1909 1910 /* 1911 * Calculate amount of space in receive window, 1912 * and then do TCP input processing. 1913 * Receive window is amount of space in rcv queue, 1914 * but not less than advertised window. 1915 */ 1916 win = sbspace(&so->so_rcv); 1917 if (win < 0) 1918 win = 0; 1919 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt)); 1920 1921 /* Reset receive buffer auto scaling when not in bulk receive mode. */ 1922 tp->rfbuf_ts = 0; 1923 tp->rfbuf_cnt = 0; 1924 1925 switch (tp->t_state) { 1926 1927 /* 1928 * If the state is SYN_RECEIVED: 1929 * if seg contains an ACK, but not for our SYN/ACK, send a RST. 1930 */ 1931 case TCPS_SYN_RECEIVED: 1932 if ((thflags & TH_ACK) && 1933 (SEQ_LEQ(th->th_ack, tp->snd_una) || 1934 SEQ_GT(th->th_ack, tp->snd_max))) { 1935 rstreason = BANDLIM_RST_OPENPORT; 1936 goto dropwithreset; 1937 } 1938 #ifdef TCP_RFC7413 1939 if (tp->t_flags & TF_FASTOPEN) { 1940 /* 1941 * When a TFO connection is in SYN_RECEIVED, the 1942 * only valid packets are the initial SYN, a 1943 * retransmit/copy of the initial SYN (possibly with 1944 * a subset of the original data), a valid ACK, a 1945 * FIN, or a RST. 1946 */ 1947 if ((thflags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) { 1948 rstreason = BANDLIM_RST_OPENPORT; 1949 goto dropwithreset; 1950 } else if (thflags & TH_SYN) { 1951 /* non-initial SYN is ignored */ 1952 if ((tcp_timer_active(tp, TT_DELACK) || 1953 tcp_timer_active(tp, TT_REXMT))) 1954 goto drop; 1955 } else if (!(thflags & (TH_ACK|TH_FIN|TH_RST))) { 1956 goto drop; 1957 } 1958 } 1959 #endif 1960 break; 1961 1962 /* 1963 * If the state is SYN_SENT: 1964 * if seg contains an ACK, but not for our SYN, drop the input. 1965 * if seg contains a RST, then drop the connection. 1966 * if seg does not contain SYN, then drop it. 1967 * Otherwise this is an acceptable SYN segment 1968 * initialize tp->rcv_nxt and tp->irs 1969 * if seg contains ack then advance tp->snd_una 1970 * if seg contains an ECE and ECN support is enabled, the stream 1971 * is ECN capable. 1972 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state 1973 * arrange for segment to be acked (eventually) 1974 * continue processing rest of data/controls, beginning with URG 1975 */ 1976 case TCPS_SYN_SENT: 1977 if ((thflags & TH_ACK) && 1978 (SEQ_LEQ(th->th_ack, tp->iss) || 1979 SEQ_GT(th->th_ack, tp->snd_max))) { 1980 rstreason = BANDLIM_UNLIMITED; 1981 goto dropwithreset; 1982 } 1983 if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) { 1984 TCP_PROBE5(connect__refused, NULL, tp, 1985 mtod(m, const char *), tp, th); 1986 tp = tcp_drop(tp, ECONNREFUSED); 1987 } 1988 if (thflags & TH_RST) 1989 goto drop; 1990 if (!(thflags & TH_SYN)) 1991 goto drop; 1992 1993 tp->irs = th->th_seq; 1994 tcp_rcvseqinit(tp); 1995 if (thflags & TH_ACK) { 1996 TCPSTAT_INC(tcps_connects); 1997 soisconnected(so); 1998 #ifdef MAC 1999 mac_socketpeer_set_from_mbuf(m, so); 2000 #endif 2001 /* Do window scaling on this connection? */ 2002 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) == 2003 (TF_RCVD_SCALE|TF_REQ_SCALE)) { 2004 tp->rcv_scale = tp->request_r_scale; 2005 } 2006 tp->rcv_adv += imin(tp->rcv_wnd, 2007 TCP_MAXWIN << tp->rcv_scale); 2008 tp->snd_una++; /* SYN is acked */ 2009 /* 2010 * If there's data, delay ACK; if there's also a FIN 2011 * ACKNOW will be turned on later. 2012 */ 2013 if (DELAY_ACK(tp, tlen) && tlen != 0) 2014 tcp_timer_activate(tp, TT_DELACK, 2015 tcp_delacktime); 2016 else 2017 tp->t_flags |= TF_ACKNOW; 2018 2019 if ((thflags & TH_ECE) && V_tcp_do_ecn) { 2020 tp->t_flags |= TF_ECN_PERMIT; 2021 TCPSTAT_INC(tcps_ecn_shs); 2022 } 2023 2024 /* 2025 * Received <SYN,ACK> in SYN_SENT[*] state. 2026 * Transitions: 2027 * SYN_SENT --> ESTABLISHED 2028 * SYN_SENT* --> FIN_WAIT_1 2029 */ 2030 tp->t_starttime = ticks; 2031 if (tp->t_flags & TF_NEEDFIN) { 2032 tcp_state_change(tp, TCPS_FIN_WAIT_1); 2033 tp->t_flags &= ~TF_NEEDFIN; 2034 thflags &= ~TH_SYN; 2035 } else { 2036 tcp_state_change(tp, TCPS_ESTABLISHED); 2037 TCP_PROBE5(connect__established, NULL, tp, 2038 mtod(m, const char *), tp, th); 2039 cc_conn_init(tp); 2040 tcp_timer_activate(tp, TT_KEEP, 2041 TP_KEEPIDLE(tp)); 2042 } 2043 } else { 2044 /* 2045 * Received initial SYN in SYN-SENT[*] state => 2046 * simultaneous open. 2047 * If it succeeds, connection is * half-synchronized. 2048 * Otherwise, do 3-way handshake: 2049 * SYN-SENT -> SYN-RECEIVED 2050 * SYN-SENT* -> SYN-RECEIVED* 2051 */ 2052 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN); 2053 tcp_timer_activate(tp, TT_REXMT, 0); 2054 tcp_state_change(tp, TCPS_SYN_RECEIVED); 2055 } 2056 2057 KASSERT(ti_locked == TI_RLOCKED, ("%s: trimthenstep6: " 2058 "ti_locked %d", __func__, ti_locked)); 2059 INP_INFO_RLOCK_ASSERT(&V_tcbinfo); 2060 INP_WLOCK_ASSERT(tp->t_inpcb); 2061 2062 /* 2063 * Advance th->th_seq to correspond to first data byte. 2064 * If data, trim to stay within window, 2065 * dropping FIN if necessary. 2066 */ 2067 th->th_seq++; 2068 if (tlen > tp->rcv_wnd) { 2069 todrop = tlen - tp->rcv_wnd; 2070 m_adj(m, -todrop); 2071 tlen = tp->rcv_wnd; 2072 thflags &= ~TH_FIN; 2073 TCPSTAT_INC(tcps_rcvpackafterwin); 2074 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop); 2075 } 2076 tp->snd_wl1 = th->th_seq - 1; 2077 tp->rcv_up = th->th_seq; 2078 /* 2079 * Client side of transaction: already sent SYN and data. 2080 * If the remote host used T/TCP to validate the SYN, 2081 * our data will be ACK'd; if so, enter normal data segment 2082 * processing in the middle of step 5, ack processing. 2083 * Otherwise, goto step 6. 2084 */ 2085 if (thflags & TH_ACK) 2086 goto process_ACK; 2087 2088 goto step6; 2089 2090 /* 2091 * If the state is LAST_ACK or CLOSING or TIME_WAIT: 2092 * do normal processing. 2093 * 2094 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later. 2095 */ 2096 case TCPS_LAST_ACK: 2097 case TCPS_CLOSING: 2098 break; /* continue normal processing */ 2099 } 2100 2101 /* 2102 * States other than LISTEN or SYN_SENT. 2103 * First check the RST flag and sequence number since reset segments 2104 * are exempt from the timestamp and connection count tests. This 2105 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix 2106 * below which allowed reset segments in half the sequence space 2107 * to fall though and be processed (which gives forged reset 2108 * segments with a random sequence number a 50 percent chance of 2109 * killing a connection). 2110 * Then check timestamp, if present. 2111 * Then check the connection count, if present. 2112 * Then check that at least some bytes of segment are within 2113 * receive window. If segment begins before rcv_nxt, 2114 * drop leading data (and SYN); if nothing left, just ack. 2115 */ 2116 if (thflags & TH_RST) { 2117 /* 2118 * RFC5961 Section 3.2 2119 * 2120 * - RST drops connection only if SEG.SEQ == RCV.NXT. 2121 * - If RST is in window, we send challenge ACK. 2122 * 2123 * Note: to take into account delayed ACKs, we should 2124 * test against last_ack_sent instead of rcv_nxt. 2125 * Note 2: we handle special case of closed window, not 2126 * covered by the RFC. 2127 */ 2128 if ((SEQ_GEQ(th->th_seq, tp->last_ack_sent) && 2129 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) || 2130 (tp->rcv_wnd == 0 && tp->last_ack_sent == th->th_seq)) { 2131 2132 INP_INFO_RLOCK_ASSERT(&V_tcbinfo); 2133 KASSERT(ti_locked == TI_RLOCKED, 2134 ("%s: TH_RST ti_locked %d, th %p tp %p", 2135 __func__, ti_locked, th, tp)); 2136 KASSERT(tp->t_state != TCPS_SYN_SENT, 2137 ("%s: TH_RST for TCPS_SYN_SENT th %p tp %p", 2138 __func__, th, tp)); 2139 2140 if (V_tcp_insecure_rst || 2141 tp->last_ack_sent == th->th_seq) { 2142 TCPSTAT_INC(tcps_drops); 2143 /* Drop the connection. */ 2144 switch (tp->t_state) { 2145 case TCPS_SYN_RECEIVED: 2146 so->so_error = ECONNREFUSED; 2147 goto close; 2148 case TCPS_ESTABLISHED: 2149 case TCPS_FIN_WAIT_1: 2150 case TCPS_FIN_WAIT_2: 2151 case TCPS_CLOSE_WAIT: 2152 so->so_error = ECONNRESET; 2153 close: 2154 tcp_state_change(tp, TCPS_CLOSED); 2155 /* FALLTHROUGH */ 2156 default: 2157 tp = tcp_close(tp); 2158 } 2159 } else { 2160 TCPSTAT_INC(tcps_badrst); 2161 /* Send challenge ACK. */ 2162 tcp_respond(tp, mtod(m, void *), th, m, 2163 tp->rcv_nxt, tp->snd_nxt, TH_ACK); 2164 tp->last_ack_sent = tp->rcv_nxt; 2165 m = NULL; 2166 } 2167 } 2168 goto drop; 2169 } 2170 2171 /* 2172 * RFC5961 Section 4.2 2173 * Send challenge ACK for any SYN in synchronized state. 2174 */ 2175 if ((thflags & TH_SYN) && tp->t_state != TCPS_SYN_SENT && 2176 tp->t_state != TCPS_SYN_RECEIVED) { 2177 KASSERT(ti_locked == TI_RLOCKED, 2178 ("tcp_do_segment: TH_SYN ti_locked %d", ti_locked)); 2179 INP_INFO_RLOCK_ASSERT(&V_tcbinfo); 2180 2181 TCPSTAT_INC(tcps_badsyn); 2182 if (V_tcp_insecure_syn && 2183 SEQ_GEQ(th->th_seq, tp->last_ack_sent) && 2184 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) { 2185 tp = tcp_drop(tp, ECONNRESET); 2186 rstreason = BANDLIM_UNLIMITED; 2187 } else { 2188 /* Send challenge ACK. */ 2189 tcp_respond(tp, mtod(m, void *), th, m, tp->rcv_nxt, 2190 tp->snd_nxt, TH_ACK); 2191 tp->last_ack_sent = tp->rcv_nxt; 2192 m = NULL; 2193 } 2194 goto drop; 2195 } 2196 2197 /* 2198 * RFC 1323 PAWS: If we have a timestamp reply on this segment 2199 * and it's less than ts_recent, drop it. 2200 */ 2201 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent && 2202 TSTMP_LT(to.to_tsval, tp->ts_recent)) { 2203 2204 /* Check to see if ts_recent is over 24 days old. */ 2205 if (tcp_ts_getticks() - tp->ts_recent_age > TCP_PAWS_IDLE) { 2206 /* 2207 * Invalidate ts_recent. If this segment updates 2208 * ts_recent, the age will be reset later and ts_recent 2209 * will get a valid value. If it does not, setting 2210 * ts_recent to zero will at least satisfy the 2211 * requirement that zero be placed in the timestamp 2212 * echo reply when ts_recent isn't valid. The 2213 * age isn't reset until we get a valid ts_recent 2214 * because we don't want out-of-order segments to be 2215 * dropped when ts_recent is old. 2216 */ 2217 tp->ts_recent = 0; 2218 } else { 2219 TCPSTAT_INC(tcps_rcvduppack); 2220 TCPSTAT_ADD(tcps_rcvdupbyte, tlen); 2221 TCPSTAT_INC(tcps_pawsdrop); 2222 if (tlen) 2223 goto dropafterack; 2224 goto drop; 2225 } 2226 } 2227 2228 /* 2229 * In the SYN-RECEIVED state, validate that the packet belongs to 2230 * this connection before trimming the data to fit the receive 2231 * window. Check the sequence number versus IRS since we know 2232 * the sequence numbers haven't wrapped. This is a partial fix 2233 * for the "LAND" DoS attack. 2234 */ 2235 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) { 2236 rstreason = BANDLIM_RST_OPENPORT; 2237 goto dropwithreset; 2238 } 2239 2240 todrop = tp->rcv_nxt - th->th_seq; 2241 if (todrop > 0) { 2242 if (thflags & TH_SYN) { 2243 thflags &= ~TH_SYN; 2244 th->th_seq++; 2245 if (th->th_urp > 1) 2246 th->th_urp--; 2247 else 2248 thflags &= ~TH_URG; 2249 todrop--; 2250 } 2251 /* 2252 * Following if statement from Stevens, vol. 2, p. 960. 2253 */ 2254 if (todrop > tlen 2255 || (todrop == tlen && (thflags & TH_FIN) == 0)) { 2256 /* 2257 * Any valid FIN must be to the left of the window. 2258 * At this point the FIN must be a duplicate or out 2259 * of sequence; drop it. 2260 */ 2261 thflags &= ~TH_FIN; 2262 2263 /* 2264 * Send an ACK to resynchronize and drop any data. 2265 * But keep on processing for RST or ACK. 2266 */ 2267 tp->t_flags |= TF_ACKNOW; 2268 todrop = tlen; 2269 TCPSTAT_INC(tcps_rcvduppack); 2270 TCPSTAT_ADD(tcps_rcvdupbyte, todrop); 2271 } else { 2272 TCPSTAT_INC(tcps_rcvpartduppack); 2273 TCPSTAT_ADD(tcps_rcvpartdupbyte, todrop); 2274 } 2275 drop_hdrlen += todrop; /* drop from the top afterwards */ 2276 th->th_seq += todrop; 2277 tlen -= todrop; 2278 if (th->th_urp > todrop) 2279 th->th_urp -= todrop; 2280 else { 2281 thflags &= ~TH_URG; 2282 th->th_urp = 0; 2283 } 2284 } 2285 2286 /* 2287 * If new data are received on a connection after the 2288 * user processes are gone, then RST the other end. 2289 */ 2290 if ((so->so_state & SS_NOFDREF) && 2291 tp->t_state > TCPS_CLOSE_WAIT && tlen) { 2292 KASSERT(ti_locked == TI_RLOCKED, ("%s: SS_NOFDEREF && " 2293 "CLOSE_WAIT && tlen ti_locked %d", __func__, ti_locked)); 2294 INP_INFO_RLOCK_ASSERT(&V_tcbinfo); 2295 2296 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) { 2297 log(LOG_DEBUG, "%s; %s: %s: Received %d bytes of data " 2298 "after socket was closed, " 2299 "sending RST and removing tcpcb\n", 2300 s, __func__, tcpstates[tp->t_state], tlen); 2301 free(s, M_TCPLOG); 2302 } 2303 tp = tcp_close(tp); 2304 TCPSTAT_INC(tcps_rcvafterclose); 2305 rstreason = BANDLIM_UNLIMITED; 2306 goto dropwithreset; 2307 } 2308 2309 /* 2310 * If segment ends after window, drop trailing data 2311 * (and PUSH and FIN); if nothing left, just ACK. 2312 */ 2313 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd); 2314 if (todrop > 0) { 2315 TCPSTAT_INC(tcps_rcvpackafterwin); 2316 if (todrop >= tlen) { 2317 TCPSTAT_ADD(tcps_rcvbyteafterwin, tlen); 2318 /* 2319 * If window is closed can only take segments at 2320 * window edge, and have to drop data and PUSH from 2321 * incoming segments. Continue processing, but 2322 * remember to ack. Otherwise, drop segment 2323 * and ack. 2324 */ 2325 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) { 2326 tp->t_flags |= TF_ACKNOW; 2327 TCPSTAT_INC(tcps_rcvwinprobe); 2328 } else 2329 goto dropafterack; 2330 } else 2331 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop); 2332 m_adj(m, -todrop); 2333 tlen -= todrop; 2334 thflags &= ~(TH_PUSH|TH_FIN); 2335 } 2336 2337 /* 2338 * If last ACK falls within this segment's sequence numbers, 2339 * record its timestamp. 2340 * NOTE: 2341 * 1) That the test incorporates suggestions from the latest 2342 * proposal of the tcplw@cray.com list (Braden 1993/04/26). 2343 * 2) That updating only on newer timestamps interferes with 2344 * our earlier PAWS tests, so this check should be solely 2345 * predicated on the sequence space of this segment. 2346 * 3) That we modify the segment boundary check to be 2347 * Last.ACK.Sent <= SEG.SEQ + SEG.Len 2348 * instead of RFC1323's 2349 * Last.ACK.Sent < SEG.SEQ + SEG.Len, 2350 * This modified check allows us to overcome RFC1323's 2351 * limitations as described in Stevens TCP/IP Illustrated 2352 * Vol. 2 p.869. In such cases, we can still calculate the 2353 * RTT correctly when RCV.NXT == Last.ACK.Sent. 2354 */ 2355 if ((to.to_flags & TOF_TS) != 0 && 2356 SEQ_LEQ(th->th_seq, tp->last_ack_sent) && 2357 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen + 2358 ((thflags & (TH_SYN|TH_FIN)) != 0))) { 2359 tp->ts_recent_age = tcp_ts_getticks(); 2360 tp->ts_recent = to.to_tsval; 2361 } 2362 2363 /* 2364 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN 2365 * flag is on (half-synchronized state), then queue data for 2366 * later processing; else drop segment and return. 2367 */ 2368 if ((thflags & TH_ACK) == 0) { 2369 if (tp->t_state == TCPS_SYN_RECEIVED || 2370 (tp->t_flags & TF_NEEDSYN)) { 2371 #ifdef TCP_RFC7413 2372 if (tp->t_state == TCPS_SYN_RECEIVED && 2373 tp->t_flags & TF_FASTOPEN) { 2374 tp->snd_wnd = tiwin; 2375 cc_conn_init(tp); 2376 } 2377 #endif 2378 goto step6; 2379 } else if (tp->t_flags & TF_ACKNOW) 2380 goto dropafterack; 2381 else 2382 goto drop; 2383 } 2384 2385 /* 2386 * Ack processing. 2387 */ 2388 switch (tp->t_state) { 2389 2390 /* 2391 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter 2392 * ESTABLISHED state and continue processing. 2393 * The ACK was checked above. 2394 */ 2395 case TCPS_SYN_RECEIVED: 2396 2397 TCPSTAT_INC(tcps_connects); 2398 soisconnected(so); 2399 /* Do window scaling? */ 2400 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) == 2401 (TF_RCVD_SCALE|TF_REQ_SCALE)) { 2402 tp->rcv_scale = tp->request_r_scale; 2403 tp->snd_wnd = tiwin; 2404 } 2405 /* 2406 * Make transitions: 2407 * SYN-RECEIVED -> ESTABLISHED 2408 * SYN-RECEIVED* -> FIN-WAIT-1 2409 */ 2410 tp->t_starttime = ticks; 2411 if (tp->t_flags & TF_NEEDFIN) { 2412 tcp_state_change(tp, TCPS_FIN_WAIT_1); 2413 tp->t_flags &= ~TF_NEEDFIN; 2414 } else { 2415 tcp_state_change(tp, TCPS_ESTABLISHED); 2416 TCP_PROBE5(accept__established, NULL, tp, 2417 mtod(m, const char *), tp, th); 2418 #ifdef TCP_RFC7413 2419 if (tp->t_tfo_pending) { 2420 tcp_fastopen_decrement_counter(tp->t_tfo_pending); 2421 tp->t_tfo_pending = NULL; 2422 2423 /* 2424 * Account for the ACK of our SYN prior to 2425 * regular ACK processing below. 2426 */ 2427 tp->snd_una++; 2428 } 2429 /* 2430 * TFO connections call cc_conn_init() during SYN 2431 * processing. Calling it again here for such 2432 * connections is not harmless as it would undo the 2433 * snd_cwnd reduction that occurs when a TFO SYN|ACK 2434 * is retransmitted. 2435 */ 2436 if (!(tp->t_flags & TF_FASTOPEN)) 2437 #endif 2438 cc_conn_init(tp); 2439 tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp)); 2440 } 2441 /* 2442 * If segment contains data or ACK, will call tcp_reass() 2443 * later; if not, do so now to pass queued data to user. 2444 */ 2445 if (tlen == 0 && (thflags & TH_FIN) == 0) 2446 (void) tcp_reass(tp, (struct tcphdr *)0, 0, 2447 (struct mbuf *)0); 2448 tp->snd_wl1 = th->th_seq - 1; 2449 /* FALLTHROUGH */ 2450 2451 /* 2452 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range 2453 * ACKs. If the ack is in the range 2454 * tp->snd_una < th->th_ack <= tp->snd_max 2455 * then advance tp->snd_una to th->th_ack and drop 2456 * data from the retransmission queue. If this ACK reflects 2457 * more up to date window information we update our window information. 2458 */ 2459 case TCPS_ESTABLISHED: 2460 case TCPS_FIN_WAIT_1: 2461 case TCPS_FIN_WAIT_2: 2462 case TCPS_CLOSE_WAIT: 2463 case TCPS_CLOSING: 2464 case TCPS_LAST_ACK: 2465 if (SEQ_GT(th->th_ack, tp->snd_max)) { 2466 TCPSTAT_INC(tcps_rcvacktoomuch); 2467 goto dropafterack; 2468 } 2469 if ((tp->t_flags & TF_SACK_PERMIT) && 2470 ((to.to_flags & TOF_SACK) || 2471 !TAILQ_EMPTY(&tp->snd_holes))) 2472 sack_changed = tcp_sack_doack(tp, &to, th->th_ack); 2473 else 2474 /* 2475 * Reset the value so that previous (valid) value 2476 * from the last ack with SACK doesn't get used. 2477 */ 2478 tp->sackhint.sacked_bytes = 0; 2479 2480 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */ 2481 hhook_run_tcp_est_in(tp, th, &to); 2482 2483 if (SEQ_LEQ(th->th_ack, tp->snd_una)) { 2484 if (tlen == 0 && 2485 (tiwin == tp->snd_wnd || 2486 (tp->t_flags & TF_SACK_PERMIT))) { 2487 /* 2488 * If this is the first time we've seen a 2489 * FIN from the remote, this is not a 2490 * duplicate and it needs to be processed 2491 * normally. This happens during a 2492 * simultaneous close. 2493 */ 2494 if ((thflags & TH_FIN) && 2495 (TCPS_HAVERCVDFIN(tp->t_state) == 0)) { 2496 tp->t_dupacks = 0; 2497 break; 2498 } 2499 TCPSTAT_INC(tcps_rcvdupack); 2500 /* 2501 * If we have outstanding data (other than 2502 * a window probe), this is a completely 2503 * duplicate ack (ie, window info didn't 2504 * change and FIN isn't set), 2505 * the ack is the biggest we've 2506 * seen and we've seen exactly our rexmt 2507 * threshhold of them, assume a packet 2508 * has been dropped and retransmit it. 2509 * Kludge snd_nxt & the congestion 2510 * window so we send only this one 2511 * packet. 2512 * 2513 * We know we're losing at the current 2514 * window size so do congestion avoidance 2515 * (set ssthresh to half the current window 2516 * and pull our congestion window back to 2517 * the new ssthresh). 2518 * 2519 * Dup acks mean that packets have left the 2520 * network (they're now cached at the receiver) 2521 * so bump cwnd by the amount in the receiver 2522 * to keep a constant cwnd packets in the 2523 * network. 2524 * 2525 * When using TCP ECN, notify the peer that 2526 * we reduced the cwnd. 2527 */ 2528 /* 2529 * Following 2 kinds of acks should not affect 2530 * dupack counting: 2531 * 1) Old acks 2532 * 2) Acks with SACK but without any new SACK 2533 * information in them. These could result from 2534 * any anomaly in the network like a switch 2535 * duplicating packets or a possible DoS attack. 2536 */ 2537 if (th->th_ack != tp->snd_una || 2538 ((tp->t_flags & TF_SACK_PERMIT) && 2539 !sack_changed)) 2540 break; 2541 else if (!tcp_timer_active(tp, TT_REXMT)) 2542 tp->t_dupacks = 0; 2543 else if (++tp->t_dupacks > tcprexmtthresh || 2544 IN_FASTRECOVERY(tp->t_flags)) { 2545 cc_ack_received(tp, th, CC_DUPACK); 2546 if ((tp->t_flags & TF_SACK_PERMIT) && 2547 IN_FASTRECOVERY(tp->t_flags)) { 2548 int awnd; 2549 2550 /* 2551 * Compute the amount of data in flight first. 2552 * We can inject new data into the pipe iff 2553 * we have less than 1/2 the original window's 2554 * worth of data in flight. 2555 */ 2556 if (V_tcp_do_rfc6675_pipe) 2557 awnd = tcp_compute_pipe(tp); 2558 else 2559 awnd = (tp->snd_nxt - tp->snd_fack) + 2560 tp->sackhint.sack_bytes_rexmit; 2561 2562 if (awnd < tp->snd_ssthresh) { 2563 tp->snd_cwnd += tp->t_maxseg; 2564 if (tp->snd_cwnd > tp->snd_ssthresh) 2565 tp->snd_cwnd = tp->snd_ssthresh; 2566 } 2567 } else 2568 tp->snd_cwnd += tp->t_maxseg; 2569 (void) tp->t_fb->tfb_tcp_output(tp); 2570 goto drop; 2571 } else if (tp->t_dupacks == tcprexmtthresh) { 2572 tcp_seq onxt = tp->snd_nxt; 2573 2574 /* 2575 * If we're doing sack, check to 2576 * see if we're already in sack 2577 * recovery. If we're not doing sack, 2578 * check to see if we're in newreno 2579 * recovery. 2580 */ 2581 if (tp->t_flags & TF_SACK_PERMIT) { 2582 if (IN_FASTRECOVERY(tp->t_flags)) { 2583 tp->t_dupacks = 0; 2584 break; 2585 } 2586 } else { 2587 if (SEQ_LEQ(th->th_ack, 2588 tp->snd_recover)) { 2589 tp->t_dupacks = 0; 2590 break; 2591 } 2592 } 2593 /* Congestion signal before ack. */ 2594 cc_cong_signal(tp, th, CC_NDUPACK); 2595 cc_ack_received(tp, th, CC_DUPACK); 2596 tcp_timer_activate(tp, TT_REXMT, 0); 2597 tp->t_rtttime = 0; 2598 if (tp->t_flags & TF_SACK_PERMIT) { 2599 TCPSTAT_INC( 2600 tcps_sack_recovery_episode); 2601 tp->sack_newdata = tp->snd_nxt; 2602 tp->snd_cwnd = tp->t_maxseg; 2603 (void) tp->t_fb->tfb_tcp_output(tp); 2604 goto drop; 2605 } 2606 tp->snd_nxt = th->th_ack; 2607 tp->snd_cwnd = tp->t_maxseg; 2608 (void) tp->t_fb->tfb_tcp_output(tp); 2609 KASSERT(tp->snd_limited <= 2, 2610 ("%s: tp->snd_limited too big", 2611 __func__)); 2612 tp->snd_cwnd = tp->snd_ssthresh + 2613 tp->t_maxseg * 2614 (tp->t_dupacks - tp->snd_limited); 2615 if (SEQ_GT(onxt, tp->snd_nxt)) 2616 tp->snd_nxt = onxt; 2617 goto drop; 2618 } else if (V_tcp_do_rfc3042) { 2619 /* 2620 * Process first and second duplicate 2621 * ACKs. Each indicates a segment 2622 * leaving the network, creating room 2623 * for more. Make sure we can send a 2624 * packet on reception of each duplicate 2625 * ACK by increasing snd_cwnd by one 2626 * segment. Restore the original 2627 * snd_cwnd after packet transmission. 2628 */ 2629 cc_ack_received(tp, th, CC_DUPACK); 2630 u_long oldcwnd = tp->snd_cwnd; 2631 tcp_seq oldsndmax = tp->snd_max; 2632 u_int sent; 2633 int avail; 2634 2635 KASSERT(tp->t_dupacks == 1 || 2636 tp->t_dupacks == 2, 2637 ("%s: dupacks not 1 or 2", 2638 __func__)); 2639 if (tp->t_dupacks == 1) 2640 tp->snd_limited = 0; 2641 tp->snd_cwnd = 2642 (tp->snd_nxt - tp->snd_una) + 2643 (tp->t_dupacks - tp->snd_limited) * 2644 tp->t_maxseg; 2645 /* 2646 * Only call tcp_output when there 2647 * is new data available to be sent. 2648 * Otherwise we would send pure ACKs. 2649 */ 2650 SOCKBUF_LOCK(&so->so_snd); 2651 avail = sbavail(&so->so_snd) - 2652 (tp->snd_nxt - tp->snd_una); 2653 SOCKBUF_UNLOCK(&so->so_snd); 2654 if (avail > 0) 2655 (void) tp->t_fb->tfb_tcp_output(tp); 2656 sent = tp->snd_max - oldsndmax; 2657 if (sent > tp->t_maxseg) { 2658 KASSERT((tp->t_dupacks == 2 && 2659 tp->snd_limited == 0) || 2660 (sent == tp->t_maxseg + 1 && 2661 tp->t_flags & TF_SENTFIN), 2662 ("%s: sent too much", 2663 __func__)); 2664 tp->snd_limited = 2; 2665 } else if (sent > 0) 2666 ++tp->snd_limited; 2667 tp->snd_cwnd = oldcwnd; 2668 goto drop; 2669 } 2670 } 2671 break; 2672 } else { 2673 /* 2674 * This ack is advancing the left edge, reset the 2675 * counter. 2676 */ 2677 tp->t_dupacks = 0; 2678 /* 2679 * If this ack also has new SACK info, increment the 2680 * counter as per rfc6675. 2681 */ 2682 if ((tp->t_flags & TF_SACK_PERMIT) && sack_changed) 2683 tp->t_dupacks++; 2684 } 2685 2686 KASSERT(SEQ_GT(th->th_ack, tp->snd_una), 2687 ("%s: th_ack <= snd_una", __func__)); 2688 2689 /* 2690 * If the congestion window was inflated to account 2691 * for the other side's cached packets, retract it. 2692 */ 2693 if (IN_FASTRECOVERY(tp->t_flags)) { 2694 if (SEQ_LT(th->th_ack, tp->snd_recover)) { 2695 if (tp->t_flags & TF_SACK_PERMIT) 2696 tcp_sack_partialack(tp, th); 2697 else 2698 tcp_newreno_partial_ack(tp, th); 2699 } else 2700 cc_post_recovery(tp, th); 2701 } 2702 /* 2703 * If we reach this point, ACK is not a duplicate, 2704 * i.e., it ACKs something we sent. 2705 */ 2706 if (tp->t_flags & TF_NEEDSYN) { 2707 /* 2708 * T/TCP: Connection was half-synchronized, and our 2709 * SYN has been ACK'd (so connection is now fully 2710 * synchronized). Go to non-starred state, 2711 * increment snd_una for ACK of SYN, and check if 2712 * we can do window scaling. 2713 */ 2714 tp->t_flags &= ~TF_NEEDSYN; 2715 tp->snd_una++; 2716 /* Do window scaling? */ 2717 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) == 2718 (TF_RCVD_SCALE|TF_REQ_SCALE)) { 2719 tp->rcv_scale = tp->request_r_scale; 2720 /* Send window already scaled. */ 2721 } 2722 } 2723 2724 process_ACK: 2725 INP_WLOCK_ASSERT(tp->t_inpcb); 2726 2727 acked = BYTES_THIS_ACK(tp, th); 2728 TCPSTAT_INC(tcps_rcvackpack); 2729 TCPSTAT_ADD(tcps_rcvackbyte, acked); 2730 2731 /* 2732 * If we just performed our first retransmit, and the ACK 2733 * arrives within our recovery window, then it was a mistake 2734 * to do the retransmit in the first place. Recover our 2735 * original cwnd and ssthresh, and proceed to transmit where 2736 * we left off. 2737 */ 2738 if (tp->t_rxtshift == 1 && tp->t_flags & TF_PREVVALID && 2739 (int)(ticks - tp->t_badrxtwin) < 0) 2740 cc_cong_signal(tp, th, CC_RTO_ERR); 2741 2742 /* 2743 * If we have a timestamp reply, update smoothed 2744 * round trip time. If no timestamp is present but 2745 * transmit timer is running and timed sequence 2746 * number was acked, update smoothed round trip time. 2747 * Since we now have an rtt measurement, cancel the 2748 * timer backoff (cf., Phil Karn's retransmit alg.). 2749 * Recompute the initial retransmit timer. 2750 * 2751 * Some boxes send broken timestamp replies 2752 * during the SYN+ACK phase, ignore 2753 * timestamps of 0 or we could calculate a 2754 * huge RTT and blow up the retransmit timer. 2755 */ 2756 if ((to.to_flags & TOF_TS) != 0 && to.to_tsecr) { 2757 u_int t; 2758 2759 t = tcp_ts_getticks() - to.to_tsecr; 2760 if (!tp->t_rttlow || tp->t_rttlow > t) 2761 tp->t_rttlow = t; 2762 tcp_xmit_timer(tp, TCP_TS_TO_TICKS(t) + 1); 2763 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) { 2764 if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime) 2765 tp->t_rttlow = ticks - tp->t_rtttime; 2766 tcp_xmit_timer(tp, ticks - tp->t_rtttime); 2767 } 2768 2769 /* 2770 * If all outstanding data is acked, stop retransmit 2771 * timer and remember to restart (more output or persist). 2772 * If there is more data to be acked, restart retransmit 2773 * timer, using current (possibly backed-off) value. 2774 */ 2775 if (th->th_ack == tp->snd_max) { 2776 tcp_timer_activate(tp, TT_REXMT, 0); 2777 needoutput = 1; 2778 } else if (!tcp_timer_active(tp, TT_PERSIST)) 2779 tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur); 2780 2781 /* 2782 * If no data (only SYN) was ACK'd, 2783 * skip rest of ACK processing. 2784 */ 2785 if (acked == 0) 2786 goto step6; 2787 2788 /* 2789 * Let the congestion control algorithm update congestion 2790 * control related information. This typically means increasing 2791 * the congestion window. 2792 */ 2793 cc_ack_received(tp, th, CC_ACK); 2794 2795 SOCKBUF_LOCK(&so->so_snd); 2796 if (acked > sbavail(&so->so_snd)) { 2797 tp->snd_wnd -= sbavail(&so->so_snd); 2798 mfree = sbcut_locked(&so->so_snd, 2799 (int)sbavail(&so->so_snd)); 2800 ourfinisacked = 1; 2801 } else { 2802 mfree = sbcut_locked(&so->so_snd, acked); 2803 tp->snd_wnd -= acked; 2804 ourfinisacked = 0; 2805 } 2806 /* NB: sowwakeup_locked() does an implicit unlock. */ 2807 sowwakeup_locked(so); 2808 m_freem(mfree); 2809 /* Detect una wraparound. */ 2810 if (!IN_RECOVERY(tp->t_flags) && 2811 SEQ_GT(tp->snd_una, tp->snd_recover) && 2812 SEQ_LEQ(th->th_ack, tp->snd_recover)) 2813 tp->snd_recover = th->th_ack - 1; 2814 /* XXXLAS: Can this be moved up into cc_post_recovery? */ 2815 if (IN_RECOVERY(tp->t_flags) && 2816 SEQ_GEQ(th->th_ack, tp->snd_recover)) { 2817 EXIT_RECOVERY(tp->t_flags); 2818 } 2819 tp->snd_una = th->th_ack; 2820 if (tp->t_flags & TF_SACK_PERMIT) { 2821 if (SEQ_GT(tp->snd_una, tp->snd_recover)) 2822 tp->snd_recover = tp->snd_una; 2823 } 2824 if (SEQ_LT(tp->snd_nxt, tp->snd_una)) 2825 tp->snd_nxt = tp->snd_una; 2826 2827 switch (tp->t_state) { 2828 2829 /* 2830 * In FIN_WAIT_1 STATE in addition to the processing 2831 * for the ESTABLISHED state if our FIN is now acknowledged 2832 * then enter FIN_WAIT_2. 2833 */ 2834 case TCPS_FIN_WAIT_1: 2835 if (ourfinisacked) { 2836 /* 2837 * If we can't receive any more 2838 * data, then closing user can proceed. 2839 * Starting the timer is contrary to the 2840 * specification, but if we don't get a FIN 2841 * we'll hang forever. 2842 * 2843 * XXXjl: 2844 * we should release the tp also, and use a 2845 * compressed state. 2846 */ 2847 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) { 2848 soisdisconnected(so); 2849 tcp_timer_activate(tp, TT_2MSL, 2850 (tcp_fast_finwait2_recycle ? 2851 tcp_finwait2_timeout : 2852 TP_MAXIDLE(tp))); 2853 } 2854 tcp_state_change(tp, TCPS_FIN_WAIT_2); 2855 } 2856 break; 2857 2858 /* 2859 * In CLOSING STATE in addition to the processing for 2860 * the ESTABLISHED state if the ACK acknowledges our FIN 2861 * then enter the TIME-WAIT state, otherwise ignore 2862 * the segment. 2863 */ 2864 case TCPS_CLOSING: 2865 if (ourfinisacked) { 2866 INP_INFO_RLOCK_ASSERT(&V_tcbinfo); 2867 tcp_twstart(tp); 2868 INP_INFO_RUNLOCK(&V_tcbinfo); 2869 m_freem(m); 2870 return; 2871 } 2872 break; 2873 2874 /* 2875 * In LAST_ACK, we may still be waiting for data to drain 2876 * and/or to be acked, as well as for the ack of our FIN. 2877 * If our FIN is now acknowledged, delete the TCB, 2878 * enter the closed state and return. 2879 */ 2880 case TCPS_LAST_ACK: 2881 if (ourfinisacked) { 2882 INP_INFO_RLOCK_ASSERT(&V_tcbinfo); 2883 tp = tcp_close(tp); 2884 goto drop; 2885 } 2886 break; 2887 } 2888 } 2889 2890 step6: 2891 INP_WLOCK_ASSERT(tp->t_inpcb); 2892 2893 /* 2894 * Update window information. 2895 * Don't look at window if no ACK: TAC's send garbage on first SYN. 2896 */ 2897 if ((thflags & TH_ACK) && 2898 (SEQ_LT(tp->snd_wl1, th->th_seq) || 2899 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) || 2900 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) { 2901 /* keep track of pure window updates */ 2902 if (tlen == 0 && 2903 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd) 2904 TCPSTAT_INC(tcps_rcvwinupd); 2905 tp->snd_wnd = tiwin; 2906 tp->snd_wl1 = th->th_seq; 2907 tp->snd_wl2 = th->th_ack; 2908 if (tp->snd_wnd > tp->max_sndwnd) 2909 tp->max_sndwnd = tp->snd_wnd; 2910 needoutput = 1; 2911 } 2912 2913 /* 2914 * Process segments with URG. 2915 */ 2916 if ((thflags & TH_URG) && th->th_urp && 2917 TCPS_HAVERCVDFIN(tp->t_state) == 0) { 2918 /* 2919 * This is a kludge, but if we receive and accept 2920 * random urgent pointers, we'll crash in 2921 * soreceive. It's hard to imagine someone 2922 * actually wanting to send this much urgent data. 2923 */ 2924 SOCKBUF_LOCK(&so->so_rcv); 2925 if (th->th_urp + sbavail(&so->so_rcv) > sb_max) { 2926 th->th_urp = 0; /* XXX */ 2927 thflags &= ~TH_URG; /* XXX */ 2928 SOCKBUF_UNLOCK(&so->so_rcv); /* XXX */ 2929 goto dodata; /* XXX */ 2930 } 2931 /* 2932 * If this segment advances the known urgent pointer, 2933 * then mark the data stream. This should not happen 2934 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since 2935 * a FIN has been received from the remote side. 2936 * In these states we ignore the URG. 2937 * 2938 * According to RFC961 (Assigned Protocols), 2939 * the urgent pointer points to the last octet 2940 * of urgent data. We continue, however, 2941 * to consider it to indicate the first octet 2942 * of data past the urgent section as the original 2943 * spec states (in one of two places). 2944 */ 2945 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) { 2946 tp->rcv_up = th->th_seq + th->th_urp; 2947 so->so_oobmark = sbavail(&so->so_rcv) + 2948 (tp->rcv_up - tp->rcv_nxt) - 1; 2949 if (so->so_oobmark == 0) 2950 so->so_rcv.sb_state |= SBS_RCVATMARK; 2951 sohasoutofband(so); 2952 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA); 2953 } 2954 SOCKBUF_UNLOCK(&so->so_rcv); 2955 /* 2956 * Remove out of band data so doesn't get presented to user. 2957 * This can happen independent of advancing the URG pointer, 2958 * but if two URG's are pending at once, some out-of-band 2959 * data may creep in... ick. 2960 */ 2961 if (th->th_urp <= (u_long)tlen && 2962 !(so->so_options & SO_OOBINLINE)) { 2963 /* hdr drop is delayed */ 2964 tcp_pulloutofband(so, th, m, drop_hdrlen); 2965 } 2966 } else { 2967 /* 2968 * If no out of band data is expected, 2969 * pull receive urgent pointer along 2970 * with the receive window. 2971 */ 2972 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up)) 2973 tp->rcv_up = tp->rcv_nxt; 2974 } 2975 dodata: /* XXX */ 2976 INP_WLOCK_ASSERT(tp->t_inpcb); 2977 2978 /* 2979 * Process the segment text, merging it into the TCP sequencing queue, 2980 * and arranging for acknowledgment of receipt if necessary. 2981 * This process logically involves adjusting tp->rcv_wnd as data 2982 * is presented to the user (this happens in tcp_usrreq.c, 2983 * case PRU_RCVD). If a FIN has already been received on this 2984 * connection then we just ignore the text. 2985 */ 2986 tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) && 2987 (tp->t_flags & TF_FASTOPEN)); 2988 if ((tlen || (thflags & TH_FIN) || tfo_syn) && 2989 TCPS_HAVERCVDFIN(tp->t_state) == 0) { 2990 tcp_seq save_start = th->th_seq; 2991 m_adj(m, drop_hdrlen); /* delayed header drop */ 2992 /* 2993 * Insert segment which includes th into TCP reassembly queue 2994 * with control block tp. Set thflags to whether reassembly now 2995 * includes a segment with FIN. This handles the common case 2996 * inline (segment is the next to be received on an established 2997 * connection, and the queue is empty), avoiding linkage into 2998 * and removal from the queue and repetition of various 2999 * conversions. 3000 * Set DELACK for segments received in order, but ack 3001 * immediately when segments are out of order (so 3002 * fast retransmit can work). 3003 */ 3004 if (th->th_seq == tp->rcv_nxt && 3005 LIST_EMPTY(&tp->t_segq) && 3006 (TCPS_HAVEESTABLISHED(tp->t_state) || 3007 tfo_syn)) { 3008 if (DELAY_ACK(tp, tlen) || tfo_syn) 3009 tp->t_flags |= TF_DELACK; 3010 else 3011 tp->t_flags |= TF_ACKNOW; 3012 tp->rcv_nxt += tlen; 3013 thflags = th->th_flags & TH_FIN; 3014 TCPSTAT_INC(tcps_rcvpack); 3015 TCPSTAT_ADD(tcps_rcvbyte, tlen); 3016 SOCKBUF_LOCK(&so->so_rcv); 3017 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) 3018 m_freem(m); 3019 else 3020 sbappendstream_locked(&so->so_rcv, m, 0); 3021 /* NB: sorwakeup_locked() does an implicit unlock. */ 3022 sorwakeup_locked(so); 3023 } else { 3024 /* 3025 * XXX: Due to the header drop above "th" is 3026 * theoretically invalid by now. Fortunately 3027 * m_adj() doesn't actually frees any mbufs 3028 * when trimming from the head. 3029 */ 3030 thflags = tcp_reass(tp, th, &tlen, m); 3031 tp->t_flags |= TF_ACKNOW; 3032 } 3033 if (tlen > 0 && (tp->t_flags & TF_SACK_PERMIT)) 3034 tcp_update_sack_list(tp, save_start, save_start + tlen); 3035 #if 0 3036 /* 3037 * Note the amount of data that peer has sent into 3038 * our window, in order to estimate the sender's 3039 * buffer size. 3040 * XXX: Unused. 3041 */ 3042 if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt)) 3043 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt); 3044 else 3045 len = so->so_rcv.sb_hiwat; 3046 #endif 3047 } else { 3048 m_freem(m); 3049 thflags &= ~TH_FIN; 3050 } 3051 3052 /* 3053 * If FIN is received ACK the FIN and let the user know 3054 * that the connection is closing. 3055 */ 3056 if (thflags & TH_FIN) { 3057 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) { 3058 socantrcvmore(so); 3059 /* 3060 * If connection is half-synchronized 3061 * (ie NEEDSYN flag on) then delay ACK, 3062 * so it may be piggybacked when SYN is sent. 3063 * Otherwise, since we received a FIN then no 3064 * more input can be expected, send ACK now. 3065 */ 3066 if (tp->t_flags & TF_NEEDSYN) 3067 tp->t_flags |= TF_DELACK; 3068 else 3069 tp->t_flags |= TF_ACKNOW; 3070 tp->rcv_nxt++; 3071 } 3072 switch (tp->t_state) { 3073 3074 /* 3075 * In SYN_RECEIVED and ESTABLISHED STATES 3076 * enter the CLOSE_WAIT state. 3077 */ 3078 case TCPS_SYN_RECEIVED: 3079 tp->t_starttime = ticks; 3080 /* FALLTHROUGH */ 3081 case TCPS_ESTABLISHED: 3082 tcp_state_change(tp, TCPS_CLOSE_WAIT); 3083 break; 3084 3085 /* 3086 * If still in FIN_WAIT_1 STATE FIN has not been acked so 3087 * enter the CLOSING state. 3088 */ 3089 case TCPS_FIN_WAIT_1: 3090 tcp_state_change(tp, TCPS_CLOSING); 3091 break; 3092 3093 /* 3094 * In FIN_WAIT_2 state enter the TIME_WAIT state, 3095 * starting the time-wait timer, turning off the other 3096 * standard timers. 3097 */ 3098 case TCPS_FIN_WAIT_2: 3099 INP_INFO_RLOCK_ASSERT(&V_tcbinfo); 3100 KASSERT(ti_locked == TI_RLOCKED, ("%s: dodata " 3101 "TCP_FIN_WAIT_2 ti_locked: %d", __func__, 3102 ti_locked)); 3103 3104 tcp_twstart(tp); 3105 INP_INFO_RUNLOCK(&V_tcbinfo); 3106 return; 3107 } 3108 } 3109 if (ti_locked == TI_RLOCKED) 3110 INP_INFO_RUNLOCK(&V_tcbinfo); 3111 ti_locked = TI_UNLOCKED; 3112 3113 #ifdef TCPDEBUG 3114 if (so->so_options & SO_DEBUG) 3115 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen, 3116 &tcp_savetcp, 0); 3117 #endif 3118 TCP_PROBE3(debug__input, tp, th, mtod(m, const char *)); 3119 3120 /* 3121 * Return any desired output. 3122 */ 3123 if (needoutput || (tp->t_flags & TF_ACKNOW)) 3124 (void) tp->t_fb->tfb_tcp_output(tp); 3125 3126 check_delack: 3127 KASSERT(ti_locked == TI_UNLOCKED, ("%s: check_delack ti_locked %d", 3128 __func__, ti_locked)); 3129 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo); 3130 INP_WLOCK_ASSERT(tp->t_inpcb); 3131 3132 if (tp->t_flags & TF_DELACK) { 3133 tp->t_flags &= ~TF_DELACK; 3134 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime); 3135 } 3136 INP_WUNLOCK(tp->t_inpcb); 3137 return; 3138 3139 dropafterack: 3140 /* 3141 * Generate an ACK dropping incoming segment if it occupies 3142 * sequence space, where the ACK reflects our state. 3143 * 3144 * We can now skip the test for the RST flag since all 3145 * paths to this code happen after packets containing 3146 * RST have been dropped. 3147 * 3148 * In the SYN-RECEIVED state, don't send an ACK unless the 3149 * segment we received passes the SYN-RECEIVED ACK test. 3150 * If it fails send a RST. This breaks the loop in the 3151 * "LAND" DoS attack, and also prevents an ACK storm 3152 * between two listening ports that have been sent forged 3153 * SYN segments, each with the source address of the other. 3154 */ 3155 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) && 3156 (SEQ_GT(tp->snd_una, th->th_ack) || 3157 SEQ_GT(th->th_ack, tp->snd_max)) ) { 3158 rstreason = BANDLIM_RST_OPENPORT; 3159 goto dropwithreset; 3160 } 3161 #ifdef TCPDEBUG 3162 if (so->so_options & SO_DEBUG) 3163 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen, 3164 &tcp_savetcp, 0); 3165 #endif 3166 TCP_PROBE3(debug__input, tp, th, mtod(m, const char *)); 3167 if (ti_locked == TI_RLOCKED) 3168 INP_INFO_RUNLOCK(&V_tcbinfo); 3169 ti_locked = TI_UNLOCKED; 3170 3171 tp->t_flags |= TF_ACKNOW; 3172 (void) tp->t_fb->tfb_tcp_output(tp); 3173 INP_WUNLOCK(tp->t_inpcb); 3174 m_freem(m); 3175 return; 3176 3177 dropwithreset: 3178 if (ti_locked == TI_RLOCKED) 3179 INP_INFO_RUNLOCK(&V_tcbinfo); 3180 ti_locked = TI_UNLOCKED; 3181 3182 if (tp != NULL) { 3183 tcp_dropwithreset(m, th, tp, tlen, rstreason); 3184 INP_WUNLOCK(tp->t_inpcb); 3185 } else 3186 tcp_dropwithreset(m, th, NULL, tlen, rstreason); 3187 return; 3188 3189 drop: 3190 if (ti_locked == TI_RLOCKED) { 3191 INP_INFO_RUNLOCK(&V_tcbinfo); 3192 ti_locked = TI_UNLOCKED; 3193 } 3194 #ifdef INVARIANTS 3195 else 3196 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo); 3197 #endif 3198 3199 /* 3200 * Drop space held by incoming segment and return. 3201 */ 3202 #ifdef TCPDEBUG 3203 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG)) 3204 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen, 3205 &tcp_savetcp, 0); 3206 #endif 3207 TCP_PROBE3(debug__input, tp, th, mtod(m, const char *)); 3208 if (tp != NULL) 3209 INP_WUNLOCK(tp->t_inpcb); 3210 m_freem(m); 3211 } 3212 3213 /* 3214 * Issue RST and make ACK acceptable to originator of segment. 3215 * The mbuf must still include the original packet header. 3216 * tp may be NULL. 3217 */ 3218 void 3219 tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp, 3220 int tlen, int rstreason) 3221 { 3222 #ifdef INET 3223 struct ip *ip; 3224 #endif 3225 #ifdef INET6 3226 struct ip6_hdr *ip6; 3227 #endif 3228 3229 if (tp != NULL) { 3230 INP_WLOCK_ASSERT(tp->t_inpcb); 3231 } 3232 3233 /* Don't bother if destination was broadcast/multicast. */ 3234 if ((th->th_flags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST)) 3235 goto drop; 3236 #ifdef INET6 3237 if (mtod(m, struct ip *)->ip_v == 6) { 3238 ip6 = mtod(m, struct ip6_hdr *); 3239 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) || 3240 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) 3241 goto drop; 3242 /* IPv6 anycast check is done at tcp6_input() */ 3243 } 3244 #endif 3245 #if defined(INET) && defined(INET6) 3246 else 3247 #endif 3248 #ifdef INET 3249 { 3250 ip = mtod(m, struct ip *); 3251 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) || 3252 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) || 3253 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) || 3254 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) 3255 goto drop; 3256 } 3257 #endif 3258 3259 /* Perform bandwidth limiting. */ 3260 if (badport_bandlim(rstreason) < 0) 3261 goto drop; 3262 3263 /* tcp_respond consumes the mbuf chain. */ 3264 if (th->th_flags & TH_ACK) { 3265 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, 3266 th->th_ack, TH_RST); 3267 } else { 3268 if (th->th_flags & TH_SYN) 3269 tlen++; 3270 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen, 3271 (tcp_seq)0, TH_RST|TH_ACK); 3272 } 3273 return; 3274 drop: 3275 m_freem(m); 3276 } 3277 3278 /* 3279 * Parse TCP options and place in tcpopt. 3280 */ 3281 void 3282 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags) 3283 { 3284 int opt, optlen; 3285 3286 to->to_flags = 0; 3287 for (; cnt > 0; cnt -= optlen, cp += optlen) { 3288 opt = cp[0]; 3289 if (opt == TCPOPT_EOL) 3290 break; 3291 if (opt == TCPOPT_NOP) 3292 optlen = 1; 3293 else { 3294 if (cnt < 2) 3295 break; 3296 optlen = cp[1]; 3297 if (optlen < 2 || optlen > cnt) 3298 break; 3299 } 3300 switch (opt) { 3301 case TCPOPT_MAXSEG: 3302 if (optlen != TCPOLEN_MAXSEG) 3303 continue; 3304 if (!(flags & TO_SYN)) 3305 continue; 3306 to->to_flags |= TOF_MSS; 3307 bcopy((char *)cp + 2, 3308 (char *)&to->to_mss, sizeof(to->to_mss)); 3309 to->to_mss = ntohs(to->to_mss); 3310 break; 3311 case TCPOPT_WINDOW: 3312 if (optlen != TCPOLEN_WINDOW) 3313 continue; 3314 if (!(flags & TO_SYN)) 3315 continue; 3316 to->to_flags |= TOF_SCALE; 3317 to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT); 3318 break; 3319 case TCPOPT_TIMESTAMP: 3320 if (optlen != TCPOLEN_TIMESTAMP) 3321 continue; 3322 to->to_flags |= TOF_TS; 3323 bcopy((char *)cp + 2, 3324 (char *)&to->to_tsval, sizeof(to->to_tsval)); 3325 to->to_tsval = ntohl(to->to_tsval); 3326 bcopy((char *)cp + 6, 3327 (char *)&to->to_tsecr, sizeof(to->to_tsecr)); 3328 to->to_tsecr = ntohl(to->to_tsecr); 3329 break; 3330 #ifdef TCP_SIGNATURE 3331 /* 3332 * XXX In order to reply to a host which has set the 3333 * TCP_SIGNATURE option in its initial SYN, we have to 3334 * record the fact that the option was observed here 3335 * for the syncache code to perform the correct response. 3336 */ 3337 case TCPOPT_SIGNATURE: 3338 if (optlen != TCPOLEN_SIGNATURE) 3339 continue; 3340 to->to_flags |= TOF_SIGNATURE; 3341 to->to_signature = cp + 2; 3342 break; 3343 #endif 3344 case TCPOPT_SACK_PERMITTED: 3345 if (optlen != TCPOLEN_SACK_PERMITTED) 3346 continue; 3347 if (!(flags & TO_SYN)) 3348 continue; 3349 if (!V_tcp_do_sack) 3350 continue; 3351 to->to_flags |= TOF_SACKPERM; 3352 break; 3353 case TCPOPT_SACK: 3354 if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0) 3355 continue; 3356 if (flags & TO_SYN) 3357 continue; 3358 to->to_flags |= TOF_SACK; 3359 to->to_nsacks = (optlen - 2) / TCPOLEN_SACK; 3360 to->to_sacks = cp + 2; 3361 TCPSTAT_INC(tcps_sack_rcv_blocks); 3362 break; 3363 #ifdef TCP_RFC7413 3364 case TCPOPT_FAST_OPEN: 3365 if ((optlen != TCPOLEN_FAST_OPEN_EMPTY) && 3366 (optlen < TCPOLEN_FAST_OPEN_MIN) && 3367 (optlen > TCPOLEN_FAST_OPEN_MAX)) 3368 continue; 3369 if (!(flags & TO_SYN)) 3370 continue; 3371 if (!V_tcp_fastopen_enabled) 3372 continue; 3373 to->to_flags |= TOF_FASTOPEN; 3374 to->to_tfo_len = optlen - 2; 3375 to->to_tfo_cookie = to->to_tfo_len ? cp + 2 : NULL; 3376 break; 3377 #endif 3378 default: 3379 continue; 3380 } 3381 } 3382 } 3383 3384 /* 3385 * Pull out of band byte out of a segment so 3386 * it doesn't appear in the user's data queue. 3387 * It is still reflected in the segment length for 3388 * sequencing purposes. 3389 */ 3390 void 3391 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m, 3392 int off) 3393 { 3394 int cnt = off + th->th_urp - 1; 3395 3396 while (cnt >= 0) { 3397 if (m->m_len > cnt) { 3398 char *cp = mtod(m, caddr_t) + cnt; 3399 struct tcpcb *tp = sototcpcb(so); 3400 3401 INP_WLOCK_ASSERT(tp->t_inpcb); 3402 3403 tp->t_iobc = *cp; 3404 tp->t_oobflags |= TCPOOB_HAVEDATA; 3405 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1)); 3406 m->m_len--; 3407 if (m->m_flags & M_PKTHDR) 3408 m->m_pkthdr.len--; 3409 return; 3410 } 3411 cnt -= m->m_len; 3412 m = m->m_next; 3413 if (m == NULL) 3414 break; 3415 } 3416 panic("tcp_pulloutofband"); 3417 } 3418 3419 /* 3420 * Collect new round-trip time estimate 3421 * and update averages and current timeout. 3422 */ 3423 void 3424 tcp_xmit_timer(struct tcpcb *tp, int rtt) 3425 { 3426 int delta; 3427 3428 INP_WLOCK_ASSERT(tp->t_inpcb); 3429 3430 TCPSTAT_INC(tcps_rttupdated); 3431 tp->t_rttupdated++; 3432 if (tp->t_srtt != 0) { 3433 /* 3434 * srtt is stored as fixed point with 5 bits after the 3435 * binary point (i.e., scaled by 8). The following magic 3436 * is equivalent to the smoothing algorithm in rfc793 with 3437 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed 3438 * point). Adjust rtt to origin 0. 3439 */ 3440 delta = ((rtt - 1) << TCP_DELTA_SHIFT) 3441 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT)); 3442 3443 if ((tp->t_srtt += delta) <= 0) 3444 tp->t_srtt = 1; 3445 3446 /* 3447 * We accumulate a smoothed rtt variance (actually, a 3448 * smoothed mean difference), then set the retransmit 3449 * timer to smoothed rtt + 4 times the smoothed variance. 3450 * rttvar is stored as fixed point with 4 bits after the 3451 * binary point (scaled by 16). The following is 3452 * equivalent to rfc793 smoothing with an alpha of .75 3453 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces 3454 * rfc793's wired-in beta. 3455 */ 3456 if (delta < 0) 3457 delta = -delta; 3458 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT); 3459 if ((tp->t_rttvar += delta) <= 0) 3460 tp->t_rttvar = 1; 3461 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar) 3462 tp->t_rttbest = tp->t_srtt + tp->t_rttvar; 3463 } else { 3464 /* 3465 * No rtt measurement yet - use the unsmoothed rtt. 3466 * Set the variance to half the rtt (so our first 3467 * retransmit happens at 3*rtt). 3468 */ 3469 tp->t_srtt = rtt << TCP_RTT_SHIFT; 3470 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1); 3471 tp->t_rttbest = tp->t_srtt + tp->t_rttvar; 3472 } 3473 tp->t_rtttime = 0; 3474 tp->t_rxtshift = 0; 3475 3476 /* 3477 * the retransmit should happen at rtt + 4 * rttvar. 3478 * Because of the way we do the smoothing, srtt and rttvar 3479 * will each average +1/2 tick of bias. When we compute 3480 * the retransmit timer, we want 1/2 tick of rounding and 3481 * 1 extra tick because of +-1/2 tick uncertainty in the 3482 * firing of the timer. The bias will give us exactly the 3483 * 1.5 tick we need. But, because the bias is 3484 * statistical, we have to test that we don't drop below 3485 * the minimum feasible timer (which is 2 ticks). 3486 */ 3487 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp), 3488 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX); 3489 3490 /* 3491 * We received an ack for a packet that wasn't retransmitted; 3492 * it is probably safe to discard any error indications we've 3493 * received recently. This isn't quite right, but close enough 3494 * for now (a route might have failed after we sent a segment, 3495 * and the return path might not be symmetrical). 3496 */ 3497 tp->t_softerror = 0; 3498 } 3499 3500 /* 3501 * Determine a reasonable value for maxseg size. 3502 * If the route is known, check route for mtu. 3503 * If none, use an mss that can be handled on the outgoing interface 3504 * without forcing IP to fragment. If no route is found, route has no mtu, 3505 * or the destination isn't local, use a default, hopefully conservative 3506 * size (usually 512 or the default IP max size, but no more than the mtu 3507 * of the interface), as we can't discover anything about intervening 3508 * gateways or networks. We also initialize the congestion/slow start 3509 * window to be a single segment if the destination isn't local. 3510 * While looking at the routing entry, we also initialize other path-dependent 3511 * parameters from pre-set or cached values in the routing entry. 3512 * 3513 * Also take into account the space needed for options that we 3514 * send regularly. Make maxseg shorter by that amount to assure 3515 * that we can send maxseg amount of data even when the options 3516 * are present. Store the upper limit of the length of options plus 3517 * data in maxopd. 3518 * 3519 * NOTE that this routine is only called when we process an incoming 3520 * segment, or an ICMP need fragmentation datagram. Outgoing SYN/ACK MSS 3521 * settings are handled in tcp_mssopt(). 3522 */ 3523 void 3524 tcp_mss_update(struct tcpcb *tp, int offer, int mtuoffer, 3525 struct hc_metrics_lite *metricptr, struct tcp_ifcap *cap) 3526 { 3527 int mss = 0; 3528 u_long maxmtu = 0; 3529 struct inpcb *inp = tp->t_inpcb; 3530 struct hc_metrics_lite metrics; 3531 int origoffer; 3532 #ifdef INET6 3533 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0; 3534 size_t min_protoh = isipv6 ? 3535 sizeof (struct ip6_hdr) + sizeof (struct tcphdr) : 3536 sizeof (struct tcpiphdr); 3537 #else 3538 const size_t min_protoh = sizeof(struct tcpiphdr); 3539 #endif 3540 3541 INP_WLOCK_ASSERT(tp->t_inpcb); 3542 3543 if (mtuoffer != -1) { 3544 KASSERT(offer == -1, ("%s: conflict", __func__)); 3545 offer = mtuoffer - min_protoh; 3546 } 3547 origoffer = offer; 3548 3549 /* Initialize. */ 3550 #ifdef INET6 3551 if (isipv6) { 3552 maxmtu = tcp_maxmtu6(&inp->inp_inc, cap); 3553 tp->t_maxopd = tp->t_maxseg = V_tcp_v6mssdflt; 3554 } 3555 #endif 3556 #if defined(INET) && defined(INET6) 3557 else 3558 #endif 3559 #ifdef INET 3560 { 3561 maxmtu = tcp_maxmtu(&inp->inp_inc, cap); 3562 tp->t_maxopd = tp->t_maxseg = V_tcp_mssdflt; 3563 } 3564 #endif 3565 3566 /* 3567 * No route to sender, stay with default mss and return. 3568 */ 3569 if (maxmtu == 0) { 3570 /* 3571 * In case we return early we need to initialize metrics 3572 * to a defined state as tcp_hc_get() would do for us 3573 * if there was no cache hit. 3574 */ 3575 if (metricptr != NULL) 3576 bzero(metricptr, sizeof(struct hc_metrics_lite)); 3577 return; 3578 } 3579 3580 /* What have we got? */ 3581 switch (offer) { 3582 case 0: 3583 /* 3584 * Offer == 0 means that there was no MSS on the SYN 3585 * segment, in this case we use tcp_mssdflt as 3586 * already assigned to t_maxopd above. 3587 */ 3588 offer = tp->t_maxopd; 3589 break; 3590 3591 case -1: 3592 /* 3593 * Offer == -1 means that we didn't receive SYN yet. 3594 */ 3595 /* FALLTHROUGH */ 3596 3597 default: 3598 /* 3599 * Prevent DoS attack with too small MSS. Round up 3600 * to at least minmss. 3601 */ 3602 offer = max(offer, V_tcp_minmss); 3603 } 3604 3605 /* 3606 * rmx information is now retrieved from tcp_hostcache. 3607 */ 3608 tcp_hc_get(&inp->inp_inc, &metrics); 3609 if (metricptr != NULL) 3610 bcopy(&metrics, metricptr, sizeof(struct hc_metrics_lite)); 3611 3612 /* 3613 * If there's a discovered mtu in tcp hostcache, use it. 3614 * Else, use the link mtu. 3615 */ 3616 if (metrics.rmx_mtu) 3617 mss = min(metrics.rmx_mtu, maxmtu) - min_protoh; 3618 else { 3619 #ifdef INET6 3620 if (isipv6) { 3621 mss = maxmtu - min_protoh; 3622 if (!V_path_mtu_discovery && 3623 !in6_localaddr(&inp->in6p_faddr)) 3624 mss = min(mss, V_tcp_v6mssdflt); 3625 } 3626 #endif 3627 #if defined(INET) && defined(INET6) 3628 else 3629 #endif 3630 #ifdef INET 3631 { 3632 mss = maxmtu - min_protoh; 3633 if (!V_path_mtu_discovery && 3634 !in_localaddr(inp->inp_faddr)) 3635 mss = min(mss, V_tcp_mssdflt); 3636 } 3637 #endif 3638 /* 3639 * XXX - The above conditional (mss = maxmtu - min_protoh) 3640 * probably violates the TCP spec. 3641 * The problem is that, since we don't know the 3642 * other end's MSS, we are supposed to use a conservative 3643 * default. But, if we do that, then MTU discovery will 3644 * never actually take place, because the conservative 3645 * default is much less than the MTUs typically seen 3646 * on the Internet today. For the moment, we'll sweep 3647 * this under the carpet. 3648 * 3649 * The conservative default might not actually be a problem 3650 * if the only case this occurs is when sending an initial 3651 * SYN with options and data to a host we've never talked 3652 * to before. Then, they will reply with an MSS value which 3653 * will get recorded and the new parameters should get 3654 * recomputed. For Further Study. 3655 */ 3656 } 3657 mss = min(mss, offer); 3658 3659 /* 3660 * Sanity check: make sure that maxopd will be large 3661 * enough to allow some data on segments even if the 3662 * all the option space is used (40bytes). Otherwise 3663 * funny things may happen in tcp_output. 3664 */ 3665 mss = max(mss, 64); 3666 3667 /* 3668 * maxopd stores the maximum length of data AND options 3669 * in a segment; maxseg is the amount of data in a normal 3670 * segment. We need to store this value (maxopd) apart 3671 * from maxseg, because now every segment carries options 3672 * and thus we normally have somewhat less data in segments. 3673 */ 3674 tp->t_maxopd = mss; 3675 3676 /* 3677 * origoffer==-1 indicates that no segments were received yet. 3678 * In this case we just guess. 3679 */ 3680 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP && 3681 (origoffer == -1 || 3682 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP)) 3683 mss -= TCPOLEN_TSTAMP_APPA; 3684 3685 tp->t_maxseg = mss; 3686 } 3687 3688 void 3689 tcp_mss(struct tcpcb *tp, int offer) 3690 { 3691 int mss; 3692 u_long bufsize; 3693 struct inpcb *inp; 3694 struct socket *so; 3695 struct hc_metrics_lite metrics; 3696 struct tcp_ifcap cap; 3697 3698 KASSERT(tp != NULL, ("%s: tp == NULL", __func__)); 3699 3700 bzero(&cap, sizeof(cap)); 3701 tcp_mss_update(tp, offer, -1, &metrics, &cap); 3702 3703 mss = tp->t_maxseg; 3704 inp = tp->t_inpcb; 3705 3706 /* 3707 * If there's a pipesize, change the socket buffer to that size, 3708 * don't change if sb_hiwat is different than default (then it 3709 * has been changed on purpose with setsockopt). 3710 * Make the socket buffers an integral number of mss units; 3711 * if the mss is larger than the socket buffer, decrease the mss. 3712 */ 3713 so = inp->inp_socket; 3714 SOCKBUF_LOCK(&so->so_snd); 3715 if ((so->so_snd.sb_hiwat == V_tcp_sendspace) && metrics.rmx_sendpipe) 3716 bufsize = metrics.rmx_sendpipe; 3717 else 3718 bufsize = so->so_snd.sb_hiwat; 3719 if (bufsize < mss) 3720 mss = bufsize; 3721 else { 3722 bufsize = roundup(bufsize, mss); 3723 if (bufsize > sb_max) 3724 bufsize = sb_max; 3725 if (bufsize > so->so_snd.sb_hiwat) 3726 (void)sbreserve_locked(&so->so_snd, bufsize, so, NULL); 3727 } 3728 SOCKBUF_UNLOCK(&so->so_snd); 3729 tp->t_maxseg = mss; 3730 3731 SOCKBUF_LOCK(&so->so_rcv); 3732 if ((so->so_rcv.sb_hiwat == V_tcp_recvspace) && metrics.rmx_recvpipe) 3733 bufsize = metrics.rmx_recvpipe; 3734 else 3735 bufsize = so->so_rcv.sb_hiwat; 3736 if (bufsize > mss) { 3737 bufsize = roundup(bufsize, mss); 3738 if (bufsize > sb_max) 3739 bufsize = sb_max; 3740 if (bufsize > so->so_rcv.sb_hiwat) 3741 (void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL); 3742 } 3743 SOCKBUF_UNLOCK(&so->so_rcv); 3744 3745 /* Check the interface for TSO capabilities. */ 3746 if (cap.ifcap & CSUM_TSO) { 3747 tp->t_flags |= TF_TSO; 3748 tp->t_tsomax = cap.tsomax; 3749 tp->t_tsomaxsegcount = cap.tsomaxsegcount; 3750 tp->t_tsomaxsegsize = cap.tsomaxsegsize; 3751 } 3752 } 3753 3754 /* 3755 * Determine the MSS option to send on an outgoing SYN. 3756 */ 3757 int 3758 tcp_mssopt(struct in_conninfo *inc) 3759 { 3760 int mss = 0; 3761 u_long maxmtu = 0; 3762 u_long thcmtu = 0; 3763 size_t min_protoh; 3764 3765 KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer")); 3766 3767 #ifdef INET6 3768 if (inc->inc_flags & INC_ISIPV6) { 3769 mss = V_tcp_v6mssdflt; 3770 maxmtu = tcp_maxmtu6(inc, NULL); 3771 min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr); 3772 } 3773 #endif 3774 #if defined(INET) && defined(INET6) 3775 else 3776 #endif 3777 #ifdef INET 3778 { 3779 mss = V_tcp_mssdflt; 3780 maxmtu = tcp_maxmtu(inc, NULL); 3781 min_protoh = sizeof(struct tcpiphdr); 3782 } 3783 #endif 3784 #if defined(INET6) || defined(INET) 3785 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */ 3786 #endif 3787 3788 if (maxmtu && thcmtu) 3789 mss = min(maxmtu, thcmtu) - min_protoh; 3790 else if (maxmtu || thcmtu) 3791 mss = max(maxmtu, thcmtu) - min_protoh; 3792 3793 return (mss); 3794 } 3795 3796 3797 /* 3798 * On a partial ack arrives, force the retransmission of the 3799 * next unacknowledged segment. Do not clear tp->t_dupacks. 3800 * By setting snd_nxt to ti_ack, this forces retransmission timer to 3801 * be started again. 3802 */ 3803 void 3804 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th) 3805 { 3806 tcp_seq onxt = tp->snd_nxt; 3807 u_long ocwnd = tp->snd_cwnd; 3808 3809 INP_WLOCK_ASSERT(tp->t_inpcb); 3810 3811 tcp_timer_activate(tp, TT_REXMT, 0); 3812 tp->t_rtttime = 0; 3813 tp->snd_nxt = th->th_ack; 3814 /* 3815 * Set snd_cwnd to one segment beyond acknowledged offset. 3816 * (tp->snd_una has not yet been updated when this function is called.) 3817 */ 3818 tp->snd_cwnd = tp->t_maxseg + BYTES_THIS_ACK(tp, th); 3819 tp->t_flags |= TF_ACKNOW; 3820 (void) tp->t_fb->tfb_tcp_output(tp); 3821 tp->snd_cwnd = ocwnd; 3822 if (SEQ_GT(onxt, tp->snd_nxt)) 3823 tp->snd_nxt = onxt; 3824 /* 3825 * Partial window deflation. Relies on fact that tp->snd_una 3826 * not updated yet. 3827 */ 3828 if (tp->snd_cwnd > BYTES_THIS_ACK(tp, th)) 3829 tp->snd_cwnd -= BYTES_THIS_ACK(tp, th); 3830 else 3831 tp->snd_cwnd = 0; 3832 tp->snd_cwnd += tp->t_maxseg; 3833 } 3834 3835 int 3836 tcp_compute_pipe(struct tcpcb *tp) 3837 { 3838 return (tp->snd_max - tp->snd_una + 3839 tp->sackhint.sack_bytes_rexmit - 3840 tp->sackhint.sacked_bytes); 3841 } 3842