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