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