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