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