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