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