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