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