tcp_timewait.c revision 126253
1/* 2 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995 3 * The Regents of the University of California. All rights reserved. 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted provided that the following conditions 7 * are met: 8 * 1. Redistributions of source code must retain the above copyright 9 * notice, this list of conditions and the following disclaimer. 10 * 2. Redistributions in binary form must reproduce the above copyright 11 * notice, this list of conditions and the following disclaimer in the 12 * documentation and/or other materials provided with the distribution. 13 * 3. All advertising materials mentioning features or use of this software 14 * must display the following acknowledgement: 15 * This product includes software developed by the University of 16 * California, Berkeley and its contributors. 17 * 4. Neither the name of the University nor the names of its contributors 18 * may be used to endorse or promote products derived from this software 19 * without specific prior written permission. 20 * 21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 31 * SUCH DAMAGE. 32 * 33 * @(#)tcp_subr.c 8.2 (Berkeley) 5/24/95 34 * $FreeBSD: head/sys/netinet/tcp_timewait.c 126253 2004-02-26 00:27:04Z truckman $ 35 */ 36 37#include "opt_compat.h" 38#include "opt_inet.h" 39#include "opt_inet6.h" 40#include "opt_ipsec.h" 41#include "opt_mac.h" 42#include "opt_tcpdebug.h" 43 44#include <sys/param.h> 45#include <sys/systm.h> 46#include <sys/callout.h> 47#include <sys/kernel.h> 48#include <sys/sysctl.h> 49#include <sys/mac.h> 50#include <sys/malloc.h> 51#include <sys/mbuf.h> 52#ifdef INET6 53#include <sys/domain.h> 54#endif 55#include <sys/proc.h> 56#include <sys/socket.h> 57#include <sys/socketvar.h> 58#include <sys/protosw.h> 59#include <sys/random.h> 60 61#include <vm/uma.h> 62 63#include <net/route.h> 64#include <net/if.h> 65 66#include <netinet/in.h> 67#include <netinet/in_systm.h> 68#include <netinet/ip.h> 69#ifdef INET6 70#include <netinet/ip6.h> 71#endif 72#include <netinet/in_pcb.h> 73#ifdef INET6 74#include <netinet6/in6_pcb.h> 75#endif 76#include <netinet/in_var.h> 77#include <netinet/ip_var.h> 78#ifdef INET6 79#include <netinet6/ip6_var.h> 80#include <netinet6/nd6.h> 81#endif 82#include <netinet/tcp.h> 83#include <netinet/tcp_fsm.h> 84#include <netinet/tcp_seq.h> 85#include <netinet/tcp_timer.h> 86#include <netinet/tcp_var.h> 87#ifdef INET6 88#include <netinet6/tcp6_var.h> 89#endif 90#include <netinet/tcpip.h> 91#ifdef TCPDEBUG 92#include <netinet/tcp_debug.h> 93#endif 94#include <netinet6/ip6protosw.h> 95 96#ifdef IPSEC 97#include <netinet6/ipsec.h> 98#ifdef INET6 99#include <netinet6/ipsec6.h> 100#endif 101#endif /*IPSEC*/ 102 103#ifdef FAST_IPSEC 104#include <netipsec/ipsec.h> 105#include <netipsec/xform.h> 106#ifdef INET6 107#include <netipsec/ipsec6.h> 108#endif 109#include <netipsec/key.h> 110#define IPSEC 111#endif /*FAST_IPSEC*/ 112 113#include <machine/in_cksum.h> 114#include <sys/md5.h> 115 116int tcp_mssdflt = TCP_MSS; 117SYSCTL_INT(_net_inet_tcp, TCPCTL_MSSDFLT, mssdflt, CTLFLAG_RW, 118 &tcp_mssdflt , 0, "Default TCP Maximum Segment Size"); 119 120#ifdef INET6 121int tcp_v6mssdflt = TCP6_MSS; 122SYSCTL_INT(_net_inet_tcp, TCPCTL_V6MSSDFLT, v6mssdflt, 123 CTLFLAG_RW, &tcp_v6mssdflt , 0, 124 "Default TCP Maximum Segment Size for IPv6"); 125#endif 126 127/* 128 * Minimum MSS we accept and use. This prevents DoS attacks where 129 * we are forced to a ridiculous low MSS like 20 and send hundreds 130 * of packets instead of one. The effect scales with the available 131 * bandwidth and quickly saturates the CPU and network interface 132 * with packet generation and sending. Set to zero to disable MINMSS 133 * checking. This setting prevents us from sending too small packets. 134 */ 135int tcp_minmss = TCP_MINMSS; 136SYSCTL_INT(_net_inet_tcp, OID_AUTO, minmss, CTLFLAG_RW, 137 &tcp_minmss , 0, "Minmum TCP Maximum Segment Size"); 138/* 139 * Number of TCP segments per second we accept from remote host 140 * before we start to calculate average segment size. If average 141 * segment size drops below the minimum TCP MSS we assume a DoS 142 * attack and reset+drop the connection. Care has to be taken not to 143 * set this value too small to not kill interactive type connections 144 * (telnet, SSH) which send many small packets. 145 */ 146int tcp_minmssoverload = TCP_MINMSSOVERLOAD; 147SYSCTL_INT(_net_inet_tcp, OID_AUTO, minmssoverload, CTLFLAG_RW, 148 &tcp_minmssoverload , 0, "Number of TCP Segments per Second allowed to" 149 "be under the MINMSS Size"); 150 151#if 0 152static int tcp_rttdflt = TCPTV_SRTTDFLT / PR_SLOWHZ; 153SYSCTL_INT(_net_inet_tcp, TCPCTL_RTTDFLT, rttdflt, CTLFLAG_RW, 154 &tcp_rttdflt , 0, "Default maximum TCP Round Trip Time"); 155#endif 156 157int tcp_do_rfc1323 = 1; 158SYSCTL_INT(_net_inet_tcp, TCPCTL_DO_RFC1323, rfc1323, CTLFLAG_RW, 159 &tcp_do_rfc1323 , 0, "Enable rfc1323 (high performance TCP) extensions"); 160 161int tcp_do_rfc1644 = 0; 162SYSCTL_INT(_net_inet_tcp, TCPCTL_DO_RFC1644, rfc1644, CTLFLAG_RW, 163 &tcp_do_rfc1644 , 0, "Enable rfc1644 (TTCP) extensions"); 164 165static int tcp_tcbhashsize = 0; 166SYSCTL_INT(_net_inet_tcp, OID_AUTO, tcbhashsize, CTLFLAG_RDTUN, 167 &tcp_tcbhashsize, 0, "Size of TCP control-block hashtable"); 168 169static int do_tcpdrain = 1; 170SYSCTL_INT(_net_inet_tcp, OID_AUTO, do_tcpdrain, CTLFLAG_RW, &do_tcpdrain, 0, 171 "Enable tcp_drain routine for extra help when low on mbufs"); 172 173SYSCTL_INT(_net_inet_tcp, OID_AUTO, pcbcount, CTLFLAG_RD, 174 &tcbinfo.ipi_count, 0, "Number of active PCBs"); 175 176static int icmp_may_rst = 1; 177SYSCTL_INT(_net_inet_tcp, OID_AUTO, icmp_may_rst, CTLFLAG_RW, &icmp_may_rst, 0, 178 "Certain ICMP unreachable messages may abort connections in SYN_SENT"); 179 180static int tcp_isn_reseed_interval = 0; 181SYSCTL_INT(_net_inet_tcp, OID_AUTO, isn_reseed_interval, CTLFLAG_RW, 182 &tcp_isn_reseed_interval, 0, "Seconds between reseeding of ISN secret"); 183 184/* 185 * TCP bandwidth limiting sysctls. Note that the default lower bound of 186 * 1024 exists only for debugging. A good production default would be 187 * something like 6100. 188 */ 189static int tcp_inflight_enable = 1; 190SYSCTL_INT(_net_inet_tcp, OID_AUTO, inflight_enable, CTLFLAG_RW, 191 &tcp_inflight_enable, 0, "Enable automatic TCP inflight data limiting"); 192 193static int tcp_inflight_debug = 0; 194SYSCTL_INT(_net_inet_tcp, OID_AUTO, inflight_debug, CTLFLAG_RW, 195 &tcp_inflight_debug, 0, "Debug TCP inflight calculations"); 196 197static int tcp_inflight_min = 6144; 198SYSCTL_INT(_net_inet_tcp, OID_AUTO, inflight_min, CTLFLAG_RW, 199 &tcp_inflight_min, 0, "Lower-bound for TCP inflight window"); 200 201static int tcp_inflight_max = TCP_MAXWIN << TCP_MAX_WINSHIFT; 202SYSCTL_INT(_net_inet_tcp, OID_AUTO, inflight_max, CTLFLAG_RW, 203 &tcp_inflight_max, 0, "Upper-bound for TCP inflight window"); 204static int tcp_inflight_stab = 20; 205SYSCTL_INT(_net_inet_tcp, OID_AUTO, inflight_stab, CTLFLAG_RW, 206 &tcp_inflight_stab, 0, "Inflight Algorithm Stabilization 20 = 2 packets"); 207 208static struct inpcb *tcp_notify(struct inpcb *, int); 209static void tcp_discardcb(struct tcpcb *); 210 211/* 212 * Target size of TCP PCB hash tables. Must be a power of two. 213 * 214 * Note that this can be overridden by the kernel environment 215 * variable net.inet.tcp.tcbhashsize 216 */ 217#ifndef TCBHASHSIZE 218#define TCBHASHSIZE 512 219#endif 220 221/* 222 * XXX 223 * Callouts should be moved into struct tcp directly. They are currently 224 * separate because the tcpcb structure is exported to userland for sysctl 225 * parsing purposes, which do not know about callouts. 226 */ 227struct tcpcb_mem { 228 struct tcpcb tcb; 229 struct callout tcpcb_mem_rexmt, tcpcb_mem_persist, tcpcb_mem_keep; 230 struct callout tcpcb_mem_2msl, tcpcb_mem_delack; 231}; 232 233static uma_zone_t tcpcb_zone; 234static uma_zone_t tcptw_zone; 235 236/* 237 * Tcp initialization 238 */ 239void 240tcp_init() 241{ 242 int hashsize = TCBHASHSIZE; 243 244 tcp_ccgen = 1; 245 246 tcp_delacktime = TCPTV_DELACK; 247 tcp_keepinit = TCPTV_KEEP_INIT; 248 tcp_keepidle = TCPTV_KEEP_IDLE; 249 tcp_keepintvl = TCPTV_KEEPINTVL; 250 tcp_maxpersistidle = TCPTV_KEEP_IDLE; 251 tcp_msl = TCPTV_MSL; 252 tcp_rexmit_min = TCPTV_MIN; 253 tcp_rexmit_slop = TCPTV_CPU_VAR; 254 255 INP_INFO_LOCK_INIT(&tcbinfo, "tcp"); 256 LIST_INIT(&tcb); 257 tcbinfo.listhead = &tcb; 258 TUNABLE_INT_FETCH("net.inet.tcp.tcbhashsize", &hashsize); 259 if (!powerof2(hashsize)) { 260 printf("WARNING: TCB hash size not a power of 2\n"); 261 hashsize = 512; /* safe default */ 262 } 263 tcp_tcbhashsize = hashsize; 264 tcbinfo.hashbase = hashinit(hashsize, M_PCB, &tcbinfo.hashmask); 265 tcbinfo.porthashbase = hashinit(hashsize, M_PCB, 266 &tcbinfo.porthashmask); 267 tcbinfo.ipi_zone = uma_zcreate("inpcb", sizeof(struct inpcb), 268 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE); 269 uma_zone_set_max(tcbinfo.ipi_zone, maxsockets); 270#ifdef INET6 271#define TCP_MINPROTOHDR (sizeof(struct ip6_hdr) + sizeof(struct tcphdr)) 272#else /* INET6 */ 273#define TCP_MINPROTOHDR (sizeof(struct tcpiphdr)) 274#endif /* INET6 */ 275 if (max_protohdr < TCP_MINPROTOHDR) 276 max_protohdr = TCP_MINPROTOHDR; 277 if (max_linkhdr + TCP_MINPROTOHDR > MHLEN) 278 panic("tcp_init"); 279#undef TCP_MINPROTOHDR 280 /* 281 * These have to be type stable for the benefit of the timers. 282 */ 283 tcpcb_zone = uma_zcreate("tcpcb", sizeof(struct tcpcb_mem), 284 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE); 285 uma_zone_set_max(tcpcb_zone, maxsockets); 286 tcptw_zone = uma_zcreate("tcptw", sizeof(struct tcptw), 287 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE); 288 uma_zone_set_max(tcptw_zone, maxsockets / 5); 289 tcp_timer_init(); 290 syncache_init(); 291 tcp_hc_init(); 292 tcp_reass_init(); 293} 294 295/* 296 * Fill in the IP and TCP headers for an outgoing packet, given the tcpcb. 297 * tcp_template used to store this data in mbufs, but we now recopy it out 298 * of the tcpcb each time to conserve mbufs. 299 */ 300void 301tcpip_fillheaders(inp, ip_ptr, tcp_ptr) 302 struct inpcb *inp; 303 void *ip_ptr; 304 void *tcp_ptr; 305{ 306 struct tcphdr *th = (struct tcphdr *)tcp_ptr; 307 308#ifdef INET6 309 if ((inp->inp_vflag & INP_IPV6) != 0) { 310 struct ip6_hdr *ip6; 311 312 ip6 = (struct ip6_hdr *)ip_ptr; 313 ip6->ip6_flow = (ip6->ip6_flow & ~IPV6_FLOWINFO_MASK) | 314 (inp->in6p_flowinfo & IPV6_FLOWINFO_MASK); 315 ip6->ip6_vfc = (ip6->ip6_vfc & ~IPV6_VERSION_MASK) | 316 (IPV6_VERSION & IPV6_VERSION_MASK); 317 ip6->ip6_nxt = IPPROTO_TCP; 318 ip6->ip6_plen = sizeof(struct tcphdr); 319 ip6->ip6_src = inp->in6p_laddr; 320 ip6->ip6_dst = inp->in6p_faddr; 321 } else 322#endif 323 { 324 struct ip *ip; 325 326 ip = (struct ip *)ip_ptr; 327 ip->ip_v = IPVERSION; 328 ip->ip_hl = 5; 329 ip->ip_tos = inp->inp_ip_tos; 330 ip->ip_len = 0; 331 ip->ip_id = 0; 332 ip->ip_off = 0; 333 ip->ip_ttl = inp->inp_ip_ttl; 334 ip->ip_sum = 0; 335 ip->ip_p = IPPROTO_TCP; 336 ip->ip_src = inp->inp_laddr; 337 ip->ip_dst = inp->inp_faddr; 338 } 339 th->th_sport = inp->inp_lport; 340 th->th_dport = inp->inp_fport; 341 th->th_seq = 0; 342 th->th_ack = 0; 343 th->th_x2 = 0; 344 th->th_off = 5; 345 th->th_flags = 0; 346 th->th_win = 0; 347 th->th_urp = 0; 348 th->th_sum = 0; /* in_pseudo() is called later for ipv4 */ 349} 350 351/* 352 * Create template to be used to send tcp packets on a connection. 353 * Allocates an mbuf and fills in a skeletal tcp/ip header. The only 354 * use for this function is in keepalives, which use tcp_respond. 355 */ 356struct tcptemp * 357tcpip_maketemplate(inp) 358 struct inpcb *inp; 359{ 360 struct mbuf *m; 361 struct tcptemp *n; 362 363 m = m_get(M_DONTWAIT, MT_HEADER); 364 if (m == NULL) 365 return (0); 366 m->m_len = sizeof(struct tcptemp); 367 n = mtod(m, struct tcptemp *); 368 369 tcpip_fillheaders(inp, (void *)&n->tt_ipgen, (void *)&n->tt_t); 370 return (n); 371} 372 373/* 374 * Send a single message to the TCP at address specified by 375 * the given TCP/IP header. If m == 0, then we make a copy 376 * of the tcpiphdr at ti and send directly to the addressed host. 377 * This is used to force keep alive messages out using the TCP 378 * template for a connection. If flags are given then we send 379 * a message back to the TCP which originated the * segment ti, 380 * and discard the mbuf containing it and any other attached mbufs. 381 * 382 * In any case the ack and sequence number of the transmitted 383 * segment are as specified by the parameters. 384 * 385 * NOTE: If m != NULL, then ti must point to *inside* the mbuf. 386 */ 387void 388tcp_respond(tp, ipgen, th, m, ack, seq, flags) 389 struct tcpcb *tp; 390 void *ipgen; 391 register struct tcphdr *th; 392 register struct mbuf *m; 393 tcp_seq ack, seq; 394 int flags; 395{ 396 register int tlen; 397 int win = 0; 398 struct ip *ip; 399 struct tcphdr *nth; 400#ifdef INET6 401 struct ip6_hdr *ip6; 402 int isipv6; 403#endif /* INET6 */ 404 int ipflags = 0; 405 struct inpcb *inp = NULL; 406 407 KASSERT(tp != NULL || m != NULL, ("tcp_respond: tp and m both NULL")); 408 409#ifdef INET6 410 isipv6 = ((struct ip *)ipgen)->ip_v == 6; 411 ip6 = ipgen; 412#endif /* INET6 */ 413 ip = ipgen; 414 415 if (tp) { 416 inp = tp->t_inpcb; 417 KASSERT(inp != NULL, ("tcp control block w/o inpcb")); 418 INP_INFO_WLOCK_ASSERT(&tcbinfo); 419 INP_LOCK_ASSERT(inp); 420 if (!(flags & TH_RST)) { 421 win = sbspace(&inp->inp_socket->so_rcv); 422 if (win > (long)TCP_MAXWIN << tp->rcv_scale) 423 win = (long)TCP_MAXWIN << tp->rcv_scale; 424 } 425 } 426 if (m == 0) { 427 m = m_gethdr(M_DONTWAIT, MT_HEADER); 428 if (m == NULL) 429 return; 430 tlen = 0; 431 m->m_data += max_linkhdr; 432#ifdef INET6 433 if (isipv6) { 434 bcopy((caddr_t)ip6, mtod(m, caddr_t), 435 sizeof(struct ip6_hdr)); 436 ip6 = mtod(m, struct ip6_hdr *); 437 nth = (struct tcphdr *)(ip6 + 1); 438 } else 439#endif /* INET6 */ 440 { 441 bcopy((caddr_t)ip, mtod(m, caddr_t), sizeof(struct ip)); 442 ip = mtod(m, struct ip *); 443 nth = (struct tcphdr *)(ip + 1); 444 } 445 bcopy((caddr_t)th, (caddr_t)nth, sizeof(struct tcphdr)); 446 flags = TH_ACK; 447 } else { 448 m_freem(m->m_next); 449 m->m_next = 0; 450 m->m_data = (caddr_t)ipgen; 451 /* m_len is set later */ 452 tlen = 0; 453#define xchg(a,b,type) { type t; t=a; a=b; b=t; } 454#ifdef INET6 455 if (isipv6) { 456 xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr); 457 nth = (struct tcphdr *)(ip6 + 1); 458 } else 459#endif /* INET6 */ 460 { 461 xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, n_long); 462 nth = (struct tcphdr *)(ip + 1); 463 } 464 if (th != nth) { 465 /* 466 * this is usually a case when an extension header 467 * exists between the IPv6 header and the 468 * TCP header. 469 */ 470 nth->th_sport = th->th_sport; 471 nth->th_dport = th->th_dport; 472 } 473 xchg(nth->th_dport, nth->th_sport, n_short); 474#undef xchg 475 } 476#ifdef INET6 477 if (isipv6) { 478 ip6->ip6_flow = 0; 479 ip6->ip6_vfc = IPV6_VERSION; 480 ip6->ip6_nxt = IPPROTO_TCP; 481 ip6->ip6_plen = htons((u_short)(sizeof (struct tcphdr) + 482 tlen)); 483 tlen += sizeof (struct ip6_hdr) + sizeof (struct tcphdr); 484 } else 485#endif 486 { 487 tlen += sizeof (struct tcpiphdr); 488 ip->ip_len = tlen; 489 ip->ip_ttl = ip_defttl; 490 if (path_mtu_discovery) 491 ip->ip_off |= IP_DF; 492 } 493 m->m_len = tlen; 494 m->m_pkthdr.len = tlen; 495 m->m_pkthdr.rcvif = (struct ifnet *) 0; 496#ifdef MAC 497 if (inp != NULL) { 498 /* 499 * Packet is associated with a socket, so allow the 500 * label of the response to reflect the socket label. 501 */ 502 mac_create_mbuf_from_socket(inp->inp_socket, m); 503 } else { 504 /* 505 * Packet is not associated with a socket, so possibly 506 * update the label in place. 507 */ 508 mac_reflect_mbuf_tcp(m); 509 } 510#endif 511 nth->th_seq = htonl(seq); 512 nth->th_ack = htonl(ack); 513 nth->th_x2 = 0; 514 nth->th_off = sizeof (struct tcphdr) >> 2; 515 nth->th_flags = flags; 516 if (tp) 517 nth->th_win = htons((u_short) (win >> tp->rcv_scale)); 518 else 519 nth->th_win = htons((u_short)win); 520 nth->th_urp = 0; 521#ifdef INET6 522 if (isipv6) { 523 nth->th_sum = 0; 524 nth->th_sum = in6_cksum(m, IPPROTO_TCP, 525 sizeof(struct ip6_hdr), 526 tlen - sizeof(struct ip6_hdr)); 527 ip6->ip6_hlim = in6_selecthlim(tp ? tp->t_inpcb : NULL, NULL); 528 } else 529#endif /* INET6 */ 530 { 531 nth->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr, 532 htons((u_short)(tlen - sizeof(struct ip) + ip->ip_p))); 533 m->m_pkthdr.csum_flags = CSUM_TCP; 534 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum); 535 } 536#ifdef TCPDEBUG 537 if (tp == NULL || (inp->inp_socket->so_options & SO_DEBUG)) 538 tcp_trace(TA_OUTPUT, 0, tp, mtod(m, void *), th, 0); 539#endif 540#ifdef INET6 541 if (isipv6) 542 (void) ip6_output(m, NULL, NULL, ipflags, NULL, NULL, inp); 543 else 544#endif /* INET6 */ 545 (void) ip_output(m, NULL, NULL, ipflags, NULL, inp); 546} 547 548/* 549 * Create a new TCP control block, making an 550 * empty reassembly queue and hooking it to the argument 551 * protocol control block. The `inp' parameter must have 552 * come from the zone allocator set up in tcp_init(). 553 */ 554struct tcpcb * 555tcp_newtcpcb(inp) 556 struct inpcb *inp; 557{ 558 struct tcpcb_mem *tm; 559 struct tcpcb *tp; 560#ifdef INET6 561 int isipv6 = (inp->inp_vflag & INP_IPV6) != 0; 562#endif /* INET6 */ 563 564 tm = uma_zalloc(tcpcb_zone, M_NOWAIT | M_ZERO); 565 if (tm == NULL) 566 return (NULL); 567 tp = &tm->tcb; 568 /* LIST_INIT(&tp->t_segq); */ /* XXX covered by M_ZERO */ 569 tp->t_maxseg = tp->t_maxopd = 570#ifdef INET6 571 isipv6 ? tcp_v6mssdflt : 572#endif /* INET6 */ 573 tcp_mssdflt; 574 575 /* Set up our timeouts. */ 576 callout_init(tp->tt_rexmt = &tm->tcpcb_mem_rexmt, 0); 577 callout_init(tp->tt_persist = &tm->tcpcb_mem_persist, 0); 578 callout_init(tp->tt_keep = &tm->tcpcb_mem_keep, 0); 579 callout_init(tp->tt_2msl = &tm->tcpcb_mem_2msl, 0); 580 callout_init(tp->tt_delack = &tm->tcpcb_mem_delack, 0); 581 582 if (tcp_do_rfc1323) 583 tp->t_flags = (TF_REQ_SCALE|TF_REQ_TSTMP); 584 if (tcp_do_rfc1644) 585 tp->t_flags |= TF_REQ_CC; 586 tp->t_inpcb = inp; /* XXX */ 587 /* 588 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no 589 * rtt estimate. Set rttvar so that srtt + 4 * rttvar gives 590 * reasonable initial retransmit time. 591 */ 592 tp->t_srtt = TCPTV_SRTTBASE; 593 tp->t_rttvar = ((TCPTV_RTOBASE - TCPTV_SRTTBASE) << TCP_RTTVAR_SHIFT) / 4; 594 tp->t_rttmin = tcp_rexmit_min; 595 tp->t_rxtcur = TCPTV_RTOBASE; 596 tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT; 597 tp->snd_bwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT; 598 tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT; 599 tp->t_rcvtime = ticks; 600 tp->t_bw_rtttime = ticks; 601 /* 602 * IPv4 TTL initialization is necessary for an IPv6 socket as well, 603 * because the socket may be bound to an IPv6 wildcard address, 604 * which may match an IPv4-mapped IPv6 address. 605 */ 606 inp->inp_ip_ttl = ip_defttl; 607 inp->inp_ppcb = (caddr_t)tp; 608 return (tp); /* XXX */ 609} 610 611/* 612 * Drop a TCP connection, reporting 613 * the specified error. If connection is synchronized, 614 * then send a RST to peer. 615 */ 616struct tcpcb * 617tcp_drop(tp, errno) 618 register struct tcpcb *tp; 619 int errno; 620{ 621 struct socket *so = tp->t_inpcb->inp_socket; 622 623 if (TCPS_HAVERCVDSYN(tp->t_state)) { 624 tp->t_state = TCPS_CLOSED; 625 (void) tcp_output(tp); 626 tcpstat.tcps_drops++; 627 } else 628 tcpstat.tcps_conndrops++; 629 if (errno == ETIMEDOUT && tp->t_softerror) 630 errno = tp->t_softerror; 631 so->so_error = errno; 632 return (tcp_close(tp)); 633} 634 635static void 636tcp_discardcb(tp) 637 struct tcpcb *tp; 638{ 639 struct tseg_qent *q; 640 struct inpcb *inp = tp->t_inpcb; 641 struct socket *so = inp->inp_socket; 642#ifdef INET6 643 int isipv6 = (inp->inp_vflag & INP_IPV6) != 0; 644#endif /* INET6 */ 645 646 /* 647 * Make sure that all of our timers are stopped before we 648 * delete the PCB. 649 */ 650 callout_stop(tp->tt_rexmt); 651 callout_stop(tp->tt_persist); 652 callout_stop(tp->tt_keep); 653 callout_stop(tp->tt_2msl); 654 callout_stop(tp->tt_delack); 655 656 /* 657 * If we got enough samples through the srtt filter, 658 * save the rtt and rttvar in the routing entry. 659 * 'Enough' is arbitrarily defined as 4 rtt samples. 660 * 4 samples is enough for the srtt filter to converge 661 * to within enough % of the correct value; fewer samples 662 * and we could save a bogus rtt. The danger is not high 663 * as tcp quickly recovers from everything. 664 * XXX: Works very well but needs some more statistics! 665 */ 666 if (tp->t_rttupdated >= 4) { 667 struct hc_metrics_lite metrics; 668 u_long ssthresh; 669 670 bzero(&metrics, sizeof(metrics)); 671 /* 672 * Update the ssthresh always when the conditions below 673 * are satisfied. This gives us better new start value 674 * for the congestion avoidance for new connections. 675 * ssthresh is only set if packet loss occured on a session. 676 */ 677 ssthresh = tp->snd_ssthresh; 678 if (ssthresh != 0 && ssthresh < so->so_snd.sb_hiwat / 2) { 679 /* 680 * convert the limit from user data bytes to 681 * packets then to packet data bytes. 682 */ 683 ssthresh = (ssthresh + tp->t_maxseg / 2) / tp->t_maxseg; 684 if (ssthresh < 2) 685 ssthresh = 2; 686 ssthresh *= (u_long)(tp->t_maxseg + 687#ifdef INET6 688 (isipv6 ? sizeof (struct ip6_hdr) + 689 sizeof (struct tcphdr) : 690#endif 691 sizeof (struct tcpiphdr) 692#ifdef INET6 693 ) 694#endif 695 ); 696 } else 697 ssthresh = 0; 698 metrics.rmx_ssthresh = ssthresh; 699 700 metrics.rmx_rtt = tp->t_srtt; 701 metrics.rmx_rttvar = tp->t_rttvar; 702 /* XXX: This wraps if the pipe is more than 4 Gbit per second */ 703 metrics.rmx_bandwidth = tp->snd_bandwidth; 704 metrics.rmx_cwnd = tp->snd_cwnd; 705 metrics.rmx_sendpipe = 0; 706 metrics.rmx_recvpipe = 0; 707 708 tcp_hc_update(&inp->inp_inc, &metrics); 709 } 710 711 /* free the reassembly queue, if any */ 712 while ((q = LIST_FIRST(&tp->t_segq)) != NULL) { 713 LIST_REMOVE(q, tqe_q); 714 m_freem(q->tqe_m); 715 uma_zfree(tcp_reass_zone, q); 716 tp->t_segqlen--; 717 tcp_reass_qsize--; 718 } 719 inp->inp_ppcb = NULL; 720 tp->t_inpcb = NULL; 721 uma_zfree(tcpcb_zone, tp); 722 soisdisconnected(so); 723} 724 725/* 726 * Close a TCP control block: 727 * discard all space held by the tcp 728 * discard internet protocol block 729 * wake up any sleepers 730 */ 731struct tcpcb * 732tcp_close(tp) 733 struct tcpcb *tp; 734{ 735 struct inpcb *inp = tp->t_inpcb; 736#ifdef INET6 737 struct socket *so = inp->inp_socket; 738#endif 739 740 tcp_discardcb(tp); 741#ifdef INET6 742 if (INP_CHECK_SOCKAF(so, AF_INET6)) 743 in6_pcbdetach(inp); 744 else 745#endif 746 in_pcbdetach(inp); 747 tcpstat.tcps_closed++; 748 return ((struct tcpcb *)0); 749} 750 751void 752tcp_drain() 753{ 754 if (do_tcpdrain) 755 { 756 struct inpcb *inpb; 757 struct tcpcb *tcpb; 758 struct tseg_qent *te; 759 760 /* 761 * Walk the tcpbs, if existing, and flush the reassembly queue, 762 * if there is one... 763 * XXX: The "Net/3" implementation doesn't imply that the TCP 764 * reassembly queue should be flushed, but in a situation 765 * where we're really low on mbufs, this is potentially 766 * usefull. 767 */ 768 INP_INFO_RLOCK(&tcbinfo); 769 LIST_FOREACH(inpb, tcbinfo.listhead, inp_list) { 770 if (inpb->inp_vflag & INP_TIMEWAIT) 771 continue; 772 INP_LOCK(inpb); 773 if ((tcpb = intotcpcb(inpb))) { 774 while ((te = LIST_FIRST(&tcpb->t_segq)) 775 != NULL) { 776 LIST_REMOVE(te, tqe_q); 777 m_freem(te->tqe_m); 778 uma_zfree(tcp_reass_zone, te); 779 tcpb->t_segqlen--; 780 tcp_reass_qsize--; 781 } 782 } 783 INP_UNLOCK(inpb); 784 } 785 INP_INFO_RUNLOCK(&tcbinfo); 786 } 787} 788 789/* 790 * Notify a tcp user of an asynchronous error; 791 * store error as soft error, but wake up user 792 * (for now, won't do anything until can select for soft error). 793 * 794 * Do not wake up user since there currently is no mechanism for 795 * reporting soft errors (yet - a kqueue filter may be added). 796 */ 797static struct inpcb * 798tcp_notify(inp, error) 799 struct inpcb *inp; 800 int error; 801{ 802 struct tcpcb *tp = (struct tcpcb *)inp->inp_ppcb; 803 804 /* 805 * Ignore some errors if we are hooked up. 806 * If connection hasn't completed, has retransmitted several times, 807 * and receives a second error, give up now. This is better 808 * than waiting a long time to establish a connection that 809 * can never complete. 810 */ 811 if (tp->t_state == TCPS_ESTABLISHED && 812 (error == EHOSTUNREACH || error == ENETUNREACH || 813 error == EHOSTDOWN)) { 814 return inp; 815 } else if (tp->t_state < TCPS_ESTABLISHED && tp->t_rxtshift > 3 && 816 tp->t_softerror) { 817 tcp_drop(tp, error); 818 return (struct inpcb *)0; 819 } else { 820 tp->t_softerror = error; 821 return inp; 822 } 823#if 0 824 wakeup( &so->so_timeo); 825 sorwakeup(so); 826 sowwakeup(so); 827#endif 828} 829 830static int 831tcp_pcblist(SYSCTL_HANDLER_ARGS) 832{ 833 int error, i, n, s; 834 struct inpcb *inp, **inp_list; 835 inp_gen_t gencnt; 836 struct xinpgen xig; 837 838 /* 839 * The process of preparing the TCB list is too time-consuming and 840 * resource-intensive to repeat twice on every request. 841 */ 842 if (req->oldptr == 0) { 843 n = tcbinfo.ipi_count; 844 req->oldidx = 2 * (sizeof xig) 845 + (n + n/8) * sizeof(struct xtcpcb); 846 return 0; 847 } 848 849 if (req->newptr != 0) 850 return EPERM; 851 852 /* 853 * OK, now we're committed to doing something. 854 */ 855 s = splnet(); 856 INP_INFO_RLOCK(&tcbinfo); 857 gencnt = tcbinfo.ipi_gencnt; 858 n = tcbinfo.ipi_count; 859 INP_INFO_RUNLOCK(&tcbinfo); 860 splx(s); 861 862 error = sysctl_wire_old_buffer(req, 2 * (sizeof xig) 863 + n * sizeof(struct xtcpcb)); 864 if (error != 0) 865 return (error); 866 867 xig.xig_len = sizeof xig; 868 xig.xig_count = n; 869 xig.xig_gen = gencnt; 870 xig.xig_sogen = so_gencnt; 871 error = SYSCTL_OUT(req, &xig, sizeof xig); 872 if (error) 873 return error; 874 875 inp_list = malloc(n * sizeof *inp_list, M_TEMP, M_WAITOK); 876 if (inp_list == 0) 877 return ENOMEM; 878 879 s = splnet(); 880 INP_INFO_RLOCK(&tcbinfo); 881 for (inp = LIST_FIRST(tcbinfo.listhead), i = 0; inp && i < n; 882 inp = LIST_NEXT(inp, inp_list)) { 883 INP_LOCK(inp); 884 if (inp->inp_gencnt <= gencnt) { 885 /* 886 * XXX: This use of cr_cansee(), introduced with 887 * TCP state changes, is not quite right, but for 888 * now, better than nothing. 889 */ 890 if (inp->inp_vflag & INP_TIMEWAIT) 891 error = cr_cansee(req->td->td_ucred, 892 intotw(inp)->tw_cred); 893 else 894 error = cr_canseesocket(req->td->td_ucred, 895 inp->inp_socket); 896 if (error == 0) 897 inp_list[i++] = inp; 898 } 899 INP_UNLOCK(inp); 900 } 901 INP_INFO_RUNLOCK(&tcbinfo); 902 splx(s); 903 n = i; 904 905 error = 0; 906 for (i = 0; i < n; i++) { 907 inp = inp_list[i]; 908 if (inp->inp_gencnt <= gencnt) { 909 struct xtcpcb xt; 910 caddr_t inp_ppcb; 911 xt.xt_len = sizeof xt; 912 /* XXX should avoid extra copy */ 913 bcopy(inp, &xt.xt_inp, sizeof *inp); 914 inp_ppcb = inp->inp_ppcb; 915 if (inp_ppcb == NULL) 916 bzero((char *) &xt.xt_tp, sizeof xt.xt_tp); 917 else if (inp->inp_vflag & INP_TIMEWAIT) { 918 bzero((char *) &xt.xt_tp, sizeof xt.xt_tp); 919 xt.xt_tp.t_state = TCPS_TIME_WAIT; 920 } else 921 bcopy(inp_ppcb, &xt.xt_tp, sizeof xt.xt_tp); 922 if (inp->inp_socket) 923 sotoxsocket(inp->inp_socket, &xt.xt_socket); 924 else { 925 bzero(&xt.xt_socket, sizeof xt.xt_socket); 926 xt.xt_socket.xso_protocol = IPPROTO_TCP; 927 } 928 xt.xt_inp.inp_gencnt = inp->inp_gencnt; 929 error = SYSCTL_OUT(req, &xt, sizeof xt); 930 } 931 } 932 if (!error) { 933 /* 934 * Give the user an updated idea of our state. 935 * If the generation differs from what we told 936 * her before, she knows that something happened 937 * while we were processing this request, and it 938 * might be necessary to retry. 939 */ 940 s = splnet(); 941 INP_INFO_RLOCK(&tcbinfo); 942 xig.xig_gen = tcbinfo.ipi_gencnt; 943 xig.xig_sogen = so_gencnt; 944 xig.xig_count = tcbinfo.ipi_count; 945 INP_INFO_RUNLOCK(&tcbinfo); 946 splx(s); 947 error = SYSCTL_OUT(req, &xig, sizeof xig); 948 } 949 free(inp_list, M_TEMP); 950 return error; 951} 952 953SYSCTL_PROC(_net_inet_tcp, TCPCTL_PCBLIST, pcblist, CTLFLAG_RD, 0, 0, 954 tcp_pcblist, "S,xtcpcb", "List of active TCP connections"); 955 956static int 957tcp_getcred(SYSCTL_HANDLER_ARGS) 958{ 959 struct xucred xuc; 960 struct sockaddr_in addrs[2]; 961 struct inpcb *inp; 962 int error, s; 963 964 error = suser_cred(req->td->td_ucred, PRISON_ROOT); 965 if (error) 966 return (error); 967 error = SYSCTL_IN(req, addrs, sizeof(addrs)); 968 if (error) 969 return (error); 970 s = splnet(); 971 INP_INFO_RLOCK(&tcbinfo); 972 inp = in_pcblookup_hash(&tcbinfo, addrs[1].sin_addr, addrs[1].sin_port, 973 addrs[0].sin_addr, addrs[0].sin_port, 0, NULL); 974 if (inp == NULL) { 975 error = ENOENT; 976 goto outunlocked; 977 } 978 INP_LOCK(inp); 979 if (inp->inp_socket == NULL) { 980 error = ENOENT; 981 goto out; 982 } 983 error = cr_canseesocket(req->td->td_ucred, inp->inp_socket); 984 if (error) 985 goto out; 986 cru2x(inp->inp_socket->so_cred, &xuc); 987out: 988 INP_UNLOCK(inp); 989outunlocked: 990 INP_INFO_RUNLOCK(&tcbinfo); 991 splx(s); 992 if (error == 0) 993 error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred)); 994 return (error); 995} 996 997SYSCTL_PROC(_net_inet_tcp, OID_AUTO, getcred, 998 CTLTYPE_OPAQUE|CTLFLAG_RW|CTLFLAG_PRISON, 0, 0, 999 tcp_getcred, "S,xucred", "Get the xucred of a TCP connection"); 1000 1001#ifdef INET6 1002static int 1003tcp6_getcred(SYSCTL_HANDLER_ARGS) 1004{ 1005 struct xucred xuc; 1006 struct sockaddr_in6 addrs[2]; 1007 struct inpcb *inp; 1008 int error, s, mapped = 0; 1009 1010 error = suser_cred(req->td->td_ucred, PRISON_ROOT); 1011 if (error) 1012 return (error); 1013 error = SYSCTL_IN(req, addrs, sizeof(addrs)); 1014 if (error) 1015 return (error); 1016 if (IN6_IS_ADDR_V4MAPPED(&addrs[0].sin6_addr)) { 1017 if (IN6_IS_ADDR_V4MAPPED(&addrs[1].sin6_addr)) 1018 mapped = 1; 1019 else 1020 return (EINVAL); 1021 } 1022 s = splnet(); 1023 INP_INFO_RLOCK(&tcbinfo); 1024 if (mapped == 1) 1025 inp = in_pcblookup_hash(&tcbinfo, 1026 *(struct in_addr *)&addrs[1].sin6_addr.s6_addr[12], 1027 addrs[1].sin6_port, 1028 *(struct in_addr *)&addrs[0].sin6_addr.s6_addr[12], 1029 addrs[0].sin6_port, 1030 0, NULL); 1031 else 1032 inp = in6_pcblookup_hash(&tcbinfo, &addrs[1].sin6_addr, 1033 addrs[1].sin6_port, 1034 &addrs[0].sin6_addr, addrs[0].sin6_port, 1035 0, NULL); 1036 if (inp == NULL) { 1037 error = ENOENT; 1038 goto outunlocked; 1039 } 1040 INP_LOCK(inp); 1041 if (inp->inp_socket == NULL) { 1042 error = ENOENT; 1043 goto out; 1044 } 1045 error = cr_canseesocket(req->td->td_ucred, inp->inp_socket); 1046 if (error) 1047 goto out; 1048 cru2x(inp->inp_socket->so_cred, &xuc); 1049out: 1050 INP_UNLOCK(inp); 1051outunlocked: 1052 INP_INFO_RUNLOCK(&tcbinfo); 1053 splx(s); 1054 if (error == 0) 1055 error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred)); 1056 return (error); 1057} 1058 1059SYSCTL_PROC(_net_inet6_tcp6, OID_AUTO, getcred, 1060 CTLTYPE_OPAQUE|CTLFLAG_RW|CTLFLAG_PRISON, 0, 0, 1061 tcp6_getcred, "S,xucred", "Get the xucred of a TCP6 connection"); 1062#endif 1063 1064 1065void 1066tcp_ctlinput(cmd, sa, vip) 1067 int cmd; 1068 struct sockaddr *sa; 1069 void *vip; 1070{ 1071 struct ip *ip = vip; 1072 struct tcphdr *th; 1073 struct in_addr faddr; 1074 struct inpcb *inp; 1075 struct tcpcb *tp; 1076 struct inpcb *(*notify)(struct inpcb *, int) = tcp_notify; 1077 tcp_seq icmp_seq; 1078 int s; 1079 1080 faddr = ((struct sockaddr_in *)sa)->sin_addr; 1081 if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY) 1082 return; 1083 1084 if (cmd == PRC_QUENCH) 1085 notify = tcp_quench; 1086 else if (icmp_may_rst && (cmd == PRC_UNREACH_ADMIN_PROHIB || 1087 cmd == PRC_UNREACH_PORT || cmd == PRC_TIMXCEED_INTRANS) && ip) 1088 notify = tcp_drop_syn_sent; 1089 else if (cmd == PRC_MSGSIZE) 1090 notify = tcp_mtudisc; 1091 /* 1092 * Redirects don't need to be handled up here. 1093 */ 1094 else if (PRC_IS_REDIRECT(cmd)) 1095 return; 1096 /* 1097 * Hostdead is ugly because it goes linearly through all PCBs. 1098 * XXX: We never get this from ICMP, otherwise it makes an 1099 * excellent DoS attack on machines with many connections. 1100 */ 1101 else if (cmd == PRC_HOSTDEAD) 1102 ip = 0; 1103 else if ((unsigned)cmd >= PRC_NCMDS || inetctlerrmap[cmd] == 0) 1104 return; 1105 if (ip) { 1106 s = splnet(); 1107 th = (struct tcphdr *)((caddr_t)ip 1108 + (ip->ip_hl << 2)); 1109 INP_INFO_WLOCK(&tcbinfo); 1110 inp = in_pcblookup_hash(&tcbinfo, faddr, th->th_dport, 1111 ip->ip_src, th->th_sport, 0, NULL); 1112 if (inp != NULL) { 1113 INP_LOCK(inp); 1114 if (inp->inp_socket != NULL) { 1115 icmp_seq = htonl(th->th_seq); 1116 tp = intotcpcb(inp); 1117 if (SEQ_GEQ(icmp_seq, tp->snd_una) && 1118 SEQ_LT(icmp_seq, tp->snd_max)) 1119 inp = (*notify)(inp, inetctlerrmap[cmd]); 1120 } 1121 if (inp) 1122 INP_UNLOCK(inp); 1123 } else { 1124 struct in_conninfo inc; 1125 1126 inc.inc_fport = th->th_dport; 1127 inc.inc_lport = th->th_sport; 1128 inc.inc_faddr = faddr; 1129 inc.inc_laddr = ip->ip_src; 1130#ifdef INET6 1131 inc.inc_isipv6 = 0; 1132#endif 1133 syncache_unreach(&inc, th); 1134 } 1135 INP_INFO_WUNLOCK(&tcbinfo); 1136 splx(s); 1137 } else 1138 in_pcbnotifyall(&tcbinfo, faddr, inetctlerrmap[cmd], notify); 1139} 1140 1141#ifdef INET6 1142void 1143tcp6_ctlinput(cmd, sa, d) 1144 int cmd; 1145 struct sockaddr *sa; 1146 void *d; 1147{ 1148 struct tcphdr th; 1149 struct inpcb *(*notify)(struct inpcb *, int) = tcp_notify; 1150 struct ip6_hdr *ip6; 1151 struct mbuf *m; 1152 struct ip6ctlparam *ip6cp = NULL; 1153 const struct sockaddr_in6 *sa6_src = NULL; 1154 int off; 1155 struct tcp_portonly { 1156 u_int16_t th_sport; 1157 u_int16_t th_dport; 1158 } *thp; 1159 1160 if (sa->sa_family != AF_INET6 || 1161 sa->sa_len != sizeof(struct sockaddr_in6)) 1162 return; 1163 1164 if (cmd == PRC_QUENCH) 1165 notify = tcp_quench; 1166 else if (cmd == PRC_MSGSIZE) 1167 notify = tcp_mtudisc; 1168 else if (!PRC_IS_REDIRECT(cmd) && 1169 ((unsigned)cmd >= PRC_NCMDS || inet6ctlerrmap[cmd] == 0)) 1170 return; 1171 1172 /* if the parameter is from icmp6, decode it. */ 1173 if (d != NULL) { 1174 ip6cp = (struct ip6ctlparam *)d; 1175 m = ip6cp->ip6c_m; 1176 ip6 = ip6cp->ip6c_ip6; 1177 off = ip6cp->ip6c_off; 1178 sa6_src = ip6cp->ip6c_src; 1179 } else { 1180 m = NULL; 1181 ip6 = NULL; 1182 off = 0; /* fool gcc */ 1183 sa6_src = &sa6_any; 1184 } 1185 1186 if (ip6) { 1187 struct in_conninfo inc; 1188 /* 1189 * XXX: We assume that when IPV6 is non NULL, 1190 * M and OFF are valid. 1191 */ 1192 1193 /* check if we can safely examine src and dst ports */ 1194 if (m->m_pkthdr.len < off + sizeof(*thp)) 1195 return; 1196 1197 bzero(&th, sizeof(th)); 1198 m_copydata(m, off, sizeof(*thp), (caddr_t)&th); 1199 1200 in6_pcbnotify(&tcb, sa, th.th_dport, 1201 (struct sockaddr *)ip6cp->ip6c_src, 1202 th.th_sport, cmd, NULL, notify); 1203 1204 inc.inc_fport = th.th_dport; 1205 inc.inc_lport = th.th_sport; 1206 inc.inc6_faddr = ((struct sockaddr_in6 *)sa)->sin6_addr; 1207 inc.inc6_laddr = ip6cp->ip6c_src->sin6_addr; 1208 inc.inc_isipv6 = 1; 1209 syncache_unreach(&inc, &th); 1210 } else 1211 in6_pcbnotify(&tcb, sa, 0, (const struct sockaddr *)sa6_src, 1212 0, cmd, NULL, notify); 1213} 1214#endif /* INET6 */ 1215 1216 1217/* 1218 * Following is where TCP initial sequence number generation occurs. 1219 * 1220 * There are two places where we must use initial sequence numbers: 1221 * 1. In SYN-ACK packets. 1222 * 2. In SYN packets. 1223 * 1224 * All ISNs for SYN-ACK packets are generated by the syncache. See 1225 * tcp_syncache.c for details. 1226 * 1227 * The ISNs in SYN packets must be monotonic; TIME_WAIT recycling 1228 * depends on this property. In addition, these ISNs should be 1229 * unguessable so as to prevent connection hijacking. To satisfy 1230 * the requirements of this situation, the algorithm outlined in 1231 * RFC 1948 is used to generate sequence numbers. 1232 * 1233 * Implementation details: 1234 * 1235 * Time is based off the system timer, and is corrected so that it 1236 * increases by one megabyte per second. This allows for proper 1237 * recycling on high speed LANs while still leaving over an hour 1238 * before rollover. 1239 * 1240 * net.inet.tcp.isn_reseed_interval controls the number of seconds 1241 * between seeding of isn_secret. This is normally set to zero, 1242 * as reseeding should not be necessary. 1243 * 1244 */ 1245 1246#define ISN_BYTES_PER_SECOND 1048576 1247 1248u_char isn_secret[32]; 1249int isn_last_reseed; 1250MD5_CTX isn_ctx; 1251 1252tcp_seq 1253tcp_new_isn(tp) 1254 struct tcpcb *tp; 1255{ 1256 u_int32_t md5_buffer[4]; 1257 tcp_seq new_isn; 1258 1259 /* Seed if this is the first use, reseed if requested. */ 1260 if ((isn_last_reseed == 0) || ((tcp_isn_reseed_interval > 0) && 1261 (((u_int)isn_last_reseed + (u_int)tcp_isn_reseed_interval*hz) 1262 < (u_int)ticks))) { 1263 read_random(&isn_secret, sizeof(isn_secret)); 1264 isn_last_reseed = ticks; 1265 } 1266 1267 /* Compute the md5 hash and return the ISN. */ 1268 MD5Init(&isn_ctx); 1269 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_fport, sizeof(u_short)); 1270 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_lport, sizeof(u_short)); 1271#ifdef INET6 1272 if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0) { 1273 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->in6p_faddr, 1274 sizeof(struct in6_addr)); 1275 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->in6p_laddr, 1276 sizeof(struct in6_addr)); 1277 } else 1278#endif 1279 { 1280 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_faddr, 1281 sizeof(struct in_addr)); 1282 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_laddr, 1283 sizeof(struct in_addr)); 1284 } 1285 MD5Update(&isn_ctx, (u_char *) &isn_secret, sizeof(isn_secret)); 1286 MD5Final((u_char *) &md5_buffer, &isn_ctx); 1287 new_isn = (tcp_seq) md5_buffer[0]; 1288 new_isn += ticks * (ISN_BYTES_PER_SECOND / hz); 1289 return new_isn; 1290} 1291 1292/* 1293 * When a source quench is received, close congestion window 1294 * to one segment. We will gradually open it again as we proceed. 1295 */ 1296struct inpcb * 1297tcp_quench(inp, errno) 1298 struct inpcb *inp; 1299 int errno; 1300{ 1301 struct tcpcb *tp = intotcpcb(inp); 1302 1303 if (tp) 1304 tp->snd_cwnd = tp->t_maxseg; 1305 return (inp); 1306} 1307 1308/* 1309 * When a specific ICMP unreachable message is received and the 1310 * connection state is SYN-SENT, drop the connection. This behavior 1311 * is controlled by the icmp_may_rst sysctl. 1312 */ 1313struct inpcb * 1314tcp_drop_syn_sent(inp, errno) 1315 struct inpcb *inp; 1316 int errno; 1317{ 1318 struct tcpcb *tp = intotcpcb(inp); 1319 1320 if (tp && tp->t_state == TCPS_SYN_SENT) { 1321 tcp_drop(tp, errno); 1322 return (struct inpcb *)0; 1323 } 1324 return inp; 1325} 1326 1327/* 1328 * When `need fragmentation' ICMP is received, update our idea of the MSS 1329 * based on the new value in the route. Also nudge TCP to send something, 1330 * since we know the packet we just sent was dropped. 1331 * This duplicates some code in the tcp_mss() function in tcp_input.c. 1332 */ 1333struct inpcb * 1334tcp_mtudisc(inp, errno) 1335 struct inpcb *inp; 1336 int errno; 1337{ 1338 struct tcpcb *tp = intotcpcb(inp); 1339 struct rmxp_tao tao; 1340 struct socket *so = inp->inp_socket; 1341 u_int maxmtu; 1342 u_int romtu; 1343 int mss; 1344#ifdef INET6 1345 int isipv6 = (tp->t_inpcb->inp_vflag & INP_IPV6) != 0; 1346#endif /* INET6 */ 1347 bzero(&tao, sizeof(tao)); 1348 1349 if (tp) { 1350 maxmtu = tcp_hc_getmtu(&inp->inp_inc); /* IPv4 and IPv6 */ 1351 romtu = 1352#ifdef INET6 1353 isipv6 ? tcp_maxmtu6(&inp->inp_inc) : 1354#endif /* INET6 */ 1355 tcp_maxmtu(&inp->inp_inc); 1356 if (!maxmtu) 1357 maxmtu = romtu; 1358 else 1359 maxmtu = min(maxmtu, romtu); 1360 if (!maxmtu) { 1361 tp->t_maxopd = tp->t_maxseg = 1362#ifdef INET6 1363 isipv6 ? tcp_v6mssdflt : 1364#endif /* INET6 */ 1365 tcp_mssdflt; 1366 return inp; 1367 } 1368 mss = maxmtu - 1369#ifdef INET6 1370 (isipv6 ? 1371 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) : 1372#endif /* INET6 */ 1373 sizeof(struct tcpiphdr) 1374#ifdef INET6 1375 ) 1376#endif /* INET6 */ 1377 ; 1378 1379 if (tcp_do_rfc1644) { 1380 tcp_hc_gettao(&inp->inp_inc, &tao); 1381 if (tao.tao_mssopt) 1382 mss = min(mss, tao.tao_mssopt); 1383 } 1384 /* 1385 * XXX - The above conditional probably violates the TCP 1386 * spec. The problem is that, since we don't know the 1387 * other end's MSS, we are supposed to use a conservative 1388 * default. But, if we do that, then MTU discovery will 1389 * never actually take place, because the conservative 1390 * default is much less than the MTUs typically seen 1391 * on the Internet today. For the moment, we'll sweep 1392 * this under the carpet. 1393 * 1394 * The conservative default might not actually be a problem 1395 * if the only case this occurs is when sending an initial 1396 * SYN with options and data to a host we've never talked 1397 * to before. Then, they will reply with an MSS value which 1398 * will get recorded and the new parameters should get 1399 * recomputed. For Further Study. 1400 */ 1401 if (tp->t_maxopd <= mss) 1402 return inp; 1403 tp->t_maxopd = mss; 1404 1405 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP && 1406 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP) 1407 mss -= TCPOLEN_TSTAMP_APPA; 1408 if ((tp->t_flags & (TF_REQ_CC|TF_NOOPT)) == TF_REQ_CC && 1409 (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC) 1410 mss -= TCPOLEN_CC_APPA; 1411#if (MCLBYTES & (MCLBYTES - 1)) == 0 1412 if (mss > MCLBYTES) 1413 mss &= ~(MCLBYTES-1); 1414#else 1415 if (mss > MCLBYTES) 1416 mss = mss / MCLBYTES * MCLBYTES; 1417#endif 1418 if (so->so_snd.sb_hiwat < mss) 1419 mss = so->so_snd.sb_hiwat; 1420 1421 tp->t_maxseg = mss; 1422 1423 tcpstat.tcps_mturesent++; 1424 tp->t_rtttime = 0; 1425 tp->snd_nxt = tp->snd_una; 1426 tcp_output(tp); 1427 } 1428 return inp; 1429} 1430 1431/* 1432 * Look-up the routing entry to the peer of this inpcb. If no route 1433 * is found and it cannot be allocated, then return NULL. This routine 1434 * is called by TCP routines that access the rmx structure and by tcp_mss 1435 * to get the interface MTU. 1436 */ 1437u_long 1438tcp_maxmtu(inc) 1439 struct in_conninfo *inc; 1440{ 1441 struct route sro; 1442 struct sockaddr_in *dst; 1443 struct ifnet *ifp; 1444 u_long maxmtu = 0; 1445 1446 KASSERT(inc != NULL, ("tcp_maxmtu with NULL in_conninfo pointer")); 1447 1448 bzero(&sro, sizeof(sro)); 1449 if (inc->inc_faddr.s_addr != INADDR_ANY) { 1450 dst = (struct sockaddr_in *)&sro.ro_dst; 1451 dst->sin_family = AF_INET; 1452 dst->sin_len = sizeof(*dst); 1453 dst->sin_addr = inc->inc_faddr; 1454 rtalloc_ign(&sro, RTF_CLONING); 1455 } 1456 if (sro.ro_rt != NULL) { 1457 ifp = sro.ro_rt->rt_ifp; 1458 if (sro.ro_rt->rt_rmx.rmx_mtu == 0) 1459 maxmtu = ifp->if_mtu; 1460 else 1461 maxmtu = min(sro.ro_rt->rt_rmx.rmx_mtu, ifp->if_mtu); 1462 RTFREE(sro.ro_rt); 1463 } 1464 return (maxmtu); 1465} 1466 1467#ifdef INET6 1468u_long 1469tcp_maxmtu6(inc) 1470 struct in_conninfo *inc; 1471{ 1472 struct route_in6 sro6; 1473 struct ifnet *ifp; 1474 u_long maxmtu = 0; 1475 1476 KASSERT(inc != NULL, ("tcp_maxmtu6 with NULL in_conninfo pointer")); 1477 1478 bzero(&sro6, sizeof(sro6)); 1479 if (!IN6_IS_ADDR_UNSPECIFIED(&inc->inc6_faddr)) { 1480 sro6.ro_dst.sin6_family = AF_INET6; 1481 sro6.ro_dst.sin6_len = sizeof(struct sockaddr_in6); 1482 sro6.ro_dst.sin6_addr = inc->inc6_faddr; 1483 rtalloc_ign((struct route *)&sro6, RTF_CLONING); 1484 } 1485 if (sro6.ro_rt != NULL) { 1486 ifp = sro6.ro_rt->rt_ifp; 1487 if (sro6.ro_rt->rt_rmx.rmx_mtu == 0) 1488 maxmtu = IN6_LINKMTU(sro6.ro_rt->rt_ifp); 1489 else 1490 maxmtu = min(sro6.ro_rt->rt_rmx.rmx_mtu, 1491 IN6_LINKMTU(sro6.ro_rt->rt_ifp)); 1492 RTFREE(sro6.ro_rt); 1493 } 1494 1495 return (maxmtu); 1496} 1497#endif /* INET6 */ 1498 1499#ifdef IPSEC 1500/* compute ESP/AH header size for TCP, including outer IP header. */ 1501size_t 1502ipsec_hdrsiz_tcp(tp) 1503 struct tcpcb *tp; 1504{ 1505 struct inpcb *inp; 1506 struct mbuf *m; 1507 size_t hdrsiz; 1508 struct ip *ip; 1509#ifdef INET6 1510 struct ip6_hdr *ip6; 1511#endif 1512 struct tcphdr *th; 1513 1514 if ((tp == NULL) || ((inp = tp->t_inpcb) == NULL)) 1515 return 0; 1516 MGETHDR(m, M_DONTWAIT, MT_DATA); 1517 if (!m) 1518 return 0; 1519 1520#ifdef INET6 1521 if ((inp->inp_vflag & INP_IPV6) != 0) { 1522 ip6 = mtod(m, struct ip6_hdr *); 1523 th = (struct tcphdr *)(ip6 + 1); 1524 m->m_pkthdr.len = m->m_len = 1525 sizeof(struct ip6_hdr) + sizeof(struct tcphdr); 1526 tcpip_fillheaders(inp, ip6, th); 1527 hdrsiz = ipsec6_hdrsiz(m, IPSEC_DIR_OUTBOUND, inp); 1528 } else 1529#endif /* INET6 */ 1530 { 1531 ip = mtod(m, struct ip *); 1532 th = (struct tcphdr *)(ip + 1); 1533 m->m_pkthdr.len = m->m_len = sizeof(struct tcpiphdr); 1534 tcpip_fillheaders(inp, ip, th); 1535 hdrsiz = ipsec4_hdrsiz(m, IPSEC_DIR_OUTBOUND, inp); 1536 } 1537 1538 m_free(m); 1539 return hdrsiz; 1540} 1541#endif /*IPSEC*/ 1542 1543/* 1544 * Move a TCP connection into TIME_WAIT state. 1545 * tcbinfo is unlocked. 1546 * inp is locked, and is unlocked before returning. 1547 */ 1548void 1549tcp_twstart(tp) 1550 struct tcpcb *tp; 1551{ 1552 struct tcptw *tw; 1553 struct inpcb *inp; 1554 int tw_time, acknow; 1555 struct socket *so; 1556 1557 tw = uma_zalloc(tcptw_zone, M_NOWAIT); 1558 if (tw == NULL) { 1559 tw = tcp_timer_2msl_tw(1); 1560 if (tw == NULL) { 1561 tcp_close(tp); 1562 return; 1563 } 1564 } 1565 inp = tp->t_inpcb; 1566 tw->tw_inpcb = inp; 1567 1568 /* 1569 * Recover last window size sent. 1570 */ 1571 tw->last_win = (tp->rcv_adv - tp->rcv_nxt) >> tp->rcv_scale; 1572 1573 /* 1574 * Set t_recent if timestamps are used on the connection. 1575 */ 1576 if ((tp->t_flags & (TF_REQ_TSTMP|TF_RCVD_TSTMP|TF_NOOPT)) == 1577 (TF_REQ_TSTMP|TF_RCVD_TSTMP)) 1578 tw->t_recent = tp->ts_recent; 1579 else 1580 tw->t_recent = 0; 1581 1582 tw->snd_nxt = tp->snd_nxt; 1583 tw->rcv_nxt = tp->rcv_nxt; 1584 tw->iss = tp->iss; 1585 tw->irs = tp->irs; 1586 tw->cc_recv = tp->cc_recv; 1587 tw->cc_send = tp->cc_send; 1588 tw->t_starttime = tp->t_starttime; 1589 tw->tw_time = 0; 1590 1591/* XXX 1592 * If this code will 1593 * be used for fin-wait-2 state also, then we may need 1594 * a ts_recent from the last segment. 1595 */ 1596 /* Shorten TIME_WAIT [RFC-1644, p.28] */ 1597 if (tp->cc_recv != 0 && (ticks - tp->t_starttime) < tcp_msl) { 1598 tw_time = tp->t_rxtcur * TCPTV_TWTRUNC; 1599 /* For T/TCP client, force ACK now. */ 1600 acknow = 1; 1601 } else { 1602 tw_time = 2 * tcp_msl; 1603 acknow = tp->t_flags & TF_ACKNOW; 1604 } 1605 tcp_discardcb(tp); 1606 so = inp->inp_socket; 1607 so->so_pcb = NULL; 1608 tw->tw_cred = crhold(so->so_cred); 1609 tw->tw_so_options = so->so_options; 1610 if (acknow) 1611 tcp_twrespond(tw, so, NULL, TH_ACK); 1612 sotryfree(so); 1613 inp->inp_socket = NULL; 1614 inp->inp_ppcb = (caddr_t)tw; 1615 inp->inp_vflag |= INP_TIMEWAIT; 1616 tcp_timer_2msl_reset(tw, tw_time); 1617 INP_UNLOCK(inp); 1618} 1619 1620/* 1621 * The appromixate rate of ISN increase of Microsoft TCP stacks; 1622 * the actual rate is slightly higher due to the addition of 1623 * random positive increments. 1624 * 1625 * Most other new OSes use semi-randomized ISN values, so we 1626 * do not need to worry about them. 1627 */ 1628#define MS_ISN_BYTES_PER_SECOND 250000 1629 1630/* 1631 * Determine if the ISN we will generate has advanced beyond the last 1632 * sequence number used by the previous connection. If so, indicate 1633 * that it is safe to recycle this tw socket by returning 1. 1634 */ 1635int 1636tcp_twrecycleable(struct tcptw *tw) 1637{ 1638 tcp_seq new_iss = tw->iss; 1639 tcp_seq new_irs = tw->irs; 1640 1641 new_iss += (ticks - tw->t_starttime) * (ISN_BYTES_PER_SECOND / hz); 1642 new_irs += (ticks - tw->t_starttime) * (MS_ISN_BYTES_PER_SECOND / hz); 1643 1644 if (SEQ_GT(new_iss, tw->snd_nxt) && SEQ_GT(new_irs, tw->rcv_nxt)) 1645 return 1; 1646 else 1647 return 0; 1648} 1649 1650struct tcptw * 1651tcp_twclose(struct tcptw *tw, int reuse) 1652{ 1653 struct inpcb *inp; 1654 1655 inp = tw->tw_inpcb; 1656 tw->tw_inpcb = NULL; 1657 tcp_timer_2msl_stop(tw); 1658 inp->inp_ppcb = NULL; 1659#ifdef INET6 1660 if (inp->inp_vflag & INP_IPV6PROTO) 1661 in6_pcbdetach(inp); 1662 else 1663#endif 1664 in_pcbdetach(inp); 1665 tcpstat.tcps_closed++; 1666 crfree(tw->tw_cred); 1667 tw->tw_cred = NULL; 1668 if (reuse) 1669 return (tw); 1670 uma_zfree(tcptw_zone, tw); 1671 return (NULL); 1672} 1673 1674/* 1675 * One of so and msrc must be non-NULL for use by the MAC Framework to 1676 * construct a label for ay resulting packet. 1677 */ 1678int 1679tcp_twrespond(struct tcptw *tw, struct socket *so, struct mbuf *msrc, 1680 int flags) 1681{ 1682 struct inpcb *inp = tw->tw_inpcb; 1683 struct tcphdr *th; 1684 struct mbuf *m; 1685 struct ip *ip = NULL; 1686 u_int8_t *optp; 1687 u_int hdrlen, optlen; 1688 int error; 1689#ifdef INET6 1690 struct ip6_hdr *ip6 = NULL; 1691 int isipv6 = inp->inp_inc.inc_isipv6; 1692#endif 1693 1694 KASSERT(so != NULL || msrc != NULL, 1695 ("tcp_twrespond: so and msrc NULL")); 1696 1697 m = m_gethdr(M_DONTWAIT, MT_HEADER); 1698 if (m == NULL) 1699 return (ENOBUFS); 1700 m->m_data += max_linkhdr; 1701 1702#ifdef MAC 1703 mac_create_mbuf_from_inpcb(inp, m); 1704#endif 1705 1706#ifdef INET6 1707 if (isipv6) { 1708 hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr); 1709 ip6 = mtod(m, struct ip6_hdr *); 1710 th = (struct tcphdr *)(ip6 + 1); 1711 tcpip_fillheaders(inp, ip6, th); 1712 } else 1713#endif 1714 { 1715 hdrlen = sizeof(struct tcpiphdr); 1716 ip = mtod(m, struct ip *); 1717 th = (struct tcphdr *)(ip + 1); 1718 tcpip_fillheaders(inp, ip, th); 1719 } 1720 optp = (u_int8_t *)(th + 1); 1721 1722 /* 1723 * Send a timestamp and echo-reply if both our side and our peer 1724 * have sent timestamps in our SYN's and this is not a RST. 1725 */ 1726 if (tw->t_recent && flags == TH_ACK) { 1727 u_int32_t *lp = (u_int32_t *)optp; 1728 1729 /* Form timestamp option as shown in appendix A of RFC 1323. */ 1730 *lp++ = htonl(TCPOPT_TSTAMP_HDR); 1731 *lp++ = htonl(ticks); 1732 *lp = htonl(tw->t_recent); 1733 optp += TCPOLEN_TSTAMP_APPA; 1734 } 1735 1736 /* 1737 * Send `CC-family' options if needed, and it's not a RST. 1738 */ 1739 if (tw->cc_recv != 0 && flags == TH_ACK) { 1740 u_int32_t *lp = (u_int32_t *)optp; 1741 1742 *lp++ = htonl(TCPOPT_CC_HDR(TCPOPT_CC)); 1743 *lp = htonl(tw->cc_send); 1744 optp += TCPOLEN_CC_APPA; 1745 } 1746 optlen = optp - (u_int8_t *)(th + 1); 1747 1748 m->m_len = hdrlen + optlen; 1749 m->m_pkthdr.len = m->m_len; 1750 1751 KASSERT(max_linkhdr + m->m_len <= MHLEN, ("tcptw: mbuf too small")); 1752 1753 th->th_seq = htonl(tw->snd_nxt); 1754 th->th_ack = htonl(tw->rcv_nxt); 1755 th->th_off = (sizeof(struct tcphdr) + optlen) >> 2; 1756 th->th_flags = flags; 1757 th->th_win = htons(tw->last_win); 1758 1759#ifdef INET6 1760 if (isipv6) { 1761 th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(struct ip6_hdr), 1762 sizeof(struct tcphdr) + optlen); 1763 ip6->ip6_hlim = in6_selecthlim(inp, NULL); 1764 error = ip6_output(m, inp->in6p_outputopts, NULL, 1765 (tw->tw_so_options & SO_DONTROUTE), NULL, NULL, inp); 1766 } else 1767#endif 1768 { 1769 th->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr, 1770 htons(sizeof(struct tcphdr) + optlen + IPPROTO_TCP)); 1771 m->m_pkthdr.csum_flags = CSUM_TCP; 1772 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum); 1773 ip->ip_len = m->m_pkthdr.len; 1774 if (path_mtu_discovery) 1775 ip->ip_off |= IP_DF; 1776 error = ip_output(m, inp->inp_options, NULL, 1777 (tw->tw_so_options & SO_DONTROUTE), NULL, inp); 1778 } 1779 if (flags & TH_ACK) 1780 tcpstat.tcps_sndacks++; 1781 else 1782 tcpstat.tcps_sndctrl++; 1783 tcpstat.tcps_sndtotal++; 1784 return (error); 1785} 1786 1787/* 1788 * TCP BANDWIDTH DELAY PRODUCT WINDOW LIMITING 1789 * 1790 * This code attempts to calculate the bandwidth-delay product as a 1791 * means of determining the optimal window size to maximize bandwidth, 1792 * minimize RTT, and avoid the over-allocation of buffers on interfaces and 1793 * routers. This code also does a fairly good job keeping RTTs in check 1794 * across slow links like modems. We implement an algorithm which is very 1795 * similar (but not meant to be) TCP/Vegas. The code operates on the 1796 * transmitter side of a TCP connection and so only effects the transmit 1797 * side of the connection. 1798 * 1799 * BACKGROUND: TCP makes no provision for the management of buffer space 1800 * at the end points or at the intermediate routers and switches. A TCP 1801 * stream, whether using NewReno or not, will eventually buffer as 1802 * many packets as it is able and the only reason this typically works is 1803 * due to the fairly small default buffers made available for a connection 1804 * (typicaly 16K or 32K). As machines use larger windows and/or window 1805 * scaling it is now fairly easy for even a single TCP connection to blow-out 1806 * all available buffer space not only on the local interface, but on 1807 * intermediate routers and switches as well. NewReno makes a misguided 1808 * attempt to 'solve' this problem by waiting for an actual failure to occur, 1809 * then backing off, then steadily increasing the window again until another 1810 * failure occurs, ad-infinitum. This results in terrible oscillation that 1811 * is only made worse as network loads increase and the idea of intentionally 1812 * blowing out network buffers is, frankly, a terrible way to manage network 1813 * resources. 1814 * 1815 * It is far better to limit the transmit window prior to the failure 1816 * condition being achieved. There are two general ways to do this: First 1817 * you can 'scan' through different transmit window sizes and locate the 1818 * point where the RTT stops increasing, indicating that you have filled the 1819 * pipe, then scan backwards until you note that RTT stops decreasing, then 1820 * repeat ad-infinitum. This method works in principle but has severe 1821 * implementation issues due to RTT variances, timer granularity, and 1822 * instability in the algorithm which can lead to many false positives and 1823 * create oscillations as well as interact badly with other TCP streams 1824 * implementing the same algorithm. 1825 * 1826 * The second method is to limit the window to the bandwidth delay product 1827 * of the link. This is the method we implement. RTT variances and our 1828 * own manipulation of the congestion window, bwnd, can potentially 1829 * destabilize the algorithm. For this reason we have to stabilize the 1830 * elements used to calculate the window. We do this by using the minimum 1831 * observed RTT, the long term average of the observed bandwidth, and 1832 * by adding two segments worth of slop. It isn't perfect but it is able 1833 * to react to changing conditions and gives us a very stable basis on 1834 * which to extend the algorithm. 1835 */ 1836void 1837tcp_xmit_bandwidth_limit(struct tcpcb *tp, tcp_seq ack_seq) 1838{ 1839 u_long bw; 1840 u_long bwnd; 1841 int save_ticks; 1842 1843 /* 1844 * If inflight_enable is disabled in the middle of a tcp connection, 1845 * make sure snd_bwnd is effectively disabled. 1846 */ 1847 if (tcp_inflight_enable == 0) { 1848 tp->snd_bwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT; 1849 tp->snd_bandwidth = 0; 1850 return; 1851 } 1852 1853 /* 1854 * Figure out the bandwidth. Due to the tick granularity this 1855 * is a very rough number and it MUST be averaged over a fairly 1856 * long period of time. XXX we need to take into account a link 1857 * that is not using all available bandwidth, but for now our 1858 * slop will ramp us up if this case occurs and the bandwidth later 1859 * increases. 1860 * 1861 * Note: if ticks rollover 'bw' may wind up negative. We must 1862 * effectively reset t_bw_rtttime for this case. 1863 */ 1864 save_ticks = ticks; 1865 if ((u_int)(save_ticks - tp->t_bw_rtttime) < 1) 1866 return; 1867 1868 bw = (int64_t)(ack_seq - tp->t_bw_rtseq) * hz / 1869 (save_ticks - tp->t_bw_rtttime); 1870 tp->t_bw_rtttime = save_ticks; 1871 tp->t_bw_rtseq = ack_seq; 1872 if (tp->t_bw_rtttime == 0 || (int)bw < 0) 1873 return; 1874 bw = ((int64_t)tp->snd_bandwidth * 15 + bw) >> 4; 1875 1876 tp->snd_bandwidth = bw; 1877 1878 /* 1879 * Calculate the semi-static bandwidth delay product, plus two maximal 1880 * segments. The additional slop puts us squarely in the sweet 1881 * spot and also handles the bandwidth run-up case and stabilization. 1882 * Without the slop we could be locking ourselves into a lower 1883 * bandwidth. 1884 * 1885 * Situations Handled: 1886 * (1) Prevents over-queueing of packets on LANs, especially on 1887 * high speed LANs, allowing larger TCP buffers to be 1888 * specified, and also does a good job preventing 1889 * over-queueing of packets over choke points like modems 1890 * (at least for the transmit side). 1891 * 1892 * (2) Is able to handle changing network loads (bandwidth 1893 * drops so bwnd drops, bandwidth increases so bwnd 1894 * increases). 1895 * 1896 * (3) Theoretically should stabilize in the face of multiple 1897 * connections implementing the same algorithm (this may need 1898 * a little work). 1899 * 1900 * (4) Stability value (defaults to 20 = 2 maximal packets) can 1901 * be adjusted with a sysctl but typically only needs to be 1902 * on very slow connections. A value no smaller then 5 1903 * should be used, but only reduce this default if you have 1904 * no other choice. 1905 */ 1906#define USERTT ((tp->t_srtt + tp->t_rttbest) / 2) 1907 bwnd = (int64_t)bw * USERTT / (hz << TCP_RTT_SHIFT) + tcp_inflight_stab * tp->t_maxseg / 10; 1908#undef USERTT 1909 1910 if (tcp_inflight_debug > 0) { 1911 static int ltime; 1912 if ((u_int)(ticks - ltime) >= hz / tcp_inflight_debug) { 1913 ltime = ticks; 1914 printf("%p bw %ld rttbest %d srtt %d bwnd %ld\n", 1915 tp, 1916 bw, 1917 tp->t_rttbest, 1918 tp->t_srtt, 1919 bwnd 1920 ); 1921 } 1922 } 1923 if ((long)bwnd < tcp_inflight_min) 1924 bwnd = tcp_inflight_min; 1925 if (bwnd > tcp_inflight_max) 1926 bwnd = tcp_inflight_max; 1927 if ((long)bwnd < tp->t_maxseg * 2) 1928 bwnd = tp->t_maxseg * 2; 1929 tp->snd_bwnd = bwnd; 1930} 1931 1932#ifdef TCP_SIGNATURE 1933/* 1934 * Callback function invoked by m_apply() to digest TCP segment data 1935 * contained within an mbuf chain. 1936 */ 1937static int 1938tcp_signature_apply(void *fstate, void *data, u_int len) 1939{ 1940 1941 MD5Update(fstate, (u_char *)data, len); 1942 return (0); 1943} 1944 1945/* 1946 * Compute TCP-MD5 hash of a TCPv4 segment. (RFC2385) 1947 * 1948 * Parameters: 1949 * m pointer to head of mbuf chain 1950 * off0 offset to TCP header within the mbuf chain 1951 * len length of TCP segment data, excluding options 1952 * optlen length of TCP segment options 1953 * buf pointer to storage for computed MD5 digest 1954 * direction direction of flow (IPSEC_DIR_INBOUND or OUTBOUND) 1955 * 1956 * We do this over ip, tcphdr, segment data, and the key in the SADB. 1957 * When called from tcp_input(), we can be sure that th_sum has been 1958 * zeroed out and verified already. 1959 * 1960 * This function is for IPv4 use only. Calling this function with an 1961 * IPv6 packet in the mbuf chain will yield undefined results. 1962 * 1963 * Return 0 if successful, otherwise return -1. 1964 * 1965 * XXX The key is retrieved from the system's PF_KEY SADB, by keying a 1966 * search with the destination IP address, and a 'magic SPI' to be 1967 * determined by the application. This is hardcoded elsewhere to 1179 1968 * right now. Another branch of this code exists which uses the SPD to 1969 * specify per-application flows but it is unstable. 1970 */ 1971int 1972tcp_signature_compute(struct mbuf *m, int off0, int len, int optlen, 1973 u_char *buf, u_int direction) 1974{ 1975 union sockaddr_union dst; 1976 struct ippseudo ippseudo; 1977 MD5_CTX ctx; 1978 int doff; 1979 struct ip *ip; 1980 struct ipovly *ipovly; 1981 struct secasvar *sav; 1982 struct tcphdr *th; 1983 u_short savecsum; 1984 1985 KASSERT(m != NULL, ("NULL mbuf chain")); 1986 KASSERT(buf != NULL, ("NULL signature pointer")); 1987 1988 /* Extract the destination from the IP header in the mbuf. */ 1989 ip = mtod(m, struct ip *); 1990 bzero(&dst, sizeof(union sockaddr_union)); 1991 dst.sa.sa_len = sizeof(struct sockaddr_in); 1992 dst.sa.sa_family = AF_INET; 1993 dst.sin.sin_addr = (direction == IPSEC_DIR_INBOUND) ? 1994 ip->ip_src : ip->ip_dst; 1995 1996 /* Look up an SADB entry which matches the address of the peer. */ 1997 sav = KEY_ALLOCSA(&dst, IPPROTO_TCP, htonl(TCP_SIG_SPI)); 1998 if (sav == NULL) { 1999 printf("%s: SADB lookup failed for %s\n", __func__, 2000 inet_ntoa(dst.sin.sin_addr)); 2001 return (EINVAL); 2002 } 2003 2004 MD5Init(&ctx); 2005 ipovly = (struct ipovly *)ip; 2006 th = (struct tcphdr *)((u_char *)ip + off0); 2007 doff = off0 + sizeof(struct tcphdr) + optlen; 2008 2009 /* 2010 * Step 1: Update MD5 hash with IP pseudo-header. 2011 * 2012 * XXX The ippseudo header MUST be digested in network byte order, 2013 * or else we'll fail the regression test. Assume all fields we've 2014 * been doing arithmetic on have been in host byte order. 2015 * XXX One cannot depend on ipovly->ih_len here. When called from 2016 * tcp_output(), the underlying ip_len member has not yet been set. 2017 */ 2018 ippseudo.ippseudo_src = ipovly->ih_src; 2019 ippseudo.ippseudo_dst = ipovly->ih_dst; 2020 ippseudo.ippseudo_pad = 0; 2021 ippseudo.ippseudo_p = IPPROTO_TCP; 2022 ippseudo.ippseudo_len = htons(len + sizeof(struct tcphdr) + optlen); 2023 MD5Update(&ctx, (char *)&ippseudo, sizeof(struct ippseudo)); 2024 2025 /* 2026 * Step 2: Update MD5 hash with TCP header, excluding options. 2027 * The TCP checksum must be set to zero. 2028 */ 2029 savecsum = th->th_sum; 2030 th->th_sum = 0; 2031 MD5Update(&ctx, (char *)th, sizeof(struct tcphdr)); 2032 th->th_sum = savecsum; 2033 2034 /* 2035 * Step 3: Update MD5 hash with TCP segment data. 2036 * Use m_apply() to avoid an early m_pullup(). 2037 */ 2038 if (len > 0) 2039 m_apply(m, doff, len, tcp_signature_apply, &ctx); 2040 2041 /* 2042 * Step 4: Update MD5 hash with shared secret. 2043 */ 2044 MD5Update(&ctx, _KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth)); 2045 MD5Final(buf, &ctx); 2046 2047 key_sa_recordxfer(sav, m); 2048 KEY_FREESAV(&sav); 2049 return (0); 2050} 2051#endif /* TCP_SIGNATURE */ 2052