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