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