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