1 /* $NetBSD: tcp_input.c,v 1.419 2020/09/02 15:08:46 kardel 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.419 2020/09/02 15:08:46 kardel 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 /* 1901 * drag snd_wl2 along so only newer 1902 * ACKs can update the window size. 1903 * also avoids the state where snd_wl2 1904 * is eventually larger than th_ack and thus 1905 * blocking the window update mechanism and 1906 * the connection gets stuck for a loooong 1907 * time in the zero sized send window state. 1908 * 1909 * see PR/kern 55567 1910 */ 1911 tp->snd_wl2 = tp->snd_una; 1912 1913 m_freem(m); 1914 1915 /* 1916 * If all outstanding data are acked, stop 1917 * retransmit timer, otherwise restart timer 1918 * using current (possibly backed-off) value. 1919 * If process is waiting for space, 1920 * wakeup/selnotify/signal. If data 1921 * are ready to send, let tcp_output 1922 * decide between more output or persist. 1923 */ 1924 if (tp->snd_una == tp->snd_max) 1925 TCP_TIMER_DISARM(tp, TCPT_REXMT); 1926 else if (TCP_TIMER_ISARMED(tp, 1927 TCPT_PERSIST) == 0) 1928 TCP_TIMER_ARM(tp, TCPT_REXMT, 1929 tp->t_rxtcur); 1930 1931 sowwakeup(so); 1932 if (so->so_snd.sb_cc) { 1933 KERNEL_LOCK(1, NULL); 1934 (void)tcp_output(tp); 1935 KERNEL_UNLOCK_ONE(NULL); 1936 } 1937 if (tcp_saveti) 1938 m_freem(tcp_saveti); 1939 return; 1940 } 1941 } else if (th->th_ack == tp->snd_una && 1942 TAILQ_FIRST(&tp->segq) == NULL && 1943 tlen <= sbspace(&so->so_rcv)) { 1944 int newsize = 0; 1945 1946 /* 1947 * this is a pure, in-sequence data packet 1948 * with nothing on the reassembly queue and 1949 * we have enough buffer space to take it. 1950 */ 1951 tp->rcv_nxt += tlen; 1952 tcps = TCP_STAT_GETREF(); 1953 tcps[TCP_STAT_PREDDAT]++; 1954 tcps[TCP_STAT_RCVPACK]++; 1955 tcps[TCP_STAT_RCVBYTE] += tlen; 1956 TCP_STAT_PUTREF(); 1957 nd6_hint(tp); 1958 1959 /* 1960 * Automatic sizing enables the performance of large buffers 1961 * and most of the efficiency of small ones by only allocating 1962 * space when it is needed. 1963 * 1964 * On the receive side the socket buffer memory is only rarely 1965 * used to any significant extent. This allows us to be much 1966 * more aggressive in scaling the receive socket buffer. For 1967 * the case that the buffer space is actually used to a large 1968 * extent and we run out of kernel memory we can simply drop 1969 * the new segments; TCP on the sender will just retransmit it 1970 * later. Setting the buffer size too big may only consume too 1971 * much kernel memory if the application doesn't read() from 1972 * the socket or packet loss or reordering makes use of the 1973 * reassembly queue. 1974 * 1975 * The criteria to step up the receive buffer one notch are: 1976 * 1. the number of bytes received during the time it takes 1977 * one timestamp to be reflected back to us (the RTT); 1978 * 2. received bytes per RTT is within seven eighth of the 1979 * current socket buffer size; 1980 * 3. receive buffer size has not hit maximal automatic size; 1981 * 1982 * This algorithm does one step per RTT at most and only if 1983 * we receive a bulk stream w/o packet losses or reorderings. 1984 * Shrinking the buffer during idle times is not necessary as 1985 * it doesn't consume any memory when idle. 1986 * 1987 * TODO: Only step up if the application is actually serving 1988 * the buffer to better manage the socket buffer resources. 1989 */ 1990 if (tcp_do_autorcvbuf && 1991 opti.ts_ecr && 1992 (so->so_rcv.sb_flags & SB_AUTOSIZE)) { 1993 if (opti.ts_ecr > tp->rfbuf_ts && 1994 opti.ts_ecr - tp->rfbuf_ts < PR_SLOWHZ) { 1995 if (tp->rfbuf_cnt > 1996 (so->so_rcv.sb_hiwat / 8 * 7) && 1997 so->so_rcv.sb_hiwat < 1998 tcp_autorcvbuf_max) { 1999 newsize = 2000 uimin(so->so_rcv.sb_hiwat + 2001 tcp_autorcvbuf_inc, 2002 tcp_autorcvbuf_max); 2003 } 2004 /* Start over with next RTT. */ 2005 tp->rfbuf_ts = 0; 2006 tp->rfbuf_cnt = 0; 2007 } else 2008 tp->rfbuf_cnt += tlen; /* add up */ 2009 } 2010 2011 /* 2012 * Drop TCP, IP headers and TCP options then add data 2013 * to socket buffer. 2014 */ 2015 if (so->so_state & SS_CANTRCVMORE) { 2016 m_freem(m); 2017 } else { 2018 /* 2019 * Set new socket buffer size. 2020 * Give up when limit is reached. 2021 */ 2022 if (newsize) 2023 if (!sbreserve(&so->so_rcv, 2024 newsize, so)) 2025 so->so_rcv.sb_flags &= ~SB_AUTOSIZE; 2026 m_adj(m, off + thlen); 2027 sbappendstream(&so->so_rcv, m); 2028 } 2029 sorwakeup(so); 2030 tcp_setup_ack(tp, th); 2031 if (tp->t_flags & TF_ACKNOW) { 2032 KERNEL_LOCK(1, NULL); 2033 (void)tcp_output(tp); 2034 KERNEL_UNLOCK_ONE(NULL); 2035 } 2036 if (tcp_saveti) 2037 m_freem(tcp_saveti); 2038 return; 2039 } 2040 } 2041 2042 /* 2043 * Compute mbuf offset to TCP data segment. 2044 */ 2045 hdroptlen = off + thlen; 2046 2047 /* 2048 * Calculate amount of space in receive window. Receive window is 2049 * amount of space in rcv queue, but not less than advertised 2050 * window. 2051 */ 2052 { 2053 int win; 2054 win = sbspace(&so->so_rcv); 2055 if (win < 0) 2056 win = 0; 2057 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt)); 2058 } 2059 2060 /* Reset receive buffer auto scaling when not in bulk receive mode. */ 2061 tp->rfbuf_ts = 0; 2062 tp->rfbuf_cnt = 0; 2063 2064 switch (tp->t_state) { 2065 /* 2066 * If the state is SYN_SENT: 2067 * if seg contains an ACK, but not for our SYN, drop the input. 2068 * if seg contains a RST, then drop the connection. 2069 * if seg does not contain SYN, then drop it. 2070 * Otherwise this is an acceptable SYN segment 2071 * initialize tp->rcv_nxt and tp->irs 2072 * if seg contains ack then advance tp->snd_una 2073 * if seg contains a ECE and ECN support is enabled, the stream 2074 * is ECN capable. 2075 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state 2076 * arrange for segment to be acked (eventually) 2077 * continue processing rest of data/controls, beginning with URG 2078 */ 2079 case TCPS_SYN_SENT: 2080 if ((tiflags & TH_ACK) && 2081 (SEQ_LEQ(th->th_ack, tp->iss) || 2082 SEQ_GT(th->th_ack, tp->snd_max))) 2083 goto dropwithreset; 2084 if (tiflags & TH_RST) { 2085 if (tiflags & TH_ACK) 2086 tp = tcp_drop(tp, ECONNREFUSED); 2087 goto drop; 2088 } 2089 if ((tiflags & TH_SYN) == 0) 2090 goto drop; 2091 if (tiflags & TH_ACK) { 2092 tp->snd_una = th->th_ack; 2093 if (SEQ_LT(tp->snd_nxt, tp->snd_una)) 2094 tp->snd_nxt = tp->snd_una; 2095 if (SEQ_LT(tp->snd_high, tp->snd_una)) 2096 tp->snd_high = tp->snd_una; 2097 TCP_TIMER_DISARM(tp, TCPT_REXMT); 2098 2099 if ((tiflags & TH_ECE) && tcp_do_ecn) { 2100 tp->t_flags |= TF_ECN_PERMIT; 2101 TCP_STATINC(TCP_STAT_ECN_SHS); 2102 } 2103 } 2104 tp->irs = th->th_seq; 2105 tcp_rcvseqinit(tp); 2106 tp->t_flags |= TF_ACKNOW; 2107 tcp_mss_from_peer(tp, opti.maxseg); 2108 2109 /* 2110 * Initialize the initial congestion window. If we 2111 * had to retransmit the SYN, we must initialize cwnd 2112 * to 1 segment (i.e. the Loss Window). 2113 */ 2114 if (tp->t_flags & TF_SYN_REXMT) 2115 tp->snd_cwnd = tp->t_peermss; 2116 else { 2117 int ss = tcp_init_win; 2118 if (inp != NULL && in_localaddr(inp->inp_faddr)) 2119 ss = tcp_init_win_local; 2120 #ifdef INET6 2121 if (in6p != NULL && in6_localaddr(&in6p->in6p_faddr)) 2122 ss = tcp_init_win_local; 2123 #endif 2124 tp->snd_cwnd = TCP_INITIAL_WINDOW(ss, tp->t_peermss); 2125 } 2126 2127 tcp_rmx_rtt(tp); 2128 if (tiflags & TH_ACK) { 2129 TCP_STATINC(TCP_STAT_CONNECTS); 2130 /* 2131 * move tcp_established before soisconnected 2132 * because upcall handler can drive tcp_output 2133 * functionality. 2134 * XXX we might call soisconnected at the end of 2135 * all processing 2136 */ 2137 tcp_established(tp); 2138 soisconnected(so); 2139 /* Do window scaling on this connection? */ 2140 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) == 2141 (TF_RCVD_SCALE|TF_REQ_SCALE)) { 2142 tp->snd_scale = tp->requested_s_scale; 2143 tp->rcv_scale = tp->request_r_scale; 2144 } 2145 TCP_REASS_LOCK(tp); 2146 (void)tcp_reass(tp, NULL, NULL, tlen); 2147 /* 2148 * if we didn't have to retransmit the SYN, 2149 * use its rtt as our initial srtt & rtt var. 2150 */ 2151 if (tp->t_rtttime) 2152 tcp_xmit_timer(tp, tcp_now - tp->t_rtttime); 2153 } else { 2154 tp->t_state = TCPS_SYN_RECEIVED; 2155 } 2156 2157 /* 2158 * Advance th->th_seq to correspond to first data byte. 2159 * If data, trim to stay within window, 2160 * dropping FIN if necessary. 2161 */ 2162 th->th_seq++; 2163 if (tlen > tp->rcv_wnd) { 2164 todrop = tlen - tp->rcv_wnd; 2165 m_adj(m, -todrop); 2166 tlen = tp->rcv_wnd; 2167 tiflags &= ~TH_FIN; 2168 tcps = TCP_STAT_GETREF(); 2169 tcps[TCP_STAT_RCVPACKAFTERWIN]++; 2170 tcps[TCP_STAT_RCVBYTEAFTERWIN] += todrop; 2171 TCP_STAT_PUTREF(); 2172 } 2173 tp->snd_wl1 = th->th_seq - 1; 2174 tp->rcv_up = th->th_seq; 2175 goto step6; 2176 2177 /* 2178 * If the state is SYN_RECEIVED: 2179 * If seg contains an ACK, but not for our SYN, drop the input 2180 * and generate an RST. See page 36, rfc793 2181 */ 2182 case TCPS_SYN_RECEIVED: 2183 if ((tiflags & TH_ACK) && 2184 (SEQ_LEQ(th->th_ack, tp->iss) || 2185 SEQ_GT(th->th_ack, tp->snd_max))) 2186 goto dropwithreset; 2187 break; 2188 } 2189 2190 /* 2191 * From here on, we're dealing with !LISTEN and !SYN_SENT. 2192 */ 2193 KASSERT(tp->t_state != TCPS_LISTEN && 2194 tp->t_state != TCPS_SYN_SENT); 2195 2196 /* 2197 * RFC1323 PAWS: if we have a timestamp reply on this segment and 2198 * it's less than ts_recent, drop it. 2199 */ 2200 if (opti.ts_present && (tiflags & TH_RST) == 0 && tp->ts_recent && 2201 TSTMP_LT(opti.ts_val, tp->ts_recent)) { 2202 /* Check to see if ts_recent is over 24 days old. */ 2203 if (tcp_now - tp->ts_recent_age > TCP_PAWS_IDLE) { 2204 /* 2205 * Invalidate ts_recent. If this segment updates 2206 * ts_recent, the age will be reset later and ts_recent 2207 * will get a valid value. If it does not, setting 2208 * ts_recent to zero will at least satisfy the 2209 * requirement that zero be placed in the timestamp 2210 * echo reply when ts_recent isn't valid. The 2211 * age isn't reset until we get a valid ts_recent 2212 * because we don't want out-of-order segments to be 2213 * dropped when ts_recent is old. 2214 */ 2215 tp->ts_recent = 0; 2216 } else { 2217 tcps = TCP_STAT_GETREF(); 2218 tcps[TCP_STAT_RCVDUPPACK]++; 2219 tcps[TCP_STAT_RCVDUPBYTE] += tlen; 2220 tcps[TCP_STAT_PAWSDROP]++; 2221 TCP_STAT_PUTREF(); 2222 tcp_new_dsack(tp, th->th_seq, tlen); 2223 goto dropafterack; 2224 } 2225 } 2226 2227 /* 2228 * Check that at least some bytes of the segment are within the 2229 * receive window. If segment begins before rcv_nxt, drop leading 2230 * data (and SYN); if nothing left, just ack. 2231 */ 2232 todrop = tp->rcv_nxt - th->th_seq; 2233 dupseg = false; 2234 if (todrop > 0) { 2235 if (tiflags & TH_SYN) { 2236 tiflags &= ~TH_SYN; 2237 th->th_seq++; 2238 tcp_urp_drop(th, 1, &tiflags); 2239 todrop--; 2240 } 2241 if (todrop > tlen || 2242 (todrop == tlen && (tiflags & TH_FIN) == 0)) { 2243 /* 2244 * Any valid FIN or RST must be to the left of the 2245 * window. At this point the FIN or RST must be a 2246 * duplicate or out of sequence; drop it. 2247 */ 2248 if (tiflags & TH_RST) 2249 goto drop; 2250 tiflags &= ~(TH_FIN|TH_RST); 2251 2252 /* 2253 * Send an ACK to resynchronize and drop any data. 2254 * But keep on processing for RST or ACK. 2255 */ 2256 tp->t_flags |= TF_ACKNOW; 2257 todrop = tlen; 2258 dupseg = true; 2259 tcps = TCP_STAT_GETREF(); 2260 tcps[TCP_STAT_RCVDUPPACK]++; 2261 tcps[TCP_STAT_RCVDUPBYTE] += todrop; 2262 TCP_STAT_PUTREF(); 2263 } else if ((tiflags & TH_RST) && th->th_seq != tp->rcv_nxt) { 2264 /* 2265 * Test for reset before adjusting the sequence 2266 * number for overlapping data. 2267 */ 2268 goto dropafterack_ratelim; 2269 } else { 2270 tcps = TCP_STAT_GETREF(); 2271 tcps[TCP_STAT_RCVPARTDUPPACK]++; 2272 tcps[TCP_STAT_RCVPARTDUPBYTE] += todrop; 2273 TCP_STAT_PUTREF(); 2274 } 2275 tcp_new_dsack(tp, th->th_seq, todrop); 2276 hdroptlen += todrop; /* drop from head afterwards (m_adj) */ 2277 th->th_seq += todrop; 2278 tlen -= todrop; 2279 tcp_urp_drop(th, todrop, &tiflags); 2280 } 2281 2282 /* 2283 * If new data is received on a connection after the user processes 2284 * are gone, then RST the other end. 2285 */ 2286 if ((so->so_state & SS_NOFDREF) && 2287 tp->t_state > TCPS_CLOSE_WAIT && tlen) { 2288 tp = tcp_close(tp); 2289 TCP_STATINC(TCP_STAT_RCVAFTERCLOSE); 2290 goto dropwithreset; 2291 } 2292 2293 /* 2294 * If the segment ends after the window, drop trailing data (and 2295 * PUSH and FIN); if nothing left, just ACK. 2296 */ 2297 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd); 2298 if (todrop > 0) { 2299 TCP_STATINC(TCP_STAT_RCVPACKAFTERWIN); 2300 if (todrop >= tlen) { 2301 /* 2302 * The segment actually starts after the window. 2303 * th->th_seq + tlen - tp->rcv_nxt - tp->rcv_wnd >= tlen 2304 * th->th_seq - tp->rcv_nxt - tp->rcv_wnd >= 0 2305 * th->th_seq >= tp->rcv_nxt + tp->rcv_wnd 2306 */ 2307 TCP_STATADD(TCP_STAT_RCVBYTEAFTERWIN, tlen); 2308 2309 /* 2310 * If a new connection request is received while in 2311 * TIME_WAIT, drop the old connection and start over 2312 * if the sequence numbers are above the previous 2313 * ones. 2314 * 2315 * NOTE: We need to put the header fields back into 2316 * network order. 2317 */ 2318 if ((tiflags & TH_SYN) && 2319 tp->t_state == TCPS_TIME_WAIT && 2320 SEQ_GT(th->th_seq, tp->rcv_nxt)) { 2321 tp = tcp_close(tp); 2322 tcp_fields_to_net(th); 2323 m_freem(tcp_saveti); 2324 tcp_saveti = NULL; 2325 goto findpcb; 2326 } 2327 2328 /* 2329 * If window is closed can only take segments at 2330 * window edge, and have to drop data and PUSH from 2331 * incoming segments. Continue processing, but 2332 * remember to ack. Otherwise, drop segment 2333 * and (if not RST) ack. 2334 */ 2335 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) { 2336 KASSERT(todrop == tlen); 2337 tp->t_flags |= TF_ACKNOW; 2338 TCP_STATINC(TCP_STAT_RCVWINPROBE); 2339 } else { 2340 goto dropafterack; 2341 } 2342 } else { 2343 TCP_STATADD(TCP_STAT_RCVBYTEAFTERWIN, todrop); 2344 } 2345 m_adj(m, -todrop); 2346 tlen -= todrop; 2347 tiflags &= ~(TH_PUSH|TH_FIN); 2348 } 2349 2350 /* 2351 * If last ACK falls within this segment's sequence numbers, 2352 * record the timestamp. 2353 * NOTE: 2354 * 1) That the test incorporates suggestions from the latest 2355 * proposal of the tcplw@cray.com list (Braden 1993/04/26). 2356 * 2) That updating only on newer timestamps interferes with 2357 * our earlier PAWS tests, so this check should be solely 2358 * predicated on the sequence space of this segment. 2359 * 3) That we modify the segment boundary check to be 2360 * Last.ACK.Sent <= SEG.SEQ + SEG.Len 2361 * instead of RFC1323's 2362 * Last.ACK.Sent < SEG.SEQ + SEG.Len, 2363 * This modified check allows us to overcome RFC1323's 2364 * limitations as described in Stevens TCP/IP Illustrated 2365 * Vol. 2 p.869. In such cases, we can still calculate the 2366 * RTT correctly when RCV.NXT == Last.ACK.Sent. 2367 */ 2368 if (opti.ts_present && 2369 SEQ_LEQ(th->th_seq, tp->last_ack_sent) && 2370 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen + 2371 ((tiflags & (TH_SYN|TH_FIN)) != 0))) { 2372 tp->ts_recent_age = tcp_now; 2373 tp->ts_recent = opti.ts_val; 2374 } 2375 2376 /* 2377 * If the RST bit is set examine the state: 2378 * RECEIVED state: 2379 * If passive open, return to LISTEN state. 2380 * If active open, inform user that connection was refused. 2381 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT states: 2382 * Inform user that connection was reset, and close tcb. 2383 * CLOSING, LAST_ACK, TIME_WAIT states: 2384 * Close the tcb. 2385 */ 2386 if (tiflags & TH_RST) { 2387 if (th->th_seq != tp->rcv_nxt) 2388 goto dropafterack_ratelim; 2389 2390 switch (tp->t_state) { 2391 case TCPS_SYN_RECEIVED: 2392 so->so_error = ECONNREFUSED; 2393 goto close; 2394 2395 case TCPS_ESTABLISHED: 2396 case TCPS_FIN_WAIT_1: 2397 case TCPS_FIN_WAIT_2: 2398 case TCPS_CLOSE_WAIT: 2399 so->so_error = ECONNRESET; 2400 close: 2401 tp->t_state = TCPS_CLOSED; 2402 TCP_STATINC(TCP_STAT_DROPS); 2403 tp = tcp_close(tp); 2404 goto drop; 2405 2406 case TCPS_CLOSING: 2407 case TCPS_LAST_ACK: 2408 case TCPS_TIME_WAIT: 2409 tp = tcp_close(tp); 2410 goto drop; 2411 } 2412 } 2413 2414 /* 2415 * Since we've covered the SYN-SENT and SYN-RECEIVED states above 2416 * we must be in a synchronized state. RFC793 states (under Reset 2417 * Generation) that any unacceptable segment (an out-of-order SYN 2418 * qualifies) received in a synchronized state must elicit only an 2419 * empty acknowledgment segment ... and the connection remains in 2420 * the same state. 2421 */ 2422 if (tiflags & TH_SYN) { 2423 if (tp->rcv_nxt == th->th_seq) { 2424 tcp_respond(tp, m, m, th, (tcp_seq)0, th->th_ack - 1, 2425 TH_ACK); 2426 if (tcp_saveti) 2427 m_freem(tcp_saveti); 2428 return; 2429 } 2430 2431 goto dropafterack_ratelim; 2432 } 2433 2434 /* 2435 * If the ACK bit is off we drop the segment and return. 2436 */ 2437 if ((tiflags & TH_ACK) == 0) { 2438 if (tp->t_flags & TF_ACKNOW) 2439 goto dropafterack; 2440 goto drop; 2441 } 2442 2443 /* 2444 * From here on, we're doing ACK processing. 2445 */ 2446 2447 switch (tp->t_state) { 2448 /* 2449 * In SYN_RECEIVED state if the ack ACKs our SYN then enter 2450 * ESTABLISHED state and continue processing, otherwise 2451 * send an RST. 2452 */ 2453 case TCPS_SYN_RECEIVED: 2454 if (SEQ_GT(tp->snd_una, th->th_ack) || 2455 SEQ_GT(th->th_ack, tp->snd_max)) 2456 goto dropwithreset; 2457 TCP_STATINC(TCP_STAT_CONNECTS); 2458 soisconnected(so); 2459 tcp_established(tp); 2460 /* Do window scaling? */ 2461 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) == 2462 (TF_RCVD_SCALE|TF_REQ_SCALE)) { 2463 tp->snd_scale = tp->requested_s_scale; 2464 tp->rcv_scale = tp->request_r_scale; 2465 } 2466 TCP_REASS_LOCK(tp); 2467 (void)tcp_reass(tp, NULL, NULL, tlen); 2468 tp->snd_wl1 = th->th_seq - 1; 2469 /* FALLTHROUGH */ 2470 2471 /* 2472 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range 2473 * ACKs. If the ack is in the range 2474 * tp->snd_una < th->th_ack <= tp->snd_max 2475 * then advance tp->snd_una to th->th_ack and drop 2476 * data from the retransmission queue. If this ACK reflects 2477 * more up to date window information we update our window information. 2478 */ 2479 case TCPS_ESTABLISHED: 2480 case TCPS_FIN_WAIT_1: 2481 case TCPS_FIN_WAIT_2: 2482 case TCPS_CLOSE_WAIT: 2483 case TCPS_CLOSING: 2484 case TCPS_LAST_ACK: 2485 case TCPS_TIME_WAIT: 2486 if (SEQ_LEQ(th->th_ack, tp->snd_una)) { 2487 if (tlen == 0 && !dupseg && tiwin == tp->snd_wnd) { 2488 TCP_STATINC(TCP_STAT_RCVDUPACK); 2489 /* 2490 * If we have outstanding data (other than 2491 * a window probe), this is a completely 2492 * duplicate ack (ie, window info didn't 2493 * change), the ack is the biggest we've 2494 * seen and we've seen exactly our rexmt 2495 * threshhold of them, assume a packet 2496 * has been dropped and retransmit it. 2497 * Kludge snd_nxt & the congestion 2498 * window so we send only this one 2499 * packet. 2500 */ 2501 if (TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 || 2502 th->th_ack != tp->snd_una) 2503 tp->t_dupacks = 0; 2504 else if (tp->t_partialacks < 0 && 2505 (++tp->t_dupacks == tcprexmtthresh || 2506 TCP_FACK_FASTRECOV(tp))) { 2507 /* 2508 * Do the fast retransmit, and adjust 2509 * congestion control paramenters. 2510 */ 2511 if (tp->t_congctl->fast_retransmit(tp, th)) { 2512 /* False fast retransmit */ 2513 break; 2514 } 2515 goto drop; 2516 } else if (tp->t_dupacks > tcprexmtthresh) { 2517 tp->snd_cwnd += tp->t_segsz; 2518 KERNEL_LOCK(1, NULL); 2519 (void)tcp_output(tp); 2520 KERNEL_UNLOCK_ONE(NULL); 2521 goto drop; 2522 } 2523 } else { 2524 /* 2525 * If the ack appears to be very old, only 2526 * allow data that is in-sequence. This 2527 * makes it somewhat more difficult to insert 2528 * forged data by guessing sequence numbers. 2529 * Sent an ack to try to update the send 2530 * sequence number on the other side. 2531 */ 2532 if (tlen && th->th_seq != tp->rcv_nxt && 2533 SEQ_LT(th->th_ack, 2534 tp->snd_una - tp->max_sndwnd)) 2535 goto dropafterack; 2536 } 2537 break; 2538 } 2539 /* 2540 * If the congestion window was inflated to account 2541 * for the other side's cached packets, retract it. 2542 */ 2543 tp->t_congctl->fast_retransmit_newack(tp, th); 2544 2545 if (SEQ_GT(th->th_ack, tp->snd_max)) { 2546 TCP_STATINC(TCP_STAT_RCVACKTOOMUCH); 2547 goto dropafterack; 2548 } 2549 acked = th->th_ack - tp->snd_una; 2550 tcps = TCP_STAT_GETREF(); 2551 tcps[TCP_STAT_RCVACKPACK]++; 2552 tcps[TCP_STAT_RCVACKBYTE] += acked; 2553 TCP_STAT_PUTREF(); 2554 2555 /* 2556 * If we have a timestamp reply, update smoothed 2557 * round trip time. If no timestamp is present but 2558 * transmit timer is running and timed sequence 2559 * number was acked, update smoothed round trip time. 2560 * Since we now have an rtt measurement, cancel the 2561 * timer backoff (cf., Phil Karn's retransmit alg.). 2562 * Recompute the initial retransmit timer. 2563 */ 2564 if (ts_rtt) 2565 tcp_xmit_timer(tp, ts_rtt - 1); 2566 else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) 2567 tcp_xmit_timer(tp, tcp_now - tp->t_rtttime); 2568 2569 /* 2570 * If all outstanding data is acked, stop retransmit 2571 * timer and remember to restart (more output or persist). 2572 * If there is more data to be acked, restart retransmit 2573 * timer, using current (possibly backed-off) value. 2574 */ 2575 if (th->th_ack == tp->snd_max) { 2576 TCP_TIMER_DISARM(tp, TCPT_REXMT); 2577 needoutput = 1; 2578 } else if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0) 2579 TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur); 2580 2581 /* 2582 * New data has been acked, adjust the congestion window. 2583 */ 2584 tp->t_congctl->newack(tp, th); 2585 2586 nd6_hint(tp); 2587 if (acked > so->so_snd.sb_cc) { 2588 tp->snd_wnd -= so->so_snd.sb_cc; 2589 sbdrop(&so->so_snd, (int)so->so_snd.sb_cc); 2590 ourfinisacked = 1; 2591 } else { 2592 if (acked > (tp->t_lastoff - tp->t_inoff)) 2593 tp->t_lastm = NULL; 2594 sbdrop(&so->so_snd, acked); 2595 tp->t_lastoff -= acked; 2596 if (tp->snd_wnd > acked) 2597 tp->snd_wnd -= acked; 2598 else 2599 tp->snd_wnd = 0; 2600 ourfinisacked = 0; 2601 } 2602 sowwakeup(so); 2603 2604 icmp_check(tp, th, acked); 2605 2606 tp->snd_una = th->th_ack; 2607 if (SEQ_GT(tp->snd_una, tp->snd_fack)) 2608 tp->snd_fack = tp->snd_una; 2609 if (SEQ_LT(tp->snd_nxt, tp->snd_una)) 2610 tp->snd_nxt = tp->snd_una; 2611 if (SEQ_LT(tp->snd_high, tp->snd_una)) 2612 tp->snd_high = tp->snd_una; 2613 2614 switch (tp->t_state) { 2615 2616 /* 2617 * In FIN_WAIT_1 STATE in addition to the processing 2618 * for the ESTABLISHED state if our FIN is now acknowledged 2619 * then enter FIN_WAIT_2. 2620 */ 2621 case TCPS_FIN_WAIT_1: 2622 if (ourfinisacked) { 2623 /* 2624 * If we can't receive any more 2625 * data, then closing user can proceed. 2626 * Starting the timer is contrary to the 2627 * specification, but if we don't get a FIN 2628 * we'll hang forever. 2629 */ 2630 if (so->so_state & SS_CANTRCVMORE) { 2631 soisdisconnected(so); 2632 if (tp->t_maxidle > 0) 2633 TCP_TIMER_ARM(tp, TCPT_2MSL, 2634 tp->t_maxidle); 2635 } 2636 tp->t_state = TCPS_FIN_WAIT_2; 2637 } 2638 break; 2639 2640 /* 2641 * In CLOSING STATE in addition to the processing for 2642 * the ESTABLISHED state if the ACK acknowledges our FIN 2643 * then enter the TIME-WAIT state, otherwise ignore 2644 * the segment. 2645 */ 2646 case TCPS_CLOSING: 2647 if (ourfinisacked) { 2648 tp->t_state = TCPS_TIME_WAIT; 2649 tcp_canceltimers(tp); 2650 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl); 2651 soisdisconnected(so); 2652 } 2653 break; 2654 2655 /* 2656 * In LAST_ACK, we may still be waiting for data to drain 2657 * and/or to be acked, as well as for the ack of our FIN. 2658 * If our FIN is now acknowledged, delete the TCB, 2659 * enter the closed state and return. 2660 */ 2661 case TCPS_LAST_ACK: 2662 if (ourfinisacked) { 2663 tp = tcp_close(tp); 2664 goto drop; 2665 } 2666 break; 2667 2668 /* 2669 * In TIME_WAIT state the only thing that should arrive 2670 * is a retransmission of the remote FIN. Acknowledge 2671 * it and restart the finack timer. 2672 */ 2673 case TCPS_TIME_WAIT: 2674 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl); 2675 goto dropafterack; 2676 } 2677 } 2678 2679 step6: 2680 /* 2681 * Update window information. 2682 * Don't look at window if no ACK: TAC's send garbage on first SYN. 2683 */ 2684 if ((tiflags & TH_ACK) && (SEQ_LT(tp->snd_wl1, th->th_seq) || 2685 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) || 2686 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) { 2687 /* keep track of pure window updates */ 2688 if (tlen == 0 && 2689 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd) 2690 TCP_STATINC(TCP_STAT_RCVWINUPD); 2691 tp->snd_wnd = tiwin; 2692 tp->snd_wl1 = th->th_seq; 2693 tp->snd_wl2 = th->th_ack; 2694 if (tp->snd_wnd > tp->max_sndwnd) 2695 tp->max_sndwnd = tp->snd_wnd; 2696 needoutput = 1; 2697 } 2698 2699 /* 2700 * Process segments with URG. 2701 */ 2702 if ((tiflags & TH_URG) && th->th_urp && 2703 TCPS_HAVERCVDFIN(tp->t_state) == 0) { 2704 /* 2705 * This is a kludge, but if we receive and accept 2706 * random urgent pointers, we'll crash in 2707 * soreceive. It's hard to imagine someone 2708 * actually wanting to send this much urgent data. 2709 */ 2710 if (th->th_urp + so->so_rcv.sb_cc > sb_max) { 2711 th->th_urp = 0; /* XXX */ 2712 tiflags &= ~TH_URG; /* XXX */ 2713 goto dodata; /* XXX */ 2714 } 2715 2716 /* 2717 * If this segment advances the known urgent pointer, 2718 * then mark the data stream. This should not happen 2719 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since 2720 * a FIN has been received from the remote side. 2721 * In these states we ignore the URG. 2722 * 2723 * According to RFC961 (Assigned Protocols), 2724 * the urgent pointer points to the last octet 2725 * of urgent data. We continue, however, 2726 * to consider it to indicate the first octet 2727 * of data past the urgent section as the original 2728 * spec states (in one of two places). 2729 */ 2730 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) { 2731 tp->rcv_up = th->th_seq + th->th_urp; 2732 so->so_oobmark = so->so_rcv.sb_cc + 2733 (tp->rcv_up - tp->rcv_nxt) - 1; 2734 if (so->so_oobmark == 0) 2735 so->so_state |= SS_RCVATMARK; 2736 sohasoutofband(so); 2737 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA); 2738 } 2739 2740 /* 2741 * Remove out of band data so doesn't get presented to user. 2742 * This can happen independent of advancing the URG pointer, 2743 * but if two URG's are pending at once, some out-of-band 2744 * data may creep in... ick. 2745 */ 2746 if (th->th_urp <= (u_int16_t)tlen && 2747 (so->so_options & SO_OOBINLINE) == 0) 2748 tcp_pulloutofband(so, th, m, hdroptlen); 2749 } else { 2750 /* 2751 * If no out of band data is expected, 2752 * pull receive urgent pointer along 2753 * with the receive window. 2754 */ 2755 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up)) 2756 tp->rcv_up = tp->rcv_nxt; 2757 } 2758 dodata: 2759 2760 /* 2761 * Process the segment text, merging it into the TCP sequencing queue, 2762 * and arranging for acknowledgement of receipt if necessary. 2763 * This process logically involves adjusting tp->rcv_wnd as data 2764 * is presented to the user (this happens in tcp_usrreq.c, 2765 * tcp_rcvd()). If a FIN has already been received on this 2766 * connection then we just ignore the text. 2767 */ 2768 if ((tlen || (tiflags & TH_FIN)) && 2769 TCPS_HAVERCVDFIN(tp->t_state) == 0) { 2770 /* 2771 * Handle the common case: 2772 * o Segment is the next to be received, and 2773 * o The queue is empty, and 2774 * o The connection is established 2775 * In this case, we avoid calling tcp_reass. 2776 * 2777 * tcp_setup_ack: set DELACK for segments received in order, 2778 * but ack immediately when segments are out of order (so that 2779 * fast retransmit can work). 2780 */ 2781 TCP_REASS_LOCK(tp); 2782 if (th->th_seq == tp->rcv_nxt && 2783 TAILQ_FIRST(&tp->segq) == NULL && 2784 tp->t_state == TCPS_ESTABLISHED) { 2785 tcp_setup_ack(tp, th); 2786 tp->rcv_nxt += tlen; 2787 tiflags = th->th_flags & TH_FIN; 2788 tcps = TCP_STAT_GETREF(); 2789 tcps[TCP_STAT_RCVPACK]++; 2790 tcps[TCP_STAT_RCVBYTE] += tlen; 2791 TCP_STAT_PUTREF(); 2792 nd6_hint(tp); 2793 if (so->so_state & SS_CANTRCVMORE) { 2794 m_freem(m); 2795 } else { 2796 m_adj(m, hdroptlen); 2797 sbappendstream(&(so)->so_rcv, m); 2798 } 2799 TCP_REASS_UNLOCK(tp); 2800 sorwakeup(so); 2801 } else { 2802 m_adj(m, hdroptlen); 2803 tiflags = tcp_reass(tp, th, m, tlen); 2804 tp->t_flags |= TF_ACKNOW; 2805 } 2806 2807 /* 2808 * Note the amount of data that peer has sent into 2809 * our window, in order to estimate the sender's 2810 * buffer size. 2811 */ 2812 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt); 2813 } else { 2814 m_freem(m); 2815 m = NULL; 2816 tiflags &= ~TH_FIN; 2817 } 2818 2819 /* 2820 * If FIN is received ACK the FIN and let the user know 2821 * that the connection is closing. Ignore a FIN received before 2822 * the connection is fully established. 2823 */ 2824 if ((tiflags & TH_FIN) && TCPS_HAVEESTABLISHED(tp->t_state)) { 2825 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) { 2826 socantrcvmore(so); 2827 tp->t_flags |= TF_ACKNOW; 2828 tp->rcv_nxt++; 2829 } 2830 switch (tp->t_state) { 2831 2832 /* 2833 * In ESTABLISHED STATE enter the CLOSE_WAIT state. 2834 */ 2835 case TCPS_ESTABLISHED: 2836 tp->t_state = TCPS_CLOSE_WAIT; 2837 break; 2838 2839 /* 2840 * If still in FIN_WAIT_1 STATE FIN has not been acked so 2841 * enter the CLOSING state. 2842 */ 2843 case TCPS_FIN_WAIT_1: 2844 tp->t_state = TCPS_CLOSING; 2845 break; 2846 2847 /* 2848 * In FIN_WAIT_2 state enter the TIME_WAIT state, 2849 * starting the time-wait timer, turning off the other 2850 * standard timers. 2851 */ 2852 case TCPS_FIN_WAIT_2: 2853 tp->t_state = TCPS_TIME_WAIT; 2854 tcp_canceltimers(tp); 2855 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl); 2856 soisdisconnected(so); 2857 break; 2858 2859 /* 2860 * In TIME_WAIT state restart the 2 MSL time_wait timer. 2861 */ 2862 case TCPS_TIME_WAIT: 2863 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl); 2864 break; 2865 } 2866 } 2867 #ifdef TCP_DEBUG 2868 if (so->so_options & SO_DEBUG) 2869 tcp_trace(TA_INPUT, ostate, tp, tcp_saveti, 0); 2870 #endif 2871 2872 /* 2873 * Return any desired output. 2874 */ 2875 if (needoutput || (tp->t_flags & TF_ACKNOW)) { 2876 KERNEL_LOCK(1, NULL); 2877 (void)tcp_output(tp); 2878 KERNEL_UNLOCK_ONE(NULL); 2879 } 2880 if (tcp_saveti) 2881 m_freem(tcp_saveti); 2882 2883 if (tp->t_state == TCPS_TIME_WAIT 2884 && (so->so_state & SS_NOFDREF) 2885 && (tp->t_inpcb || af != AF_INET) 2886 && (tp->t_in6pcb || af != AF_INET6) 2887 && ((af == AF_INET ? tcp4_vtw_enable : tcp6_vtw_enable) & 1) != 0 2888 && TAILQ_EMPTY(&tp->segq) 2889 && vtw_add(af, tp)) { 2890 ; 2891 } 2892 return; 2893 2894 badsyn: 2895 /* 2896 * Received a bad SYN. Increment counters and dropwithreset. 2897 */ 2898 TCP_STATINC(TCP_STAT_BADSYN); 2899 tp = NULL; 2900 goto dropwithreset; 2901 2902 dropafterack: 2903 /* 2904 * Generate an ACK dropping incoming segment if it occupies 2905 * sequence space, where the ACK reflects our state. 2906 */ 2907 if (tiflags & TH_RST) 2908 goto drop; 2909 goto dropafterack2; 2910 2911 dropafterack_ratelim: 2912 /* 2913 * We may want to rate-limit ACKs against SYN/RST attack. 2914 */ 2915 if (ppsratecheck(&tcp_ackdrop_ppslim_last, &tcp_ackdrop_ppslim_count, 2916 tcp_ackdrop_ppslim) == 0) { 2917 /* XXX stat */ 2918 goto drop; 2919 } 2920 2921 dropafterack2: 2922 m_freem(m); 2923 tp->t_flags |= TF_ACKNOW; 2924 KERNEL_LOCK(1, NULL); 2925 (void)tcp_output(tp); 2926 KERNEL_UNLOCK_ONE(NULL); 2927 if (tcp_saveti) 2928 m_freem(tcp_saveti); 2929 return; 2930 2931 dropwithreset_ratelim: 2932 /* 2933 * We may want to rate-limit RSTs in certain situations, 2934 * particularly if we are sending an RST in response to 2935 * an attempt to connect to or otherwise communicate with 2936 * a port for which we have no socket. 2937 */ 2938 if (ppsratecheck(&tcp_rst_ppslim_last, &tcp_rst_ppslim_count, 2939 tcp_rst_ppslim) == 0) { 2940 /* XXX stat */ 2941 goto drop; 2942 } 2943 2944 dropwithreset: 2945 /* 2946 * Generate a RST, dropping incoming segment. 2947 * Make ACK acceptable to originator of segment. 2948 */ 2949 if (tiflags & TH_RST) 2950 goto drop; 2951 if (tiflags & TH_ACK) { 2952 (void)tcp_respond(tp, m, m, th, (tcp_seq)0, th->th_ack, TH_RST); 2953 } else { 2954 if (tiflags & TH_SYN) 2955 tlen++; 2956 (void)tcp_respond(tp, m, m, th, th->th_seq + tlen, (tcp_seq)0, 2957 TH_RST|TH_ACK); 2958 } 2959 if (tcp_saveti) 2960 m_freem(tcp_saveti); 2961 return; 2962 2963 badcsum: 2964 drop: 2965 /* 2966 * Drop space held by incoming segment and return. 2967 */ 2968 if (tp) { 2969 if (tp->t_inpcb) 2970 so = tp->t_inpcb->inp_socket; 2971 #ifdef INET6 2972 else if (tp->t_in6pcb) 2973 so = tp->t_in6pcb->in6p_socket; 2974 #endif 2975 else 2976 so = NULL; 2977 #ifdef TCP_DEBUG 2978 if (so && (so->so_options & SO_DEBUG) != 0) 2979 tcp_trace(TA_DROP, ostate, tp, tcp_saveti, 0); 2980 #endif 2981 } 2982 if (tcp_saveti) 2983 m_freem(tcp_saveti); 2984 m_freem(m); 2985 return; 2986 } 2987 2988 #ifdef TCP_SIGNATURE 2989 int 2990 tcp_signature_apply(void *fstate, void *data, u_int len) 2991 { 2992 2993 MD5Update(fstate, (u_char *)data, len); 2994 return (0); 2995 } 2996 2997 struct secasvar * 2998 tcp_signature_getsav(struct mbuf *m) 2999 { 3000 struct ip *ip; 3001 struct ip6_hdr *ip6; 3002 3003 ip = mtod(m, struct ip *); 3004 switch (ip->ip_v) { 3005 case 4: 3006 ip = mtod(m, struct ip *); 3007 ip6 = NULL; 3008 break; 3009 case 6: 3010 ip = NULL; 3011 ip6 = mtod(m, struct ip6_hdr *); 3012 break; 3013 default: 3014 return (NULL); 3015 } 3016 3017 #ifdef IPSEC 3018 union sockaddr_union dst; 3019 3020 /* Extract the destination from the IP header in the mbuf. */ 3021 memset(&dst, 0, sizeof(union sockaddr_union)); 3022 if (ip != NULL) { 3023 dst.sa.sa_len = sizeof(struct sockaddr_in); 3024 dst.sa.sa_family = AF_INET; 3025 dst.sin.sin_addr = ip->ip_dst; 3026 } else { 3027 dst.sa.sa_len = sizeof(struct sockaddr_in6); 3028 dst.sa.sa_family = AF_INET6; 3029 dst.sin6.sin6_addr = ip6->ip6_dst; 3030 } 3031 3032 /* 3033 * Look up an SADB entry which matches the address of the peer. 3034 */ 3035 return KEY_LOOKUP_SA(&dst, IPPROTO_TCP, htonl(TCP_SIG_SPI), 0, 0); 3036 #else 3037 return NULL; 3038 #endif 3039 } 3040 3041 int 3042 tcp_signature(struct mbuf *m, struct tcphdr *th, int thoff, 3043 struct secasvar *sav, char *sig) 3044 { 3045 MD5_CTX ctx; 3046 struct ip *ip; 3047 struct ipovly *ipovly; 3048 #ifdef INET6 3049 struct ip6_hdr *ip6; 3050 struct ip6_hdr_pseudo ip6pseudo; 3051 #endif 3052 struct ippseudo ippseudo; 3053 struct tcphdr th0; 3054 int l, tcphdrlen; 3055 3056 if (sav == NULL) 3057 return (-1); 3058 3059 tcphdrlen = th->th_off * 4; 3060 3061 switch (mtod(m, struct ip *)->ip_v) { 3062 case 4: 3063 MD5Init(&ctx); 3064 ip = mtod(m, struct ip *); 3065 memset(&ippseudo, 0, sizeof(ippseudo)); 3066 ipovly = (struct ipovly *)ip; 3067 ippseudo.ippseudo_src = ipovly->ih_src; 3068 ippseudo.ippseudo_dst = ipovly->ih_dst; 3069 ippseudo.ippseudo_pad = 0; 3070 ippseudo.ippseudo_p = IPPROTO_TCP; 3071 ippseudo.ippseudo_len = htons(m->m_pkthdr.len - thoff); 3072 MD5Update(&ctx, (char *)&ippseudo, sizeof(ippseudo)); 3073 break; 3074 #if INET6 3075 case 6: 3076 MD5Init(&ctx); 3077 ip6 = mtod(m, struct ip6_hdr *); 3078 memset(&ip6pseudo, 0, sizeof(ip6pseudo)); 3079 ip6pseudo.ip6ph_src = ip6->ip6_src; 3080 in6_clearscope(&ip6pseudo.ip6ph_src); 3081 ip6pseudo.ip6ph_dst = ip6->ip6_dst; 3082 in6_clearscope(&ip6pseudo.ip6ph_dst); 3083 ip6pseudo.ip6ph_len = htons(m->m_pkthdr.len - thoff); 3084 ip6pseudo.ip6ph_nxt = IPPROTO_TCP; 3085 MD5Update(&ctx, (char *)&ip6pseudo, sizeof(ip6pseudo)); 3086 break; 3087 #endif 3088 default: 3089 return (-1); 3090 } 3091 3092 th0 = *th; 3093 th0.th_sum = 0; 3094 MD5Update(&ctx, (char *)&th0, sizeof(th0)); 3095 3096 l = m->m_pkthdr.len - thoff - tcphdrlen; 3097 if (l > 0) 3098 m_apply(m, thoff + tcphdrlen, 3099 m->m_pkthdr.len - thoff - tcphdrlen, 3100 tcp_signature_apply, &ctx); 3101 3102 MD5Update(&ctx, _KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth)); 3103 MD5Final(sig, &ctx); 3104 3105 return (0); 3106 } 3107 #endif 3108 3109 /* 3110 * Parse and process tcp options. 3111 * 3112 * Returns -1 if this segment should be dropped. (eg. wrong signature) 3113 * Otherwise returns 0. 3114 */ 3115 static int 3116 tcp_dooptions(struct tcpcb *tp, const u_char *cp, int cnt, struct tcphdr *th, 3117 struct mbuf *m, int toff, struct tcp_opt_info *oi) 3118 { 3119 u_int16_t mss; 3120 int opt, optlen = 0; 3121 #ifdef TCP_SIGNATURE 3122 void *sigp = NULL; 3123 char sigbuf[TCP_SIGLEN]; 3124 struct secasvar *sav = NULL; 3125 #endif 3126 3127 for (; cp && cnt > 0; cnt -= optlen, cp += optlen) { 3128 opt = cp[0]; 3129 if (opt == TCPOPT_EOL) 3130 break; 3131 if (opt == TCPOPT_NOP) 3132 optlen = 1; 3133 else { 3134 if (cnt < 2) 3135 break; 3136 optlen = cp[1]; 3137 if (optlen < 2 || optlen > cnt) 3138 break; 3139 } 3140 switch (opt) { 3141 3142 default: 3143 continue; 3144 3145 case TCPOPT_MAXSEG: 3146 if (optlen != TCPOLEN_MAXSEG) 3147 continue; 3148 if (!(th->th_flags & TH_SYN)) 3149 continue; 3150 if (TCPS_HAVERCVDSYN(tp->t_state)) 3151 continue; 3152 memcpy(&mss, cp + 2, sizeof(mss)); 3153 oi->maxseg = ntohs(mss); 3154 break; 3155 3156 case TCPOPT_WINDOW: 3157 if (optlen != TCPOLEN_WINDOW) 3158 continue; 3159 if (!(th->th_flags & TH_SYN)) 3160 continue; 3161 if (TCPS_HAVERCVDSYN(tp->t_state)) 3162 continue; 3163 tp->t_flags |= TF_RCVD_SCALE; 3164 tp->requested_s_scale = cp[2]; 3165 if (tp->requested_s_scale > TCP_MAX_WINSHIFT) { 3166 char buf[INET6_ADDRSTRLEN]; 3167 struct ip *ip = mtod(m, struct ip *); 3168 #ifdef INET6 3169 struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *); 3170 #endif 3171 3172 switch (ip->ip_v) { 3173 case 4: 3174 in_print(buf, sizeof(buf), 3175 &ip->ip_src); 3176 break; 3177 #ifdef INET6 3178 case 6: 3179 in6_print(buf, sizeof(buf), 3180 &ip6->ip6_src); 3181 break; 3182 #endif 3183 default: 3184 strlcpy(buf, "(unknown)", sizeof(buf)); 3185 break; 3186 } 3187 3188 log(LOG_ERR, "TCP: invalid wscale %d from %s, " 3189 "assuming %d\n", 3190 tp->requested_s_scale, buf, 3191 TCP_MAX_WINSHIFT); 3192 tp->requested_s_scale = TCP_MAX_WINSHIFT; 3193 } 3194 break; 3195 3196 case TCPOPT_TIMESTAMP: 3197 if (optlen != TCPOLEN_TIMESTAMP) 3198 continue; 3199 oi->ts_present = 1; 3200 memcpy(&oi->ts_val, cp + 2, sizeof(oi->ts_val)); 3201 NTOHL(oi->ts_val); 3202 memcpy(&oi->ts_ecr, cp + 6, sizeof(oi->ts_ecr)); 3203 NTOHL(oi->ts_ecr); 3204 3205 if (!(th->th_flags & TH_SYN)) 3206 continue; 3207 if (TCPS_HAVERCVDSYN(tp->t_state)) 3208 continue; 3209 /* 3210 * A timestamp received in a SYN makes 3211 * it ok to send timestamp requests and replies. 3212 */ 3213 tp->t_flags |= TF_RCVD_TSTMP; 3214 tp->ts_recent = oi->ts_val; 3215 tp->ts_recent_age = tcp_now; 3216 break; 3217 3218 case TCPOPT_SACK_PERMITTED: 3219 if (optlen != TCPOLEN_SACK_PERMITTED) 3220 continue; 3221 if (!(th->th_flags & TH_SYN)) 3222 continue; 3223 if (TCPS_HAVERCVDSYN(tp->t_state)) 3224 continue; 3225 if (tcp_do_sack) { 3226 tp->t_flags |= TF_SACK_PERMIT; 3227 tp->t_flags |= TF_WILL_SACK; 3228 } 3229 break; 3230 3231 case TCPOPT_SACK: 3232 tcp_sack_option(tp, th, cp, optlen); 3233 break; 3234 #ifdef TCP_SIGNATURE 3235 case TCPOPT_SIGNATURE: 3236 if (optlen != TCPOLEN_SIGNATURE) 3237 continue; 3238 if (sigp && 3239 !consttime_memequal(sigp, cp + 2, TCP_SIGLEN)) 3240 return (-1); 3241 3242 sigp = sigbuf; 3243 memcpy(sigbuf, cp + 2, TCP_SIGLEN); 3244 tp->t_flags |= TF_SIGNATURE; 3245 break; 3246 #endif 3247 } 3248 } 3249 3250 #ifndef TCP_SIGNATURE 3251 return 0; 3252 #else 3253 if (tp->t_flags & TF_SIGNATURE) { 3254 sav = tcp_signature_getsav(m); 3255 if (sav == NULL && tp->t_state == TCPS_LISTEN) 3256 return (-1); 3257 } 3258 3259 if ((sigp ? TF_SIGNATURE : 0) ^ (tp->t_flags & TF_SIGNATURE)) 3260 goto out; 3261 3262 if (sigp) { 3263 char sig[TCP_SIGLEN]; 3264 3265 tcp_fields_to_net(th); 3266 if (tcp_signature(m, th, toff, sav, sig) < 0) { 3267 tcp_fields_to_host(th); 3268 goto out; 3269 } 3270 tcp_fields_to_host(th); 3271 3272 if (!consttime_memequal(sig, sigp, TCP_SIGLEN)) { 3273 TCP_STATINC(TCP_STAT_BADSIG); 3274 goto out; 3275 } else 3276 TCP_STATINC(TCP_STAT_GOODSIG); 3277 3278 key_sa_recordxfer(sav, m); 3279 KEY_SA_UNREF(&sav); 3280 } 3281 return 0; 3282 out: 3283 if (sav != NULL) 3284 KEY_SA_UNREF(&sav); 3285 return -1; 3286 #endif 3287 } 3288 3289 /* 3290 * Pull out of band byte out of a segment so 3291 * it doesn't appear in the user's data queue. 3292 * It is still reflected in the segment length for 3293 * sequencing purposes. 3294 */ 3295 void 3296 tcp_pulloutofband(struct socket *so, struct tcphdr *th, 3297 struct mbuf *m, int off) 3298 { 3299 int cnt = off + th->th_urp - 1; 3300 3301 while (cnt >= 0) { 3302 if (m->m_len > cnt) { 3303 char *cp = mtod(m, char *) + cnt; 3304 struct tcpcb *tp = sototcpcb(so); 3305 3306 tp->t_iobc = *cp; 3307 tp->t_oobflags |= TCPOOB_HAVEDATA; 3308 memmove(cp, cp + 1, (unsigned)(m->m_len - cnt - 1)); 3309 m->m_len--; 3310 return; 3311 } 3312 cnt -= m->m_len; 3313 m = m->m_next; 3314 if (m == NULL) 3315 break; 3316 } 3317 panic("tcp_pulloutofband"); 3318 } 3319 3320 /* 3321 * Collect new round-trip time estimate 3322 * and update averages and current timeout. 3323 * 3324 * rtt is in units of slow ticks (typically 500 ms) -- essentially the 3325 * difference of two timestamps. 3326 */ 3327 void 3328 tcp_xmit_timer(struct tcpcb *tp, uint32_t rtt) 3329 { 3330 int32_t delta; 3331 3332 TCP_STATINC(TCP_STAT_RTTUPDATED); 3333 if (tp->t_srtt != 0) { 3334 /* 3335 * Compute the amount to add to srtt for smoothing, 3336 * *alpha, or 2^(-TCP_RTT_SHIFT). Because 3337 * srtt is stored in 1/32 slow ticks, we conceptually 3338 * shift left 5 bits, subtract srtt to get the 3339 * diference, and then shift right by TCP_RTT_SHIFT 3340 * (3) to obtain 1/8 of the difference. 3341 */ 3342 delta = (rtt << 2) - (tp->t_srtt >> TCP_RTT_SHIFT); 3343 /* 3344 * This can never happen, because delta's lowest 3345 * possible value is 1/8 of t_srtt. But if it does, 3346 * set srtt to some reasonable value, here chosen 3347 * as 1/8 tick. 3348 */ 3349 if ((tp->t_srtt += delta) <= 0) 3350 tp->t_srtt = 1 << 2; 3351 /* 3352 * RFC2988 requires that rttvar be updated first. 3353 * This code is compliant because "delta" is the old 3354 * srtt minus the new observation (scaled). 3355 * 3356 * RFC2988 says: 3357 * rttvar = (1-beta) * rttvar + beta * |srtt-observed| 3358 * 3359 * delta is in units of 1/32 ticks, and has then been 3360 * divided by 8. This is equivalent to being in 1/16s 3361 * units and divided by 4. Subtract from it 1/4 of 3362 * the existing rttvar to form the (signed) amount to 3363 * adjust. 3364 */ 3365 if (delta < 0) 3366 delta = -delta; 3367 delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT); 3368 /* 3369 * As with srtt, this should never happen. There is 3370 * no support in RFC2988 for this operation. But 1/4s 3371 * as rttvar when faced with something arguably wrong 3372 * is ok. 3373 */ 3374 if ((tp->t_rttvar += delta) <= 0) 3375 tp->t_rttvar = 1 << 2; 3376 3377 /* 3378 * If srtt exceeds .01 second, ensure we use the 'remote' MSL 3379 * Problem is: it doesn't work. Disabled by defaulting 3380 * tcp_rttlocal to 0; see corresponding code in 3381 * tcp_subr that selects local vs remote in a different way. 3382 * 3383 * The static branch prediction hint here should be removed 3384 * when the rtt estimator is fixed and the rtt_enable code 3385 * is turned back on. 3386 */ 3387 if (__predict_false(tcp_rttlocal) && tcp_msl_enable 3388 && tp->t_srtt > tcp_msl_remote_threshold 3389 && tp->t_msl < tcp_msl_remote) { 3390 tp->t_msl = MIN(tcp_msl_remote, TCP_MAXMSL); 3391 } 3392 } else { 3393 /* 3394 * This is the first measurement. Per RFC2988, 2.2, 3395 * set rtt=R and srtt=R/2. 3396 * For srtt, storage representation is 1/32 ticks, 3397 * so shift left by 5. 3398 * For rttvar, storage representation is 1/16 ticks, 3399 * So shift left by 4, but then right by 1 to halve. 3400 */ 3401 tp->t_srtt = rtt << (TCP_RTT_SHIFT + 2); 3402 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT + 2 - 1); 3403 } 3404 tp->t_rtttime = 0; 3405 tp->t_rxtshift = 0; 3406 3407 /* 3408 * the retransmit should happen at rtt + 4 * rttvar. 3409 * Because of the way we do the smoothing, srtt and rttvar 3410 * will each average +1/2 tick of bias. When we compute 3411 * the retransmit timer, we want 1/2 tick of rounding and 3412 * 1 extra tick because of +-1/2 tick uncertainty in the 3413 * firing of the timer. The bias will give us exactly the 3414 * 1.5 tick we need. But, because the bias is 3415 * statistical, we have to test that we don't drop below 3416 * the minimum feasible timer (which is 2 ticks). 3417 */ 3418 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp), 3419 uimax(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX); 3420 3421 /* 3422 * We received an ack for a packet that wasn't retransmitted; 3423 * it is probably safe to discard any error indications we've 3424 * received recently. This isn't quite right, but close enough 3425 * for now (a route might have failed after we sent a segment, 3426 * and the return path might not be symmetrical). 3427 */ 3428 tp->t_softerror = 0; 3429 } 3430 3431 3432 /* 3433 * TCP compressed state engine. Currently used to hold compressed 3434 * state for SYN_RECEIVED. 3435 */ 3436 3437 u_long syn_cache_count; 3438 u_int32_t syn_hash1, syn_hash2; 3439 3440 #define SYN_HASH(sa, sp, dp) \ 3441 ((((sa)->s_addr^syn_hash1)*(((((u_int32_t)(dp))<<16) + \ 3442 ((u_int32_t)(sp)))^syn_hash2))) 3443 #ifndef INET6 3444 #define SYN_HASHALL(hash, src, dst) \ 3445 do { \ 3446 hash = SYN_HASH(&((const struct sockaddr_in *)(src))->sin_addr, \ 3447 ((const struct sockaddr_in *)(src))->sin_port, \ 3448 ((const struct sockaddr_in *)(dst))->sin_port); \ 3449 } while (/*CONSTCOND*/ 0) 3450 #else 3451 #define SYN_HASH6(sa, sp, dp) \ 3452 ((((sa)->s6_addr32[0] ^ (sa)->s6_addr32[3] ^ syn_hash1) * \ 3453 (((((u_int32_t)(dp))<<16) + ((u_int32_t)(sp)))^syn_hash2)) \ 3454 & 0x7fffffff) 3455 3456 #define SYN_HASHALL(hash, src, dst) \ 3457 do { \ 3458 switch ((src)->sa_family) { \ 3459 case AF_INET: \ 3460 hash = SYN_HASH(&((const struct sockaddr_in *)(src))->sin_addr, \ 3461 ((const struct sockaddr_in *)(src))->sin_port, \ 3462 ((const struct sockaddr_in *)(dst))->sin_port); \ 3463 break; \ 3464 case AF_INET6: \ 3465 hash = SYN_HASH6(&((const struct sockaddr_in6 *)(src))->sin6_addr, \ 3466 ((const struct sockaddr_in6 *)(src))->sin6_port, \ 3467 ((const struct sockaddr_in6 *)(dst))->sin6_port); \ 3468 break; \ 3469 default: \ 3470 hash = 0; \ 3471 } \ 3472 } while (/*CONSTCOND*/0) 3473 #endif /* INET6 */ 3474 3475 static struct pool syn_cache_pool; 3476 3477 /* 3478 * We don't estimate RTT with SYNs, so each packet starts with the default 3479 * RTT and each timer step has a fixed timeout value. 3480 */ 3481 static inline void 3482 syn_cache_timer_arm(struct syn_cache *sc) 3483 { 3484 3485 TCPT_RANGESET(sc->sc_rxtcur, 3486 TCPTV_SRTTDFLT * tcp_backoff[sc->sc_rxtshift], TCPTV_MIN, 3487 TCPTV_REXMTMAX); 3488 callout_reset(&sc->sc_timer, 3489 sc->sc_rxtcur * (hz / PR_SLOWHZ), syn_cache_timer, sc); 3490 } 3491 3492 #define SYN_CACHE_TIMESTAMP(sc) (tcp_now - (sc)->sc_timebase) 3493 3494 static inline void 3495 syn_cache_rm(struct syn_cache *sc) 3496 { 3497 TAILQ_REMOVE(&tcp_syn_cache[sc->sc_bucketidx].sch_bucket, 3498 sc, sc_bucketq); 3499 sc->sc_tp = NULL; 3500 LIST_REMOVE(sc, sc_tpq); 3501 tcp_syn_cache[sc->sc_bucketidx].sch_length--; 3502 callout_stop(&sc->sc_timer); 3503 syn_cache_count--; 3504 } 3505 3506 static inline void 3507 syn_cache_put(struct syn_cache *sc) 3508 { 3509 if (sc->sc_ipopts) 3510 (void) m_free(sc->sc_ipopts); 3511 rtcache_free(&sc->sc_route); 3512 sc->sc_flags |= SCF_DEAD; 3513 if (!callout_invoking(&sc->sc_timer)) 3514 callout_schedule(&(sc)->sc_timer, 1); 3515 } 3516 3517 void 3518 syn_cache_init(void) 3519 { 3520 int i; 3521 3522 pool_init(&syn_cache_pool, sizeof(struct syn_cache), 0, 0, 0, 3523 "synpl", NULL, IPL_SOFTNET); 3524 3525 /* Initialize the hash buckets. */ 3526 for (i = 0; i < tcp_syn_cache_size; i++) 3527 TAILQ_INIT(&tcp_syn_cache[i].sch_bucket); 3528 } 3529 3530 void 3531 syn_cache_insert(struct syn_cache *sc, struct tcpcb *tp) 3532 { 3533 struct syn_cache_head *scp; 3534 struct syn_cache *sc2; 3535 int s; 3536 3537 /* 3538 * If there are no entries in the hash table, reinitialize 3539 * the hash secrets. 3540 */ 3541 if (syn_cache_count == 0) { 3542 syn_hash1 = cprng_fast32(); 3543 syn_hash2 = cprng_fast32(); 3544 } 3545 3546 SYN_HASHALL(sc->sc_hash, &sc->sc_src.sa, &sc->sc_dst.sa); 3547 sc->sc_bucketidx = sc->sc_hash % tcp_syn_cache_size; 3548 scp = &tcp_syn_cache[sc->sc_bucketidx]; 3549 3550 /* 3551 * Make sure that we don't overflow the per-bucket 3552 * limit or the total cache size limit. 3553 */ 3554 s = splsoftnet(); 3555 if (scp->sch_length >= tcp_syn_bucket_limit) { 3556 TCP_STATINC(TCP_STAT_SC_BUCKETOVERFLOW); 3557 /* 3558 * The bucket is full. Toss the oldest element in the 3559 * bucket. This will be the first entry in the bucket. 3560 */ 3561 sc2 = TAILQ_FIRST(&scp->sch_bucket); 3562 #ifdef DIAGNOSTIC 3563 /* 3564 * This should never happen; we should always find an 3565 * entry in our bucket. 3566 */ 3567 if (sc2 == NULL) 3568 panic("syn_cache_insert: bucketoverflow: impossible"); 3569 #endif 3570 syn_cache_rm(sc2); 3571 syn_cache_put(sc2); /* calls pool_put but see spl above */ 3572 } else if (syn_cache_count >= tcp_syn_cache_limit) { 3573 struct syn_cache_head *scp2, *sce; 3574 3575 TCP_STATINC(TCP_STAT_SC_OVERFLOWED); 3576 /* 3577 * The cache is full. Toss the oldest entry in the 3578 * first non-empty bucket we can find. 3579 * 3580 * XXX We would really like to toss the oldest 3581 * entry in the cache, but we hope that this 3582 * condition doesn't happen very often. 3583 */ 3584 scp2 = scp; 3585 if (TAILQ_EMPTY(&scp2->sch_bucket)) { 3586 sce = &tcp_syn_cache[tcp_syn_cache_size]; 3587 for (++scp2; scp2 != scp; scp2++) { 3588 if (scp2 >= sce) 3589 scp2 = &tcp_syn_cache[0]; 3590 if (! TAILQ_EMPTY(&scp2->sch_bucket)) 3591 break; 3592 } 3593 #ifdef DIAGNOSTIC 3594 /* 3595 * This should never happen; we should always find a 3596 * non-empty bucket. 3597 */ 3598 if (scp2 == scp) 3599 panic("syn_cache_insert: cacheoverflow: " 3600 "impossible"); 3601 #endif 3602 } 3603 sc2 = TAILQ_FIRST(&scp2->sch_bucket); 3604 syn_cache_rm(sc2); 3605 syn_cache_put(sc2); /* calls pool_put but see spl above */ 3606 } 3607 3608 /* 3609 * Initialize the entry's timer. 3610 */ 3611 sc->sc_rxttot = 0; 3612 sc->sc_rxtshift = 0; 3613 syn_cache_timer_arm(sc); 3614 3615 /* Link it from tcpcb entry */ 3616 LIST_INSERT_HEAD(&tp->t_sc, sc, sc_tpq); 3617 3618 /* Put it into the bucket. */ 3619 TAILQ_INSERT_TAIL(&scp->sch_bucket, sc, sc_bucketq); 3620 scp->sch_length++; 3621 syn_cache_count++; 3622 3623 TCP_STATINC(TCP_STAT_SC_ADDED); 3624 splx(s); 3625 } 3626 3627 /* 3628 * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted. 3629 * If we have retransmitted an entry the maximum number of times, expire 3630 * that entry. 3631 */ 3632 static void 3633 syn_cache_timer(void *arg) 3634 { 3635 struct syn_cache *sc = arg; 3636 3637 mutex_enter(softnet_lock); 3638 KERNEL_LOCK(1, NULL); 3639 3640 callout_ack(&sc->sc_timer); 3641 3642 if (__predict_false(sc->sc_flags & SCF_DEAD)) { 3643 TCP_STATINC(TCP_STAT_SC_DELAYED_FREE); 3644 goto free; 3645 } 3646 3647 if (__predict_false(sc->sc_rxtshift == TCP_MAXRXTSHIFT)) { 3648 /* Drop it -- too many retransmissions. */ 3649 goto dropit; 3650 } 3651 3652 /* 3653 * Compute the total amount of time this entry has 3654 * been on a queue. If this entry has been on longer 3655 * than the keep alive timer would allow, expire it. 3656 */ 3657 sc->sc_rxttot += sc->sc_rxtcur; 3658 if (sc->sc_rxttot >= MIN(tcp_keepinit, TCP_TIMER_MAXTICKS)) 3659 goto dropit; 3660 3661 TCP_STATINC(TCP_STAT_SC_RETRANSMITTED); 3662 (void)syn_cache_respond(sc); 3663 3664 /* Advance the timer back-off. */ 3665 sc->sc_rxtshift++; 3666 syn_cache_timer_arm(sc); 3667 3668 goto out; 3669 3670 dropit: 3671 TCP_STATINC(TCP_STAT_SC_TIMED_OUT); 3672 syn_cache_rm(sc); 3673 if (sc->sc_ipopts) 3674 (void) m_free(sc->sc_ipopts); 3675 rtcache_free(&sc->sc_route); 3676 3677 free: 3678 callout_destroy(&sc->sc_timer); 3679 pool_put(&syn_cache_pool, sc); 3680 3681 out: 3682 KERNEL_UNLOCK_ONE(NULL); 3683 mutex_exit(softnet_lock); 3684 } 3685 3686 /* 3687 * Remove syn cache created by the specified tcb entry, 3688 * because this does not make sense to keep them 3689 * (if there's no tcb entry, syn cache entry will never be used) 3690 */ 3691 void 3692 syn_cache_cleanup(struct tcpcb *tp) 3693 { 3694 struct syn_cache *sc, *nsc; 3695 int s; 3696 3697 s = splsoftnet(); 3698 3699 for (sc = LIST_FIRST(&tp->t_sc); sc != NULL; sc = nsc) { 3700 nsc = LIST_NEXT(sc, sc_tpq); 3701 3702 #ifdef DIAGNOSTIC 3703 if (sc->sc_tp != tp) 3704 panic("invalid sc_tp in syn_cache_cleanup"); 3705 #endif 3706 syn_cache_rm(sc); 3707 syn_cache_put(sc); /* calls pool_put but see spl above */ 3708 } 3709 /* just for safety */ 3710 LIST_INIT(&tp->t_sc); 3711 3712 splx(s); 3713 } 3714 3715 /* 3716 * Find an entry in the syn cache. 3717 */ 3718 struct syn_cache * 3719 syn_cache_lookup(const struct sockaddr *src, const struct sockaddr *dst, 3720 struct syn_cache_head **headp) 3721 { 3722 struct syn_cache *sc; 3723 struct syn_cache_head *scp; 3724 u_int32_t hash; 3725 int s; 3726 3727 SYN_HASHALL(hash, src, dst); 3728 3729 scp = &tcp_syn_cache[hash % tcp_syn_cache_size]; 3730 *headp = scp; 3731 s = splsoftnet(); 3732 for (sc = TAILQ_FIRST(&scp->sch_bucket); sc != NULL; 3733 sc = TAILQ_NEXT(sc, sc_bucketq)) { 3734 if (sc->sc_hash != hash) 3735 continue; 3736 if (!memcmp(&sc->sc_src, src, src->sa_len) && 3737 !memcmp(&sc->sc_dst, dst, dst->sa_len)) { 3738 splx(s); 3739 return (sc); 3740 } 3741 } 3742 splx(s); 3743 return (NULL); 3744 } 3745 3746 /* 3747 * This function gets called when we receive an ACK for a socket in the 3748 * LISTEN state. We look up the connection in the syn cache, and if it's 3749 * there, we pull it out of the cache and turn it into a full-blown 3750 * connection in the SYN-RECEIVED state. 3751 * 3752 * The return values may not be immediately obvious, and their effects 3753 * can be subtle, so here they are: 3754 * 3755 * NULL SYN was not found in cache; caller should drop the 3756 * packet and send an RST. 3757 * 3758 * -1 We were unable to create the new connection, and are 3759 * aborting it. An ACK,RST is being sent to the peer 3760 * (unless we got screwey sequence numbers; see below), 3761 * because the 3-way handshake has been completed. Caller 3762 * should not free the mbuf, since we may be using it. If 3763 * we are not, we will free it. 3764 * 3765 * Otherwise, the return value is a pointer to the new socket 3766 * associated with the connection. 3767 */ 3768 struct socket * 3769 syn_cache_get(struct sockaddr *src, struct sockaddr *dst, 3770 struct tcphdr *th, struct socket *so, struct mbuf *m) 3771 { 3772 struct syn_cache *sc; 3773 struct syn_cache_head *scp; 3774 struct inpcb *inp = NULL; 3775 #ifdef INET6 3776 struct in6pcb *in6p = NULL; 3777 #endif 3778 struct tcpcb *tp; 3779 int s; 3780 struct socket *oso; 3781 3782 s = splsoftnet(); 3783 if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) { 3784 splx(s); 3785 return NULL; 3786 } 3787 3788 /* 3789 * Verify the sequence and ack numbers. Try getting the correct 3790 * response again. 3791 */ 3792 if ((th->th_ack != sc->sc_iss + 1) || 3793 SEQ_LEQ(th->th_seq, sc->sc_irs) || 3794 SEQ_GT(th->th_seq, sc->sc_irs + 1 + sc->sc_win)) { 3795 m_freem(m); 3796 (void)syn_cache_respond(sc); 3797 splx(s); 3798 return ((struct socket *)(-1)); 3799 } 3800 3801 /* Remove this cache entry */ 3802 syn_cache_rm(sc); 3803 splx(s); 3804 3805 /* 3806 * Ok, create the full blown connection, and set things up 3807 * as they would have been set up if we had created the 3808 * connection when the SYN arrived. If we can't create 3809 * the connection, abort it. 3810 */ 3811 /* 3812 * inp still has the OLD in_pcb stuff, set the 3813 * v6-related flags on the new guy, too. This is 3814 * done particularly for the case where an AF_INET6 3815 * socket is bound only to a port, and a v4 connection 3816 * comes in on that port. 3817 * we also copy the flowinfo from the original pcb 3818 * to the new one. 3819 */ 3820 oso = so; 3821 so = sonewconn(so, true); 3822 if (so == NULL) 3823 goto resetandabort; 3824 3825 switch (so->so_proto->pr_domain->dom_family) { 3826 case AF_INET: 3827 inp = sotoinpcb(so); 3828 break; 3829 #ifdef INET6 3830 case AF_INET6: 3831 in6p = sotoin6pcb(so); 3832 break; 3833 #endif 3834 } 3835 3836 switch (src->sa_family) { 3837 case AF_INET: 3838 if (inp) { 3839 inp->inp_laddr = ((struct sockaddr_in *)dst)->sin_addr; 3840 inp->inp_lport = ((struct sockaddr_in *)dst)->sin_port; 3841 inp->inp_options = ip_srcroute(m); 3842 in_pcbstate(inp, INP_BOUND); 3843 if (inp->inp_options == NULL) { 3844 inp->inp_options = sc->sc_ipopts; 3845 sc->sc_ipopts = NULL; 3846 } 3847 } 3848 #ifdef INET6 3849 else if (in6p) { 3850 /* IPv4 packet to AF_INET6 socket */ 3851 memset(&in6p->in6p_laddr, 0, sizeof(in6p->in6p_laddr)); 3852 in6p->in6p_laddr.s6_addr16[5] = htons(0xffff); 3853 bcopy(&((struct sockaddr_in *)dst)->sin_addr, 3854 &in6p->in6p_laddr.s6_addr32[3], 3855 sizeof(((struct sockaddr_in *)dst)->sin_addr)); 3856 in6p->in6p_lport = ((struct sockaddr_in *)dst)->sin_port; 3857 in6totcpcb(in6p)->t_family = AF_INET; 3858 if (sotoin6pcb(oso)->in6p_flags & IN6P_IPV6_V6ONLY) 3859 in6p->in6p_flags |= IN6P_IPV6_V6ONLY; 3860 else 3861 in6p->in6p_flags &= ~IN6P_IPV6_V6ONLY; 3862 in6_pcbstate(in6p, IN6P_BOUND); 3863 } 3864 #endif 3865 break; 3866 #ifdef INET6 3867 case AF_INET6: 3868 if (in6p) { 3869 in6p->in6p_laddr = ((struct sockaddr_in6 *)dst)->sin6_addr; 3870 in6p->in6p_lport = ((struct sockaddr_in6 *)dst)->sin6_port; 3871 in6_pcbstate(in6p, IN6P_BOUND); 3872 } 3873 break; 3874 #endif 3875 } 3876 3877 #ifdef INET6 3878 if (in6p && in6totcpcb(in6p)->t_family == AF_INET6 && sotoinpcb(oso)) { 3879 struct in6pcb *oin6p = sotoin6pcb(oso); 3880 /* inherit socket options from the listening socket */ 3881 in6p->in6p_flags |= (oin6p->in6p_flags & IN6P_CONTROLOPTS); 3882 if (in6p->in6p_flags & IN6P_CONTROLOPTS) { 3883 m_freem(in6p->in6p_options); 3884 in6p->in6p_options = NULL; 3885 } 3886 ip6_savecontrol(in6p, &in6p->in6p_options, 3887 mtod(m, struct ip6_hdr *), m); 3888 } 3889 #endif 3890 3891 /* 3892 * Give the new socket our cached route reference. 3893 */ 3894 if (inp) { 3895 rtcache_copy(&inp->inp_route, &sc->sc_route); 3896 rtcache_free(&sc->sc_route); 3897 } 3898 #ifdef INET6 3899 else { 3900 rtcache_copy(&in6p->in6p_route, &sc->sc_route); 3901 rtcache_free(&sc->sc_route); 3902 } 3903 #endif 3904 3905 if (inp) { 3906 struct sockaddr_in sin; 3907 memcpy(&sin, src, src->sa_len); 3908 if (in_pcbconnect(inp, &sin, &lwp0)) { 3909 goto resetandabort; 3910 } 3911 } 3912 #ifdef INET6 3913 else if (in6p) { 3914 struct sockaddr_in6 sin6; 3915 memcpy(&sin6, src, src->sa_len); 3916 if (src->sa_family == AF_INET) { 3917 /* IPv4 packet to AF_INET6 socket */ 3918 in6_sin_2_v4mapsin6((struct sockaddr_in *)src, &sin6); 3919 } 3920 if (in6_pcbconnect(in6p, &sin6, NULL)) { 3921 goto resetandabort; 3922 } 3923 } 3924 #endif 3925 else { 3926 goto resetandabort; 3927 } 3928 3929 if (inp) 3930 tp = intotcpcb(inp); 3931 #ifdef INET6 3932 else if (in6p) 3933 tp = in6totcpcb(in6p); 3934 #endif 3935 else 3936 tp = NULL; 3937 3938 tp->t_flags = sototcpcb(oso)->t_flags & TF_NODELAY; 3939 if (sc->sc_request_r_scale != 15) { 3940 tp->requested_s_scale = sc->sc_requested_s_scale; 3941 tp->request_r_scale = sc->sc_request_r_scale; 3942 tp->snd_scale = sc->sc_requested_s_scale; 3943 tp->rcv_scale = sc->sc_request_r_scale; 3944 tp->t_flags |= TF_REQ_SCALE|TF_RCVD_SCALE; 3945 } 3946 if (sc->sc_flags & SCF_TIMESTAMP) 3947 tp->t_flags |= TF_REQ_TSTMP|TF_RCVD_TSTMP; 3948 tp->ts_timebase = sc->sc_timebase; 3949 3950 tp->t_template = tcp_template(tp); 3951 if (tp->t_template == 0) { 3952 tp = tcp_drop(tp, ENOBUFS); /* destroys socket */ 3953 so = NULL; 3954 m_freem(m); 3955 goto abort; 3956 } 3957 3958 tp->iss = sc->sc_iss; 3959 tp->irs = sc->sc_irs; 3960 tcp_sendseqinit(tp); 3961 tcp_rcvseqinit(tp); 3962 tp->t_state = TCPS_SYN_RECEIVED; 3963 TCP_TIMER_ARM(tp, TCPT_KEEP, tp->t_keepinit); 3964 TCP_STATINC(TCP_STAT_ACCEPTS); 3965 3966 if ((sc->sc_flags & SCF_SACK_PERMIT) && tcp_do_sack) 3967 tp->t_flags |= TF_WILL_SACK; 3968 3969 if ((sc->sc_flags & SCF_ECN_PERMIT) && tcp_do_ecn) 3970 tp->t_flags |= TF_ECN_PERMIT; 3971 3972 #ifdef TCP_SIGNATURE 3973 if (sc->sc_flags & SCF_SIGNATURE) 3974 tp->t_flags |= TF_SIGNATURE; 3975 #endif 3976 3977 /* Initialize tp->t_ourmss before we deal with the peer's! */ 3978 tp->t_ourmss = sc->sc_ourmaxseg; 3979 tcp_mss_from_peer(tp, sc->sc_peermaxseg); 3980 3981 /* 3982 * Initialize the initial congestion window. If we 3983 * had to retransmit the SYN,ACK, we must initialize cwnd 3984 * to 1 segment (i.e. the Loss Window). 3985 */ 3986 if (sc->sc_rxtshift) 3987 tp->snd_cwnd = tp->t_peermss; 3988 else { 3989 int ss = tcp_init_win; 3990 if (inp != NULL && in_localaddr(inp->inp_faddr)) 3991 ss = tcp_init_win_local; 3992 #ifdef INET6 3993 if (in6p != NULL && in6_localaddr(&in6p->in6p_faddr)) 3994 ss = tcp_init_win_local; 3995 #endif 3996 tp->snd_cwnd = TCP_INITIAL_WINDOW(ss, tp->t_peermss); 3997 } 3998 3999 tcp_rmx_rtt(tp); 4000 tp->snd_wl1 = sc->sc_irs; 4001 tp->rcv_up = sc->sc_irs + 1; 4002 4003 /* 4004 * This is what whould have happened in tcp_output() when 4005 * the SYN,ACK was sent. 4006 */ 4007 tp->snd_up = tp->snd_una; 4008 tp->snd_max = tp->snd_nxt = tp->iss+1; 4009 TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur); 4010 if (sc->sc_win > 0 && SEQ_GT(tp->rcv_nxt + sc->sc_win, tp->rcv_adv)) 4011 tp->rcv_adv = tp->rcv_nxt + sc->sc_win; 4012 tp->last_ack_sent = tp->rcv_nxt; 4013 tp->t_partialacks = -1; 4014 tp->t_dupacks = 0; 4015 4016 TCP_STATINC(TCP_STAT_SC_COMPLETED); 4017 s = splsoftnet(); 4018 syn_cache_put(sc); 4019 splx(s); 4020 return so; 4021 4022 resetandabort: 4023 (void)tcp_respond(NULL, m, m, th, (tcp_seq)0, th->th_ack, TH_RST); 4024 abort: 4025 if (so != NULL) { 4026 (void) soqremque(so, 1); 4027 (void) soabort(so); 4028 mutex_enter(softnet_lock); 4029 } 4030 s = splsoftnet(); 4031 syn_cache_put(sc); 4032 splx(s); 4033 TCP_STATINC(TCP_STAT_SC_ABORTED); 4034 return ((struct socket *)(-1)); 4035 } 4036 4037 /* 4038 * This function is called when we get a RST for a 4039 * non-existent connection, so that we can see if the 4040 * connection is in the syn cache. If it is, zap it. 4041 */ 4042 4043 void 4044 syn_cache_reset(struct sockaddr *src, struct sockaddr *dst, struct tcphdr *th) 4045 { 4046 struct syn_cache *sc; 4047 struct syn_cache_head *scp; 4048 int s = splsoftnet(); 4049 4050 if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) { 4051 splx(s); 4052 return; 4053 } 4054 if (SEQ_LT(th->th_seq, sc->sc_irs) || 4055 SEQ_GT(th->th_seq, sc->sc_irs+1)) { 4056 splx(s); 4057 return; 4058 } 4059 syn_cache_rm(sc); 4060 TCP_STATINC(TCP_STAT_SC_RESET); 4061 syn_cache_put(sc); /* calls pool_put but see spl above */ 4062 splx(s); 4063 } 4064 4065 void 4066 syn_cache_unreach(const struct sockaddr *src, const struct sockaddr *dst, 4067 struct tcphdr *th) 4068 { 4069 struct syn_cache *sc; 4070 struct syn_cache_head *scp; 4071 int s; 4072 4073 s = splsoftnet(); 4074 if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) { 4075 splx(s); 4076 return; 4077 } 4078 /* If the sequence number != sc_iss, then it's a bogus ICMP msg */ 4079 if (ntohl(th->th_seq) != sc->sc_iss) { 4080 splx(s); 4081 return; 4082 } 4083 4084 /* 4085 * If we've retransmitted 3 times and this is our second error, 4086 * we remove the entry. Otherwise, we allow it to continue on. 4087 * This prevents us from incorrectly nuking an entry during a 4088 * spurious network outage. 4089 * 4090 * See tcp_notify(). 4091 */ 4092 if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxtshift < 3) { 4093 sc->sc_flags |= SCF_UNREACH; 4094 splx(s); 4095 return; 4096 } 4097 4098 syn_cache_rm(sc); 4099 TCP_STATINC(TCP_STAT_SC_UNREACH); 4100 syn_cache_put(sc); /* calls pool_put but see spl above */ 4101 splx(s); 4102 } 4103 4104 /* 4105 * Given a LISTEN socket and an inbound SYN request, add this to the syn 4106 * cache, and send back a segment: 4107 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK> 4108 * to the source. 4109 * 4110 * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN. 4111 * Doing so would require that we hold onto the data and deliver it 4112 * to the application. However, if we are the target of a SYN-flood 4113 * DoS attack, an attacker could send data which would eventually 4114 * consume all available buffer space if it were ACKed. By not ACKing 4115 * the data, we avoid this DoS scenario. 4116 */ 4117 int 4118 syn_cache_add(struct sockaddr *src, struct sockaddr *dst, struct tcphdr *th, 4119 unsigned int toff, struct socket *so, struct mbuf *m, u_char *optp, 4120 int optlen, struct tcp_opt_info *oi) 4121 { 4122 struct tcpcb tb, *tp; 4123 long win; 4124 struct syn_cache *sc; 4125 struct syn_cache_head *scp; 4126 struct mbuf *ipopts; 4127 int s; 4128 4129 tp = sototcpcb(so); 4130 4131 /* 4132 * Initialize some local state. 4133 */ 4134 win = sbspace(&so->so_rcv); 4135 if (win > TCP_MAXWIN) 4136 win = TCP_MAXWIN; 4137 4138 #ifdef TCP_SIGNATURE 4139 if (optp || (tp->t_flags & TF_SIGNATURE)) 4140 #else 4141 if (optp) 4142 #endif 4143 { 4144 tb.t_flags = tcp_do_rfc1323 ? (TF_REQ_SCALE|TF_REQ_TSTMP) : 0; 4145 #ifdef TCP_SIGNATURE 4146 tb.t_flags |= (tp->t_flags & TF_SIGNATURE); 4147 #endif 4148 tb.t_state = TCPS_LISTEN; 4149 if (tcp_dooptions(&tb, optp, optlen, th, m, toff, oi) < 0) 4150 return 0; 4151 } else 4152 tb.t_flags = 0; 4153 4154 switch (src->sa_family) { 4155 case AF_INET: 4156 /* Remember the IP options, if any. */ 4157 ipopts = ip_srcroute(m); 4158 break; 4159 default: 4160 ipopts = NULL; 4161 } 4162 4163 /* 4164 * See if we already have an entry for this connection. 4165 * If we do, resend the SYN,ACK. We do not count this 4166 * as a retransmission (XXX though maybe we should). 4167 */ 4168 if ((sc = syn_cache_lookup(src, dst, &scp)) != NULL) { 4169 TCP_STATINC(TCP_STAT_SC_DUPESYN); 4170 if (ipopts) { 4171 /* 4172 * If we were remembering a previous source route, 4173 * forget it and use the new one we've been given. 4174 */ 4175 if (sc->sc_ipopts) 4176 (void)m_free(sc->sc_ipopts); 4177 sc->sc_ipopts = ipopts; 4178 } 4179 sc->sc_timestamp = tb.ts_recent; 4180 m_freem(m); 4181 if (syn_cache_respond(sc) == 0) { 4182 uint64_t *tcps = TCP_STAT_GETREF(); 4183 tcps[TCP_STAT_SNDACKS]++; 4184 tcps[TCP_STAT_SNDTOTAL]++; 4185 TCP_STAT_PUTREF(); 4186 } 4187 return 1; 4188 } 4189 4190 s = splsoftnet(); 4191 sc = pool_get(&syn_cache_pool, PR_NOWAIT); 4192 splx(s); 4193 if (sc == NULL) { 4194 if (ipopts) 4195 (void)m_free(ipopts); 4196 return 0; 4197 } 4198 4199 /* 4200 * Fill in the cache, and put the necessary IP and TCP 4201 * options into the reply. 4202 */ 4203 memset(sc, 0, sizeof(struct syn_cache)); 4204 callout_init(&sc->sc_timer, CALLOUT_MPSAFE); 4205 memcpy(&sc->sc_src, src, src->sa_len); 4206 memcpy(&sc->sc_dst, dst, dst->sa_len); 4207 sc->sc_flags = 0; 4208 sc->sc_ipopts = ipopts; 4209 sc->sc_irs = th->th_seq; 4210 switch (src->sa_family) { 4211 case AF_INET: 4212 { 4213 struct sockaddr_in *srcin = (void *)src; 4214 struct sockaddr_in *dstin = (void *)dst; 4215 4216 sc->sc_iss = tcp_new_iss1(&dstin->sin_addr, 4217 &srcin->sin_addr, dstin->sin_port, 4218 srcin->sin_port, sizeof(dstin->sin_addr), 0); 4219 break; 4220 } 4221 #ifdef INET6 4222 case AF_INET6: 4223 { 4224 struct sockaddr_in6 *srcin6 = (void *)src; 4225 struct sockaddr_in6 *dstin6 = (void *)dst; 4226 4227 sc->sc_iss = tcp_new_iss1(&dstin6->sin6_addr, 4228 &srcin6->sin6_addr, dstin6->sin6_port, 4229 srcin6->sin6_port, sizeof(dstin6->sin6_addr), 0); 4230 break; 4231 } 4232 #endif 4233 } 4234 sc->sc_peermaxseg = oi->maxseg; 4235 sc->sc_ourmaxseg = tcp_mss_to_advertise(m->m_flags & M_PKTHDR ? 4236 m_get_rcvif_NOMPSAFE(m) : NULL, sc->sc_src.sa.sa_family); 4237 sc->sc_win = win; 4238 sc->sc_timebase = tcp_now - 1; /* see tcp_newtcpcb() */ 4239 sc->sc_timestamp = tb.ts_recent; 4240 if ((tb.t_flags & (TF_REQ_TSTMP|TF_RCVD_TSTMP)) == 4241 (TF_REQ_TSTMP|TF_RCVD_TSTMP)) 4242 sc->sc_flags |= SCF_TIMESTAMP; 4243 if ((tb.t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) == 4244 (TF_RCVD_SCALE|TF_REQ_SCALE)) { 4245 sc->sc_requested_s_scale = tb.requested_s_scale; 4246 sc->sc_request_r_scale = 0; 4247 /* 4248 * Pick the smallest possible scaling factor that 4249 * will still allow us to scale up to sb_max. 4250 * 4251 * We do this because there are broken firewalls that 4252 * will corrupt the window scale option, leading to 4253 * the other endpoint believing that our advertised 4254 * window is unscaled. At scale factors larger than 4255 * 5 the unscaled window will drop below 1500 bytes, 4256 * leading to serious problems when traversing these 4257 * broken firewalls. 4258 * 4259 * With the default sbmax of 256K, a scale factor 4260 * of 3 will be chosen by this algorithm. Those who 4261 * choose a larger sbmax should watch out 4262 * for the compatiblity problems mentioned above. 4263 * 4264 * RFC1323: The Window field in a SYN (i.e., a <SYN> 4265 * or <SYN,ACK>) segment itself is never scaled. 4266 */ 4267 while (sc->sc_request_r_scale < TCP_MAX_WINSHIFT && 4268 (TCP_MAXWIN << sc->sc_request_r_scale) < sb_max) 4269 sc->sc_request_r_scale++; 4270 } else { 4271 sc->sc_requested_s_scale = 15; 4272 sc->sc_request_r_scale = 15; 4273 } 4274 if ((tb.t_flags & TF_SACK_PERMIT) && tcp_do_sack) 4275 sc->sc_flags |= SCF_SACK_PERMIT; 4276 4277 /* 4278 * ECN setup packet received. 4279 */ 4280 if ((th->th_flags & (TH_ECE|TH_CWR)) && tcp_do_ecn) 4281 sc->sc_flags |= SCF_ECN_PERMIT; 4282 4283 #ifdef TCP_SIGNATURE 4284 if (tb.t_flags & TF_SIGNATURE) 4285 sc->sc_flags |= SCF_SIGNATURE; 4286 #endif 4287 sc->sc_tp = tp; 4288 m_freem(m); 4289 if (syn_cache_respond(sc) == 0) { 4290 uint64_t *tcps = TCP_STAT_GETREF(); 4291 tcps[TCP_STAT_SNDACKS]++; 4292 tcps[TCP_STAT_SNDTOTAL]++; 4293 TCP_STAT_PUTREF(); 4294 syn_cache_insert(sc, tp); 4295 } else { 4296 s = splsoftnet(); 4297 /* 4298 * syn_cache_put() will try to schedule the timer, so 4299 * we need to initialize it 4300 */ 4301 syn_cache_timer_arm(sc); 4302 syn_cache_put(sc); 4303 splx(s); 4304 TCP_STATINC(TCP_STAT_SC_DROPPED); 4305 } 4306 return 1; 4307 } 4308 4309 /* 4310 * syn_cache_respond: (re)send SYN+ACK. 4311 * 4312 * Returns 0 on success. 4313 */ 4314 4315 int 4316 syn_cache_respond(struct syn_cache *sc) 4317 { 4318 #ifdef INET6 4319 struct rtentry *rt = NULL; 4320 #endif 4321 struct route *ro; 4322 u_int8_t *optp; 4323 int optlen, error; 4324 u_int16_t tlen; 4325 struct ip *ip = NULL; 4326 #ifdef INET6 4327 struct ip6_hdr *ip6 = NULL; 4328 #endif 4329 struct tcpcb *tp; 4330 struct tcphdr *th; 4331 struct mbuf *m; 4332 u_int hlen; 4333 #ifdef TCP_SIGNATURE 4334 struct secasvar *sav = NULL; 4335 u_int8_t *sigp = NULL; 4336 #endif 4337 4338 ro = &sc->sc_route; 4339 switch (sc->sc_src.sa.sa_family) { 4340 case AF_INET: 4341 hlen = sizeof(struct ip); 4342 break; 4343 #ifdef INET6 4344 case AF_INET6: 4345 hlen = sizeof(struct ip6_hdr); 4346 break; 4347 #endif 4348 default: 4349 return EAFNOSUPPORT; 4350 } 4351 4352 /* Worst case scanario, since we don't know the option size yet. */ 4353 tlen = hlen + sizeof(struct tcphdr) + MAX_TCPOPTLEN; 4354 KASSERT(max_linkhdr + tlen <= MCLBYTES); 4355 4356 /* 4357 * Create the IP+TCP header from scratch. 4358 */ 4359 MGETHDR(m, M_DONTWAIT, MT_DATA); 4360 if (m && (max_linkhdr + tlen) > MHLEN) { 4361 MCLGET(m, M_DONTWAIT); 4362 if ((m->m_flags & M_EXT) == 0) { 4363 m_freem(m); 4364 m = NULL; 4365 } 4366 } 4367 if (m == NULL) 4368 return ENOBUFS; 4369 MCLAIM(m, &tcp_tx_mowner); 4370 4371 tp = sc->sc_tp; 4372 4373 /* Fixup the mbuf. */ 4374 m->m_data += max_linkhdr; 4375 m_reset_rcvif(m); 4376 memset(mtod(m, void *), 0, tlen); 4377 4378 switch (sc->sc_src.sa.sa_family) { 4379 case AF_INET: 4380 ip = mtod(m, struct ip *); 4381 ip->ip_v = 4; 4382 ip->ip_dst = sc->sc_src.sin.sin_addr; 4383 ip->ip_src = sc->sc_dst.sin.sin_addr; 4384 ip->ip_p = IPPROTO_TCP; 4385 th = (struct tcphdr *)(ip + 1); 4386 th->th_dport = sc->sc_src.sin.sin_port; 4387 th->th_sport = sc->sc_dst.sin.sin_port; 4388 break; 4389 #ifdef INET6 4390 case AF_INET6: 4391 ip6 = mtod(m, struct ip6_hdr *); 4392 ip6->ip6_vfc = IPV6_VERSION; 4393 ip6->ip6_dst = sc->sc_src.sin6.sin6_addr; 4394 ip6->ip6_src = sc->sc_dst.sin6.sin6_addr; 4395 ip6->ip6_nxt = IPPROTO_TCP; 4396 /* ip6_plen will be updated in ip6_output() */ 4397 th = (struct tcphdr *)(ip6 + 1); 4398 th->th_dport = sc->sc_src.sin6.sin6_port; 4399 th->th_sport = sc->sc_dst.sin6.sin6_port; 4400 break; 4401 #endif 4402 default: 4403 panic("%s: impossible (1)", __func__); 4404 } 4405 4406 th->th_seq = htonl(sc->sc_iss); 4407 th->th_ack = htonl(sc->sc_irs + 1); 4408 th->th_flags = TH_SYN|TH_ACK; 4409 th->th_win = htons(sc->sc_win); 4410 /* th_x2, th_sum, th_urp already 0 from memset */ 4411 4412 /* Tack on the TCP options. */ 4413 optp = (u_int8_t *)(th + 1); 4414 optlen = 0; 4415 *optp++ = TCPOPT_MAXSEG; 4416 *optp++ = TCPOLEN_MAXSEG; 4417 *optp++ = (sc->sc_ourmaxseg >> 8) & 0xff; 4418 *optp++ = sc->sc_ourmaxseg & 0xff; 4419 optlen += TCPOLEN_MAXSEG; 4420 4421 if (sc->sc_request_r_scale != 15) { 4422 *((u_int32_t *)optp) = htonl(TCPOPT_NOP << 24 | 4423 TCPOPT_WINDOW << 16 | TCPOLEN_WINDOW << 8 | 4424 sc->sc_request_r_scale); 4425 optp += TCPOLEN_WINDOW + TCPOLEN_NOP; 4426 optlen += TCPOLEN_WINDOW + TCPOLEN_NOP; 4427 } 4428 4429 if (sc->sc_flags & SCF_SACK_PERMIT) { 4430 /* Let the peer know that we will SACK. */ 4431 *optp++ = TCPOPT_SACK_PERMITTED; 4432 *optp++ = TCPOLEN_SACK_PERMITTED; 4433 optlen += TCPOLEN_SACK_PERMITTED; 4434 } 4435 4436 if (sc->sc_flags & SCF_TIMESTAMP) { 4437 while (optlen % 4 != 2) { 4438 optlen += TCPOLEN_NOP; 4439 *optp++ = TCPOPT_NOP; 4440 } 4441 *optp++ = TCPOPT_TIMESTAMP; 4442 *optp++ = TCPOLEN_TIMESTAMP; 4443 u_int32_t *lp = (u_int32_t *)(optp); 4444 /* Form timestamp option as shown in appendix A of RFC 1323. */ 4445 *lp++ = htonl(SYN_CACHE_TIMESTAMP(sc)); 4446 *lp = htonl(sc->sc_timestamp); 4447 optp += TCPOLEN_TIMESTAMP - 2; 4448 optlen += TCPOLEN_TIMESTAMP; 4449 } 4450 4451 #ifdef TCP_SIGNATURE 4452 if (sc->sc_flags & SCF_SIGNATURE) { 4453 sav = tcp_signature_getsav(m); 4454 if (sav == NULL) { 4455 m_freem(m); 4456 return EPERM; 4457 } 4458 4459 *optp++ = TCPOPT_SIGNATURE; 4460 *optp++ = TCPOLEN_SIGNATURE; 4461 sigp = optp; 4462 memset(optp, 0, TCP_SIGLEN); 4463 optp += TCP_SIGLEN; 4464 optlen += TCPOLEN_SIGNATURE; 4465 } 4466 #endif 4467 4468 /* 4469 * Terminate and pad TCP options to a 4 byte boundary. 4470 * 4471 * According to RFC793: "The content of the header beyond the 4472 * End-of-Option option must be header padding (i.e., zero)." 4473 * And later: "The padding is composed of zeros." 4474 */ 4475 if (optlen % 4) { 4476 optlen += TCPOLEN_EOL; 4477 *optp++ = TCPOPT_EOL; 4478 } 4479 while (optlen % 4) { 4480 optlen += TCPOLEN_PAD; 4481 *optp++ = TCPOPT_PAD; 4482 } 4483 4484 /* Compute the actual values now that we've added the options. */ 4485 tlen = hlen + sizeof(struct tcphdr) + optlen; 4486 m->m_len = m->m_pkthdr.len = tlen; 4487 th->th_off = (sizeof(struct tcphdr) + optlen) >> 2; 4488 4489 #ifdef TCP_SIGNATURE 4490 if (sav) { 4491 (void)tcp_signature(m, th, hlen, sav, sigp); 4492 key_sa_recordxfer(sav, m); 4493 KEY_SA_UNREF(&sav); 4494 } 4495 #endif 4496 4497 /* 4498 * Send ECN SYN-ACK setup packet. 4499 * Routes can be asymetric, so, even if we receive a packet 4500 * with ECE and CWR set, we must not assume no one will block 4501 * the ECE packet we are about to send. 4502 */ 4503 if ((sc->sc_flags & SCF_ECN_PERMIT) && tp && 4504 SEQ_GEQ(tp->snd_nxt, tp->snd_max)) { 4505 th->th_flags |= TH_ECE; 4506 TCP_STATINC(TCP_STAT_ECN_SHS); 4507 4508 /* 4509 * draft-ietf-tcpm-ecnsyn-00.txt 4510 * 4511 * "[...] a TCP node MAY respond to an ECN-setup 4512 * SYN packet by setting ECT in the responding 4513 * ECN-setup SYN/ACK packet, indicating to routers 4514 * that the SYN/ACK packet is ECN-Capable. 4515 * This allows a congested router along the path 4516 * to mark the packet instead of dropping the 4517 * packet as an indication of congestion." 4518 * 4519 * "[...] There can be a great benefit in setting 4520 * an ECN-capable codepoint in SYN/ACK packets [...] 4521 * Congestion is most likely to occur in 4522 * the server-to-client direction. As a result, 4523 * setting an ECN-capable codepoint in SYN/ACK 4524 * packets can reduce the occurence of three-second 4525 * retransmit timeouts resulting from the drop 4526 * of SYN/ACK packets." 4527 * 4528 * Page 4 and 6, January 2006. 4529 */ 4530 4531 switch (sc->sc_src.sa.sa_family) { 4532 case AF_INET: 4533 ip->ip_tos |= IPTOS_ECN_ECT0; 4534 break; 4535 #ifdef INET6 4536 case AF_INET6: 4537 ip6->ip6_flow |= htonl(IPTOS_ECN_ECT0 << 20); 4538 break; 4539 #endif 4540 } 4541 TCP_STATINC(TCP_STAT_ECN_ECT); 4542 } 4543 4544 4545 /* 4546 * Compute the packet's checksum. 4547 * 4548 * Fill in some straggling IP bits. Note the stack expects 4549 * ip_len to be in host order, for convenience. 4550 */ 4551 switch (sc->sc_src.sa.sa_family) { 4552 case AF_INET: 4553 ip->ip_len = htons(tlen - hlen); 4554 th->th_sum = 0; 4555 th->th_sum = in4_cksum(m, IPPROTO_TCP, hlen, tlen - hlen); 4556 ip->ip_len = htons(tlen); 4557 ip->ip_ttl = ip_defttl; 4558 /* XXX tos? */ 4559 break; 4560 #ifdef INET6 4561 case AF_INET6: 4562 ip6->ip6_plen = htons(tlen - hlen); 4563 th->th_sum = 0; 4564 th->th_sum = in6_cksum(m, IPPROTO_TCP, hlen, tlen - hlen); 4565 ip6->ip6_vfc &= ~IPV6_VERSION_MASK; 4566 ip6->ip6_vfc |= IPV6_VERSION; 4567 ip6->ip6_plen = htons(tlen - hlen); 4568 /* ip6_hlim will be initialized afterwards */ 4569 /* XXX flowlabel? */ 4570 break; 4571 #endif 4572 } 4573 4574 /* XXX use IPsec policy on listening socket, on SYN ACK */ 4575 tp = sc->sc_tp; 4576 4577 switch (sc->sc_src.sa.sa_family) { 4578 case AF_INET: 4579 error = ip_output(m, sc->sc_ipopts, ro, 4580 (ip_mtudisc ? IP_MTUDISC : 0), 4581 NULL, tp ? tp->t_inpcb : NULL); 4582 break; 4583 #ifdef INET6 4584 case AF_INET6: 4585 ip6->ip6_hlim = in6_selecthlim(NULL, 4586 (rt = rtcache_validate(ro)) != NULL ? rt->rt_ifp : NULL); 4587 rtcache_unref(rt, ro); 4588 4589 error = ip6_output(m, NULL /*XXX*/, ro, 0, NULL, 4590 tp ? tp->t_in6pcb : NULL, NULL); 4591 break; 4592 #endif 4593 default: 4594 panic("%s: impossible (2)", __func__); 4595 } 4596 4597 return error; 4598 } 4599