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