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