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