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