1 /* $NetBSD: tcp_input.c,v 1.341 2015/05/24 15:43:45 rtr Exp $ */ 2 3 /* 4 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. 5 * All rights reserved. 6 * 7 * Redistribution and use in source and binary forms, with or without 8 * modification, are permitted provided that the following conditions 9 * are met: 10 * 1. Redistributions of source code must retain the above copyright 11 * notice, this list of conditions and the following disclaimer. 12 * 2. Redistributions in binary form must reproduce the above copyright 13 * notice, this list of conditions and the following disclaimer in the 14 * documentation and/or other materials provided with the distribution. 15 * 3. Neither the name of the project nor the names of its contributors 16 * may be used to endorse or promote products derived from this software 17 * without specific prior written permission. 18 * 19 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND 20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 22 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE 23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 29 * SUCH DAMAGE. 30 */ 31 32 /* 33 * @(#)COPYRIGHT 1.1 (NRL) 17 January 1995 34 * 35 * NRL grants permission for redistribution and use in source and binary 36 * forms, with or without modification, of the software and documentation 37 * created at NRL provided that the following conditions are met: 38 * 39 * 1. Redistributions of source code must retain the above copyright 40 * notice, this list of conditions and the following disclaimer. 41 * 2. Redistributions in binary form must reproduce the above copyright 42 * notice, this list of conditions and the following disclaimer in the 43 * documentation and/or other materials provided with the distribution. 44 * 3. All advertising materials mentioning features or use of this software 45 * must display the following acknowledgements: 46 * This product includes software developed by the University of 47 * California, Berkeley and its contributors. 48 * This product includes software developed at the Information 49 * Technology Division, US Naval Research Laboratory. 50 * 4. Neither the name of the NRL 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 * THE SOFTWARE PROVIDED BY NRL IS PROVIDED BY NRL AND CONTRIBUTORS ``AS 55 * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 56 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 57 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL NRL OR 58 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 59 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 60 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 61 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 62 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 63 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 64 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 65 * 66 * The views and conclusions contained in the software and documentation 67 * are those of the authors and should not be interpreted as representing 68 * official policies, either expressed or implied, of the US Naval 69 * Research Laboratory (NRL). 70 */ 71 72 /*- 73 * Copyright (c) 1997, 1998, 1999, 2001, 2005, 2006, 74 * 2011 The NetBSD Foundation, Inc. 75 * All rights reserved. 76 * 77 * This code is derived from software contributed to The NetBSD Foundation 78 * by Coyote Point Systems, Inc. 79 * This code is derived from software contributed to The NetBSD Foundation 80 * by Jason R. Thorpe and Kevin M. Lahey of the Numerical Aerospace Simulation 81 * Facility, NASA Ames Research Center. 82 * This code is derived from software contributed to The NetBSD Foundation 83 * by Charles M. Hannum. 84 * This code is derived from software contributed to The NetBSD Foundation 85 * by Rui Paulo. 86 * 87 * Redistribution and use in source and binary forms, with or without 88 * modification, are permitted provided that the following conditions 89 * are met: 90 * 1. Redistributions of source code must retain the above copyright 91 * notice, this list of conditions and the following disclaimer. 92 * 2. Redistributions in binary form must reproduce the above copyright 93 * notice, this list of conditions and the following disclaimer in the 94 * documentation and/or other materials provided with the distribution. 95 * 96 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS 97 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 98 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 99 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS 100 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 101 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 102 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 103 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 104 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 105 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 106 * POSSIBILITY OF SUCH DAMAGE. 107 */ 108 109 /* 110 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995 111 * The Regents of the University of California. All rights reserved. 112 * 113 * Redistribution and use in source and binary forms, with or without 114 * modification, are permitted provided that the following conditions 115 * are met: 116 * 1. Redistributions of source code must retain the above copyright 117 * notice, this list of conditions and the following disclaimer. 118 * 2. Redistributions in binary form must reproduce the above copyright 119 * notice, this list of conditions and the following disclaimer in the 120 * documentation and/or other materials provided with the distribution. 121 * 3. Neither the name of the University nor the names of its contributors 122 * may be used to endorse or promote products derived from this software 123 * without specific prior written permission. 124 * 125 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 126 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 127 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 128 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 129 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 130 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 131 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 132 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 133 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 134 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 135 * SUCH DAMAGE. 136 * 137 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95 138 */ 139 140 /* 141 * TODO list for SYN cache stuff: 142 * 143 * Find room for a "state" field, which is needed to keep a 144 * compressed state for TIME_WAIT TCBs. It's been noted already 145 * that this is fairly important for very high-volume web and 146 * mail servers, which use a large number of short-lived 147 * connections. 148 */ 149 150 #include <sys/cdefs.h> 151 __KERNEL_RCSID(0, "$NetBSD: tcp_input.c,v 1.341 2015/05/24 15:43:45 rtr Exp $"); 152 153 #include "opt_inet.h" 154 #include "opt_ipsec.h" 155 #include "opt_inet_csum.h" 156 #include "opt_tcp_debug.h" 157 158 #include <sys/param.h> 159 #include <sys/systm.h> 160 #include <sys/malloc.h> 161 #include <sys/mbuf.h> 162 #include <sys/protosw.h> 163 #include <sys/socket.h> 164 #include <sys/socketvar.h> 165 #include <sys/errno.h> 166 #include <sys/syslog.h> 167 #include <sys/pool.h> 168 #include <sys/domain.h> 169 #include <sys/kernel.h> 170 #ifdef TCP_SIGNATURE 171 #include <sys/md5.h> 172 #endif 173 #include <sys/lwp.h> /* for lwp0 */ 174 #include <sys/cprng.h> 175 176 #include <net/if.h> 177 #include <net/if_types.h> 178 179 #include <netinet/in.h> 180 #include <netinet/in_systm.h> 181 #include <netinet/ip.h> 182 #include <netinet/in_pcb.h> 183 #include <netinet/in_var.h> 184 #include <netinet/ip_var.h> 185 #include <netinet/in_offload.h> 186 187 #ifdef INET6 188 #ifndef INET 189 #include <netinet/in.h> 190 #endif 191 #include <netinet/ip6.h> 192 #include <netinet6/ip6_var.h> 193 #include <netinet6/in6_pcb.h> 194 #include <netinet6/ip6_var.h> 195 #include <netinet6/in6_var.h> 196 #include <netinet/icmp6.h> 197 #include <netinet6/nd6.h> 198 #ifdef TCP_SIGNATURE 199 #include <netinet6/scope6_var.h> 200 #endif 201 #endif 202 203 #ifndef INET6 204 /* always need ip6.h for IP6_EXTHDR_GET */ 205 #include <netinet/ip6.h> 206 #endif 207 208 #include <netinet/tcp.h> 209 #include <netinet/tcp_fsm.h> 210 #include <netinet/tcp_seq.h> 211 #include <netinet/tcp_timer.h> 212 #include <netinet/tcp_var.h> 213 #include <netinet/tcp_private.h> 214 #include <netinet/tcpip.h> 215 #include <netinet/tcp_congctl.h> 216 #include <netinet/tcp_debug.h> 217 218 #ifdef INET6 219 #include "faith.h" 220 #if defined(NFAITH) && NFAITH > 0 221 #include <net/if_faith.h> 222 #endif 223 #endif /* INET6 */ 224 225 #ifdef IPSEC 226 #include <netipsec/ipsec.h> 227 #include <netipsec/ipsec_var.h> 228 #include <netipsec/ipsec_private.h> 229 #include <netipsec/key.h> 230 #ifdef INET6 231 #include <netipsec/ipsec6.h> 232 #endif 233 #endif /* IPSEC*/ 234 235 #include <netinet/tcp_vtw.h> 236 237 int tcprexmtthresh = 3; 238 int tcp_log_refused; 239 240 int tcp_do_autorcvbuf = 1; 241 int tcp_autorcvbuf_inc = 16 * 1024; 242 int tcp_autorcvbuf_max = 256 * 1024; 243 int tcp_msl = (TCPTV_MSL / PR_SLOWHZ); 244 245 static int tcp_rst_ppslim_count = 0; 246 static struct timeval tcp_rst_ppslim_last; 247 static int tcp_ackdrop_ppslim_count = 0; 248 static struct timeval tcp_ackdrop_ppslim_last; 249 250 #define TCP_PAWS_IDLE (24U * 24 * 60 * 60 * PR_SLOWHZ) 251 252 /* for modulo comparisons of timestamps */ 253 #define TSTMP_LT(a,b) ((int)((a)-(b)) < 0) 254 #define TSTMP_GEQ(a,b) ((int)((a)-(b)) >= 0) 255 256 /* 257 * Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. 258 */ 259 #ifdef INET6 260 static inline void 261 nd6_hint(struct tcpcb *tp) 262 { 263 struct rtentry *rt; 264 265 if (tp != NULL && tp->t_in6pcb != NULL && tp->t_family == AF_INET6 && 266 (rt = rtcache_validate(&tp->t_in6pcb->in6p_route)) != NULL) 267 nd6_nud_hint(rt, NULL, 0); 268 } 269 #else 270 static inline void 271 nd6_hint(struct tcpcb *tp) 272 { 273 } 274 #endif 275 276 /* 277 * Compute ACK transmission behavior. Delay the ACK unless 278 * we have already delayed an ACK (must send an ACK every two segments). 279 * We also ACK immediately if we received a PUSH and the ACK-on-PUSH 280 * option is enabled. 281 */ 282 static void 283 tcp_setup_ack(struct tcpcb *tp, const struct tcphdr *th) 284 { 285 286 if (tp->t_flags & TF_DELACK || 287 (tcp_ack_on_push && th->th_flags & TH_PUSH)) 288 tp->t_flags |= TF_ACKNOW; 289 else 290 TCP_SET_DELACK(tp); 291 } 292 293 static void 294 icmp_check(struct tcpcb *tp, const struct tcphdr *th, int acked) 295 { 296 297 /* 298 * If we had a pending ICMP message that refers to data that have 299 * just been acknowledged, disregard the recorded ICMP message. 300 */ 301 if ((tp->t_flags & TF_PMTUD_PEND) && 302 SEQ_GT(th->th_ack, tp->t_pmtud_th_seq)) 303 tp->t_flags &= ~TF_PMTUD_PEND; 304 305 /* 306 * Keep track of the largest chunk of data 307 * acknowledged since last PMTU update 308 */ 309 if (tp->t_pmtud_mss_acked < acked) 310 tp->t_pmtud_mss_acked = acked; 311 } 312 313 /* 314 * Convert TCP protocol fields to host order for easier processing. 315 */ 316 static void 317 tcp_fields_to_host(struct tcphdr *th) 318 { 319 320 NTOHL(th->th_seq); 321 NTOHL(th->th_ack); 322 NTOHS(th->th_win); 323 NTOHS(th->th_urp); 324 } 325 326 /* 327 * ... and reverse the above. 328 */ 329 static void 330 tcp_fields_to_net(struct tcphdr *th) 331 { 332 333 HTONL(th->th_seq); 334 HTONL(th->th_ack); 335 HTONS(th->th_win); 336 HTONS(th->th_urp); 337 } 338 339 #ifdef TCP_CSUM_COUNTERS 340 #include <sys/device.h> 341 342 #if defined(INET) 343 extern struct evcnt tcp_hwcsum_ok; 344 extern struct evcnt tcp_hwcsum_bad; 345 extern struct evcnt tcp_hwcsum_data; 346 extern struct evcnt tcp_swcsum; 347 #endif /* defined(INET) */ 348 #if defined(INET6) 349 extern struct evcnt tcp6_hwcsum_ok; 350 extern struct evcnt tcp6_hwcsum_bad; 351 extern struct evcnt tcp6_hwcsum_data; 352 extern struct evcnt tcp6_swcsum; 353 #endif /* defined(INET6) */ 354 355 #define TCP_CSUM_COUNTER_INCR(ev) (ev)->ev_count++ 356 357 #else 358 359 #define TCP_CSUM_COUNTER_INCR(ev) /* nothing */ 360 361 #endif /* TCP_CSUM_COUNTERS */ 362 363 #ifdef TCP_REASS_COUNTERS 364 #include <sys/device.h> 365 366 extern struct evcnt tcp_reass_; 367 extern struct evcnt tcp_reass_empty; 368 extern struct evcnt tcp_reass_iteration[8]; 369 extern struct evcnt tcp_reass_prependfirst; 370 extern struct evcnt tcp_reass_prepend; 371 extern struct evcnt tcp_reass_insert; 372 extern struct evcnt tcp_reass_inserttail; 373 extern struct evcnt tcp_reass_append; 374 extern struct evcnt tcp_reass_appendtail; 375 extern struct evcnt tcp_reass_overlaptail; 376 extern struct evcnt tcp_reass_overlapfront; 377 extern struct evcnt tcp_reass_segdup; 378 extern struct evcnt tcp_reass_fragdup; 379 380 #define TCP_REASS_COUNTER_INCR(ev) (ev)->ev_count++ 381 382 #else 383 384 #define TCP_REASS_COUNTER_INCR(ev) /* nothing */ 385 386 #endif /* TCP_REASS_COUNTERS */ 387 388 static int tcp_reass(struct tcpcb *, const struct tcphdr *, struct mbuf *, 389 int *); 390 static int tcp_dooptions(struct tcpcb *, const u_char *, int, 391 struct tcphdr *, struct mbuf *, int, struct tcp_opt_info *); 392 393 #ifdef INET 394 static void tcp4_log_refused(const struct ip *, const struct tcphdr *); 395 #endif 396 #ifdef INET6 397 static void tcp6_log_refused(const struct ip6_hdr *, const struct tcphdr *); 398 #endif 399 400 #define TRAVERSE(x) while ((x)->m_next) (x) = (x)->m_next 401 402 #if defined(MBUFTRACE) 403 struct mowner tcp_reass_mowner = MOWNER_INIT("tcp", "reass"); 404 #endif /* defined(MBUFTRACE) */ 405 406 static struct pool tcpipqent_pool; 407 408 void 409 tcpipqent_init(void) 410 { 411 412 pool_init(&tcpipqent_pool, sizeof(struct ipqent), 0, 0, 0, "tcpipqepl", 413 NULL, IPL_VM); 414 } 415 416 struct ipqent * 417 tcpipqent_alloc(void) 418 { 419 struct ipqent *ipqe; 420 int s; 421 422 s = splvm(); 423 ipqe = pool_get(&tcpipqent_pool, PR_NOWAIT); 424 splx(s); 425 426 return ipqe; 427 } 428 429 void 430 tcpipqent_free(struct ipqent *ipqe) 431 { 432 int s; 433 434 s = splvm(); 435 pool_put(&tcpipqent_pool, ipqe); 436 splx(s); 437 } 438 439 static int 440 tcp_reass(struct tcpcb *tp, const struct tcphdr *th, struct mbuf *m, int *tlen) 441 { 442 struct ipqent *p, *q, *nq, *tiqe = NULL; 443 struct socket *so = NULL; 444 int pkt_flags; 445 tcp_seq pkt_seq; 446 unsigned pkt_len; 447 u_long rcvpartdupbyte = 0; 448 u_long rcvoobyte; 449 #ifdef TCP_REASS_COUNTERS 450 u_int count = 0; 451 #endif 452 uint64_t *tcps; 453 454 if (tp->t_inpcb) 455 so = tp->t_inpcb->inp_socket; 456 #ifdef INET6 457 else if (tp->t_in6pcb) 458 so = tp->t_in6pcb->in6p_socket; 459 #endif 460 461 TCP_REASS_LOCK_CHECK(tp); 462 463 /* 464 * Call with th==0 after become established to 465 * force pre-ESTABLISHED data up to user socket. 466 */ 467 if (th == 0) 468 goto present; 469 470 m_claimm(m, &tcp_reass_mowner); 471 472 rcvoobyte = *tlen; 473 /* 474 * Copy these to local variables because the tcpiphdr 475 * gets munged while we are collapsing mbufs. 476 */ 477 pkt_seq = th->th_seq; 478 pkt_len = *tlen; 479 pkt_flags = th->th_flags; 480 481 TCP_REASS_COUNTER_INCR(&tcp_reass_); 482 483 if ((p = TAILQ_LAST(&tp->segq, ipqehead)) != NULL) { 484 /* 485 * When we miss a packet, the vast majority of time we get 486 * packets that follow it in order. So optimize for that. 487 */ 488 if (pkt_seq == p->ipqe_seq + p->ipqe_len) { 489 p->ipqe_len += pkt_len; 490 p->ipqe_flags |= pkt_flags; 491 m_cat(p->ipre_mlast, m); 492 TRAVERSE(p->ipre_mlast); 493 m = NULL; 494 tiqe = p; 495 TAILQ_REMOVE(&tp->timeq, p, ipqe_timeq); 496 TCP_REASS_COUNTER_INCR(&tcp_reass_appendtail); 497 goto skip_replacement; 498 } 499 /* 500 * While we're here, if the pkt is completely beyond 501 * anything we have, just insert it at the tail. 502 */ 503 if (SEQ_GT(pkt_seq, p->ipqe_seq + p->ipqe_len)) { 504 TCP_REASS_COUNTER_INCR(&tcp_reass_inserttail); 505 goto insert_it; 506 } 507 } 508 509 q = TAILQ_FIRST(&tp->segq); 510 511 if (q != NULL) { 512 /* 513 * If this segment immediately precedes the first out-of-order 514 * block, simply slap the segment in front of it and (mostly) 515 * skip the complicated logic. 516 */ 517 if (pkt_seq + pkt_len == q->ipqe_seq) { 518 q->ipqe_seq = pkt_seq; 519 q->ipqe_len += pkt_len; 520 q->ipqe_flags |= pkt_flags; 521 m_cat(m, q->ipqe_m); 522 q->ipqe_m = m; 523 q->ipre_mlast = m; /* last mbuf may have changed */ 524 TRAVERSE(q->ipre_mlast); 525 tiqe = q; 526 TAILQ_REMOVE(&tp->timeq, q, ipqe_timeq); 527 TCP_REASS_COUNTER_INCR(&tcp_reass_prependfirst); 528 goto skip_replacement; 529 } 530 } else { 531 TCP_REASS_COUNTER_INCR(&tcp_reass_empty); 532 } 533 534 /* 535 * Find a segment which begins after this one does. 536 */ 537 for (p = NULL; q != NULL; q = nq) { 538 nq = TAILQ_NEXT(q, ipqe_q); 539 #ifdef TCP_REASS_COUNTERS 540 count++; 541 #endif 542 /* 543 * If the received segment is just right after this 544 * fragment, merge the two together and then check 545 * for further overlaps. 546 */ 547 if (q->ipqe_seq + q->ipqe_len == pkt_seq) { 548 #ifdef TCPREASS_DEBUG 549 printf("tcp_reass[%p]: concat %u:%u(%u) to %u:%u(%u)\n", 550 tp, pkt_seq, pkt_seq + pkt_len, pkt_len, 551 q->ipqe_seq, q->ipqe_seq + q->ipqe_len, q->ipqe_len); 552 #endif 553 pkt_len += q->ipqe_len; 554 pkt_flags |= q->ipqe_flags; 555 pkt_seq = q->ipqe_seq; 556 m_cat(q->ipre_mlast, m); 557 TRAVERSE(q->ipre_mlast); 558 m = q->ipqe_m; 559 TCP_REASS_COUNTER_INCR(&tcp_reass_append); 560 goto free_ipqe; 561 } 562 /* 563 * If the received segment is completely past this 564 * fragment, we need to go the next fragment. 565 */ 566 if (SEQ_LT(q->ipqe_seq + q->ipqe_len, pkt_seq)) { 567 p = q; 568 continue; 569 } 570 /* 571 * If the fragment is past the received segment, 572 * it (or any following) can't be concatenated. 573 */ 574 if (SEQ_GT(q->ipqe_seq, pkt_seq + pkt_len)) { 575 TCP_REASS_COUNTER_INCR(&tcp_reass_insert); 576 break; 577 } 578 579 /* 580 * We've received all the data in this segment before. 581 * mark it as a duplicate and return. 582 */ 583 if (SEQ_LEQ(q->ipqe_seq, pkt_seq) && 584 SEQ_GEQ(q->ipqe_seq + q->ipqe_len, pkt_seq + pkt_len)) { 585 tcps = TCP_STAT_GETREF(); 586 tcps[TCP_STAT_RCVDUPPACK]++; 587 tcps[TCP_STAT_RCVDUPBYTE] += pkt_len; 588 TCP_STAT_PUTREF(); 589 tcp_new_dsack(tp, pkt_seq, pkt_len); 590 m_freem(m); 591 if (tiqe != NULL) { 592 tcpipqent_free(tiqe); 593 } 594 TCP_REASS_COUNTER_INCR(&tcp_reass_segdup); 595 goto out; 596 } 597 /* 598 * Received segment completely overlaps this fragment 599 * so we drop the fragment (this keeps the temporal 600 * ordering of segments correct). 601 */ 602 if (SEQ_GEQ(q->ipqe_seq, pkt_seq) && 603 SEQ_LEQ(q->ipqe_seq + q->ipqe_len, pkt_seq + pkt_len)) { 604 rcvpartdupbyte += q->ipqe_len; 605 m_freem(q->ipqe_m); 606 TCP_REASS_COUNTER_INCR(&tcp_reass_fragdup); 607 goto free_ipqe; 608 } 609 /* 610 * RX'ed segment extends past the end of the 611 * fragment. Drop the overlapping bytes. Then 612 * merge the fragment and segment then treat as 613 * a longer received packet. 614 */ 615 if (SEQ_LT(q->ipqe_seq, pkt_seq) && 616 SEQ_GT(q->ipqe_seq + q->ipqe_len, pkt_seq)) { 617 int overlap = q->ipqe_seq + q->ipqe_len - pkt_seq; 618 #ifdef TCPREASS_DEBUG 619 printf("tcp_reass[%p]: trim starting %d bytes of %u:%u(%u)\n", 620 tp, overlap, 621 pkt_seq, pkt_seq + pkt_len, pkt_len); 622 #endif 623 m_adj(m, overlap); 624 rcvpartdupbyte += overlap; 625 m_cat(q->ipre_mlast, m); 626 TRAVERSE(q->ipre_mlast); 627 m = q->ipqe_m; 628 pkt_seq = q->ipqe_seq; 629 pkt_len += q->ipqe_len - overlap; 630 rcvoobyte -= overlap; 631 TCP_REASS_COUNTER_INCR(&tcp_reass_overlaptail); 632 goto free_ipqe; 633 } 634 /* 635 * RX'ed segment extends past the front of the 636 * fragment. Drop the overlapping bytes on the 637 * received packet. The packet will then be 638 * contatentated with this fragment a bit later. 639 */ 640 if (SEQ_GT(q->ipqe_seq, pkt_seq) && 641 SEQ_LT(q->ipqe_seq, pkt_seq + pkt_len)) { 642 int overlap = pkt_seq + pkt_len - q->ipqe_seq; 643 #ifdef TCPREASS_DEBUG 644 printf("tcp_reass[%p]: trim trailing %d bytes of %u:%u(%u)\n", 645 tp, overlap, 646 pkt_seq, pkt_seq + pkt_len, pkt_len); 647 #endif 648 m_adj(m, -overlap); 649 pkt_len -= overlap; 650 rcvpartdupbyte += overlap; 651 TCP_REASS_COUNTER_INCR(&tcp_reass_overlapfront); 652 rcvoobyte -= overlap; 653 } 654 /* 655 * If the received segment immediates precedes this 656 * fragment then tack the fragment onto this segment 657 * and reinsert the data. 658 */ 659 if (q->ipqe_seq == pkt_seq + pkt_len) { 660 #ifdef TCPREASS_DEBUG 661 printf("tcp_reass[%p]: append %u:%u(%u) to %u:%u(%u)\n", 662 tp, q->ipqe_seq, q->ipqe_seq + q->ipqe_len, q->ipqe_len, 663 pkt_seq, pkt_seq + pkt_len, pkt_len); 664 #endif 665 pkt_len += q->ipqe_len; 666 pkt_flags |= q->ipqe_flags; 667 m_cat(m, q->ipqe_m); 668 TAILQ_REMOVE(&tp->segq, q, ipqe_q); 669 TAILQ_REMOVE(&tp->timeq, q, ipqe_timeq); 670 tp->t_segqlen--; 671 KASSERT(tp->t_segqlen >= 0); 672 KASSERT(tp->t_segqlen != 0 || 673 (TAILQ_EMPTY(&tp->segq) && 674 TAILQ_EMPTY(&tp->timeq))); 675 if (tiqe == NULL) { 676 tiqe = q; 677 } else { 678 tcpipqent_free(q); 679 } 680 TCP_REASS_COUNTER_INCR(&tcp_reass_prepend); 681 break; 682 } 683 /* 684 * If the fragment is before the segment, remember it. 685 * When this loop is terminated, p will contain the 686 * pointer to fragment that is right before the received 687 * segment. 688 */ 689 if (SEQ_LEQ(q->ipqe_seq, pkt_seq)) 690 p = q; 691 692 continue; 693 694 /* 695 * This is a common operation. It also will allow 696 * to save doing a malloc/free in most instances. 697 */ 698 free_ipqe: 699 TAILQ_REMOVE(&tp->segq, q, ipqe_q); 700 TAILQ_REMOVE(&tp->timeq, q, ipqe_timeq); 701 tp->t_segqlen--; 702 KASSERT(tp->t_segqlen >= 0); 703 KASSERT(tp->t_segqlen != 0 || 704 (TAILQ_EMPTY(&tp->segq) && TAILQ_EMPTY(&tp->timeq))); 705 if (tiqe == NULL) { 706 tiqe = q; 707 } else { 708 tcpipqent_free(q); 709 } 710 } 711 712 #ifdef TCP_REASS_COUNTERS 713 if (count > 7) 714 TCP_REASS_COUNTER_INCR(&tcp_reass_iteration[0]); 715 else if (count > 0) 716 TCP_REASS_COUNTER_INCR(&tcp_reass_iteration[count]); 717 #endif 718 719 insert_it: 720 721 /* 722 * Allocate a new queue entry since the received segment did not 723 * collapse onto any other out-of-order block; thus we are allocating 724 * a new block. If it had collapsed, tiqe would not be NULL and 725 * we would be reusing it. 726 * XXX If we can't, just drop the packet. XXX 727 */ 728 if (tiqe == NULL) { 729 tiqe = tcpipqent_alloc(); 730 if (tiqe == NULL) { 731 TCP_STATINC(TCP_STAT_RCVMEMDROP); 732 m_freem(m); 733 goto out; 734 } 735 } 736 737 /* 738 * Update the counters. 739 */ 740 tp->t_rcvoopack++; 741 tcps = TCP_STAT_GETREF(); 742 tcps[TCP_STAT_RCVOOPACK]++; 743 tcps[TCP_STAT_RCVOOBYTE] += rcvoobyte; 744 if (rcvpartdupbyte) { 745 tcps[TCP_STAT_RCVPARTDUPPACK]++; 746 tcps[TCP_STAT_RCVPARTDUPBYTE] += rcvpartdupbyte; 747 } 748 TCP_STAT_PUTREF(); 749 750 /* 751 * Insert the new fragment queue entry into both queues. 752 */ 753 tiqe->ipqe_m = m; 754 tiqe->ipre_mlast = m; 755 tiqe->ipqe_seq = pkt_seq; 756 tiqe->ipqe_len = pkt_len; 757 tiqe->ipqe_flags = pkt_flags; 758 if (p == NULL) { 759 TAILQ_INSERT_HEAD(&tp->segq, tiqe, ipqe_q); 760 #ifdef TCPREASS_DEBUG 761 if (tiqe->ipqe_seq != tp->rcv_nxt) 762 printf("tcp_reass[%p]: insert %u:%u(%u) at front\n", 763 tp, pkt_seq, pkt_seq + pkt_len, pkt_len); 764 #endif 765 } else { 766 TAILQ_INSERT_AFTER(&tp->segq, p, tiqe, ipqe_q); 767 #ifdef TCPREASS_DEBUG 768 printf("tcp_reass[%p]: insert %u:%u(%u) after %u:%u(%u)\n", 769 tp, pkt_seq, pkt_seq + pkt_len, pkt_len, 770 p->ipqe_seq, p->ipqe_seq + p->ipqe_len, p->ipqe_len); 771 #endif 772 } 773 tp->t_segqlen++; 774 775 skip_replacement: 776 777 TAILQ_INSERT_HEAD(&tp->timeq, tiqe, ipqe_timeq); 778 779 present: 780 /* 781 * Present data to user, advancing rcv_nxt through 782 * completed sequence space. 783 */ 784 if (TCPS_HAVEESTABLISHED(tp->t_state) == 0) 785 goto out; 786 q = TAILQ_FIRST(&tp->segq); 787 if (q == NULL || q->ipqe_seq != tp->rcv_nxt) 788 goto out; 789 if (tp->t_state == TCPS_SYN_RECEIVED && q->ipqe_len) 790 goto out; 791 792 tp->rcv_nxt += q->ipqe_len; 793 pkt_flags = q->ipqe_flags & TH_FIN; 794 nd6_hint(tp); 795 796 TAILQ_REMOVE(&tp->segq, q, ipqe_q); 797 TAILQ_REMOVE(&tp->timeq, q, ipqe_timeq); 798 tp->t_segqlen--; 799 KASSERT(tp->t_segqlen >= 0); 800 KASSERT(tp->t_segqlen != 0 || 801 (TAILQ_EMPTY(&tp->segq) && TAILQ_EMPTY(&tp->timeq))); 802 if (so->so_state & SS_CANTRCVMORE) 803 m_freem(q->ipqe_m); 804 else 805 sbappendstream(&so->so_rcv, q->ipqe_m); 806 tcpipqent_free(q); 807 TCP_REASS_UNLOCK(tp); 808 sorwakeup(so); 809 return (pkt_flags); 810 out: 811 TCP_REASS_UNLOCK(tp); 812 return (0); 813 } 814 815 #ifdef INET6 816 int 817 tcp6_input(struct mbuf **mp, int *offp, int proto) 818 { 819 struct mbuf *m = *mp; 820 821 /* 822 * draft-itojun-ipv6-tcp-to-anycast 823 * better place to put this in? 824 */ 825 if (m->m_flags & M_ANYCAST6) { 826 struct ip6_hdr *ip6; 827 if (m->m_len < sizeof(struct ip6_hdr)) { 828 if ((m = m_pullup(m, sizeof(struct ip6_hdr))) == NULL) { 829 TCP_STATINC(TCP_STAT_RCVSHORT); 830 return IPPROTO_DONE; 831 } 832 } 833 ip6 = mtod(m, struct ip6_hdr *); 834 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR, 835 (char *)&ip6->ip6_dst - (char *)ip6); 836 return IPPROTO_DONE; 837 } 838 839 tcp_input(m, *offp, proto); 840 return IPPROTO_DONE; 841 } 842 #endif 843 844 #ifdef INET 845 static void 846 tcp4_log_refused(const struct ip *ip, const struct tcphdr *th) 847 { 848 char src[INET_ADDRSTRLEN]; 849 char dst[INET_ADDRSTRLEN]; 850 851 if (ip) { 852 in_print(src, sizeof(src), &ip->ip_src); 853 in_print(dst, sizeof(dst), &ip->ip_dst); 854 } 855 else { 856 strlcpy(src, "(unknown)", sizeof(src)); 857 strlcpy(dst, "(unknown)", sizeof(dst)); 858 } 859 log(LOG_INFO, 860 "Connection attempt to TCP %s:%d from %s:%d\n", 861 dst, ntohs(th->th_dport), 862 src, ntohs(th->th_sport)); 863 } 864 #endif 865 866 #ifdef INET6 867 static void 868 tcp6_log_refused(const struct ip6_hdr *ip6, const struct tcphdr *th) 869 { 870 char src[INET6_ADDRSTRLEN]; 871 char dst[INET6_ADDRSTRLEN]; 872 873 if (ip6) { 874 in6_print(src, sizeof(src), &ip6->ip6_src); 875 in6_print(dst, sizeof(dst), &ip6->ip6_dst); 876 } 877 else { 878 strlcpy(src, "(unknown v6)", sizeof(src)); 879 strlcpy(dst, "(unknown v6)", sizeof(dst)); 880 } 881 log(LOG_INFO, 882 "Connection attempt to TCP [%s]:%d from [%s]:%d\n", 883 dst, ntohs(th->th_dport), 884 src, ntohs(th->th_sport)); 885 } 886 #endif 887 888 /* 889 * Checksum extended TCP header and data. 890 */ 891 int 892 tcp_input_checksum(int af, struct mbuf *m, const struct tcphdr *th, 893 int toff, int off, int tlen) 894 { 895 896 /* 897 * XXX it's better to record and check if this mbuf is 898 * already checked. 899 */ 900 901 switch (af) { 902 #ifdef INET 903 case AF_INET: 904 switch (m->m_pkthdr.csum_flags & 905 ((m->m_pkthdr.rcvif->if_csum_flags_rx & M_CSUM_TCPv4) | 906 M_CSUM_TCP_UDP_BAD | M_CSUM_DATA)) { 907 case M_CSUM_TCPv4|M_CSUM_TCP_UDP_BAD: 908 TCP_CSUM_COUNTER_INCR(&tcp_hwcsum_bad); 909 goto badcsum; 910 911 case M_CSUM_TCPv4|M_CSUM_DATA: { 912 u_int32_t hw_csum = m->m_pkthdr.csum_data; 913 914 TCP_CSUM_COUNTER_INCR(&tcp_hwcsum_data); 915 if (m->m_pkthdr.csum_flags & M_CSUM_NO_PSEUDOHDR) { 916 const struct ip *ip = 917 mtod(m, const struct ip *); 918 919 hw_csum = in_cksum_phdr(ip->ip_src.s_addr, 920 ip->ip_dst.s_addr, 921 htons(hw_csum + tlen + off + IPPROTO_TCP)); 922 } 923 if ((hw_csum ^ 0xffff) != 0) 924 goto badcsum; 925 break; 926 } 927 928 case M_CSUM_TCPv4: 929 /* Checksum was okay. */ 930 TCP_CSUM_COUNTER_INCR(&tcp_hwcsum_ok); 931 break; 932 933 default: 934 /* 935 * Must compute it ourselves. Maybe skip checksum 936 * on loopback interfaces. 937 */ 938 if (__predict_true(!(m->m_pkthdr.rcvif->if_flags & 939 IFF_LOOPBACK) || 940 tcp_do_loopback_cksum)) { 941 TCP_CSUM_COUNTER_INCR(&tcp_swcsum); 942 if (in4_cksum(m, IPPROTO_TCP, toff, 943 tlen + off) != 0) 944 goto badcsum; 945 } 946 break; 947 } 948 break; 949 #endif /* INET4 */ 950 951 #ifdef INET6 952 case AF_INET6: 953 switch (m->m_pkthdr.csum_flags & 954 ((m->m_pkthdr.rcvif->if_csum_flags_rx & M_CSUM_TCPv6) | 955 M_CSUM_TCP_UDP_BAD | M_CSUM_DATA)) { 956 case M_CSUM_TCPv6|M_CSUM_TCP_UDP_BAD: 957 TCP_CSUM_COUNTER_INCR(&tcp6_hwcsum_bad); 958 goto badcsum; 959 960 #if 0 /* notyet */ 961 case M_CSUM_TCPv6|M_CSUM_DATA: 962 #endif 963 964 case M_CSUM_TCPv6: 965 /* Checksum was okay. */ 966 TCP_CSUM_COUNTER_INCR(&tcp6_hwcsum_ok); 967 break; 968 969 default: 970 /* 971 * Must compute it ourselves. Maybe skip checksum 972 * on loopback interfaces. 973 */ 974 if (__predict_true((m->m_flags & M_LOOP) == 0 || 975 tcp_do_loopback_cksum)) { 976 TCP_CSUM_COUNTER_INCR(&tcp6_swcsum); 977 if (in6_cksum(m, IPPROTO_TCP, toff, 978 tlen + off) != 0) 979 goto badcsum; 980 } 981 } 982 break; 983 #endif /* INET6 */ 984 } 985 986 return 0; 987 988 badcsum: 989 TCP_STATINC(TCP_STAT_RCVBADSUM); 990 return -1; 991 } 992 993 /* When a packet arrives addressed to a vestigial tcpbp, we 994 * nevertheless have to respond to it per the spec. 995 */ 996 static void tcp_vtw_input(struct tcphdr *th, vestigial_inpcb_t *vp, 997 struct mbuf *m, int tlen, int multicast) 998 { 999 int tiflags; 1000 int todrop; 1001 uint32_t t_flags = 0; 1002 uint64_t *tcps; 1003 1004 tiflags = th->th_flags; 1005 todrop = vp->rcv_nxt - th->th_seq; 1006 1007 if (todrop > 0) { 1008 if (tiflags & TH_SYN) { 1009 tiflags &= ~TH_SYN; 1010 ++th->th_seq; 1011 if (th->th_urp > 1) 1012 --th->th_urp; 1013 else { 1014 tiflags &= ~TH_URG; 1015 th->th_urp = 0; 1016 } 1017 --todrop; 1018 } 1019 if (todrop > tlen || 1020 (todrop == tlen && (tiflags & TH_FIN) == 0)) { 1021 /* 1022 * Any valid FIN or RST must be to the left of the 1023 * window. At this point the FIN or RST must be a 1024 * duplicate or out of sequence; drop it. 1025 */ 1026 if (tiflags & TH_RST) 1027 goto drop; 1028 tiflags &= ~(TH_FIN|TH_RST); 1029 /* 1030 * Send an ACK to resynchronize and drop any data. 1031 * But keep on processing for RST or ACK. 1032 */ 1033 t_flags |= TF_ACKNOW; 1034 todrop = tlen; 1035 tcps = TCP_STAT_GETREF(); 1036 tcps[TCP_STAT_RCVDUPPACK] += 1; 1037 tcps[TCP_STAT_RCVDUPBYTE] += todrop; 1038 TCP_STAT_PUTREF(); 1039 } else if ((tiflags & TH_RST) 1040 && th->th_seq != vp->rcv_nxt) { 1041 /* 1042 * Test for reset before adjusting the sequence 1043 * number for overlapping data. 1044 */ 1045 goto dropafterack_ratelim; 1046 } else { 1047 tcps = TCP_STAT_GETREF(); 1048 tcps[TCP_STAT_RCVPARTDUPPACK] += 1; 1049 tcps[TCP_STAT_RCVPARTDUPBYTE] += todrop; 1050 TCP_STAT_PUTREF(); 1051 } 1052 1053 // tcp_new_dsack(tp, th->th_seq, todrop); 1054 // hdroptlen += todrop; /*drop from head afterwards*/ 1055 1056 th->th_seq += todrop; 1057 tlen -= todrop; 1058 1059 if (th->th_urp > todrop) 1060 th->th_urp -= todrop; 1061 else { 1062 tiflags &= ~TH_URG; 1063 th->th_urp = 0; 1064 } 1065 } 1066 1067 /* 1068 * If new data are received on a connection after the 1069 * user processes are gone, then RST the other end. 1070 */ 1071 if (tlen) { 1072 TCP_STATINC(TCP_STAT_RCVAFTERCLOSE); 1073 goto dropwithreset; 1074 } 1075 1076 /* 1077 * If segment ends after window, drop trailing data 1078 * (and PUSH and FIN); if nothing left, just ACK. 1079 */ 1080 todrop = (th->th_seq + tlen) - (vp->rcv_nxt+vp->rcv_wnd); 1081 1082 if (todrop > 0) { 1083 TCP_STATINC(TCP_STAT_RCVPACKAFTERWIN); 1084 if (todrop >= tlen) { 1085 /* 1086 * The segment actually starts after the window. 1087 * th->th_seq + tlen - vp->rcv_nxt - vp->rcv_wnd >= tlen 1088 * th->th_seq - vp->rcv_nxt - vp->rcv_wnd >= 0 1089 * th->th_seq >= vp->rcv_nxt + vp->rcv_wnd 1090 */ 1091 TCP_STATADD(TCP_STAT_RCVBYTEAFTERWIN, tlen); 1092 /* 1093 * If a new connection request is received 1094 * while in TIME_WAIT, drop the old connection 1095 * and start over if the sequence numbers 1096 * are above the previous ones. 1097 */ 1098 if ((tiflags & TH_SYN) 1099 && SEQ_GT(th->th_seq, vp->rcv_nxt)) { 1100 /* We only support this in the !NOFDREF case, which 1101 * is to say: not here. 1102 */ 1103 goto dropwithreset; 1104 } 1105 /* 1106 * If window is closed can only take segments at 1107 * window edge, and have to drop data and PUSH from 1108 * incoming segments. Continue processing, but 1109 * remember to ack. Otherwise, drop segment 1110 * and (if not RST) ack. 1111 */ 1112 if (vp->rcv_wnd == 0 && th->th_seq == vp->rcv_nxt) { 1113 t_flags |= TF_ACKNOW; 1114 TCP_STATINC(TCP_STAT_RCVWINPROBE); 1115 } else 1116 goto dropafterack; 1117 } else 1118 TCP_STATADD(TCP_STAT_RCVBYTEAFTERWIN, todrop); 1119 m_adj(m, -todrop); 1120 tlen -= todrop; 1121 tiflags &= ~(TH_PUSH|TH_FIN); 1122 } 1123 1124 if (tiflags & TH_RST) { 1125 if (th->th_seq != vp->rcv_nxt) 1126 goto dropafterack_ratelim; 1127 1128 vtw_del(vp->ctl, vp->vtw); 1129 goto drop; 1130 } 1131 1132 /* 1133 * If the ACK bit is off we drop the segment and return. 1134 */ 1135 if ((tiflags & TH_ACK) == 0) { 1136 if (t_flags & TF_ACKNOW) 1137 goto dropafterack; 1138 else 1139 goto drop; 1140 } 1141 1142 /* 1143 * In TIME_WAIT state the only thing that should arrive 1144 * is a retransmission of the remote FIN. Acknowledge 1145 * it and restart the finack timer. 1146 */ 1147 vtw_restart(vp); 1148 goto dropafterack; 1149 1150 dropafterack: 1151 /* 1152 * Generate an ACK dropping incoming segment if it occupies 1153 * sequence space, where the ACK reflects our state. 1154 */ 1155 if (tiflags & TH_RST) 1156 goto drop; 1157 goto dropafterack2; 1158 1159 dropafterack_ratelim: 1160 /* 1161 * We may want to rate-limit ACKs against SYN/RST attack. 1162 */ 1163 if (ppsratecheck(&tcp_ackdrop_ppslim_last, &tcp_ackdrop_ppslim_count, 1164 tcp_ackdrop_ppslim) == 0) { 1165 /* XXX stat */ 1166 goto drop; 1167 } 1168 /* ...fall into dropafterack2... */ 1169 1170 dropafterack2: 1171 (void)tcp_respond(0, m, m, th, th->th_seq + tlen, th->th_ack, 1172 TH_ACK); 1173 return; 1174 1175 dropwithreset: 1176 /* 1177 * Generate a RST, dropping incoming segment. 1178 * Make ACK acceptable to originator of segment. 1179 */ 1180 if (tiflags & TH_RST) 1181 goto drop; 1182 1183 if (tiflags & TH_ACK) 1184 tcp_respond(0, m, m, th, (tcp_seq)0, th->th_ack, TH_RST); 1185 else { 1186 if (tiflags & TH_SYN) 1187 ++tlen; 1188 (void)tcp_respond(0, m, m, th, th->th_seq + tlen, (tcp_seq)0, 1189 TH_RST|TH_ACK); 1190 } 1191 return; 1192 drop: 1193 m_freem(m); 1194 } 1195 1196 /* 1197 * TCP input routine, follows pages 65-76 of RFC 793 very closely. 1198 */ 1199 void 1200 tcp_input(struct mbuf *m, ...) 1201 { 1202 struct tcphdr *th; 1203 struct ip *ip; 1204 struct inpcb *inp; 1205 #ifdef INET6 1206 struct ip6_hdr *ip6; 1207 struct in6pcb *in6p; 1208 #endif 1209 u_int8_t *optp = NULL; 1210 int optlen = 0; 1211 int len, tlen, toff, hdroptlen = 0; 1212 struct tcpcb *tp = 0; 1213 int tiflags; 1214 struct socket *so = NULL; 1215 int todrop, acked, ourfinisacked, needoutput = 0; 1216 bool dupseg; 1217 #ifdef TCP_DEBUG 1218 short ostate = 0; 1219 #endif 1220 u_long tiwin; 1221 struct tcp_opt_info opti; 1222 int off, iphlen; 1223 va_list ap; 1224 int af; /* af on the wire */ 1225 struct mbuf *tcp_saveti = NULL; 1226 uint32_t ts_rtt; 1227 uint8_t iptos; 1228 uint64_t *tcps; 1229 vestigial_inpcb_t vestige; 1230 1231 vestige.valid = 0; 1232 1233 MCLAIM(m, &tcp_rx_mowner); 1234 va_start(ap, m); 1235 toff = va_arg(ap, int); 1236 (void)va_arg(ap, int); /* ignore value, advance ap */ 1237 va_end(ap); 1238 1239 TCP_STATINC(TCP_STAT_RCVTOTAL); 1240 1241 memset(&opti, 0, sizeof(opti)); 1242 opti.ts_present = 0; 1243 opti.maxseg = 0; 1244 1245 /* 1246 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN. 1247 * 1248 * TCP is, by definition, unicast, so we reject all 1249 * multicast outright. 1250 * 1251 * Note, there are additional src/dst address checks in 1252 * the AF-specific code below. 1253 */ 1254 if (m->m_flags & (M_BCAST|M_MCAST)) { 1255 /* XXX stat */ 1256 goto drop; 1257 } 1258 #ifdef INET6 1259 if (m->m_flags & M_ANYCAST6) { 1260 /* XXX stat */ 1261 goto drop; 1262 } 1263 #endif 1264 1265 /* 1266 * Get IP and TCP header. 1267 * Note: IP leaves IP header in first mbuf. 1268 */ 1269 ip = mtod(m, struct ip *); 1270 switch (ip->ip_v) { 1271 #ifdef INET 1272 case 4: 1273 #ifdef INET6 1274 ip6 = NULL; 1275 #endif 1276 af = AF_INET; 1277 iphlen = sizeof(struct ip); 1278 IP6_EXTHDR_GET(th, struct tcphdr *, m, toff, 1279 sizeof(struct tcphdr)); 1280 if (th == NULL) { 1281 TCP_STATINC(TCP_STAT_RCVSHORT); 1282 return; 1283 } 1284 /* We do the checksum after PCB lookup... */ 1285 len = ntohs(ip->ip_len); 1286 tlen = len - toff; 1287 iptos = ip->ip_tos; 1288 break; 1289 #endif 1290 #ifdef INET6 1291 case 6: 1292 ip = NULL; 1293 iphlen = sizeof(struct ip6_hdr); 1294 af = AF_INET6; 1295 ip6 = mtod(m, struct ip6_hdr *); 1296 IP6_EXTHDR_GET(th, struct tcphdr *, m, toff, 1297 sizeof(struct tcphdr)); 1298 if (th == NULL) { 1299 TCP_STATINC(TCP_STAT_RCVSHORT); 1300 return; 1301 } 1302 1303 /* Be proactive about malicious use of IPv4 mapped address */ 1304 if (IN6_IS_ADDR_V4MAPPED(&ip6->ip6_src) || 1305 IN6_IS_ADDR_V4MAPPED(&ip6->ip6_dst)) { 1306 /* XXX stat */ 1307 goto drop; 1308 } 1309 1310 /* 1311 * Be proactive about unspecified IPv6 address in source. 1312 * As we use all-zero to indicate unbounded/unconnected pcb, 1313 * unspecified IPv6 address can be used to confuse us. 1314 * 1315 * Note that packets with unspecified IPv6 destination is 1316 * already dropped in ip6_input. 1317 */ 1318 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) { 1319 /* XXX stat */ 1320 goto drop; 1321 } 1322 1323 /* 1324 * Make sure destination address is not multicast. 1325 * Source address checked in ip6_input(). 1326 */ 1327 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) { 1328 /* XXX stat */ 1329 goto drop; 1330 } 1331 1332 /* We do the checksum after PCB lookup... */ 1333 len = m->m_pkthdr.len; 1334 tlen = len - toff; 1335 iptos = (ntohl(ip6->ip6_flow) >> 20) & 0xff; 1336 break; 1337 #endif 1338 default: 1339 m_freem(m); 1340 return; 1341 } 1342 1343 KASSERT(TCP_HDR_ALIGNED_P(th)); 1344 1345 /* 1346 * Check that TCP offset makes sense, 1347 * pull out TCP options and adjust length. XXX 1348 */ 1349 off = th->th_off << 2; 1350 if (off < sizeof (struct tcphdr) || off > tlen) { 1351 TCP_STATINC(TCP_STAT_RCVBADOFF); 1352 goto drop; 1353 } 1354 tlen -= off; 1355 1356 /* 1357 * tcp_input() has been modified to use tlen to mean the TCP data 1358 * length throughout the function. Other functions can use 1359 * m->m_pkthdr.len as the basis for calculating the TCP data length. 1360 * rja 1361 */ 1362 1363 if (off > sizeof (struct tcphdr)) { 1364 IP6_EXTHDR_GET(th, struct tcphdr *, m, toff, off); 1365 if (th == NULL) { 1366 TCP_STATINC(TCP_STAT_RCVSHORT); 1367 return; 1368 } 1369 /* 1370 * NOTE: ip/ip6 will not be affected by m_pulldown() 1371 * (as they're before toff) and we don't need to update those. 1372 */ 1373 KASSERT(TCP_HDR_ALIGNED_P(th)); 1374 optlen = off - sizeof (struct tcphdr); 1375 optp = ((u_int8_t *)th) + sizeof(struct tcphdr); 1376 /* 1377 * Do quick retrieval of timestamp options ("options 1378 * prediction?"). If timestamp is the only option and it's 1379 * formatted as recommended in RFC 1323 appendix A, we 1380 * quickly get the values now and not bother calling 1381 * tcp_dooptions(), etc. 1382 */ 1383 if ((optlen == TCPOLEN_TSTAMP_APPA || 1384 (optlen > TCPOLEN_TSTAMP_APPA && 1385 optp[TCPOLEN_TSTAMP_APPA] == TCPOPT_EOL)) && 1386 *(u_int32_t *)optp == htonl(TCPOPT_TSTAMP_HDR) && 1387 (th->th_flags & TH_SYN) == 0) { 1388 opti.ts_present = 1; 1389 opti.ts_val = ntohl(*(u_int32_t *)(optp + 4)); 1390 opti.ts_ecr = ntohl(*(u_int32_t *)(optp + 8)); 1391 optp = NULL; /* we've parsed the options */ 1392 } 1393 } 1394 tiflags = th->th_flags; 1395 1396 /* 1397 * Checksum extended TCP header and data 1398 */ 1399 if (tcp_input_checksum(af, m, th, toff, off, tlen)) 1400 goto badcsum; 1401 1402 /* 1403 * Locate pcb for segment. 1404 */ 1405 findpcb: 1406 inp = NULL; 1407 #ifdef INET6 1408 in6p = NULL; 1409 #endif 1410 switch (af) { 1411 #ifdef INET 1412 case AF_INET: 1413 inp = in_pcblookup_connect(&tcbtable, ip->ip_src, th->th_sport, 1414 ip->ip_dst, th->th_dport, 1415 &vestige); 1416 if (inp == 0 && !vestige.valid) { 1417 TCP_STATINC(TCP_STAT_PCBHASHMISS); 1418 inp = in_pcblookup_bind(&tcbtable, ip->ip_dst, th->th_dport); 1419 } 1420 #ifdef INET6 1421 if (inp == 0 && !vestige.valid) { 1422 struct in6_addr s, d; 1423 1424 /* mapped addr case */ 1425 memset(&s, 0, sizeof(s)); 1426 s.s6_addr16[5] = htons(0xffff); 1427 bcopy(&ip->ip_src, &s.s6_addr32[3], sizeof(ip->ip_src)); 1428 memset(&d, 0, sizeof(d)); 1429 d.s6_addr16[5] = htons(0xffff); 1430 bcopy(&ip->ip_dst, &d.s6_addr32[3], sizeof(ip->ip_dst)); 1431 in6p = in6_pcblookup_connect(&tcbtable, &s, 1432 th->th_sport, &d, th->th_dport, 1433 0, &vestige); 1434 if (in6p == 0 && !vestige.valid) { 1435 TCP_STATINC(TCP_STAT_PCBHASHMISS); 1436 in6p = in6_pcblookup_bind(&tcbtable, &d, 1437 th->th_dport, 0); 1438 } 1439 } 1440 #endif 1441 #ifndef INET6 1442 if (inp == 0 && !vestige.valid) 1443 #else 1444 if (inp == 0 && in6p == 0 && !vestige.valid) 1445 #endif 1446 { 1447 TCP_STATINC(TCP_STAT_NOPORT); 1448 if (tcp_log_refused && 1449 (tiflags & (TH_RST|TH_ACK|TH_SYN)) == TH_SYN) { 1450 tcp4_log_refused(ip, th); 1451 } 1452 tcp_fields_to_host(th); 1453 goto dropwithreset_ratelim; 1454 } 1455 #if defined(IPSEC) 1456 if (ipsec_used) { 1457 if (inp && 1458 (inp->inp_socket->so_options & SO_ACCEPTCONN) == 0 1459 && ipsec4_in_reject(m, inp)) { 1460 IPSEC_STATINC(IPSEC_STAT_IN_POLVIO); 1461 goto drop; 1462 } 1463 #ifdef INET6 1464 else if (in6p && 1465 (in6p->in6p_socket->so_options & SO_ACCEPTCONN) == 0 1466 && ipsec6_in_reject_so(m, in6p->in6p_socket)) { 1467 IPSEC_STATINC(IPSEC_STAT_IN_POLVIO); 1468 goto drop; 1469 } 1470 #endif 1471 } 1472 #endif /*IPSEC*/ 1473 break; 1474 #endif /*INET*/ 1475 #ifdef INET6 1476 case AF_INET6: 1477 { 1478 int faith; 1479 1480 #if defined(NFAITH) && NFAITH > 0 1481 faith = faithprefix(&ip6->ip6_dst); 1482 #else 1483 faith = 0; 1484 #endif 1485 in6p = in6_pcblookup_connect(&tcbtable, &ip6->ip6_src, 1486 th->th_sport, &ip6->ip6_dst, th->th_dport, faith, &vestige); 1487 if (!in6p && !vestige.valid) { 1488 TCP_STATINC(TCP_STAT_PCBHASHMISS); 1489 in6p = in6_pcblookup_bind(&tcbtable, &ip6->ip6_dst, 1490 th->th_dport, faith); 1491 } 1492 if (!in6p && !vestige.valid) { 1493 TCP_STATINC(TCP_STAT_NOPORT); 1494 if (tcp_log_refused && 1495 (tiflags & (TH_RST|TH_ACK|TH_SYN)) == TH_SYN) { 1496 tcp6_log_refused(ip6, th); 1497 } 1498 tcp_fields_to_host(th); 1499 goto dropwithreset_ratelim; 1500 } 1501 #if defined(IPSEC) 1502 if (ipsec_used && in6p 1503 && (in6p->in6p_socket->so_options & SO_ACCEPTCONN) == 0 1504 && ipsec6_in_reject(m, in6p)) { 1505 IPSEC6_STATINC(IPSEC_STAT_IN_POLVIO); 1506 goto drop; 1507 } 1508 #endif /*IPSEC*/ 1509 break; 1510 } 1511 #endif 1512 } 1513 1514 /* 1515 * If the state is CLOSED (i.e., TCB does not exist) then 1516 * all data in the incoming segment is discarded. 1517 * If the TCB exists but is in CLOSED state, it is embryonic, 1518 * but should either do a listen or a connect soon. 1519 */ 1520 tp = NULL; 1521 so = NULL; 1522 if (inp) { 1523 /* Check the minimum TTL for socket. */ 1524 if (ip->ip_ttl < inp->inp_ip_minttl) 1525 goto drop; 1526 1527 tp = intotcpcb(inp); 1528 so = inp->inp_socket; 1529 } 1530 #ifdef INET6 1531 else if (in6p) { 1532 tp = in6totcpcb(in6p); 1533 so = in6p->in6p_socket; 1534 } 1535 #endif 1536 else if (vestige.valid) { 1537 int mc = 0; 1538 1539 /* We do not support the resurrection of vtw tcpcps. 1540 */ 1541 if (tcp_input_checksum(af, m, th, toff, off, tlen)) 1542 goto badcsum; 1543 1544 switch (af) { 1545 #ifdef INET6 1546 case AF_INET6: 1547 mc = IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst); 1548 break; 1549 #endif 1550 1551 case AF_INET: 1552 mc = (IN_MULTICAST(ip->ip_dst.s_addr) 1553 || in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)); 1554 break; 1555 } 1556 1557 tcp_fields_to_host(th); 1558 tcp_vtw_input(th, &vestige, m, tlen, mc); 1559 m = 0; 1560 goto drop; 1561 } 1562 1563 if (tp == 0) { 1564 tcp_fields_to_host(th); 1565 goto dropwithreset_ratelim; 1566 } 1567 if (tp->t_state == TCPS_CLOSED) 1568 goto drop; 1569 1570 KASSERT(so->so_lock == softnet_lock); 1571 KASSERT(solocked(so)); 1572 1573 tcp_fields_to_host(th); 1574 1575 /* Unscale the window into a 32-bit value. */ 1576 if ((tiflags & TH_SYN) == 0) 1577 tiwin = th->th_win << tp->snd_scale; 1578 else 1579 tiwin = th->th_win; 1580 1581 #ifdef INET6 1582 /* save packet options if user wanted */ 1583 if (in6p && (in6p->in6p_flags & IN6P_CONTROLOPTS)) { 1584 if (in6p->in6p_options) { 1585 m_freem(in6p->in6p_options); 1586 in6p->in6p_options = 0; 1587 } 1588 KASSERT(ip6 != NULL); 1589 ip6_savecontrol(in6p, &in6p->in6p_options, ip6, m); 1590 } 1591 #endif 1592 1593 if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) { 1594 union syn_cache_sa src; 1595 union syn_cache_sa dst; 1596 1597 memset(&src, 0, sizeof(src)); 1598 memset(&dst, 0, sizeof(dst)); 1599 switch (af) { 1600 #ifdef INET 1601 case AF_INET: 1602 src.sin.sin_len = sizeof(struct sockaddr_in); 1603 src.sin.sin_family = AF_INET; 1604 src.sin.sin_addr = ip->ip_src; 1605 src.sin.sin_port = th->th_sport; 1606 1607 dst.sin.sin_len = sizeof(struct sockaddr_in); 1608 dst.sin.sin_family = AF_INET; 1609 dst.sin.sin_addr = ip->ip_dst; 1610 dst.sin.sin_port = th->th_dport; 1611 break; 1612 #endif 1613 #ifdef INET6 1614 case AF_INET6: 1615 src.sin6.sin6_len = sizeof(struct sockaddr_in6); 1616 src.sin6.sin6_family = AF_INET6; 1617 src.sin6.sin6_addr = ip6->ip6_src; 1618 src.sin6.sin6_port = th->th_sport; 1619 1620 dst.sin6.sin6_len = sizeof(struct sockaddr_in6); 1621 dst.sin6.sin6_family = AF_INET6; 1622 dst.sin6.sin6_addr = ip6->ip6_dst; 1623 dst.sin6.sin6_port = th->th_dport; 1624 break; 1625 #endif /* INET6 */ 1626 default: 1627 goto badsyn; /*sanity*/ 1628 } 1629 1630 if (so->so_options & SO_DEBUG) { 1631 #ifdef TCP_DEBUG 1632 ostate = tp->t_state; 1633 #endif 1634 1635 tcp_saveti = NULL; 1636 if (iphlen + sizeof(struct tcphdr) > MHLEN) 1637 goto nosave; 1638 1639 if (m->m_len > iphlen && (m->m_flags & M_EXT) == 0) { 1640 tcp_saveti = m_copym(m, 0, iphlen, M_DONTWAIT); 1641 if (!tcp_saveti) 1642 goto nosave; 1643 } else { 1644 MGETHDR(tcp_saveti, M_DONTWAIT, MT_HEADER); 1645 if (!tcp_saveti) 1646 goto nosave; 1647 MCLAIM(m, &tcp_mowner); 1648 tcp_saveti->m_len = iphlen; 1649 m_copydata(m, 0, iphlen, 1650 mtod(tcp_saveti, void *)); 1651 } 1652 1653 if (M_TRAILINGSPACE(tcp_saveti) < sizeof(struct tcphdr)) { 1654 m_freem(tcp_saveti); 1655 tcp_saveti = NULL; 1656 } else { 1657 tcp_saveti->m_len += sizeof(struct tcphdr); 1658 memcpy(mtod(tcp_saveti, char *) + iphlen, th, 1659 sizeof(struct tcphdr)); 1660 } 1661 nosave:; 1662 } 1663 if (so->so_options & SO_ACCEPTCONN) { 1664 if ((tiflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) { 1665 if (tiflags & TH_RST) { 1666 syn_cache_reset(&src.sa, &dst.sa, th); 1667 } else if ((tiflags & (TH_ACK|TH_SYN)) == 1668 (TH_ACK|TH_SYN)) { 1669 /* 1670 * Received a SYN,ACK. This should 1671 * never happen while we are in 1672 * LISTEN. Send an RST. 1673 */ 1674 goto badsyn; 1675 } else if (tiflags & TH_ACK) { 1676 so = syn_cache_get(&src.sa, &dst.sa, 1677 th, toff, tlen, so, m); 1678 if (so == NULL) { 1679 /* 1680 * We don't have a SYN for 1681 * this ACK; send an RST. 1682 */ 1683 goto badsyn; 1684 } else if (so == 1685 (struct socket *)(-1)) { 1686 /* 1687 * We were unable to create 1688 * the connection. If the 1689 * 3-way handshake was 1690 * completed, and RST has 1691 * been sent to the peer. 1692 * Since the mbuf might be 1693 * in use for the reply, 1694 * do not free it. 1695 */ 1696 m = NULL; 1697 } else { 1698 /* 1699 * We have created a 1700 * full-blown connection. 1701 */ 1702 tp = NULL; 1703 inp = NULL; 1704 #ifdef INET6 1705 in6p = NULL; 1706 #endif 1707 switch (so->so_proto->pr_domain->dom_family) { 1708 #ifdef INET 1709 case AF_INET: 1710 inp = sotoinpcb(so); 1711 tp = intotcpcb(inp); 1712 break; 1713 #endif 1714 #ifdef INET6 1715 case AF_INET6: 1716 in6p = sotoin6pcb(so); 1717 tp = in6totcpcb(in6p); 1718 break; 1719 #endif 1720 } 1721 if (tp == NULL) 1722 goto badsyn; /*XXX*/ 1723 tiwin <<= tp->snd_scale; 1724 goto after_listen; 1725 } 1726 } else { 1727 /* 1728 * None of RST, SYN or ACK was set. 1729 * This is an invalid packet for a 1730 * TCB in LISTEN state. Send a RST. 1731 */ 1732 goto badsyn; 1733 } 1734 } else { 1735 /* 1736 * Received a SYN. 1737 * 1738 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN 1739 */ 1740 if (m->m_flags & (M_BCAST|M_MCAST)) 1741 goto drop; 1742 1743 switch (af) { 1744 #ifdef INET6 1745 case AF_INET6: 1746 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) 1747 goto drop; 1748 break; 1749 #endif /* INET6 */ 1750 case AF_INET: 1751 if (IN_MULTICAST(ip->ip_dst.s_addr) || 1752 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) 1753 goto drop; 1754 break; 1755 } 1756 1757 #ifdef INET6 1758 /* 1759 * If deprecated address is forbidden, we do 1760 * not accept SYN to deprecated interface 1761 * address to prevent any new inbound 1762 * connection from getting established. 1763 * When we do not accept SYN, we send a TCP 1764 * RST, with deprecated source address (instead 1765 * of dropping it). We compromise it as it is 1766 * much better for peer to send a RST, and 1767 * RST will be the final packet for the 1768 * exchange. 1769 * 1770 * If we do not forbid deprecated addresses, we 1771 * accept the SYN packet. RFC2462 does not 1772 * suggest dropping SYN in this case. 1773 * If we decipher RFC2462 5.5.4, it says like 1774 * this: 1775 * 1. use of deprecated addr with existing 1776 * communication is okay - "SHOULD continue 1777 * to be used" 1778 * 2. use of it with new communication: 1779 * (2a) "SHOULD NOT be used if alternate 1780 * address with sufficient scope is 1781 * available" 1782 * (2b) nothing mentioned otherwise. 1783 * Here we fall into (2b) case as we have no 1784 * choice in our source address selection - we 1785 * must obey the peer. 1786 * 1787 * The wording in RFC2462 is confusing, and 1788 * there are multiple description text for 1789 * deprecated address handling - worse, they 1790 * are not exactly the same. I believe 5.5.4 1791 * is the best one, so we follow 5.5.4. 1792 */ 1793 if (af == AF_INET6 && !ip6_use_deprecated) { 1794 struct in6_ifaddr *ia6; 1795 if ((ia6 = in6ifa_ifpwithaddr(m->m_pkthdr.rcvif, 1796 &ip6->ip6_dst)) && 1797 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) { 1798 tp = NULL; 1799 goto dropwithreset; 1800 } 1801 } 1802 #endif 1803 1804 #if defined(IPSEC) 1805 if (ipsec_used) { 1806 switch (af) { 1807 #ifdef INET 1808 case AF_INET: 1809 if (!ipsec4_in_reject_so(m, so)) 1810 break; 1811 IPSEC_STATINC( 1812 IPSEC_STAT_IN_POLVIO); 1813 tp = NULL; 1814 goto dropwithreset; 1815 #endif 1816 #ifdef INET6 1817 case AF_INET6: 1818 if (!ipsec6_in_reject_so(m, so)) 1819 break; 1820 IPSEC6_STATINC( 1821 IPSEC_STAT_IN_POLVIO); 1822 tp = NULL; 1823 goto dropwithreset; 1824 #endif /*INET6*/ 1825 } 1826 } 1827 #endif /*IPSEC*/ 1828 1829 /* 1830 * LISTEN socket received a SYN 1831 * from itself? This can't possibly 1832 * be valid; drop the packet. 1833 */ 1834 if (th->th_sport == th->th_dport) { 1835 int i; 1836 1837 switch (af) { 1838 #ifdef INET 1839 case AF_INET: 1840 i = in_hosteq(ip->ip_src, ip->ip_dst); 1841 break; 1842 #endif 1843 #ifdef INET6 1844 case AF_INET6: 1845 i = IN6_ARE_ADDR_EQUAL(&ip6->ip6_src, &ip6->ip6_dst); 1846 break; 1847 #endif 1848 default: 1849 i = 1; 1850 } 1851 if (i) { 1852 TCP_STATINC(TCP_STAT_BADSYN); 1853 goto drop; 1854 } 1855 } 1856 1857 /* 1858 * SYN looks ok; create compressed TCP 1859 * state for it. 1860 */ 1861 if (so->so_qlen <= so->so_qlimit && 1862 syn_cache_add(&src.sa, &dst.sa, th, tlen, 1863 so, m, optp, optlen, &opti)) 1864 m = NULL; 1865 } 1866 goto drop; 1867 } 1868 } 1869 1870 after_listen: 1871 #ifdef DIAGNOSTIC 1872 /* 1873 * Should not happen now that all embryonic connections 1874 * are handled with compressed state. 1875 */ 1876 if (tp->t_state == TCPS_LISTEN) 1877 panic("tcp_input: TCPS_LISTEN"); 1878 #endif 1879 1880 /* 1881 * Segment received on connection. 1882 * Reset idle time and keep-alive timer. 1883 */ 1884 tp->t_rcvtime = tcp_now; 1885 if (TCPS_HAVEESTABLISHED(tp->t_state)) 1886 TCP_TIMER_ARM(tp, TCPT_KEEP, tp->t_keepidle); 1887 1888 /* 1889 * Process options. 1890 */ 1891 #ifdef TCP_SIGNATURE 1892 if (optp || (tp->t_flags & TF_SIGNATURE)) 1893 #else 1894 if (optp) 1895 #endif 1896 if (tcp_dooptions(tp, optp, optlen, th, m, toff, &opti) < 0) 1897 goto drop; 1898 1899 if (TCP_SACK_ENABLED(tp)) { 1900 tcp_del_sackholes(tp, th); 1901 } 1902 1903 if (TCP_ECN_ALLOWED(tp)) { 1904 if (tiflags & TH_CWR) { 1905 tp->t_flags &= ~TF_ECN_SND_ECE; 1906 } 1907 switch (iptos & IPTOS_ECN_MASK) { 1908 case IPTOS_ECN_CE: 1909 tp->t_flags |= TF_ECN_SND_ECE; 1910 TCP_STATINC(TCP_STAT_ECN_CE); 1911 break; 1912 case IPTOS_ECN_ECT0: 1913 TCP_STATINC(TCP_STAT_ECN_ECT); 1914 break; 1915 case IPTOS_ECN_ECT1: 1916 /* XXX: ignore for now -- rpaulo */ 1917 break; 1918 } 1919 /* 1920 * Congestion experienced. 1921 * Ignore if we are already trying to recover. 1922 */ 1923 if ((tiflags & TH_ECE) && SEQ_GEQ(tp->snd_una, tp->snd_recover)) 1924 tp->t_congctl->cong_exp(tp); 1925 } 1926 1927 if (opti.ts_present && opti.ts_ecr) { 1928 /* 1929 * Calculate the RTT from the returned time stamp and the 1930 * connection's time base. If the time stamp is later than 1931 * the current time, or is extremely old, fall back to non-1323 1932 * RTT calculation. Since ts_rtt is unsigned, we can test both 1933 * at the same time. 1934 * 1935 * Note that ts_rtt is in units of slow ticks (500 1936 * ms). Since most earthbound RTTs are < 500 ms, 1937 * observed values will have large quantization noise. 1938 * Our smoothed RTT is then the fraction of observed 1939 * samples that are 1 tick instead of 0 (times 500 1940 * ms). 1941 * 1942 * ts_rtt is increased by 1 to denote a valid sample, 1943 * with 0 indicating an invalid measurement. This 1944 * extra 1 must be removed when ts_rtt is used, or 1945 * else an an erroneous extra 500 ms will result. 1946 */ 1947 ts_rtt = TCP_TIMESTAMP(tp) - opti.ts_ecr + 1; 1948 if (ts_rtt > TCP_PAWS_IDLE) 1949 ts_rtt = 0; 1950 } else { 1951 ts_rtt = 0; 1952 } 1953 1954 /* 1955 * Header prediction: check for the two common cases 1956 * of a uni-directional data xfer. If the packet has 1957 * no control flags, is in-sequence, the window didn't 1958 * change and we're not retransmitting, it's a 1959 * candidate. If the length is zero and the ack moved 1960 * forward, we're the sender side of the xfer. Just 1961 * free the data acked & wake any higher level process 1962 * that was blocked waiting for space. If the length 1963 * is non-zero and the ack didn't move, we're the 1964 * receiver side. If we're getting packets in-order 1965 * (the reassembly queue is empty), add the data to 1966 * the socket buffer and note that we need a delayed ack. 1967 */ 1968 if (tp->t_state == TCPS_ESTABLISHED && 1969 (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ECE|TH_CWR|TH_ACK)) 1970 == TH_ACK && 1971 (!opti.ts_present || TSTMP_GEQ(opti.ts_val, tp->ts_recent)) && 1972 th->th_seq == tp->rcv_nxt && 1973 tiwin && tiwin == tp->snd_wnd && 1974 tp->snd_nxt == tp->snd_max) { 1975 1976 /* 1977 * If last ACK falls within this segment's sequence numbers, 1978 * record the timestamp. 1979 * NOTE that the test is modified according to the latest 1980 * proposal of the tcplw@cray.com list (Braden 1993/04/26). 1981 * 1982 * note that we already know 1983 * TSTMP_GEQ(opti.ts_val, tp->ts_recent) 1984 */ 1985 if (opti.ts_present && 1986 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) { 1987 tp->ts_recent_age = tcp_now; 1988 tp->ts_recent = opti.ts_val; 1989 } 1990 1991 if (tlen == 0) { 1992 /* Ack prediction. */ 1993 if (SEQ_GT(th->th_ack, tp->snd_una) && 1994 SEQ_LEQ(th->th_ack, tp->snd_max) && 1995 tp->snd_cwnd >= tp->snd_wnd && 1996 tp->t_partialacks < 0) { 1997 /* 1998 * this is a pure ack for outstanding data. 1999 */ 2000 if (ts_rtt) 2001 tcp_xmit_timer(tp, ts_rtt - 1); 2002 else if (tp->t_rtttime && 2003 SEQ_GT(th->th_ack, tp->t_rtseq)) 2004 tcp_xmit_timer(tp, 2005 tcp_now - tp->t_rtttime); 2006 acked = th->th_ack - tp->snd_una; 2007 tcps = TCP_STAT_GETREF(); 2008 tcps[TCP_STAT_PREDACK]++; 2009 tcps[TCP_STAT_RCVACKPACK]++; 2010 tcps[TCP_STAT_RCVACKBYTE] += acked; 2011 TCP_STAT_PUTREF(); 2012 nd6_hint(tp); 2013 2014 if (acked > (tp->t_lastoff - tp->t_inoff)) 2015 tp->t_lastm = NULL; 2016 sbdrop(&so->so_snd, acked); 2017 tp->t_lastoff -= acked; 2018 2019 icmp_check(tp, th, acked); 2020 2021 tp->snd_una = th->th_ack; 2022 tp->snd_fack = tp->snd_una; 2023 if (SEQ_LT(tp->snd_high, tp->snd_una)) 2024 tp->snd_high = tp->snd_una; 2025 m_freem(m); 2026 2027 /* 2028 * If all outstanding data are acked, stop 2029 * retransmit timer, otherwise restart timer 2030 * using current (possibly backed-off) value. 2031 * If process is waiting for space, 2032 * wakeup/selnotify/signal. If data 2033 * are ready to send, let tcp_output 2034 * decide between more output or persist. 2035 */ 2036 if (tp->snd_una == tp->snd_max) 2037 TCP_TIMER_DISARM(tp, TCPT_REXMT); 2038 else if (TCP_TIMER_ISARMED(tp, 2039 TCPT_PERSIST) == 0) 2040 TCP_TIMER_ARM(tp, TCPT_REXMT, 2041 tp->t_rxtcur); 2042 2043 sowwakeup(so); 2044 if (so->so_snd.sb_cc) { 2045 KERNEL_LOCK(1, NULL); 2046 (void) tcp_output(tp); 2047 KERNEL_UNLOCK_ONE(NULL); 2048 } 2049 if (tcp_saveti) 2050 m_freem(tcp_saveti); 2051 return; 2052 } 2053 } else if (th->th_ack == tp->snd_una && 2054 TAILQ_FIRST(&tp->segq) == NULL && 2055 tlen <= sbspace(&so->so_rcv)) { 2056 int newsize = 0; /* automatic sockbuf scaling */ 2057 2058 /* 2059 * this is a pure, in-sequence data packet 2060 * with nothing on the reassembly queue and 2061 * we have enough buffer space to take it. 2062 */ 2063 tp->rcv_nxt += tlen; 2064 tcps = TCP_STAT_GETREF(); 2065 tcps[TCP_STAT_PREDDAT]++; 2066 tcps[TCP_STAT_RCVPACK]++; 2067 tcps[TCP_STAT_RCVBYTE] += tlen; 2068 TCP_STAT_PUTREF(); 2069 nd6_hint(tp); 2070 2071 /* 2072 * Automatic sizing enables the performance of large buffers 2073 * and most of the efficiency of small ones by only allocating 2074 * space when it is needed. 2075 * 2076 * On the receive side the socket buffer memory is only rarely 2077 * used to any significant extent. This allows us to be much 2078 * more aggressive in scaling the receive socket buffer. For 2079 * the case that the buffer space is actually used to a large 2080 * extent and we run out of kernel memory we can simply drop 2081 * the new segments; TCP on the sender will just retransmit it 2082 * later. Setting the buffer size too big may only consume too 2083 * much kernel memory if the application doesn't read() from 2084 * the socket or packet loss or reordering makes use of the 2085 * reassembly queue. 2086 * 2087 * The criteria to step up the receive buffer one notch are: 2088 * 1. the number of bytes received during the time it takes 2089 * one timestamp to be reflected back to us (the RTT); 2090 * 2. received bytes per RTT is within seven eighth of the 2091 * current socket buffer size; 2092 * 3. receive buffer size has not hit maximal automatic size; 2093 * 2094 * This algorithm does one step per RTT at most and only if 2095 * we receive a bulk stream w/o packet losses or reorderings. 2096 * Shrinking the buffer during idle times is not necessary as 2097 * it doesn't consume any memory when idle. 2098 * 2099 * TODO: Only step up if the application is actually serving 2100 * the buffer to better manage the socket buffer resources. 2101 */ 2102 if (tcp_do_autorcvbuf && 2103 opti.ts_ecr && 2104 (so->so_rcv.sb_flags & SB_AUTOSIZE)) { 2105 if (opti.ts_ecr > tp->rfbuf_ts && 2106 opti.ts_ecr - tp->rfbuf_ts < PR_SLOWHZ) { 2107 if (tp->rfbuf_cnt > 2108 (so->so_rcv.sb_hiwat / 8 * 7) && 2109 so->so_rcv.sb_hiwat < 2110 tcp_autorcvbuf_max) { 2111 newsize = 2112 min(so->so_rcv.sb_hiwat + 2113 tcp_autorcvbuf_inc, 2114 tcp_autorcvbuf_max); 2115 } 2116 /* Start over with next RTT. */ 2117 tp->rfbuf_ts = 0; 2118 tp->rfbuf_cnt = 0; 2119 } else 2120 tp->rfbuf_cnt += tlen; /* add up */ 2121 } 2122 2123 /* 2124 * Drop TCP, IP headers and TCP options then add data 2125 * to socket buffer. 2126 */ 2127 if (so->so_state & SS_CANTRCVMORE) 2128 m_freem(m); 2129 else { 2130 /* 2131 * Set new socket buffer size. 2132 * Give up when limit is reached. 2133 */ 2134 if (newsize) 2135 if (!sbreserve(&so->so_rcv, 2136 newsize, so)) 2137 so->so_rcv.sb_flags &= ~SB_AUTOSIZE; 2138 m_adj(m, toff + off); 2139 sbappendstream(&so->so_rcv, m); 2140 } 2141 sorwakeup(so); 2142 tcp_setup_ack(tp, th); 2143 if (tp->t_flags & TF_ACKNOW) { 2144 KERNEL_LOCK(1, NULL); 2145 (void) tcp_output(tp); 2146 KERNEL_UNLOCK_ONE(NULL); 2147 } 2148 if (tcp_saveti) 2149 m_freem(tcp_saveti); 2150 return; 2151 } 2152 } 2153 2154 /* 2155 * Compute mbuf offset to TCP data segment. 2156 */ 2157 hdroptlen = toff + off; 2158 2159 /* 2160 * Calculate amount of space in receive window, 2161 * and then do TCP input processing. 2162 * Receive window is amount of space in rcv queue, 2163 * but not less than advertised window. 2164 */ 2165 { int win; 2166 2167 win = sbspace(&so->so_rcv); 2168 if (win < 0) 2169 win = 0; 2170 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt)); 2171 } 2172 2173 /* Reset receive buffer auto scaling when not in bulk receive mode. */ 2174 tp->rfbuf_ts = 0; 2175 tp->rfbuf_cnt = 0; 2176 2177 switch (tp->t_state) { 2178 /* 2179 * If the state is SYN_SENT: 2180 * if seg contains an ACK, but not for our SYN, drop the input. 2181 * if seg contains a RST, then drop the connection. 2182 * if seg does not contain SYN, then drop it. 2183 * Otherwise this is an acceptable SYN segment 2184 * initialize tp->rcv_nxt and tp->irs 2185 * if seg contains ack then advance tp->snd_una 2186 * if seg contains a ECE and ECN support is enabled, the stream 2187 * is ECN capable. 2188 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state 2189 * arrange for segment to be acked (eventually) 2190 * continue processing rest of data/controls, beginning with URG 2191 */ 2192 case TCPS_SYN_SENT: 2193 if ((tiflags & TH_ACK) && 2194 (SEQ_LEQ(th->th_ack, tp->iss) || 2195 SEQ_GT(th->th_ack, tp->snd_max))) 2196 goto dropwithreset; 2197 if (tiflags & TH_RST) { 2198 if (tiflags & TH_ACK) 2199 tp = tcp_drop(tp, ECONNREFUSED); 2200 goto drop; 2201 } 2202 if ((tiflags & TH_SYN) == 0) 2203 goto drop; 2204 if (tiflags & TH_ACK) { 2205 tp->snd_una = th->th_ack; 2206 if (SEQ_LT(tp->snd_nxt, tp->snd_una)) 2207 tp->snd_nxt = tp->snd_una; 2208 if (SEQ_LT(tp->snd_high, tp->snd_una)) 2209 tp->snd_high = tp->snd_una; 2210 TCP_TIMER_DISARM(tp, TCPT_REXMT); 2211 2212 if ((tiflags & TH_ECE) && tcp_do_ecn) { 2213 tp->t_flags |= TF_ECN_PERMIT; 2214 TCP_STATINC(TCP_STAT_ECN_SHS); 2215 } 2216 2217 } 2218 tp->irs = th->th_seq; 2219 tcp_rcvseqinit(tp); 2220 tp->t_flags |= TF_ACKNOW; 2221 tcp_mss_from_peer(tp, opti.maxseg); 2222 2223 /* 2224 * Initialize the initial congestion window. If we 2225 * had to retransmit the SYN, we must initialize cwnd 2226 * to 1 segment (i.e. the Loss Window). 2227 */ 2228 if (tp->t_flags & TF_SYN_REXMT) 2229 tp->snd_cwnd = tp->t_peermss; 2230 else { 2231 int ss = tcp_init_win; 2232 #ifdef INET 2233 if (inp != NULL && in_localaddr(inp->inp_faddr)) 2234 ss = tcp_init_win_local; 2235 #endif 2236 #ifdef INET6 2237 if (in6p != NULL && in6_localaddr(&in6p->in6p_faddr)) 2238 ss = tcp_init_win_local; 2239 #endif 2240 tp->snd_cwnd = TCP_INITIAL_WINDOW(ss, tp->t_peermss); 2241 } 2242 2243 tcp_rmx_rtt(tp); 2244 if (tiflags & TH_ACK) { 2245 TCP_STATINC(TCP_STAT_CONNECTS); 2246 /* 2247 * move tcp_established before soisconnected 2248 * because upcall handler can drive tcp_output 2249 * functionality. 2250 * XXX we might call soisconnected at the end of 2251 * all processing 2252 */ 2253 tcp_established(tp); 2254 soisconnected(so); 2255 /* Do window scaling on this connection? */ 2256 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) == 2257 (TF_RCVD_SCALE|TF_REQ_SCALE)) { 2258 tp->snd_scale = tp->requested_s_scale; 2259 tp->rcv_scale = tp->request_r_scale; 2260 } 2261 TCP_REASS_LOCK(tp); 2262 (void) tcp_reass(tp, NULL, NULL, &tlen); 2263 /* 2264 * if we didn't have to retransmit the SYN, 2265 * use its rtt as our initial srtt & rtt var. 2266 */ 2267 if (tp->t_rtttime) 2268 tcp_xmit_timer(tp, tcp_now - tp->t_rtttime); 2269 } else 2270 tp->t_state = TCPS_SYN_RECEIVED; 2271 2272 /* 2273 * Advance th->th_seq to correspond to first data byte. 2274 * If data, trim to stay within window, 2275 * dropping FIN if necessary. 2276 */ 2277 th->th_seq++; 2278 if (tlen > tp->rcv_wnd) { 2279 todrop = tlen - tp->rcv_wnd; 2280 m_adj(m, -todrop); 2281 tlen = tp->rcv_wnd; 2282 tiflags &= ~TH_FIN; 2283 tcps = TCP_STAT_GETREF(); 2284 tcps[TCP_STAT_RCVPACKAFTERWIN]++; 2285 tcps[TCP_STAT_RCVBYTEAFTERWIN] += todrop; 2286 TCP_STAT_PUTREF(); 2287 } 2288 tp->snd_wl1 = th->th_seq - 1; 2289 tp->rcv_up = th->th_seq; 2290 goto step6; 2291 2292 /* 2293 * If the state is SYN_RECEIVED: 2294 * If seg contains an ACK, but not for our SYN, drop the input 2295 * and generate an RST. See page 36, rfc793 2296 */ 2297 case TCPS_SYN_RECEIVED: 2298 if ((tiflags & TH_ACK) && 2299 (SEQ_LEQ(th->th_ack, tp->iss) || 2300 SEQ_GT(th->th_ack, tp->snd_max))) 2301 goto dropwithreset; 2302 break; 2303 } 2304 2305 /* 2306 * States other than LISTEN or SYN_SENT. 2307 * First check timestamp, if present. 2308 * Then check that at least some bytes of segment are within 2309 * receive window. If segment begins before rcv_nxt, 2310 * drop leading data (and SYN); if nothing left, just ack. 2311 * 2312 * RFC 1323 PAWS: If we have a timestamp reply on this segment 2313 * and it's less than ts_recent, drop it. 2314 */ 2315 if (opti.ts_present && (tiflags & TH_RST) == 0 && tp->ts_recent && 2316 TSTMP_LT(opti.ts_val, tp->ts_recent)) { 2317 2318 /* Check to see if ts_recent is over 24 days old. */ 2319 if (tcp_now - tp->ts_recent_age > TCP_PAWS_IDLE) { 2320 /* 2321 * Invalidate ts_recent. If this segment updates 2322 * ts_recent, the age will be reset later and ts_recent 2323 * will get a valid value. If it does not, setting 2324 * ts_recent to zero will at least satisfy the 2325 * requirement that zero be placed in the timestamp 2326 * echo reply when ts_recent isn't valid. The 2327 * age isn't reset until we get a valid ts_recent 2328 * because we don't want out-of-order segments to be 2329 * dropped when ts_recent is old. 2330 */ 2331 tp->ts_recent = 0; 2332 } else { 2333 tcps = TCP_STAT_GETREF(); 2334 tcps[TCP_STAT_RCVDUPPACK]++; 2335 tcps[TCP_STAT_RCVDUPBYTE] += tlen; 2336 tcps[TCP_STAT_PAWSDROP]++; 2337 TCP_STAT_PUTREF(); 2338 tcp_new_dsack(tp, th->th_seq, tlen); 2339 goto dropafterack; 2340 } 2341 } 2342 2343 todrop = tp->rcv_nxt - th->th_seq; 2344 dupseg = false; 2345 if (todrop > 0) { 2346 if (tiflags & TH_SYN) { 2347 tiflags &= ~TH_SYN; 2348 th->th_seq++; 2349 if (th->th_urp > 1) 2350 th->th_urp--; 2351 else { 2352 tiflags &= ~TH_URG; 2353 th->th_urp = 0; 2354 } 2355 todrop--; 2356 } 2357 if (todrop > tlen || 2358 (todrop == tlen && (tiflags & TH_FIN) == 0)) { 2359 /* 2360 * Any valid FIN or RST must be to the left of the 2361 * window. At this point the FIN or RST must be a 2362 * duplicate or out of sequence; drop it. 2363 */ 2364 if (tiflags & TH_RST) 2365 goto drop; 2366 tiflags &= ~(TH_FIN|TH_RST); 2367 /* 2368 * Send an ACK to resynchronize and drop any data. 2369 * But keep on processing for RST or ACK. 2370 */ 2371 tp->t_flags |= TF_ACKNOW; 2372 todrop = tlen; 2373 dupseg = true; 2374 tcps = TCP_STAT_GETREF(); 2375 tcps[TCP_STAT_RCVDUPPACK]++; 2376 tcps[TCP_STAT_RCVDUPBYTE] += todrop; 2377 TCP_STAT_PUTREF(); 2378 } else if ((tiflags & TH_RST) && 2379 th->th_seq != tp->rcv_nxt) { 2380 /* 2381 * Test for reset before adjusting the sequence 2382 * number for overlapping data. 2383 */ 2384 goto dropafterack_ratelim; 2385 } else { 2386 tcps = TCP_STAT_GETREF(); 2387 tcps[TCP_STAT_RCVPARTDUPPACK]++; 2388 tcps[TCP_STAT_RCVPARTDUPBYTE] += todrop; 2389 TCP_STAT_PUTREF(); 2390 } 2391 tcp_new_dsack(tp, th->th_seq, todrop); 2392 hdroptlen += todrop; /*drop from head afterwards*/ 2393 th->th_seq += todrop; 2394 tlen -= todrop; 2395 if (th->th_urp > todrop) 2396 th->th_urp -= todrop; 2397 else { 2398 tiflags &= ~TH_URG; 2399 th->th_urp = 0; 2400 } 2401 } 2402 2403 /* 2404 * If new data are received on a connection after the 2405 * user processes are gone, then RST the other end. 2406 */ 2407 if ((so->so_state & SS_NOFDREF) && 2408 tp->t_state > TCPS_CLOSE_WAIT && tlen) { 2409 tp = tcp_close(tp); 2410 TCP_STATINC(TCP_STAT_RCVAFTERCLOSE); 2411 goto dropwithreset; 2412 } 2413 2414 /* 2415 * If segment ends after window, drop trailing data 2416 * (and PUSH and FIN); if nothing left, just ACK. 2417 */ 2418 todrop = (th->th_seq + tlen) - (tp->rcv_nxt+tp->rcv_wnd); 2419 if (todrop > 0) { 2420 TCP_STATINC(TCP_STAT_RCVPACKAFTERWIN); 2421 if (todrop >= tlen) { 2422 /* 2423 * The segment actually starts after the window. 2424 * th->th_seq + tlen - tp->rcv_nxt - tp->rcv_wnd >= tlen 2425 * th->th_seq - tp->rcv_nxt - tp->rcv_wnd >= 0 2426 * th->th_seq >= tp->rcv_nxt + tp->rcv_wnd 2427 */ 2428 TCP_STATADD(TCP_STAT_RCVBYTEAFTERWIN, tlen); 2429 /* 2430 * If a new connection request is received 2431 * while in TIME_WAIT, drop the old connection 2432 * and start over if the sequence numbers 2433 * are above the previous ones. 2434 * 2435 * NOTE: We will checksum the packet again, and 2436 * so we need to put the header fields back into 2437 * network order! 2438 * XXX This kind of sucks, but we don't expect 2439 * XXX this to happen very often, so maybe it 2440 * XXX doesn't matter so much. 2441 */ 2442 if (tiflags & TH_SYN && 2443 tp->t_state == TCPS_TIME_WAIT && 2444 SEQ_GT(th->th_seq, tp->rcv_nxt)) { 2445 tp = tcp_close(tp); 2446 tcp_fields_to_net(th); 2447 goto findpcb; 2448 } 2449 /* 2450 * If window is closed can only take segments at 2451 * window edge, and have to drop data and PUSH from 2452 * incoming segments. Continue processing, but 2453 * remember to ack. Otherwise, drop segment 2454 * and (if not RST) ack. 2455 */ 2456 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) { 2457 tp->t_flags |= TF_ACKNOW; 2458 TCP_STATINC(TCP_STAT_RCVWINPROBE); 2459 } else 2460 goto dropafterack; 2461 } else 2462 TCP_STATADD(TCP_STAT_RCVBYTEAFTERWIN, todrop); 2463 m_adj(m, -todrop); 2464 tlen -= todrop; 2465 tiflags &= ~(TH_PUSH|TH_FIN); 2466 } 2467 2468 /* 2469 * If last ACK falls within this segment's sequence numbers, 2470 * record the timestamp. 2471 * NOTE: 2472 * 1) That the test incorporates suggestions from the latest 2473 * proposal of the tcplw@cray.com list (Braden 1993/04/26). 2474 * 2) That updating only on newer timestamps interferes with 2475 * our earlier PAWS tests, so this check should be solely 2476 * predicated on the sequence space of this segment. 2477 * 3) That we modify the segment boundary check to be 2478 * Last.ACK.Sent <= SEG.SEQ + SEG.Len 2479 * instead of RFC1323's 2480 * Last.ACK.Sent < SEG.SEQ + SEG.Len, 2481 * This modified check allows us to overcome RFC1323's 2482 * limitations as described in Stevens TCP/IP Illustrated 2483 * Vol. 2 p.869. In such cases, we can still calculate the 2484 * RTT correctly when RCV.NXT == Last.ACK.Sent. 2485 */ 2486 if (opti.ts_present && 2487 SEQ_LEQ(th->th_seq, tp->last_ack_sent) && 2488 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen + 2489 ((tiflags & (TH_SYN|TH_FIN)) != 0))) { 2490 tp->ts_recent_age = tcp_now; 2491 tp->ts_recent = opti.ts_val; 2492 } 2493 2494 /* 2495 * If the RST bit is set examine the state: 2496 * SYN_RECEIVED STATE: 2497 * If passive open, return to LISTEN state. 2498 * If active open, inform user that connection was refused. 2499 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES: 2500 * Inform user that connection was reset, and close tcb. 2501 * CLOSING, LAST_ACK, TIME_WAIT STATES 2502 * Close the tcb. 2503 */ 2504 if (tiflags & TH_RST) { 2505 if (th->th_seq != tp->rcv_nxt) 2506 goto dropafterack_ratelim; 2507 2508 switch (tp->t_state) { 2509 case TCPS_SYN_RECEIVED: 2510 so->so_error = ECONNREFUSED; 2511 goto close; 2512 2513 case TCPS_ESTABLISHED: 2514 case TCPS_FIN_WAIT_1: 2515 case TCPS_FIN_WAIT_2: 2516 case TCPS_CLOSE_WAIT: 2517 so->so_error = ECONNRESET; 2518 close: 2519 tp->t_state = TCPS_CLOSED; 2520 TCP_STATINC(TCP_STAT_DROPS); 2521 tp = tcp_close(tp); 2522 goto drop; 2523 2524 case TCPS_CLOSING: 2525 case TCPS_LAST_ACK: 2526 case TCPS_TIME_WAIT: 2527 tp = tcp_close(tp); 2528 goto drop; 2529 } 2530 } 2531 2532 /* 2533 * Since we've covered the SYN-SENT and SYN-RECEIVED states above 2534 * we must be in a synchronized state. RFC791 states (under RST 2535 * generation) that any unacceptable segment (an out-of-order SYN 2536 * qualifies) received in a synchronized state must elicit only an 2537 * empty acknowledgment segment ... and the connection remains in 2538 * the same state. 2539 */ 2540 if (tiflags & TH_SYN) { 2541 if (tp->rcv_nxt == th->th_seq) { 2542 tcp_respond(tp, m, m, th, (tcp_seq)0, th->th_ack - 1, 2543 TH_ACK); 2544 if (tcp_saveti) 2545 m_freem(tcp_saveti); 2546 return; 2547 } 2548 2549 goto dropafterack_ratelim; 2550 } 2551 2552 /* 2553 * If the ACK bit is off we drop the segment and return. 2554 */ 2555 if ((tiflags & TH_ACK) == 0) { 2556 if (tp->t_flags & TF_ACKNOW) 2557 goto dropafterack; 2558 else 2559 goto drop; 2560 } 2561 2562 /* 2563 * Ack processing. 2564 */ 2565 switch (tp->t_state) { 2566 2567 /* 2568 * In SYN_RECEIVED state if the ack ACKs our SYN then enter 2569 * ESTABLISHED state and continue processing, otherwise 2570 * send an RST. 2571 */ 2572 case TCPS_SYN_RECEIVED: 2573 if (SEQ_GT(tp->snd_una, th->th_ack) || 2574 SEQ_GT(th->th_ack, tp->snd_max)) 2575 goto dropwithreset; 2576 TCP_STATINC(TCP_STAT_CONNECTS); 2577 soisconnected(so); 2578 tcp_established(tp); 2579 /* Do window scaling? */ 2580 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) == 2581 (TF_RCVD_SCALE|TF_REQ_SCALE)) { 2582 tp->snd_scale = tp->requested_s_scale; 2583 tp->rcv_scale = tp->request_r_scale; 2584 } 2585 TCP_REASS_LOCK(tp); 2586 (void) tcp_reass(tp, NULL, NULL, &tlen); 2587 tp->snd_wl1 = th->th_seq - 1; 2588 /* fall into ... */ 2589 2590 /* 2591 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range 2592 * ACKs. If the ack is in the range 2593 * tp->snd_una < th->th_ack <= tp->snd_max 2594 * then advance tp->snd_una to th->th_ack and drop 2595 * data from the retransmission queue. If this ACK reflects 2596 * more up to date window information we update our window information. 2597 */ 2598 case TCPS_ESTABLISHED: 2599 case TCPS_FIN_WAIT_1: 2600 case TCPS_FIN_WAIT_2: 2601 case TCPS_CLOSE_WAIT: 2602 case TCPS_CLOSING: 2603 case TCPS_LAST_ACK: 2604 case TCPS_TIME_WAIT: 2605 2606 if (SEQ_LEQ(th->th_ack, tp->snd_una)) { 2607 if (tlen == 0 && !dupseg && tiwin == tp->snd_wnd) { 2608 TCP_STATINC(TCP_STAT_RCVDUPACK); 2609 /* 2610 * If we have outstanding data (other than 2611 * a window probe), this is a completely 2612 * duplicate ack (ie, window info didn't 2613 * change), the ack is the biggest we've 2614 * seen and we've seen exactly our rexmt 2615 * threshhold of them, assume a packet 2616 * has been dropped and retransmit it. 2617 * Kludge snd_nxt & the congestion 2618 * window so we send only this one 2619 * packet. 2620 */ 2621 if (TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 || 2622 th->th_ack != tp->snd_una) 2623 tp->t_dupacks = 0; 2624 else if (tp->t_partialacks < 0 && 2625 (++tp->t_dupacks == tcprexmtthresh || 2626 TCP_FACK_FASTRECOV(tp))) { 2627 /* 2628 * Do the fast retransmit, and adjust 2629 * congestion control paramenters. 2630 */ 2631 if (tp->t_congctl->fast_retransmit(tp, th)) { 2632 /* False fast retransmit */ 2633 break; 2634 } else 2635 goto drop; 2636 } else if (tp->t_dupacks > tcprexmtthresh) { 2637 tp->snd_cwnd += tp->t_segsz; 2638 KERNEL_LOCK(1, NULL); 2639 (void) tcp_output(tp); 2640 KERNEL_UNLOCK_ONE(NULL); 2641 goto drop; 2642 } 2643 } else { 2644 /* 2645 * If the ack appears to be very old, only 2646 * allow data that is in-sequence. This 2647 * makes it somewhat more difficult to insert 2648 * forged data by guessing sequence numbers. 2649 * Sent an ack to try to update the send 2650 * sequence number on the other side. 2651 */ 2652 if (tlen && th->th_seq != tp->rcv_nxt && 2653 SEQ_LT(th->th_ack, 2654 tp->snd_una - tp->max_sndwnd)) 2655 goto dropafterack; 2656 } 2657 break; 2658 } 2659 /* 2660 * If the congestion window was inflated to account 2661 * for the other side's cached packets, retract it. 2662 */ 2663 tp->t_congctl->fast_retransmit_newack(tp, th); 2664 2665 if (SEQ_GT(th->th_ack, tp->snd_max)) { 2666 TCP_STATINC(TCP_STAT_RCVACKTOOMUCH); 2667 goto dropafterack; 2668 } 2669 acked = th->th_ack - tp->snd_una; 2670 tcps = TCP_STAT_GETREF(); 2671 tcps[TCP_STAT_RCVACKPACK]++; 2672 tcps[TCP_STAT_RCVACKBYTE] += acked; 2673 TCP_STAT_PUTREF(); 2674 2675 /* 2676 * If we have a timestamp reply, update smoothed 2677 * round trip time. If no timestamp is present but 2678 * transmit timer is running and timed sequence 2679 * number was acked, update smoothed round trip time. 2680 * Since we now have an rtt measurement, cancel the 2681 * timer backoff (cf., Phil Karn's retransmit alg.). 2682 * Recompute the initial retransmit timer. 2683 */ 2684 if (ts_rtt) 2685 tcp_xmit_timer(tp, ts_rtt - 1); 2686 else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) 2687 tcp_xmit_timer(tp, tcp_now - tp->t_rtttime); 2688 2689 /* 2690 * If all outstanding data is acked, stop retransmit 2691 * timer and remember to restart (more output or persist). 2692 * If there is more data to be acked, restart retransmit 2693 * timer, using current (possibly backed-off) value. 2694 */ 2695 if (th->th_ack == tp->snd_max) { 2696 TCP_TIMER_DISARM(tp, TCPT_REXMT); 2697 needoutput = 1; 2698 } else if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0) 2699 TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur); 2700 2701 /* 2702 * New data has been acked, adjust the congestion window. 2703 */ 2704 tp->t_congctl->newack(tp, th); 2705 2706 nd6_hint(tp); 2707 if (acked > so->so_snd.sb_cc) { 2708 tp->snd_wnd -= so->so_snd.sb_cc; 2709 sbdrop(&so->so_snd, (int)so->so_snd.sb_cc); 2710 ourfinisacked = 1; 2711 } else { 2712 if (acked > (tp->t_lastoff - tp->t_inoff)) 2713 tp->t_lastm = NULL; 2714 sbdrop(&so->so_snd, acked); 2715 tp->t_lastoff -= acked; 2716 tp->snd_wnd -= acked; 2717 ourfinisacked = 0; 2718 } 2719 sowwakeup(so); 2720 2721 icmp_check(tp, th, acked); 2722 2723 tp->snd_una = th->th_ack; 2724 if (SEQ_GT(tp->snd_una, tp->snd_fack)) 2725 tp->snd_fack = tp->snd_una; 2726 if (SEQ_LT(tp->snd_nxt, tp->snd_una)) 2727 tp->snd_nxt = tp->snd_una; 2728 if (SEQ_LT(tp->snd_high, tp->snd_una)) 2729 tp->snd_high = tp->snd_una; 2730 2731 switch (tp->t_state) { 2732 2733 /* 2734 * In FIN_WAIT_1 STATE in addition to the processing 2735 * for the ESTABLISHED state if our FIN is now acknowledged 2736 * then enter FIN_WAIT_2. 2737 */ 2738 case TCPS_FIN_WAIT_1: 2739 if (ourfinisacked) { 2740 /* 2741 * If we can't receive any more 2742 * data, then closing user can proceed. 2743 * Starting the timer is contrary to the 2744 * specification, but if we don't get a FIN 2745 * we'll hang forever. 2746 */ 2747 if (so->so_state & SS_CANTRCVMORE) { 2748 soisdisconnected(so); 2749 if (tp->t_maxidle > 0) 2750 TCP_TIMER_ARM(tp, TCPT_2MSL, 2751 tp->t_maxidle); 2752 } 2753 tp->t_state = TCPS_FIN_WAIT_2; 2754 } 2755 break; 2756 2757 /* 2758 * In CLOSING STATE in addition to the processing for 2759 * the ESTABLISHED state if the ACK acknowledges our FIN 2760 * then enter the TIME-WAIT state, otherwise ignore 2761 * the segment. 2762 */ 2763 case TCPS_CLOSING: 2764 if (ourfinisacked) { 2765 tp->t_state = TCPS_TIME_WAIT; 2766 tcp_canceltimers(tp); 2767 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl); 2768 soisdisconnected(so); 2769 } 2770 break; 2771 2772 /* 2773 * In LAST_ACK, we may still be waiting for data to drain 2774 * and/or to be acked, as well as for the ack of our FIN. 2775 * If our FIN is now acknowledged, delete the TCB, 2776 * enter the closed state and return. 2777 */ 2778 case TCPS_LAST_ACK: 2779 if (ourfinisacked) { 2780 tp = tcp_close(tp); 2781 goto drop; 2782 } 2783 break; 2784 2785 /* 2786 * In TIME_WAIT state the only thing that should arrive 2787 * is a retransmission of the remote FIN. Acknowledge 2788 * it and restart the finack timer. 2789 */ 2790 case TCPS_TIME_WAIT: 2791 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl); 2792 goto dropafterack; 2793 } 2794 } 2795 2796 step6: 2797 /* 2798 * Update window information. 2799 * Don't look at window if no ACK: TAC's send garbage on first SYN. 2800 */ 2801 if ((tiflags & TH_ACK) && (SEQ_LT(tp->snd_wl1, th->th_seq) || 2802 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) || 2803 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) { 2804 /* keep track of pure window updates */ 2805 if (tlen == 0 && 2806 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd) 2807 TCP_STATINC(TCP_STAT_RCVWINUPD); 2808 tp->snd_wnd = tiwin; 2809 tp->snd_wl1 = th->th_seq; 2810 tp->snd_wl2 = th->th_ack; 2811 if (tp->snd_wnd > tp->max_sndwnd) 2812 tp->max_sndwnd = tp->snd_wnd; 2813 needoutput = 1; 2814 } 2815 2816 /* 2817 * Process segments with URG. 2818 */ 2819 if ((tiflags & TH_URG) && th->th_urp && 2820 TCPS_HAVERCVDFIN(tp->t_state) == 0) { 2821 /* 2822 * This is a kludge, but if we receive and accept 2823 * random urgent pointers, we'll crash in 2824 * soreceive. It's hard to imagine someone 2825 * actually wanting to send this much urgent data. 2826 */ 2827 if (th->th_urp + so->so_rcv.sb_cc > sb_max) { 2828 th->th_urp = 0; /* XXX */ 2829 tiflags &= ~TH_URG; /* XXX */ 2830 goto dodata; /* XXX */ 2831 } 2832 /* 2833 * If this segment advances the known urgent pointer, 2834 * then mark the data stream. This should not happen 2835 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since 2836 * a FIN has been received from the remote side. 2837 * In these states we ignore the URG. 2838 * 2839 * According to RFC961 (Assigned Protocols), 2840 * the urgent pointer points to the last octet 2841 * of urgent data. We continue, however, 2842 * to consider it to indicate the first octet 2843 * of data past the urgent section as the original 2844 * spec states (in one of two places). 2845 */ 2846 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) { 2847 tp->rcv_up = th->th_seq + th->th_urp; 2848 so->so_oobmark = so->so_rcv.sb_cc + 2849 (tp->rcv_up - tp->rcv_nxt) - 1; 2850 if (so->so_oobmark == 0) 2851 so->so_state |= SS_RCVATMARK; 2852 sohasoutofband(so); 2853 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA); 2854 } 2855 /* 2856 * Remove out of band data so doesn't get presented to user. 2857 * This can happen independent of advancing the URG pointer, 2858 * but if two URG's are pending at once, some out-of-band 2859 * data may creep in... ick. 2860 */ 2861 if (th->th_urp <= (u_int16_t) tlen 2862 #ifdef SO_OOBINLINE 2863 && (so->so_options & SO_OOBINLINE) == 0 2864 #endif 2865 ) 2866 tcp_pulloutofband(so, th, m, hdroptlen); 2867 } else 2868 /* 2869 * If no out of band data is expected, 2870 * pull receive urgent pointer along 2871 * with the receive window. 2872 */ 2873 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up)) 2874 tp->rcv_up = tp->rcv_nxt; 2875 dodata: /* XXX */ 2876 2877 /* 2878 * Process the segment text, merging it into the TCP sequencing queue, 2879 * and arranging for acknowledgement of receipt if necessary. 2880 * This process logically involves adjusting tp->rcv_wnd as data 2881 * is presented to the user (this happens in tcp_usrreq.c, 2882 * tcp_rcvd()). If a FIN has already been received on this 2883 * connection then we just ignore the text. 2884 */ 2885 if ((tlen || (tiflags & TH_FIN)) && 2886 TCPS_HAVERCVDFIN(tp->t_state) == 0) { 2887 /* 2888 * Insert segment ti into reassembly queue of tcp with 2889 * control block tp. Return TH_FIN if reassembly now includes 2890 * a segment with FIN. The macro form does the common case 2891 * inline (segment is the next to be received on an 2892 * established connection, and the queue is empty), 2893 * avoiding linkage into and removal from the queue and 2894 * repetition of various conversions. 2895 * Set DELACK for segments received in order, but ack 2896 * immediately when segments are out of order 2897 * (so fast retransmit can work). 2898 */ 2899 /* NOTE: this was TCP_REASS() macro, but used only once */ 2900 TCP_REASS_LOCK(tp); 2901 if (th->th_seq == tp->rcv_nxt && 2902 TAILQ_FIRST(&tp->segq) == NULL && 2903 tp->t_state == TCPS_ESTABLISHED) { 2904 tcp_setup_ack(tp, th); 2905 tp->rcv_nxt += tlen; 2906 tiflags = th->th_flags & TH_FIN; 2907 tcps = TCP_STAT_GETREF(); 2908 tcps[TCP_STAT_RCVPACK]++; 2909 tcps[TCP_STAT_RCVBYTE] += tlen; 2910 TCP_STAT_PUTREF(); 2911 nd6_hint(tp); 2912 if (so->so_state & SS_CANTRCVMORE) 2913 m_freem(m); 2914 else { 2915 m_adj(m, hdroptlen); 2916 sbappendstream(&(so)->so_rcv, m); 2917 } 2918 TCP_REASS_UNLOCK(tp); 2919 sorwakeup(so); 2920 } else { 2921 m_adj(m, hdroptlen); 2922 tiflags = tcp_reass(tp, th, m, &tlen); 2923 tp->t_flags |= TF_ACKNOW; 2924 } 2925 2926 /* 2927 * Note the amount of data that peer has sent into 2928 * our window, in order to estimate the sender's 2929 * buffer size. 2930 */ 2931 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt); 2932 } else { 2933 m_freem(m); 2934 m = NULL; 2935 tiflags &= ~TH_FIN; 2936 } 2937 2938 /* 2939 * If FIN is received ACK the FIN and let the user know 2940 * that the connection is closing. Ignore a FIN received before 2941 * the connection is fully established. 2942 */ 2943 if ((tiflags & TH_FIN) && TCPS_HAVEESTABLISHED(tp->t_state)) { 2944 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) { 2945 socantrcvmore(so); 2946 tp->t_flags |= TF_ACKNOW; 2947 tp->rcv_nxt++; 2948 } 2949 switch (tp->t_state) { 2950 2951 /* 2952 * In ESTABLISHED STATE enter the CLOSE_WAIT state. 2953 */ 2954 case TCPS_ESTABLISHED: 2955 tp->t_state = TCPS_CLOSE_WAIT; 2956 break; 2957 2958 /* 2959 * If still in FIN_WAIT_1 STATE FIN has not been acked so 2960 * enter the CLOSING state. 2961 */ 2962 case TCPS_FIN_WAIT_1: 2963 tp->t_state = TCPS_CLOSING; 2964 break; 2965 2966 /* 2967 * In FIN_WAIT_2 state enter the TIME_WAIT state, 2968 * starting the time-wait timer, turning off the other 2969 * standard timers. 2970 */ 2971 case TCPS_FIN_WAIT_2: 2972 tp->t_state = TCPS_TIME_WAIT; 2973 tcp_canceltimers(tp); 2974 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl); 2975 soisdisconnected(so); 2976 break; 2977 2978 /* 2979 * In TIME_WAIT state restart the 2 MSL time_wait timer. 2980 */ 2981 case TCPS_TIME_WAIT: 2982 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl); 2983 break; 2984 } 2985 } 2986 #ifdef TCP_DEBUG 2987 if (so->so_options & SO_DEBUG) 2988 tcp_trace(TA_INPUT, ostate, tp, tcp_saveti, 0); 2989 #endif 2990 2991 /* 2992 * Return any desired output. 2993 */ 2994 if (needoutput || (tp->t_flags & TF_ACKNOW)) { 2995 KERNEL_LOCK(1, NULL); 2996 (void) tcp_output(tp); 2997 KERNEL_UNLOCK_ONE(NULL); 2998 } 2999 if (tcp_saveti) 3000 m_freem(tcp_saveti); 3001 3002 if (tp->t_state == TCPS_TIME_WAIT 3003 && (so->so_state & SS_NOFDREF) 3004 && (tp->t_inpcb || af != AF_INET) 3005 && (tp->t_in6pcb || af != AF_INET6) 3006 && ((af == AF_INET ? tcp4_vtw_enable : tcp6_vtw_enable) & 1) != 0 3007 && TAILQ_EMPTY(&tp->segq) 3008 && vtw_add(af, tp)) { 3009 ; 3010 } 3011 return; 3012 3013 badsyn: 3014 /* 3015 * Received a bad SYN. Increment counters and dropwithreset. 3016 */ 3017 TCP_STATINC(TCP_STAT_BADSYN); 3018 tp = NULL; 3019 goto dropwithreset; 3020 3021 dropafterack: 3022 /* 3023 * Generate an ACK dropping incoming segment if it occupies 3024 * sequence space, where the ACK reflects our state. 3025 */ 3026 if (tiflags & TH_RST) 3027 goto drop; 3028 goto dropafterack2; 3029 3030 dropafterack_ratelim: 3031 /* 3032 * We may want to rate-limit ACKs against SYN/RST attack. 3033 */ 3034 if (ppsratecheck(&tcp_ackdrop_ppslim_last, &tcp_ackdrop_ppslim_count, 3035 tcp_ackdrop_ppslim) == 0) { 3036 /* XXX stat */ 3037 goto drop; 3038 } 3039 /* ...fall into dropafterack2... */ 3040 3041 dropafterack2: 3042 m_freem(m); 3043 tp->t_flags |= TF_ACKNOW; 3044 KERNEL_LOCK(1, NULL); 3045 (void) tcp_output(tp); 3046 KERNEL_UNLOCK_ONE(NULL); 3047 if (tcp_saveti) 3048 m_freem(tcp_saveti); 3049 return; 3050 3051 dropwithreset_ratelim: 3052 /* 3053 * We may want to rate-limit RSTs in certain situations, 3054 * particularly if we are sending an RST in response to 3055 * an attempt to connect to or otherwise communicate with 3056 * a port for which we have no socket. 3057 */ 3058 if (ppsratecheck(&tcp_rst_ppslim_last, &tcp_rst_ppslim_count, 3059 tcp_rst_ppslim) == 0) { 3060 /* XXX stat */ 3061 goto drop; 3062 } 3063 /* ...fall into dropwithreset... */ 3064 3065 dropwithreset: 3066 /* 3067 * Generate a RST, dropping incoming segment. 3068 * Make ACK acceptable to originator of segment. 3069 */ 3070 if (tiflags & TH_RST) 3071 goto drop; 3072 3073 switch (af) { 3074 #ifdef INET6 3075 case AF_INET6: 3076 /* For following calls to tcp_respond */ 3077 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) 3078 goto drop; 3079 break; 3080 #endif /* INET6 */ 3081 case AF_INET: 3082 if (IN_MULTICAST(ip->ip_dst.s_addr) || 3083 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) 3084 goto drop; 3085 } 3086 3087 if (tiflags & TH_ACK) 3088 (void)tcp_respond(tp, m, m, th, (tcp_seq)0, th->th_ack, TH_RST); 3089 else { 3090 if (tiflags & TH_SYN) 3091 tlen++; 3092 (void)tcp_respond(tp, m, m, th, th->th_seq + tlen, (tcp_seq)0, 3093 TH_RST|TH_ACK); 3094 } 3095 if (tcp_saveti) 3096 m_freem(tcp_saveti); 3097 return; 3098 3099 badcsum: 3100 drop: 3101 /* 3102 * Drop space held by incoming segment and return. 3103 */ 3104 if (tp) { 3105 if (tp->t_inpcb) 3106 so = tp->t_inpcb->inp_socket; 3107 #ifdef INET6 3108 else if (tp->t_in6pcb) 3109 so = tp->t_in6pcb->in6p_socket; 3110 #endif 3111 else 3112 so = NULL; 3113 #ifdef TCP_DEBUG 3114 if (so && (so->so_options & SO_DEBUG) != 0) 3115 tcp_trace(TA_DROP, ostate, tp, tcp_saveti, 0); 3116 #endif 3117 } 3118 if (tcp_saveti) 3119 m_freem(tcp_saveti); 3120 m_freem(m); 3121 return; 3122 } 3123 3124 #ifdef TCP_SIGNATURE 3125 int 3126 tcp_signature_apply(void *fstate, void *data, u_int len) 3127 { 3128 3129 MD5Update(fstate, (u_char *)data, len); 3130 return (0); 3131 } 3132 3133 struct secasvar * 3134 tcp_signature_getsav(struct mbuf *m, struct tcphdr *th) 3135 { 3136 struct ip *ip; 3137 struct ip6_hdr *ip6; 3138 3139 ip = mtod(m, struct ip *); 3140 switch (ip->ip_v) { 3141 case 4: 3142 ip = mtod(m, struct ip *); 3143 ip6 = NULL; 3144 break; 3145 case 6: 3146 ip = NULL; 3147 ip6 = mtod(m, struct ip6_hdr *); 3148 break; 3149 default: 3150 return (NULL); 3151 } 3152 3153 #ifdef IPSEC 3154 if (ipsec_used) { 3155 union sockaddr_union dst; 3156 /* Extract the destination from the IP header in the mbuf. */ 3157 memset(&dst, 0, sizeof(union sockaddr_union)); 3158 if (ip != NULL) { 3159 dst.sa.sa_len = sizeof(struct sockaddr_in); 3160 dst.sa.sa_family = AF_INET; 3161 dst.sin.sin_addr = ip->ip_dst; 3162 } else { 3163 dst.sa.sa_len = sizeof(struct sockaddr_in6); 3164 dst.sa.sa_family = AF_INET6; 3165 dst.sin6.sin6_addr = ip6->ip6_dst; 3166 } 3167 3168 /* 3169 * Look up an SADB entry which matches the address of the peer. 3170 */ 3171 return KEY_ALLOCSA(&dst, IPPROTO_TCP, htonl(TCP_SIG_SPI), 0, 0); 3172 } 3173 return NULL; 3174 #else 3175 if (ip) 3176 return key_allocsa(AF_INET, (void *)&ip->ip_src, 3177 (void *)&ip->ip_dst, IPPROTO_TCP, 3178 htonl(TCP_SIG_SPI), 0, 0); 3179 else 3180 return key_allocsa(AF_INET6, (void *)&ip6->ip6_src, 3181 (void *)&ip6->ip6_dst, IPPROTO_TCP, 3182 htonl(TCP_SIG_SPI), 0, 0); 3183 #endif 3184 } 3185 3186 int 3187 tcp_signature(struct mbuf *m, struct tcphdr *th, int thoff, 3188 struct secasvar *sav, char *sig) 3189 { 3190 MD5_CTX ctx; 3191 struct ip *ip; 3192 struct ipovly *ipovly; 3193 #ifdef INET6 3194 struct ip6_hdr *ip6; 3195 struct ip6_hdr_pseudo ip6pseudo; 3196 #endif /* INET6 */ 3197 struct ippseudo ippseudo; 3198 struct tcphdr th0; 3199 int l, tcphdrlen; 3200 3201 if (sav == NULL) 3202 return (-1); 3203 3204 tcphdrlen = th->th_off * 4; 3205 3206 switch (mtod(m, struct ip *)->ip_v) { 3207 case 4: 3208 MD5Init(&ctx); 3209 ip = mtod(m, struct ip *); 3210 memset(&ippseudo, 0, sizeof(ippseudo)); 3211 ipovly = (struct ipovly *)ip; 3212 ippseudo.ippseudo_src = ipovly->ih_src; 3213 ippseudo.ippseudo_dst = ipovly->ih_dst; 3214 ippseudo.ippseudo_pad = 0; 3215 ippseudo.ippseudo_p = IPPROTO_TCP; 3216 ippseudo.ippseudo_len = htons(m->m_pkthdr.len - thoff); 3217 MD5Update(&ctx, (char *)&ippseudo, sizeof(ippseudo)); 3218 break; 3219 #if INET6 3220 case 6: 3221 MD5Init(&ctx); 3222 ip6 = mtod(m, struct ip6_hdr *); 3223 memset(&ip6pseudo, 0, sizeof(ip6pseudo)); 3224 ip6pseudo.ip6ph_src = ip6->ip6_src; 3225 in6_clearscope(&ip6pseudo.ip6ph_src); 3226 ip6pseudo.ip6ph_dst = ip6->ip6_dst; 3227 in6_clearscope(&ip6pseudo.ip6ph_dst); 3228 ip6pseudo.ip6ph_len = htons(m->m_pkthdr.len - thoff); 3229 ip6pseudo.ip6ph_nxt = IPPROTO_TCP; 3230 MD5Update(&ctx, (char *)&ip6pseudo, sizeof(ip6pseudo)); 3231 break; 3232 #endif /* INET6 */ 3233 default: 3234 return (-1); 3235 } 3236 3237 th0 = *th; 3238 th0.th_sum = 0; 3239 MD5Update(&ctx, (char *)&th0, sizeof(th0)); 3240 3241 l = m->m_pkthdr.len - thoff - tcphdrlen; 3242 if (l > 0) 3243 m_apply(m, thoff + tcphdrlen, 3244 m->m_pkthdr.len - thoff - tcphdrlen, 3245 tcp_signature_apply, &ctx); 3246 3247 MD5Update(&ctx, _KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth)); 3248 MD5Final(sig, &ctx); 3249 3250 return (0); 3251 } 3252 #endif 3253 3254 /* 3255 * tcp_dooptions: parse and process tcp options. 3256 * 3257 * returns -1 if this segment should be dropped. (eg. wrong signature) 3258 * otherwise returns 0. 3259 */ 3260 3261 static int 3262 tcp_dooptions(struct tcpcb *tp, const u_char *cp, int cnt, 3263 struct tcphdr *th, 3264 struct mbuf *m, int toff, struct tcp_opt_info *oi) 3265 { 3266 u_int16_t mss; 3267 int opt, optlen = 0; 3268 #ifdef TCP_SIGNATURE 3269 void *sigp = NULL; 3270 char sigbuf[TCP_SIGLEN]; 3271 struct secasvar *sav = NULL; 3272 #endif 3273 3274 for (; cp && cnt > 0; cnt -= optlen, cp += optlen) { 3275 opt = cp[0]; 3276 if (opt == TCPOPT_EOL) 3277 break; 3278 if (opt == TCPOPT_NOP) 3279 optlen = 1; 3280 else { 3281 if (cnt < 2) 3282 break; 3283 optlen = cp[1]; 3284 if (optlen < 2 || optlen > cnt) 3285 break; 3286 } 3287 switch (opt) { 3288 3289 default: 3290 continue; 3291 3292 case TCPOPT_MAXSEG: 3293 if (optlen != TCPOLEN_MAXSEG) 3294 continue; 3295 if (!(th->th_flags & TH_SYN)) 3296 continue; 3297 if (TCPS_HAVERCVDSYN(tp->t_state)) 3298 continue; 3299 bcopy(cp + 2, &mss, sizeof(mss)); 3300 oi->maxseg = ntohs(mss); 3301 break; 3302 3303 case TCPOPT_WINDOW: 3304 if (optlen != TCPOLEN_WINDOW) 3305 continue; 3306 if (!(th->th_flags & TH_SYN)) 3307 continue; 3308 if (TCPS_HAVERCVDSYN(tp->t_state)) 3309 continue; 3310 tp->t_flags |= TF_RCVD_SCALE; 3311 tp->requested_s_scale = cp[2]; 3312 if (tp->requested_s_scale > TCP_MAX_WINSHIFT) { 3313 char buf[INET6_ADDRSTRLEN]; 3314 struct ip *ip = mtod(m, struct ip *); 3315 #ifdef INET6 3316 struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *); 3317 #endif 3318 if (ip) 3319 in_print(buf, sizeof(buf), 3320 &ip->ip_src); 3321 #ifdef INET6 3322 else if (ip6) 3323 in6_print(buf, sizeof(buf), 3324 &ip6->ip6_src); 3325 #endif 3326 else 3327 strlcpy(buf, "(unknown)", sizeof(buf)); 3328 log(LOG_ERR, "TCP: invalid wscale %d from %s, " 3329 "assuming %d\n", 3330 tp->requested_s_scale, buf, 3331 TCP_MAX_WINSHIFT); 3332 tp->requested_s_scale = TCP_MAX_WINSHIFT; 3333 } 3334 break; 3335 3336 case TCPOPT_TIMESTAMP: 3337 if (optlen != TCPOLEN_TIMESTAMP) 3338 continue; 3339 oi->ts_present = 1; 3340 bcopy(cp + 2, &oi->ts_val, sizeof(oi->ts_val)); 3341 NTOHL(oi->ts_val); 3342 bcopy(cp + 6, &oi->ts_ecr, sizeof(oi->ts_ecr)); 3343 NTOHL(oi->ts_ecr); 3344 3345 if (!(th->th_flags & TH_SYN)) 3346 continue; 3347 if (TCPS_HAVERCVDSYN(tp->t_state)) 3348 continue; 3349 /* 3350 * A timestamp received in a SYN makes 3351 * it ok to send timestamp requests and replies. 3352 */ 3353 tp->t_flags |= TF_RCVD_TSTMP; 3354 tp->ts_recent = oi->ts_val; 3355 tp->ts_recent_age = tcp_now; 3356 break; 3357 3358 case TCPOPT_SACK_PERMITTED: 3359 if (optlen != TCPOLEN_SACK_PERMITTED) 3360 continue; 3361 if (!(th->th_flags & TH_SYN)) 3362 continue; 3363 if (TCPS_HAVERCVDSYN(tp->t_state)) 3364 continue; 3365 if (tcp_do_sack) { 3366 tp->t_flags |= TF_SACK_PERMIT; 3367 tp->t_flags |= TF_WILL_SACK; 3368 } 3369 break; 3370 3371 case TCPOPT_SACK: 3372 tcp_sack_option(tp, th, cp, optlen); 3373 break; 3374 #ifdef TCP_SIGNATURE 3375 case TCPOPT_SIGNATURE: 3376 if (optlen != TCPOLEN_SIGNATURE) 3377 continue; 3378 if (sigp && memcmp(sigp, cp + 2, TCP_SIGLEN)) 3379 return (-1); 3380 3381 sigp = sigbuf; 3382 memcpy(sigbuf, cp + 2, TCP_SIGLEN); 3383 tp->t_flags |= TF_SIGNATURE; 3384 break; 3385 #endif 3386 } 3387 } 3388 3389 #ifndef TCP_SIGNATURE 3390 return 0; 3391 #else 3392 if (tp->t_flags & TF_SIGNATURE) { 3393 3394 sav = tcp_signature_getsav(m, th); 3395 3396 if (sav == NULL && tp->t_state == TCPS_LISTEN) 3397 return (-1); 3398 } 3399 3400 if ((sigp ? TF_SIGNATURE : 0) ^ (tp->t_flags & TF_SIGNATURE)) 3401 goto out; 3402 3403 if (sigp) { 3404 char sig[TCP_SIGLEN]; 3405 3406 tcp_fields_to_net(th); 3407 if (tcp_signature(m, th, toff, sav, sig) < 0) { 3408 tcp_fields_to_host(th); 3409 goto out; 3410 } 3411 tcp_fields_to_host(th); 3412 3413 if (memcmp(sig, sigp, TCP_SIGLEN)) { 3414 TCP_STATINC(TCP_STAT_BADSIG); 3415 goto out; 3416 } else 3417 TCP_STATINC(TCP_STAT_GOODSIG); 3418 3419 key_sa_recordxfer(sav, m); 3420 KEY_FREESAV(&sav); 3421 } 3422 return 0; 3423 out: 3424 if (sav != NULL) 3425 KEY_FREESAV(&sav); 3426 return -1; 3427 #endif 3428 } 3429 3430 /* 3431 * Pull out of band byte out of a segment so 3432 * it doesn't appear in the user's data queue. 3433 * It is still reflected in the segment length for 3434 * sequencing purposes. 3435 */ 3436 void 3437 tcp_pulloutofband(struct socket *so, struct tcphdr *th, 3438 struct mbuf *m, int off) 3439 { 3440 int cnt = off + th->th_urp - 1; 3441 3442 while (cnt >= 0) { 3443 if (m->m_len > cnt) { 3444 char *cp = mtod(m, char *) + cnt; 3445 struct tcpcb *tp = sototcpcb(so); 3446 3447 tp->t_iobc = *cp; 3448 tp->t_oobflags |= TCPOOB_HAVEDATA; 3449 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1)); 3450 m->m_len--; 3451 return; 3452 } 3453 cnt -= m->m_len; 3454 m = m->m_next; 3455 if (m == 0) 3456 break; 3457 } 3458 panic("tcp_pulloutofband"); 3459 } 3460 3461 /* 3462 * Collect new round-trip time estimate 3463 * and update averages and current timeout. 3464 * 3465 * rtt is in units of slow ticks (typically 500 ms) -- essentially the 3466 * difference of two timestamps. 3467 */ 3468 void 3469 tcp_xmit_timer(struct tcpcb *tp, uint32_t rtt) 3470 { 3471 int32_t delta; 3472 3473 TCP_STATINC(TCP_STAT_RTTUPDATED); 3474 if (tp->t_srtt != 0) { 3475 /* 3476 * Compute the amount to add to srtt for smoothing, 3477 * *alpha, or 2^(-TCP_RTT_SHIFT). Because 3478 * srtt is stored in 1/32 slow ticks, we conceptually 3479 * shift left 5 bits, subtract srtt to get the 3480 * diference, and then shift right by TCP_RTT_SHIFT 3481 * (3) to obtain 1/8 of the difference. 3482 */ 3483 delta = (rtt << 2) - (tp->t_srtt >> TCP_RTT_SHIFT); 3484 /* 3485 * This can never happen, because delta's lowest 3486 * possible value is 1/8 of t_srtt. But if it does, 3487 * set srtt to some reasonable value, here chosen 3488 * as 1/8 tick. 3489 */ 3490 if ((tp->t_srtt += delta) <= 0) 3491 tp->t_srtt = 1 << 2; 3492 /* 3493 * RFC2988 requires that rttvar be updated first. 3494 * This code is compliant because "delta" is the old 3495 * srtt minus the new observation (scaled). 3496 * 3497 * RFC2988 says: 3498 * rttvar = (1-beta) * rttvar + beta * |srtt-observed| 3499 * 3500 * delta is in units of 1/32 ticks, and has then been 3501 * divided by 8. This is equivalent to being in 1/16s 3502 * units and divided by 4. Subtract from it 1/4 of 3503 * the existing rttvar to form the (signed) amount to 3504 * adjust. 3505 */ 3506 if (delta < 0) 3507 delta = -delta; 3508 delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT); 3509 /* 3510 * As with srtt, this should never happen. There is 3511 * no support in RFC2988 for this operation. But 1/4s 3512 * as rttvar when faced with something arguably wrong 3513 * is ok. 3514 */ 3515 if ((tp->t_rttvar += delta) <= 0) 3516 tp->t_rttvar = 1 << 2; 3517 3518 /* 3519 * If srtt exceeds .01 second, ensure we use the 'remote' MSL 3520 * Problem is: it doesn't work. Disabled by defaulting 3521 * tcp_rttlocal to 0; see corresponding code in 3522 * tcp_subr that selects local vs remote in a different way. 3523 * 3524 * The static branch prediction hint here should be removed 3525 * when the rtt estimator is fixed and the rtt_enable code 3526 * is turned back on. 3527 */ 3528 if (__predict_false(tcp_rttlocal) && tcp_msl_enable 3529 && tp->t_srtt > tcp_msl_remote_threshold 3530 && tp->t_msl < tcp_msl_remote) { 3531 tp->t_msl = tcp_msl_remote; 3532 } 3533 } else { 3534 /* 3535 * This is the first measurement. Per RFC2988, 2.2, 3536 * set rtt=R and srtt=R/2. 3537 * For srtt, storage representation is 1/32 ticks, 3538 * so shift left by 5. 3539 * For rttvar, storage representation is 1/16 ticks, 3540 * So shift left by 4, but then right by 1 to halve. 3541 */ 3542 tp->t_srtt = rtt << (TCP_RTT_SHIFT + 2); 3543 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT + 2 - 1); 3544 } 3545 tp->t_rtttime = 0; 3546 tp->t_rxtshift = 0; 3547 3548 /* 3549 * the retransmit should happen at rtt + 4 * rttvar. 3550 * Because of the way we do the smoothing, srtt and rttvar 3551 * will each average +1/2 tick of bias. When we compute 3552 * the retransmit timer, we want 1/2 tick of rounding and 3553 * 1 extra tick because of +-1/2 tick uncertainty in the 3554 * firing of the timer. The bias will give us exactly the 3555 * 1.5 tick we need. But, because the bias is 3556 * statistical, we have to test that we don't drop below 3557 * the minimum feasible timer (which is 2 ticks). 3558 */ 3559 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp), 3560 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX); 3561 3562 /* 3563 * We received an ack for a packet that wasn't retransmitted; 3564 * it is probably safe to discard any error indications we've 3565 * received recently. This isn't quite right, but close enough 3566 * for now (a route might have failed after we sent a segment, 3567 * and the return path might not be symmetrical). 3568 */ 3569 tp->t_softerror = 0; 3570 } 3571 3572 3573 /* 3574 * TCP compressed state engine. Currently used to hold compressed 3575 * state for SYN_RECEIVED. 3576 */ 3577 3578 u_long syn_cache_count; 3579 u_int32_t syn_hash1, syn_hash2; 3580 3581 #define SYN_HASH(sa, sp, dp) \ 3582 ((((sa)->s_addr^syn_hash1)*(((((u_int32_t)(dp))<<16) + \ 3583 ((u_int32_t)(sp)))^syn_hash2))) 3584 #ifndef INET6 3585 #define SYN_HASHALL(hash, src, dst) \ 3586 do { \ 3587 hash = SYN_HASH(&((const struct sockaddr_in *)(src))->sin_addr, \ 3588 ((const struct sockaddr_in *)(src))->sin_port, \ 3589 ((const struct sockaddr_in *)(dst))->sin_port); \ 3590 } while (/*CONSTCOND*/ 0) 3591 #else 3592 #define SYN_HASH6(sa, sp, dp) \ 3593 ((((sa)->s6_addr32[0] ^ (sa)->s6_addr32[3] ^ syn_hash1) * \ 3594 (((((u_int32_t)(dp))<<16) + ((u_int32_t)(sp)))^syn_hash2)) \ 3595 & 0x7fffffff) 3596 3597 #define SYN_HASHALL(hash, src, dst) \ 3598 do { \ 3599 switch ((src)->sa_family) { \ 3600 case AF_INET: \ 3601 hash = SYN_HASH(&((const struct sockaddr_in *)(src))->sin_addr, \ 3602 ((const struct sockaddr_in *)(src))->sin_port, \ 3603 ((const struct sockaddr_in *)(dst))->sin_port); \ 3604 break; \ 3605 case AF_INET6: \ 3606 hash = SYN_HASH6(&((const struct sockaddr_in6 *)(src))->sin6_addr, \ 3607 ((const struct sockaddr_in6 *)(src))->sin6_port, \ 3608 ((const struct sockaddr_in6 *)(dst))->sin6_port); \ 3609 break; \ 3610 default: \ 3611 hash = 0; \ 3612 } \ 3613 } while (/*CONSTCOND*/0) 3614 #endif /* INET6 */ 3615 3616 static struct pool syn_cache_pool; 3617 3618 /* 3619 * We don't estimate RTT with SYNs, so each packet starts with the default 3620 * RTT and each timer step has a fixed timeout value. 3621 */ 3622 #define SYN_CACHE_TIMER_ARM(sc) \ 3623 do { \ 3624 TCPT_RANGESET((sc)->sc_rxtcur, \ 3625 TCPTV_SRTTDFLT * tcp_backoff[(sc)->sc_rxtshift], TCPTV_MIN, \ 3626 TCPTV_REXMTMAX); \ 3627 callout_reset(&(sc)->sc_timer, \ 3628 (sc)->sc_rxtcur * (hz / PR_SLOWHZ), syn_cache_timer, (sc)); \ 3629 } while (/*CONSTCOND*/0) 3630 3631 #define SYN_CACHE_TIMESTAMP(sc) (tcp_now - (sc)->sc_timebase) 3632 3633 static inline void 3634 syn_cache_rm(struct syn_cache *sc) 3635 { 3636 TAILQ_REMOVE(&tcp_syn_cache[sc->sc_bucketidx].sch_bucket, 3637 sc, sc_bucketq); 3638 sc->sc_tp = NULL; 3639 LIST_REMOVE(sc, sc_tpq); 3640 tcp_syn_cache[sc->sc_bucketidx].sch_length--; 3641 callout_stop(&sc->sc_timer); 3642 syn_cache_count--; 3643 } 3644 3645 static inline void 3646 syn_cache_put(struct syn_cache *sc) 3647 { 3648 if (sc->sc_ipopts) 3649 (void) m_free(sc->sc_ipopts); 3650 rtcache_free(&sc->sc_route); 3651 sc->sc_flags |= SCF_DEAD; 3652 if (!callout_invoking(&sc->sc_timer)) 3653 callout_schedule(&(sc)->sc_timer, 1); 3654 } 3655 3656 void 3657 syn_cache_init(void) 3658 { 3659 int i; 3660 3661 pool_init(&syn_cache_pool, sizeof(struct syn_cache), 0, 0, 0, 3662 "synpl", NULL, IPL_SOFTNET); 3663 3664 /* Initialize the hash buckets. */ 3665 for (i = 0; i < tcp_syn_cache_size; i++) 3666 TAILQ_INIT(&tcp_syn_cache[i].sch_bucket); 3667 } 3668 3669 void 3670 syn_cache_insert(struct syn_cache *sc, struct tcpcb *tp) 3671 { 3672 struct syn_cache_head *scp; 3673 struct syn_cache *sc2; 3674 int s; 3675 3676 /* 3677 * If there are no entries in the hash table, reinitialize 3678 * the hash secrets. 3679 */ 3680 if (syn_cache_count == 0) { 3681 syn_hash1 = cprng_fast32(); 3682 syn_hash2 = cprng_fast32(); 3683 } 3684 3685 SYN_HASHALL(sc->sc_hash, &sc->sc_src.sa, &sc->sc_dst.sa); 3686 sc->sc_bucketidx = sc->sc_hash % tcp_syn_cache_size; 3687 scp = &tcp_syn_cache[sc->sc_bucketidx]; 3688 3689 /* 3690 * Make sure that we don't overflow the per-bucket 3691 * limit or the total cache size limit. 3692 */ 3693 s = splsoftnet(); 3694 if (scp->sch_length >= tcp_syn_bucket_limit) { 3695 TCP_STATINC(TCP_STAT_SC_BUCKETOVERFLOW); 3696 /* 3697 * The bucket is full. Toss the oldest element in the 3698 * bucket. This will be the first entry in the bucket. 3699 */ 3700 sc2 = TAILQ_FIRST(&scp->sch_bucket); 3701 #ifdef DIAGNOSTIC 3702 /* 3703 * This should never happen; we should always find an 3704 * entry in our bucket. 3705 */ 3706 if (sc2 == NULL) 3707 panic("syn_cache_insert: bucketoverflow: impossible"); 3708 #endif 3709 syn_cache_rm(sc2); 3710 syn_cache_put(sc2); /* calls pool_put but see spl above */ 3711 } else if (syn_cache_count >= tcp_syn_cache_limit) { 3712 struct syn_cache_head *scp2, *sce; 3713 3714 TCP_STATINC(TCP_STAT_SC_OVERFLOWED); 3715 /* 3716 * The cache is full. Toss the oldest entry in the 3717 * first non-empty bucket we can find. 3718 * 3719 * XXX We would really like to toss the oldest 3720 * entry in the cache, but we hope that this 3721 * condition doesn't happen very often. 3722 */ 3723 scp2 = scp; 3724 if (TAILQ_EMPTY(&scp2->sch_bucket)) { 3725 sce = &tcp_syn_cache[tcp_syn_cache_size]; 3726 for (++scp2; scp2 != scp; scp2++) { 3727 if (scp2 >= sce) 3728 scp2 = &tcp_syn_cache[0]; 3729 if (! TAILQ_EMPTY(&scp2->sch_bucket)) 3730 break; 3731 } 3732 #ifdef DIAGNOSTIC 3733 /* 3734 * This should never happen; we should always find a 3735 * non-empty bucket. 3736 */ 3737 if (scp2 == scp) 3738 panic("syn_cache_insert: cacheoverflow: " 3739 "impossible"); 3740 #endif 3741 } 3742 sc2 = TAILQ_FIRST(&scp2->sch_bucket); 3743 syn_cache_rm(sc2); 3744 syn_cache_put(sc2); /* calls pool_put but see spl above */ 3745 } 3746 3747 /* 3748 * Initialize the entry's timer. 3749 */ 3750 sc->sc_rxttot = 0; 3751 sc->sc_rxtshift = 0; 3752 SYN_CACHE_TIMER_ARM(sc); 3753 3754 /* Link it from tcpcb entry */ 3755 LIST_INSERT_HEAD(&tp->t_sc, sc, sc_tpq); 3756 3757 /* Put it into the bucket. */ 3758 TAILQ_INSERT_TAIL(&scp->sch_bucket, sc, sc_bucketq); 3759 scp->sch_length++; 3760 syn_cache_count++; 3761 3762 TCP_STATINC(TCP_STAT_SC_ADDED); 3763 splx(s); 3764 } 3765 3766 /* 3767 * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted. 3768 * If we have retransmitted an entry the maximum number of times, expire 3769 * that entry. 3770 */ 3771 void 3772 syn_cache_timer(void *arg) 3773 { 3774 struct syn_cache *sc = arg; 3775 3776 mutex_enter(softnet_lock); 3777 KERNEL_LOCK(1, NULL); 3778 callout_ack(&sc->sc_timer); 3779 3780 if (__predict_false(sc->sc_flags & SCF_DEAD)) { 3781 TCP_STATINC(TCP_STAT_SC_DELAYED_FREE); 3782 callout_destroy(&sc->sc_timer); 3783 pool_put(&syn_cache_pool, sc); 3784 KERNEL_UNLOCK_ONE(NULL); 3785 mutex_exit(softnet_lock); 3786 return; 3787 } 3788 3789 if (__predict_false(sc->sc_rxtshift == TCP_MAXRXTSHIFT)) { 3790 /* Drop it -- too many retransmissions. */ 3791 goto dropit; 3792 } 3793 3794 /* 3795 * Compute the total amount of time this entry has 3796 * been on a queue. If this entry has been on longer 3797 * than the keep alive timer would allow, expire it. 3798 */ 3799 sc->sc_rxttot += sc->sc_rxtcur; 3800 if (sc->sc_rxttot >= tcp_keepinit) 3801 goto dropit; 3802 3803 TCP_STATINC(TCP_STAT_SC_RETRANSMITTED); 3804 (void) syn_cache_respond(sc, NULL); 3805 3806 /* Advance the timer back-off. */ 3807 sc->sc_rxtshift++; 3808 SYN_CACHE_TIMER_ARM(sc); 3809 3810 KERNEL_UNLOCK_ONE(NULL); 3811 mutex_exit(softnet_lock); 3812 return; 3813 3814 dropit: 3815 TCP_STATINC(TCP_STAT_SC_TIMED_OUT); 3816 syn_cache_rm(sc); 3817 if (sc->sc_ipopts) 3818 (void) m_free(sc->sc_ipopts); 3819 rtcache_free(&sc->sc_route); 3820 callout_destroy(&sc->sc_timer); 3821 pool_put(&syn_cache_pool, sc); 3822 KERNEL_UNLOCK_ONE(NULL); 3823 mutex_exit(softnet_lock); 3824 } 3825 3826 /* 3827 * Remove syn cache created by the specified tcb entry, 3828 * because this does not make sense to keep them 3829 * (if there's no tcb entry, syn cache entry will never be used) 3830 */ 3831 void 3832 syn_cache_cleanup(struct tcpcb *tp) 3833 { 3834 struct syn_cache *sc, *nsc; 3835 int s; 3836 3837 s = splsoftnet(); 3838 3839 for (sc = LIST_FIRST(&tp->t_sc); sc != NULL; sc = nsc) { 3840 nsc = LIST_NEXT(sc, sc_tpq); 3841 3842 #ifdef DIAGNOSTIC 3843 if (sc->sc_tp != tp) 3844 panic("invalid sc_tp in syn_cache_cleanup"); 3845 #endif 3846 syn_cache_rm(sc); 3847 syn_cache_put(sc); /* calls pool_put but see spl above */ 3848 } 3849 /* just for safety */ 3850 LIST_INIT(&tp->t_sc); 3851 3852 splx(s); 3853 } 3854 3855 /* 3856 * Find an entry in the syn cache. 3857 */ 3858 struct syn_cache * 3859 syn_cache_lookup(const struct sockaddr *src, const struct sockaddr *dst, 3860 struct syn_cache_head **headp) 3861 { 3862 struct syn_cache *sc; 3863 struct syn_cache_head *scp; 3864 u_int32_t hash; 3865 int s; 3866 3867 SYN_HASHALL(hash, src, dst); 3868 3869 scp = &tcp_syn_cache[hash % tcp_syn_cache_size]; 3870 *headp = scp; 3871 s = splsoftnet(); 3872 for (sc = TAILQ_FIRST(&scp->sch_bucket); sc != NULL; 3873 sc = TAILQ_NEXT(sc, sc_bucketq)) { 3874 if (sc->sc_hash != hash) 3875 continue; 3876 if (!memcmp(&sc->sc_src, src, src->sa_len) && 3877 !memcmp(&sc->sc_dst, dst, dst->sa_len)) { 3878 splx(s); 3879 return (sc); 3880 } 3881 } 3882 splx(s); 3883 return (NULL); 3884 } 3885 3886 /* 3887 * This function gets called when we receive an ACK for a 3888 * socket in the LISTEN state. We look up the connection 3889 * in the syn cache, and if its there, we pull it out of 3890 * the cache and turn it into a full-blown connection in 3891 * the SYN-RECEIVED state. 3892 * 3893 * The return values may not be immediately obvious, and their effects 3894 * can be subtle, so here they are: 3895 * 3896 * NULL SYN was not found in cache; caller should drop the 3897 * packet and send an RST. 3898 * 3899 * -1 We were unable to create the new connection, and are 3900 * aborting it. An ACK,RST is being sent to the peer 3901 * (unless we got screwey sequence numbners; see below), 3902 * because the 3-way handshake has been completed. Caller 3903 * should not free the mbuf, since we may be using it. If 3904 * we are not, we will free it. 3905 * 3906 * Otherwise, the return value is a pointer to the new socket 3907 * associated with the connection. 3908 */ 3909 struct socket * 3910 syn_cache_get(struct sockaddr *src, struct sockaddr *dst, 3911 struct tcphdr *th, unsigned int hlen, unsigned int tlen, 3912 struct socket *so, struct mbuf *m) 3913 { 3914 struct syn_cache *sc; 3915 struct syn_cache_head *scp; 3916 struct inpcb *inp = NULL; 3917 #ifdef INET6 3918 struct in6pcb *in6p = NULL; 3919 #endif 3920 struct tcpcb *tp = 0; 3921 int s; 3922 struct socket *oso; 3923 3924 s = splsoftnet(); 3925 if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) { 3926 splx(s); 3927 return (NULL); 3928 } 3929 3930 /* 3931 * Verify the sequence and ack numbers. Try getting the correct 3932 * response again. 3933 */ 3934 if ((th->th_ack != sc->sc_iss + 1) || 3935 SEQ_LEQ(th->th_seq, sc->sc_irs) || 3936 SEQ_GT(th->th_seq, sc->sc_irs + 1 + sc->sc_win)) { 3937 (void) syn_cache_respond(sc, m); 3938 splx(s); 3939 return ((struct socket *)(-1)); 3940 } 3941 3942 /* Remove this cache entry */ 3943 syn_cache_rm(sc); 3944 splx(s); 3945 3946 /* 3947 * Ok, create the full blown connection, and set things up 3948 * as they would have been set up if we had created the 3949 * connection when the SYN arrived. If we can't create 3950 * the connection, abort it. 3951 */ 3952 /* 3953 * inp still has the OLD in_pcb stuff, set the 3954 * v6-related flags on the new guy, too. This is 3955 * done particularly for the case where an AF_INET6 3956 * socket is bound only to a port, and a v4 connection 3957 * comes in on that port. 3958 * we also copy the flowinfo from the original pcb 3959 * to the new one. 3960 */ 3961 oso = so; 3962 so = sonewconn(so, true); 3963 if (so == NULL) 3964 goto resetandabort; 3965 3966 switch (so->so_proto->pr_domain->dom_family) { 3967 #ifdef INET 3968 case AF_INET: 3969 inp = sotoinpcb(so); 3970 break; 3971 #endif 3972 #ifdef INET6 3973 case AF_INET6: 3974 in6p = sotoin6pcb(so); 3975 break; 3976 #endif 3977 } 3978 switch (src->sa_family) { 3979 #ifdef INET 3980 case AF_INET: 3981 if (inp) { 3982 inp->inp_laddr = ((struct sockaddr_in *)dst)->sin_addr; 3983 inp->inp_lport = ((struct sockaddr_in *)dst)->sin_port; 3984 inp->inp_options = ip_srcroute(); 3985 in_pcbstate(inp, INP_BOUND); 3986 if (inp->inp_options == NULL) { 3987 inp->inp_options = sc->sc_ipopts; 3988 sc->sc_ipopts = NULL; 3989 } 3990 } 3991 #ifdef INET6 3992 else if (in6p) { 3993 /* IPv4 packet to AF_INET6 socket */ 3994 memset(&in6p->in6p_laddr, 0, sizeof(in6p->in6p_laddr)); 3995 in6p->in6p_laddr.s6_addr16[5] = htons(0xffff); 3996 bcopy(&((struct sockaddr_in *)dst)->sin_addr, 3997 &in6p->in6p_laddr.s6_addr32[3], 3998 sizeof(((struct sockaddr_in *)dst)->sin_addr)); 3999 in6p->in6p_lport = ((struct sockaddr_in *)dst)->sin_port; 4000 in6totcpcb(in6p)->t_family = AF_INET; 4001 if (sotoin6pcb(oso)->in6p_flags & IN6P_IPV6_V6ONLY) 4002 in6p->in6p_flags |= IN6P_IPV6_V6ONLY; 4003 else 4004 in6p->in6p_flags &= ~IN6P_IPV6_V6ONLY; 4005 in6_pcbstate(in6p, IN6P_BOUND); 4006 } 4007 #endif 4008 break; 4009 #endif 4010 #ifdef INET6 4011 case AF_INET6: 4012 if (in6p) { 4013 in6p->in6p_laddr = ((struct sockaddr_in6 *)dst)->sin6_addr; 4014 in6p->in6p_lport = ((struct sockaddr_in6 *)dst)->sin6_port; 4015 in6_pcbstate(in6p, IN6P_BOUND); 4016 } 4017 break; 4018 #endif 4019 } 4020 #ifdef INET6 4021 if (in6p && in6totcpcb(in6p)->t_family == AF_INET6 && sotoinpcb(oso)) { 4022 struct in6pcb *oin6p = sotoin6pcb(oso); 4023 /* inherit socket options from the listening socket */ 4024 in6p->in6p_flags |= (oin6p->in6p_flags & IN6P_CONTROLOPTS); 4025 if (in6p->in6p_flags & IN6P_CONTROLOPTS) { 4026 m_freem(in6p->in6p_options); 4027 in6p->in6p_options = 0; 4028 } 4029 ip6_savecontrol(in6p, &in6p->in6p_options, 4030 mtod(m, struct ip6_hdr *), m); 4031 } 4032 #endif 4033 4034 #if defined(IPSEC) 4035 if (ipsec_used) { 4036 /* 4037 * we make a copy of policy, instead of sharing the policy, for 4038 * better behavior in terms of SA lookup and dead SA removal. 4039 */ 4040 if (inp) { 4041 /* copy old policy into new socket's */ 4042 if (ipsec_copy_pcbpolicy(sotoinpcb(oso)->inp_sp, 4043 inp->inp_sp)) 4044 printf("tcp_input: could not copy policy\n"); 4045 } 4046 #ifdef INET6 4047 else if (in6p) { 4048 /* copy old policy into new socket's */ 4049 if (ipsec_copy_pcbpolicy(sotoin6pcb(oso)->in6p_sp, 4050 in6p->in6p_sp)) 4051 printf("tcp_input: could not copy policy\n"); 4052 } 4053 #endif 4054 } 4055 #endif 4056 4057 /* 4058 * Give the new socket our cached route reference. 4059 */ 4060 if (inp) { 4061 rtcache_copy(&inp->inp_route, &sc->sc_route); 4062 rtcache_free(&sc->sc_route); 4063 } 4064 #ifdef INET6 4065 else { 4066 rtcache_copy(&in6p->in6p_route, &sc->sc_route); 4067 rtcache_free(&sc->sc_route); 4068 } 4069 #endif 4070 4071 if (inp) { 4072 struct sockaddr_in sin; 4073 memcpy(&sin, src, src->sa_len); 4074 if (in_pcbconnect(inp, &sin, &lwp0)) { 4075 goto resetandabort; 4076 } 4077 } 4078 #ifdef INET6 4079 else if (in6p) { 4080 struct sockaddr_in6 sin6; 4081 memcpy(&sin6, src, src->sa_len); 4082 if (src->sa_family == AF_INET) { 4083 /* IPv4 packet to AF_INET6 socket */ 4084 memset(&sin6, 0, sizeof(sin6)); 4085 sin6.sin6_family = AF_INET6; 4086 sin6.sin6_len = sizeof(sin6); 4087 sin6.sin6_port = ((struct sockaddr_in *)src)->sin_port; 4088 sin6.sin6_addr.s6_addr16[5] = htons(0xffff); 4089 bcopy(&((struct sockaddr_in *)src)->sin_addr, 4090 &sin6.sin6_addr.s6_addr32[3], 4091 sizeof(sin6.sin6_addr.s6_addr32[3])); 4092 } 4093 if (in6_pcbconnect(in6p, &sin6, NULL)) { 4094 goto resetandabort; 4095 } 4096 } 4097 #endif 4098 else { 4099 goto resetandabort; 4100 } 4101 4102 if (inp) 4103 tp = intotcpcb(inp); 4104 #ifdef INET6 4105 else if (in6p) 4106 tp = in6totcpcb(in6p); 4107 #endif 4108 else 4109 tp = NULL; 4110 tp->t_flags = sototcpcb(oso)->t_flags & TF_NODELAY; 4111 if (sc->sc_request_r_scale != 15) { 4112 tp->requested_s_scale = sc->sc_requested_s_scale; 4113 tp->request_r_scale = sc->sc_request_r_scale; 4114 tp->snd_scale = sc->sc_requested_s_scale; 4115 tp->rcv_scale = sc->sc_request_r_scale; 4116 tp->t_flags |= TF_REQ_SCALE|TF_RCVD_SCALE; 4117 } 4118 if (sc->sc_flags & SCF_TIMESTAMP) 4119 tp->t_flags |= TF_REQ_TSTMP|TF_RCVD_TSTMP; 4120 tp->ts_timebase = sc->sc_timebase; 4121 4122 tp->t_template = tcp_template(tp); 4123 if (tp->t_template == 0) { 4124 tp = tcp_drop(tp, ENOBUFS); /* destroys socket */ 4125 so = NULL; 4126 m_freem(m); 4127 goto abort; 4128 } 4129 4130 tp->iss = sc->sc_iss; 4131 tp->irs = sc->sc_irs; 4132 tcp_sendseqinit(tp); 4133 tcp_rcvseqinit(tp); 4134 tp->t_state = TCPS_SYN_RECEIVED; 4135 TCP_TIMER_ARM(tp, TCPT_KEEP, tp->t_keepinit); 4136 TCP_STATINC(TCP_STAT_ACCEPTS); 4137 4138 if ((sc->sc_flags & SCF_SACK_PERMIT) && tcp_do_sack) 4139 tp->t_flags |= TF_WILL_SACK; 4140 4141 if ((sc->sc_flags & SCF_ECN_PERMIT) && tcp_do_ecn) 4142 tp->t_flags |= TF_ECN_PERMIT; 4143 4144 #ifdef TCP_SIGNATURE 4145 if (sc->sc_flags & SCF_SIGNATURE) 4146 tp->t_flags |= TF_SIGNATURE; 4147 #endif 4148 4149 /* Initialize tp->t_ourmss before we deal with the peer's! */ 4150 tp->t_ourmss = sc->sc_ourmaxseg; 4151 tcp_mss_from_peer(tp, sc->sc_peermaxseg); 4152 4153 /* 4154 * Initialize the initial congestion window. If we 4155 * had to retransmit the SYN,ACK, we must initialize cwnd 4156 * to 1 segment (i.e. the Loss Window). 4157 */ 4158 if (sc->sc_rxtshift) 4159 tp->snd_cwnd = tp->t_peermss; 4160 else { 4161 int ss = tcp_init_win; 4162 #ifdef INET 4163 if (inp != NULL && in_localaddr(inp->inp_faddr)) 4164 ss = tcp_init_win_local; 4165 #endif 4166 #ifdef INET6 4167 if (in6p != NULL && in6_localaddr(&in6p->in6p_faddr)) 4168 ss = tcp_init_win_local; 4169 #endif 4170 tp->snd_cwnd = TCP_INITIAL_WINDOW(ss, tp->t_peermss); 4171 } 4172 4173 tcp_rmx_rtt(tp); 4174 tp->snd_wl1 = sc->sc_irs; 4175 tp->rcv_up = sc->sc_irs + 1; 4176 4177 /* 4178 * This is what whould have happened in tcp_output() when 4179 * the SYN,ACK was sent. 4180 */ 4181 tp->snd_up = tp->snd_una; 4182 tp->snd_max = tp->snd_nxt = tp->iss+1; 4183 TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur); 4184 if (sc->sc_win > 0 && SEQ_GT(tp->rcv_nxt + sc->sc_win, tp->rcv_adv)) 4185 tp->rcv_adv = tp->rcv_nxt + sc->sc_win; 4186 tp->last_ack_sent = tp->rcv_nxt; 4187 tp->t_partialacks = -1; 4188 tp->t_dupacks = 0; 4189 4190 TCP_STATINC(TCP_STAT_SC_COMPLETED); 4191 s = splsoftnet(); 4192 syn_cache_put(sc); 4193 splx(s); 4194 return (so); 4195 4196 resetandabort: 4197 (void)tcp_respond(NULL, m, m, th, (tcp_seq)0, th->th_ack, TH_RST); 4198 abort: 4199 if (so != NULL) { 4200 (void) soqremque(so, 1); 4201 (void) soabort(so); 4202 mutex_enter(softnet_lock); 4203 } 4204 s = splsoftnet(); 4205 syn_cache_put(sc); 4206 splx(s); 4207 TCP_STATINC(TCP_STAT_SC_ABORTED); 4208 return ((struct socket *)(-1)); 4209 } 4210 4211 /* 4212 * This function is called when we get a RST for a 4213 * non-existent connection, so that we can see if the 4214 * connection is in the syn cache. If it is, zap it. 4215 */ 4216 4217 void 4218 syn_cache_reset(struct sockaddr *src, struct sockaddr *dst, struct tcphdr *th) 4219 { 4220 struct syn_cache *sc; 4221 struct syn_cache_head *scp; 4222 int s = splsoftnet(); 4223 4224 if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) { 4225 splx(s); 4226 return; 4227 } 4228 if (SEQ_LT(th->th_seq, sc->sc_irs) || 4229 SEQ_GT(th->th_seq, sc->sc_irs+1)) { 4230 splx(s); 4231 return; 4232 } 4233 syn_cache_rm(sc); 4234 TCP_STATINC(TCP_STAT_SC_RESET); 4235 syn_cache_put(sc); /* calls pool_put but see spl above */ 4236 splx(s); 4237 } 4238 4239 void 4240 syn_cache_unreach(const struct sockaddr *src, const struct sockaddr *dst, 4241 struct tcphdr *th) 4242 { 4243 struct syn_cache *sc; 4244 struct syn_cache_head *scp; 4245 int s; 4246 4247 s = splsoftnet(); 4248 if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) { 4249 splx(s); 4250 return; 4251 } 4252 /* If the sequence number != sc_iss, then it's a bogus ICMP msg */ 4253 if (ntohl (th->th_seq) != sc->sc_iss) { 4254 splx(s); 4255 return; 4256 } 4257 4258 /* 4259 * If we've retransmitted 3 times and this is our second error, 4260 * we remove the entry. Otherwise, we allow it to continue on. 4261 * This prevents us from incorrectly nuking an entry during a 4262 * spurious network outage. 4263 * 4264 * See tcp_notify(). 4265 */ 4266 if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxtshift < 3) { 4267 sc->sc_flags |= SCF_UNREACH; 4268 splx(s); 4269 return; 4270 } 4271 4272 syn_cache_rm(sc); 4273 TCP_STATINC(TCP_STAT_SC_UNREACH); 4274 syn_cache_put(sc); /* calls pool_put but see spl above */ 4275 splx(s); 4276 } 4277 4278 /* 4279 * Given a LISTEN socket and an inbound SYN request, add 4280 * this to the syn cache, and send back a segment: 4281 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK> 4282 * to the source. 4283 * 4284 * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN. 4285 * Doing so would require that we hold onto the data and deliver it 4286 * to the application. However, if we are the target of a SYN-flood 4287 * DoS attack, an attacker could send data which would eventually 4288 * consume all available buffer space if it were ACKed. By not ACKing 4289 * the data, we avoid this DoS scenario. 4290 */ 4291 4292 int 4293 syn_cache_add(struct sockaddr *src, struct sockaddr *dst, struct tcphdr *th, 4294 unsigned int hlen, struct socket *so, struct mbuf *m, u_char *optp, 4295 int optlen, struct tcp_opt_info *oi) 4296 { 4297 struct tcpcb tb, *tp; 4298 long win; 4299 struct syn_cache *sc; 4300 struct syn_cache_head *scp; 4301 struct mbuf *ipopts; 4302 struct tcp_opt_info opti; 4303 int s; 4304 4305 tp = sototcpcb(so); 4306 4307 memset(&opti, 0, sizeof(opti)); 4308 4309 /* 4310 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN 4311 * 4312 * Note this check is performed in tcp_input() very early on. 4313 */ 4314 4315 /* 4316 * Initialize some local state. 4317 */ 4318 win = sbspace(&so->so_rcv); 4319 if (win > TCP_MAXWIN) 4320 win = TCP_MAXWIN; 4321 4322 switch (src->sa_family) { 4323 #ifdef INET 4324 case AF_INET: 4325 /* 4326 * Remember the IP options, if any. 4327 */ 4328 ipopts = ip_srcroute(); 4329 break; 4330 #endif 4331 default: 4332 ipopts = NULL; 4333 } 4334 4335 #ifdef TCP_SIGNATURE 4336 if (optp || (tp->t_flags & TF_SIGNATURE)) 4337 #else 4338 if (optp) 4339 #endif 4340 { 4341 tb.t_flags = tcp_do_rfc1323 ? (TF_REQ_SCALE|TF_REQ_TSTMP) : 0; 4342 #ifdef TCP_SIGNATURE 4343 tb.t_flags |= (tp->t_flags & TF_SIGNATURE); 4344 #endif 4345 tb.t_state = TCPS_LISTEN; 4346 if (tcp_dooptions(&tb, optp, optlen, th, m, m->m_pkthdr.len - 4347 sizeof(struct tcphdr) - optlen - hlen, oi) < 0) 4348 return (0); 4349 } else 4350 tb.t_flags = 0; 4351 4352 /* 4353 * See if we already have an entry for this connection. 4354 * If we do, resend the SYN,ACK. We do not count this 4355 * as a retransmission (XXX though maybe we should). 4356 */ 4357 if ((sc = syn_cache_lookup(src, dst, &scp)) != NULL) { 4358 TCP_STATINC(TCP_STAT_SC_DUPESYN); 4359 if (ipopts) { 4360 /* 4361 * If we were remembering a previous source route, 4362 * forget it and use the new one we've been given. 4363 */ 4364 if (sc->sc_ipopts) 4365 (void) m_free(sc->sc_ipopts); 4366 sc->sc_ipopts = ipopts; 4367 } 4368 sc->sc_timestamp = tb.ts_recent; 4369 if (syn_cache_respond(sc, m) == 0) { 4370 uint64_t *tcps = TCP_STAT_GETREF(); 4371 tcps[TCP_STAT_SNDACKS]++; 4372 tcps[TCP_STAT_SNDTOTAL]++; 4373 TCP_STAT_PUTREF(); 4374 } 4375 return (1); 4376 } 4377 4378 s = splsoftnet(); 4379 sc = pool_get(&syn_cache_pool, PR_NOWAIT); 4380 splx(s); 4381 if (sc == NULL) { 4382 if (ipopts) 4383 (void) m_free(ipopts); 4384 return (0); 4385 } 4386 4387 /* 4388 * Fill in the cache, and put the necessary IP and TCP 4389 * options into the reply. 4390 */ 4391 memset(sc, 0, sizeof(struct syn_cache)); 4392 callout_init(&sc->sc_timer, CALLOUT_MPSAFE); 4393 bcopy(src, &sc->sc_src, src->sa_len); 4394 bcopy(dst, &sc->sc_dst, dst->sa_len); 4395 sc->sc_flags = 0; 4396 sc->sc_ipopts = ipopts; 4397 sc->sc_irs = th->th_seq; 4398 switch (src->sa_family) { 4399 #ifdef INET 4400 case AF_INET: 4401 { 4402 struct sockaddr_in *srcin = (void *) src; 4403 struct sockaddr_in *dstin = (void *) dst; 4404 4405 sc->sc_iss = tcp_new_iss1(&dstin->sin_addr, 4406 &srcin->sin_addr, dstin->sin_port, 4407 srcin->sin_port, sizeof(dstin->sin_addr), 0); 4408 break; 4409 } 4410 #endif /* INET */ 4411 #ifdef INET6 4412 case AF_INET6: 4413 { 4414 struct sockaddr_in6 *srcin6 = (void *) src; 4415 struct sockaddr_in6 *dstin6 = (void *) dst; 4416 4417 sc->sc_iss = tcp_new_iss1(&dstin6->sin6_addr, 4418 &srcin6->sin6_addr, dstin6->sin6_port, 4419 srcin6->sin6_port, sizeof(dstin6->sin6_addr), 0); 4420 break; 4421 } 4422 #endif /* INET6 */ 4423 } 4424 sc->sc_peermaxseg = oi->maxseg; 4425 sc->sc_ourmaxseg = tcp_mss_to_advertise(m->m_flags & M_PKTHDR ? 4426 m->m_pkthdr.rcvif : NULL, 4427 sc->sc_src.sa.sa_family); 4428 sc->sc_win = win; 4429 sc->sc_timebase = tcp_now - 1; /* see tcp_newtcpcb() */ 4430 sc->sc_timestamp = tb.ts_recent; 4431 if ((tb.t_flags & (TF_REQ_TSTMP|TF_RCVD_TSTMP)) == 4432 (TF_REQ_TSTMP|TF_RCVD_TSTMP)) 4433 sc->sc_flags |= SCF_TIMESTAMP; 4434 if ((tb.t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) == 4435 (TF_RCVD_SCALE|TF_REQ_SCALE)) { 4436 sc->sc_requested_s_scale = tb.requested_s_scale; 4437 sc->sc_request_r_scale = 0; 4438 /* 4439 * Pick the smallest possible scaling factor that 4440 * will still allow us to scale up to sb_max. 4441 * 4442 * We do this because there are broken firewalls that 4443 * will corrupt the window scale option, leading to 4444 * the other endpoint believing that our advertised 4445 * window is unscaled. At scale factors larger than 4446 * 5 the unscaled window will drop below 1500 bytes, 4447 * leading to serious problems when traversing these 4448 * broken firewalls. 4449 * 4450 * With the default sbmax of 256K, a scale factor 4451 * of 3 will be chosen by this algorithm. Those who 4452 * choose a larger sbmax should watch out 4453 * for the compatiblity problems mentioned above. 4454 * 4455 * RFC1323: The Window field in a SYN (i.e., a <SYN> 4456 * or <SYN,ACK>) segment itself is never scaled. 4457 */ 4458 while (sc->sc_request_r_scale < TCP_MAX_WINSHIFT && 4459 (TCP_MAXWIN << sc->sc_request_r_scale) < sb_max) 4460 sc->sc_request_r_scale++; 4461 } else { 4462 sc->sc_requested_s_scale = 15; 4463 sc->sc_request_r_scale = 15; 4464 } 4465 if ((tb.t_flags & TF_SACK_PERMIT) && tcp_do_sack) 4466 sc->sc_flags |= SCF_SACK_PERMIT; 4467 4468 /* 4469 * ECN setup packet recieved. 4470 */ 4471 if ((th->th_flags & (TH_ECE|TH_CWR)) && tcp_do_ecn) 4472 sc->sc_flags |= SCF_ECN_PERMIT; 4473 4474 #ifdef TCP_SIGNATURE 4475 if (tb.t_flags & TF_SIGNATURE) 4476 sc->sc_flags |= SCF_SIGNATURE; 4477 #endif 4478 sc->sc_tp = tp; 4479 if (syn_cache_respond(sc, m) == 0) { 4480 uint64_t *tcps = TCP_STAT_GETREF(); 4481 tcps[TCP_STAT_SNDACKS]++; 4482 tcps[TCP_STAT_SNDTOTAL]++; 4483 TCP_STAT_PUTREF(); 4484 syn_cache_insert(sc, tp); 4485 } else { 4486 s = splsoftnet(); 4487 /* 4488 * syn_cache_put() will try to schedule the timer, so 4489 * we need to initialize it 4490 */ 4491 SYN_CACHE_TIMER_ARM(sc); 4492 syn_cache_put(sc); 4493 splx(s); 4494 TCP_STATINC(TCP_STAT_SC_DROPPED); 4495 } 4496 return (1); 4497 } 4498 4499 /* 4500 * syn_cache_respond: (re)send SYN+ACK. 4501 * 4502 * returns 0 on success. otherwise returns an errno, typically ENOBUFS. 4503 */ 4504 4505 int 4506 syn_cache_respond(struct syn_cache *sc, struct mbuf *m) 4507 { 4508 #ifdef INET6 4509 struct rtentry *rt; 4510 #endif 4511 struct route *ro; 4512 u_int8_t *optp; 4513 int optlen, error; 4514 u_int16_t tlen; 4515 struct ip *ip = NULL; 4516 #ifdef INET6 4517 struct ip6_hdr *ip6 = NULL; 4518 #endif 4519 struct tcpcb *tp = NULL; 4520 struct tcphdr *th; 4521 u_int hlen; 4522 struct socket *so; 4523 4524 ro = &sc->sc_route; 4525 switch (sc->sc_src.sa.sa_family) { 4526 case AF_INET: 4527 hlen = sizeof(struct ip); 4528 break; 4529 #ifdef INET6 4530 case AF_INET6: 4531 hlen = sizeof(struct ip6_hdr); 4532 break; 4533 #endif 4534 default: 4535 if (m) 4536 m_freem(m); 4537 return (EAFNOSUPPORT); 4538 } 4539 4540 /* Compute the size of the TCP options. */ 4541 optlen = 4 + (sc->sc_request_r_scale != 15 ? 4 : 0) + 4542 ((sc->sc_flags & SCF_SACK_PERMIT) ? (TCPOLEN_SACK_PERMITTED + 2) : 0) + 4543 #ifdef TCP_SIGNATURE 4544 ((sc->sc_flags & SCF_SIGNATURE) ? (TCPOLEN_SIGNATURE + 2) : 0) + 4545 #endif 4546 ((sc->sc_flags & SCF_TIMESTAMP) ? TCPOLEN_TSTAMP_APPA : 0); 4547 4548 tlen = hlen + sizeof(struct tcphdr) + optlen; 4549 4550 /* 4551 * Create the IP+TCP header from scratch. 4552 */ 4553 if (m) 4554 m_freem(m); 4555 #ifdef DIAGNOSTIC 4556 if (max_linkhdr + tlen > MCLBYTES) 4557 return (ENOBUFS); 4558 #endif 4559 MGETHDR(m, M_DONTWAIT, MT_DATA); 4560 if (m && (max_linkhdr + tlen) > MHLEN) { 4561 MCLGET(m, M_DONTWAIT); 4562 if ((m->m_flags & M_EXT) == 0) { 4563 m_freem(m); 4564 m = NULL; 4565 } 4566 } 4567 if (m == NULL) 4568 return (ENOBUFS); 4569 MCLAIM(m, &tcp_tx_mowner); 4570 4571 /* Fixup the mbuf. */ 4572 m->m_data += max_linkhdr; 4573 m->m_len = m->m_pkthdr.len = tlen; 4574 if (sc->sc_tp) { 4575 tp = sc->sc_tp; 4576 if (tp->t_inpcb) 4577 so = tp->t_inpcb->inp_socket; 4578 #ifdef INET6 4579 else if (tp->t_in6pcb) 4580 so = tp->t_in6pcb->in6p_socket; 4581 #endif 4582 else 4583 so = NULL; 4584 } else 4585 so = NULL; 4586 m->m_pkthdr.rcvif = NULL; 4587 memset(mtod(m, u_char *), 0, tlen); 4588 4589 switch (sc->sc_src.sa.sa_family) { 4590 case AF_INET: 4591 ip = mtod(m, struct ip *); 4592 ip->ip_v = 4; 4593 ip->ip_dst = sc->sc_src.sin.sin_addr; 4594 ip->ip_src = sc->sc_dst.sin.sin_addr; 4595 ip->ip_p = IPPROTO_TCP; 4596 th = (struct tcphdr *)(ip + 1); 4597 th->th_dport = sc->sc_src.sin.sin_port; 4598 th->th_sport = sc->sc_dst.sin.sin_port; 4599 break; 4600 #ifdef INET6 4601 case AF_INET6: 4602 ip6 = mtod(m, struct ip6_hdr *); 4603 ip6->ip6_vfc = IPV6_VERSION; 4604 ip6->ip6_dst = sc->sc_src.sin6.sin6_addr; 4605 ip6->ip6_src = sc->sc_dst.sin6.sin6_addr; 4606 ip6->ip6_nxt = IPPROTO_TCP; 4607 /* ip6_plen will be updated in ip6_output() */ 4608 th = (struct tcphdr *)(ip6 + 1); 4609 th->th_dport = sc->sc_src.sin6.sin6_port; 4610 th->th_sport = sc->sc_dst.sin6.sin6_port; 4611 break; 4612 #endif 4613 default: 4614 th = NULL; 4615 } 4616 4617 th->th_seq = htonl(sc->sc_iss); 4618 th->th_ack = htonl(sc->sc_irs + 1); 4619 th->th_off = (sizeof(struct tcphdr) + optlen) >> 2; 4620 th->th_flags = TH_SYN|TH_ACK; 4621 th->th_win = htons(sc->sc_win); 4622 /* th_sum already 0 */ 4623 /* th_urp already 0 */ 4624 4625 /* Tack on the TCP options. */ 4626 optp = (u_int8_t *)(th + 1); 4627 *optp++ = TCPOPT_MAXSEG; 4628 *optp++ = 4; 4629 *optp++ = (sc->sc_ourmaxseg >> 8) & 0xff; 4630 *optp++ = sc->sc_ourmaxseg & 0xff; 4631 4632 if (sc->sc_request_r_scale != 15) { 4633 *((u_int32_t *)optp) = htonl(TCPOPT_NOP << 24 | 4634 TCPOPT_WINDOW << 16 | TCPOLEN_WINDOW << 8 | 4635 sc->sc_request_r_scale); 4636 optp += 4; 4637 } 4638 4639 if (sc->sc_flags & SCF_TIMESTAMP) { 4640 u_int32_t *lp = (u_int32_t *)(optp); 4641 /* Form timestamp option as shown in appendix A of RFC 1323. */ 4642 *lp++ = htonl(TCPOPT_TSTAMP_HDR); 4643 *lp++ = htonl(SYN_CACHE_TIMESTAMP(sc)); 4644 *lp = htonl(sc->sc_timestamp); 4645 optp += TCPOLEN_TSTAMP_APPA; 4646 } 4647 4648 if (sc->sc_flags & SCF_SACK_PERMIT) { 4649 u_int8_t *p = optp; 4650 4651 /* Let the peer know that we will SACK. */ 4652 p[0] = TCPOPT_SACK_PERMITTED; 4653 p[1] = 2; 4654 p[2] = TCPOPT_NOP; 4655 p[3] = TCPOPT_NOP; 4656 optp += 4; 4657 } 4658 4659 /* 4660 * Send ECN SYN-ACK setup packet. 4661 * Routes can be asymetric, so, even if we receive a packet 4662 * with ECE and CWR set, we must not assume no one will block 4663 * the ECE packet we are about to send. 4664 */ 4665 if ((sc->sc_flags & SCF_ECN_PERMIT) && tp && 4666 SEQ_GEQ(tp->snd_nxt, tp->snd_max)) { 4667 th->th_flags |= TH_ECE; 4668 TCP_STATINC(TCP_STAT_ECN_SHS); 4669 4670 /* 4671 * draft-ietf-tcpm-ecnsyn-00.txt 4672 * 4673 * "[...] a TCP node MAY respond to an ECN-setup 4674 * SYN packet by setting ECT in the responding 4675 * ECN-setup SYN/ACK packet, indicating to routers 4676 * that the SYN/ACK packet is ECN-Capable. 4677 * This allows a congested router along the path 4678 * to mark the packet instead of dropping the 4679 * packet as an indication of congestion." 4680 * 4681 * "[...] There can be a great benefit in setting 4682 * an ECN-capable codepoint in SYN/ACK packets [...] 4683 * Congestion is most likely to occur in 4684 * the server-to-client direction. As a result, 4685 * setting an ECN-capable codepoint in SYN/ACK 4686 * packets can reduce the occurence of three-second 4687 * retransmit timeouts resulting from the drop 4688 * of SYN/ACK packets." 4689 * 4690 * Page 4 and 6, January 2006. 4691 */ 4692 4693 switch (sc->sc_src.sa.sa_family) { 4694 #ifdef INET 4695 case AF_INET: 4696 ip->ip_tos |= IPTOS_ECN_ECT0; 4697 break; 4698 #endif 4699 #ifdef INET6 4700 case AF_INET6: 4701 ip6->ip6_flow |= htonl(IPTOS_ECN_ECT0 << 20); 4702 break; 4703 #endif 4704 } 4705 TCP_STATINC(TCP_STAT_ECN_ECT); 4706 } 4707 4708 #ifdef TCP_SIGNATURE 4709 if (sc->sc_flags & SCF_SIGNATURE) { 4710 struct secasvar *sav; 4711 u_int8_t *sigp; 4712 4713 sav = tcp_signature_getsav(m, th); 4714 4715 if (sav == NULL) { 4716 if (m) 4717 m_freem(m); 4718 return (EPERM); 4719 } 4720 4721 *optp++ = TCPOPT_SIGNATURE; 4722 *optp++ = TCPOLEN_SIGNATURE; 4723 sigp = optp; 4724 memset(optp, 0, TCP_SIGLEN); 4725 optp += TCP_SIGLEN; 4726 *optp++ = TCPOPT_NOP; 4727 *optp++ = TCPOPT_EOL; 4728 4729 (void)tcp_signature(m, th, hlen, sav, sigp); 4730 4731 key_sa_recordxfer(sav, m); 4732 KEY_FREESAV(&sav); 4733 } 4734 #endif 4735 4736 /* Compute the packet's checksum. */ 4737 switch (sc->sc_src.sa.sa_family) { 4738 case AF_INET: 4739 ip->ip_len = htons(tlen - hlen); 4740 th->th_sum = 0; 4741 th->th_sum = in4_cksum(m, IPPROTO_TCP, hlen, tlen - hlen); 4742 break; 4743 #ifdef INET6 4744 case AF_INET6: 4745 ip6->ip6_plen = htons(tlen - hlen); 4746 th->th_sum = 0; 4747 th->th_sum = in6_cksum(m, IPPROTO_TCP, hlen, tlen - hlen); 4748 break; 4749 #endif 4750 } 4751 4752 /* 4753 * Fill in some straggling IP bits. Note the stack expects 4754 * ip_len to be in host order, for convenience. 4755 */ 4756 switch (sc->sc_src.sa.sa_family) { 4757 #ifdef INET 4758 case AF_INET: 4759 ip->ip_len = htons(tlen); 4760 ip->ip_ttl = ip_defttl; 4761 /* XXX tos? */ 4762 break; 4763 #endif 4764 #ifdef INET6 4765 case AF_INET6: 4766 ip6->ip6_vfc &= ~IPV6_VERSION_MASK; 4767 ip6->ip6_vfc |= IPV6_VERSION; 4768 ip6->ip6_plen = htons(tlen - hlen); 4769 /* ip6_hlim will be initialized afterwards */ 4770 /* XXX flowlabel? */ 4771 break; 4772 #endif 4773 } 4774 4775 /* XXX use IPsec policy on listening socket, on SYN ACK */ 4776 tp = sc->sc_tp; 4777 4778 switch (sc->sc_src.sa.sa_family) { 4779 #ifdef INET 4780 case AF_INET: 4781 error = ip_output(m, sc->sc_ipopts, ro, 4782 (ip_mtudisc ? IP_MTUDISC : 0), 4783 NULL, so); 4784 break; 4785 #endif 4786 #ifdef INET6 4787 case AF_INET6: 4788 ip6->ip6_hlim = in6_selecthlim(NULL, 4789 (rt = rtcache_validate(ro)) != NULL ? rt->rt_ifp : NULL); 4790 4791 error = ip6_output(m, NULL /*XXX*/, ro, 0, NULL, so, NULL); 4792 break; 4793 #endif 4794 default: 4795 error = EAFNOSUPPORT; 4796 break; 4797 } 4798 return (error); 4799 } 4800