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