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