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