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