1 /*- 2 * SPDX-License-Identifier: BSD-3-Clause 3 * 4 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995 5 * The Regents of the University of California. All rights reserved. 6 * 7 * Redistribution and use in source and binary forms, with or without 8 * modification, are permitted provided that the following conditions 9 * are met: 10 * 1. Redistributions of source code must retain the above copyright 11 * notice, this list of conditions and the following disclaimer. 12 * 2. Redistributions in binary form must reproduce the above copyright 13 * notice, this list of conditions and the following disclaimer in the 14 * documentation and/or other materials provided with the distribution. 15 * 3. Neither the name of the University nor the names of its contributors 16 * may be used to endorse or promote products derived from this software 17 * without specific prior written permission. 18 * 19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 29 * SUCH DAMAGE. 30 * 31 * @(#)tcp_subr.c 8.2 (Berkeley) 5/24/95 32 */ 33 34 #include <sys/cdefs.h> 35 __FBSDID("$FreeBSD$"); 36 37 #include "opt_inet.h" 38 #include "opt_inet6.h" 39 #include "opt_ipsec.h" 40 #include "opt_tcpdebug.h" 41 42 #include <sys/param.h> 43 #include <sys/systm.h> 44 #include <sys/callout.h> 45 #include <sys/eventhandler.h> 46 #ifdef TCP_HHOOK 47 #include <sys/hhook.h> 48 #endif 49 #include <sys/kernel.h> 50 #ifdef TCP_HHOOK 51 #include <sys/khelp.h> 52 #endif 53 #include <sys/sysctl.h> 54 #include <sys/jail.h> 55 #include <sys/malloc.h> 56 #include <sys/refcount.h> 57 #include <sys/mbuf.h> 58 #ifdef INET6 59 #include <sys/domain.h> 60 #endif 61 #include <sys/priv.h> 62 #include <sys/proc.h> 63 #include <sys/sdt.h> 64 #include <sys/socket.h> 65 #include <sys/socketvar.h> 66 #include <sys/protosw.h> 67 #include <sys/random.h> 68 69 #include <vm/uma.h> 70 71 #include <net/route.h> 72 #include <net/if.h> 73 #include <net/if_var.h> 74 #include <net/vnet.h> 75 76 #include <netinet/in.h> 77 #include <netinet/in_fib.h> 78 #include <netinet/in_kdtrace.h> 79 #include <netinet/in_pcb.h> 80 #include <netinet/in_systm.h> 81 #include <netinet/in_var.h> 82 #include <netinet/ip.h> 83 #include <netinet/ip_icmp.h> 84 #include <netinet/ip_var.h> 85 #ifdef INET6 86 #include <netinet/icmp6.h> 87 #include <netinet/ip6.h> 88 #include <netinet6/in6_fib.h> 89 #include <netinet6/in6_pcb.h> 90 #include <netinet6/ip6_var.h> 91 #include <netinet6/scope6_var.h> 92 #include <netinet6/nd6.h> 93 #endif 94 95 #include <netinet/tcp.h> 96 #include <netinet/tcp_fsm.h> 97 #include <netinet/tcp_seq.h> 98 #include <netinet/tcp_timer.h> 99 #include <netinet/tcp_var.h> 100 #include <netinet/tcp_log_buf.h> 101 #include <netinet/tcp_syncache.h> 102 #include <netinet/cc/cc.h> 103 #ifdef INET6 104 #include <netinet6/tcp6_var.h> 105 #endif 106 #include <netinet/tcpip.h> 107 #include <netinet/tcp_fastopen.h> 108 #ifdef TCPPCAP 109 #include <netinet/tcp_pcap.h> 110 #endif 111 #ifdef TCPDEBUG 112 #include <netinet/tcp_debug.h> 113 #endif 114 #ifdef INET6 115 #include <netinet6/ip6protosw.h> 116 #endif 117 #ifdef TCP_OFFLOAD 118 #include <netinet/tcp_offload.h> 119 #endif 120 121 #include <netipsec/ipsec_support.h> 122 123 #include <machine/in_cksum.h> 124 #include <sys/md5.h> 125 126 #include <security/mac/mac_framework.h> 127 128 VNET_DEFINE(int, tcp_mssdflt) = TCP_MSS; 129 #ifdef INET6 130 VNET_DEFINE(int, tcp_v6mssdflt) = TCP6_MSS; 131 #endif 132 133 struct rwlock tcp_function_lock; 134 135 static int 136 sysctl_net_inet_tcp_mss_check(SYSCTL_HANDLER_ARGS) 137 { 138 int error, new; 139 140 new = V_tcp_mssdflt; 141 error = sysctl_handle_int(oidp, &new, 0, req); 142 if (error == 0 && req->newptr) { 143 if (new < TCP_MINMSS) 144 error = EINVAL; 145 else 146 V_tcp_mssdflt = new; 147 } 148 return (error); 149 } 150 151 SYSCTL_PROC(_net_inet_tcp, TCPCTL_MSSDFLT, mssdflt, 152 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW, &VNET_NAME(tcp_mssdflt), 0, 153 &sysctl_net_inet_tcp_mss_check, "I", 154 "Default TCP Maximum Segment Size"); 155 156 #ifdef INET6 157 static int 158 sysctl_net_inet_tcp_mss_v6_check(SYSCTL_HANDLER_ARGS) 159 { 160 int error, new; 161 162 new = V_tcp_v6mssdflt; 163 error = sysctl_handle_int(oidp, &new, 0, req); 164 if (error == 0 && req->newptr) { 165 if (new < TCP_MINMSS) 166 error = EINVAL; 167 else 168 V_tcp_v6mssdflt = new; 169 } 170 return (error); 171 } 172 173 SYSCTL_PROC(_net_inet_tcp, TCPCTL_V6MSSDFLT, v6mssdflt, 174 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW, &VNET_NAME(tcp_v6mssdflt), 0, 175 &sysctl_net_inet_tcp_mss_v6_check, "I", 176 "Default TCP Maximum Segment Size for IPv6"); 177 #endif /* INET6 */ 178 179 /* 180 * Minimum MSS we accept and use. This prevents DoS attacks where 181 * we are forced to a ridiculous low MSS like 20 and send hundreds 182 * of packets instead of one. The effect scales with the available 183 * bandwidth and quickly saturates the CPU and network interface 184 * with packet generation and sending. Set to zero to disable MINMSS 185 * checking. This setting prevents us from sending too small packets. 186 */ 187 VNET_DEFINE(int, tcp_minmss) = TCP_MINMSS; 188 SYSCTL_INT(_net_inet_tcp, OID_AUTO, minmss, CTLFLAG_VNET | CTLFLAG_RW, 189 &VNET_NAME(tcp_minmss), 0, 190 "Minimum TCP Maximum Segment Size"); 191 192 VNET_DEFINE(int, tcp_do_rfc1323) = 1; 193 SYSCTL_INT(_net_inet_tcp, TCPCTL_DO_RFC1323, rfc1323, CTLFLAG_VNET | CTLFLAG_RW, 194 &VNET_NAME(tcp_do_rfc1323), 0, 195 "Enable rfc1323 (high performance TCP) extensions"); 196 197 static int tcp_log_debug = 0; 198 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_debug, CTLFLAG_RW, 199 &tcp_log_debug, 0, "Log errors caused by incoming TCP segments"); 200 201 static int tcp_tcbhashsize; 202 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tcbhashsize, CTLFLAG_RDTUN | CTLFLAG_NOFETCH, 203 &tcp_tcbhashsize, 0, "Size of TCP control-block hashtable"); 204 205 static int do_tcpdrain = 1; 206 SYSCTL_INT(_net_inet_tcp, OID_AUTO, do_tcpdrain, CTLFLAG_RW, &do_tcpdrain, 0, 207 "Enable tcp_drain routine for extra help when low on mbufs"); 208 209 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, pcbcount, CTLFLAG_VNET | CTLFLAG_RD, 210 &VNET_NAME(tcbinfo.ipi_count), 0, "Number of active PCBs"); 211 212 static VNET_DEFINE(int, icmp_may_rst) = 1; 213 #define V_icmp_may_rst VNET(icmp_may_rst) 214 SYSCTL_INT(_net_inet_tcp, OID_AUTO, icmp_may_rst, CTLFLAG_VNET | CTLFLAG_RW, 215 &VNET_NAME(icmp_may_rst), 0, 216 "Certain ICMP unreachable messages may abort connections in SYN_SENT"); 217 218 static VNET_DEFINE(int, tcp_isn_reseed_interval) = 0; 219 #define V_tcp_isn_reseed_interval VNET(tcp_isn_reseed_interval) 220 SYSCTL_INT(_net_inet_tcp, OID_AUTO, isn_reseed_interval, CTLFLAG_VNET | CTLFLAG_RW, 221 &VNET_NAME(tcp_isn_reseed_interval), 0, 222 "Seconds between reseeding of ISN secret"); 223 224 static int tcp_soreceive_stream; 225 SYSCTL_INT(_net_inet_tcp, OID_AUTO, soreceive_stream, CTLFLAG_RDTUN, 226 &tcp_soreceive_stream, 0, "Using soreceive_stream for TCP sockets"); 227 228 VNET_DEFINE(uma_zone_t, sack_hole_zone); 229 #define V_sack_hole_zone VNET(sack_hole_zone) 230 231 #ifdef TCP_HHOOK 232 VNET_DEFINE(struct hhook_head *, tcp_hhh[HHOOK_TCP_LAST+1]); 233 #endif 234 235 static struct inpcb *tcp_notify(struct inpcb *, int); 236 static struct inpcb *tcp_mtudisc_notify(struct inpcb *, int); 237 static void tcp_mtudisc(struct inpcb *, int); 238 static char * tcp_log_addr(struct in_conninfo *inc, struct tcphdr *th, 239 void *ip4hdr, const void *ip6hdr); 240 241 242 static struct tcp_function_block tcp_def_funcblk = { 243 "default", 244 tcp_output, 245 tcp_do_segment, 246 tcp_default_ctloutput, 247 NULL, 248 NULL, 249 NULL, 250 NULL, 251 NULL, 252 NULL, 253 0, 254 0 255 }; 256 257 int t_functions_inited = 0; 258 struct tcp_funchead t_functions; 259 static struct tcp_function_block *tcp_func_set_ptr = &tcp_def_funcblk; 260 261 static void 262 init_tcp_functions(void) 263 { 264 if (t_functions_inited == 0) { 265 TAILQ_INIT(&t_functions); 266 rw_init_flags(&tcp_function_lock, "tcp_func_lock" , 0); 267 t_functions_inited = 1; 268 } 269 } 270 271 static struct tcp_function_block * 272 find_tcp_functions_locked(struct tcp_function_set *fs) 273 { 274 struct tcp_function *f; 275 struct tcp_function_block *blk=NULL; 276 277 TAILQ_FOREACH(f, &t_functions, tf_next) { 278 if (strcmp(f->tf_name, fs->function_set_name) == 0) { 279 blk = f->tf_fb; 280 break; 281 } 282 } 283 return(blk); 284 } 285 286 static struct tcp_function_block * 287 find_tcp_fb_locked(struct tcp_function_block *blk, struct tcp_function **s) 288 { 289 struct tcp_function_block *rblk=NULL; 290 struct tcp_function *f; 291 292 TAILQ_FOREACH(f, &t_functions, tf_next) { 293 if (f->tf_fb == blk) { 294 rblk = blk; 295 if (s) { 296 *s = f; 297 } 298 break; 299 } 300 } 301 return (rblk); 302 } 303 304 struct tcp_function_block * 305 find_and_ref_tcp_functions(struct tcp_function_set *fs) 306 { 307 struct tcp_function_block *blk; 308 309 rw_rlock(&tcp_function_lock); 310 blk = find_tcp_functions_locked(fs); 311 if (blk) 312 refcount_acquire(&blk->tfb_refcnt); 313 rw_runlock(&tcp_function_lock); 314 return(blk); 315 } 316 317 struct tcp_function_block * 318 find_and_ref_tcp_fb(struct tcp_function_block *blk) 319 { 320 struct tcp_function_block *rblk; 321 322 rw_rlock(&tcp_function_lock); 323 rblk = find_tcp_fb_locked(blk, NULL); 324 if (rblk) 325 refcount_acquire(&rblk->tfb_refcnt); 326 rw_runlock(&tcp_function_lock); 327 return(rblk); 328 } 329 330 331 static int 332 sysctl_net_inet_default_tcp_functions(SYSCTL_HANDLER_ARGS) 333 { 334 int error=ENOENT; 335 struct tcp_function_set fs; 336 struct tcp_function_block *blk; 337 338 memset(&fs, 0, sizeof(fs)); 339 rw_rlock(&tcp_function_lock); 340 blk = find_tcp_fb_locked(tcp_func_set_ptr, NULL); 341 if (blk) { 342 /* Found him */ 343 strcpy(fs.function_set_name, blk->tfb_tcp_block_name); 344 fs.pcbcnt = blk->tfb_refcnt; 345 } 346 rw_runlock(&tcp_function_lock); 347 error = sysctl_handle_string(oidp, fs.function_set_name, 348 sizeof(fs.function_set_name), req); 349 350 /* Check for error or no change */ 351 if (error != 0 || req->newptr == NULL) 352 return(error); 353 354 rw_wlock(&tcp_function_lock); 355 blk = find_tcp_functions_locked(&fs); 356 if ((blk == NULL) || 357 (blk->tfb_flags & TCP_FUNC_BEING_REMOVED)) { 358 error = ENOENT; 359 goto done; 360 } 361 tcp_func_set_ptr = blk; 362 done: 363 rw_wunlock(&tcp_function_lock); 364 return (error); 365 } 366 367 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, functions_default, 368 CTLTYPE_STRING | CTLFLAG_RW, 369 NULL, 0, sysctl_net_inet_default_tcp_functions, "A", 370 "Set/get the default TCP functions"); 371 372 static int 373 sysctl_net_inet_list_available(SYSCTL_HANDLER_ARGS) 374 { 375 int error, cnt, linesz; 376 struct tcp_function *f; 377 char *buffer, *cp; 378 size_t bufsz, outsz; 379 bool alias; 380 381 cnt = 0; 382 rw_rlock(&tcp_function_lock); 383 TAILQ_FOREACH(f, &t_functions, tf_next) { 384 cnt++; 385 } 386 rw_runlock(&tcp_function_lock); 387 388 bufsz = (cnt+2) * ((TCP_FUNCTION_NAME_LEN_MAX * 2) + 13) + 1; 389 buffer = malloc(bufsz, M_TEMP, M_WAITOK); 390 391 error = 0; 392 cp = buffer; 393 394 linesz = snprintf(cp, bufsz, "\n%-32s%c %-32s %s\n", "Stack", 'D', 395 "Alias", "PCB count"); 396 cp += linesz; 397 bufsz -= linesz; 398 outsz = linesz; 399 400 rw_rlock(&tcp_function_lock); 401 TAILQ_FOREACH(f, &t_functions, tf_next) { 402 alias = (f->tf_name != f->tf_fb->tfb_tcp_block_name); 403 linesz = snprintf(cp, bufsz, "%-32s%c %-32s %u\n", 404 f->tf_fb->tfb_tcp_block_name, 405 (f->tf_fb == tcp_func_set_ptr) ? '*' : ' ', 406 alias ? f->tf_name : "-", 407 f->tf_fb->tfb_refcnt); 408 if (linesz >= bufsz) { 409 error = EOVERFLOW; 410 break; 411 } 412 cp += linesz; 413 bufsz -= linesz; 414 outsz += linesz; 415 } 416 rw_runlock(&tcp_function_lock); 417 if (error == 0) 418 error = sysctl_handle_string(oidp, buffer, outsz + 1, req); 419 free(buffer, M_TEMP); 420 return (error); 421 } 422 423 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, functions_available, 424 CTLTYPE_STRING|CTLFLAG_RD, 425 NULL, 0, sysctl_net_inet_list_available, "A", 426 "list available TCP Function sets"); 427 428 /* 429 * Exports one (struct tcp_function_id) for each non-alias. 430 */ 431 static int 432 sysctl_net_inet_list_func_ids(SYSCTL_HANDLER_ARGS) 433 { 434 int error, cnt; 435 struct tcp_function *f; 436 struct tcp_function_id tfi; 437 438 /* 439 * We don't allow writes. 440 */ 441 if (req->newptr != NULL) 442 return (EINVAL); 443 444 /* 445 * Wire the old buffer so we can directly copy the functions to 446 * user space without dropping the lock. 447 */ 448 if (req->oldptr != NULL) { 449 error = sysctl_wire_old_buffer(req, 0); 450 if (error) 451 return (error); 452 } 453 454 /* 455 * Walk the list, comparing the name of the function entry and 456 * function block to determine which is an alias. 457 * If exporting the list, copy out matching entries. Otherwise, 458 * just record the total length. 459 */ 460 cnt = 0; 461 rw_rlock(&tcp_function_lock); 462 TAILQ_FOREACH(f, &t_functions, tf_next) { 463 if (strncmp(f->tf_name, f->tf_fb->tfb_tcp_block_name, 464 TCP_FUNCTION_NAME_LEN_MAX)) 465 continue; 466 if (req->oldptr != NULL) { 467 tfi.tfi_id = f->tf_fb->tfb_id; 468 (void)strncpy(tfi.tfi_name, f->tf_name, 469 TCP_FUNCTION_NAME_LEN_MAX); 470 tfi.tfi_name[TCP_FUNCTION_NAME_LEN_MAX - 1] = '\0'; 471 error = SYSCTL_OUT(req, &tfi, sizeof(tfi)); 472 /* 473 * Don't stop on error, as that is the 474 * mechanism we use to accumulate length 475 * information if the buffer was too short. 476 */ 477 } else 478 cnt++; 479 } 480 rw_runlock(&tcp_function_lock); 481 if (req->oldptr == NULL) 482 error = SYSCTL_OUT(req, NULL, 483 (cnt + 1) * sizeof(struct tcp_function_id)); 484 485 return (error); 486 } 487 488 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, function_ids, 489 CTLTYPE_OPAQUE | CTLFLAG_SKIP | CTLFLAG_RD | CTLFLAG_MPSAFE, 490 NULL, 0, sysctl_net_inet_list_func_ids, "S,tcp_function_id", 491 "List TCP function block name-to-ID mappings"); 492 493 /* 494 * Target size of TCP PCB hash tables. Must be a power of two. 495 * 496 * Note that this can be overridden by the kernel environment 497 * variable net.inet.tcp.tcbhashsize 498 */ 499 #ifndef TCBHASHSIZE 500 #define TCBHASHSIZE 0 501 #endif 502 503 /* 504 * XXX 505 * Callouts should be moved into struct tcp directly. They are currently 506 * separate because the tcpcb structure is exported to userland for sysctl 507 * parsing purposes, which do not know about callouts. 508 */ 509 struct tcpcb_mem { 510 struct tcpcb tcb; 511 struct tcp_timer tt; 512 struct cc_var ccv; 513 #ifdef TCP_HHOOK 514 struct osd osd; 515 #endif 516 }; 517 518 static VNET_DEFINE(uma_zone_t, tcpcb_zone); 519 #define V_tcpcb_zone VNET(tcpcb_zone) 520 521 MALLOC_DEFINE(M_TCPLOG, "tcplog", "TCP address and flags print buffers"); 522 MALLOC_DEFINE(M_TCPFUNCTIONS, "tcpfunc", "TCP function set memory"); 523 524 static struct mtx isn_mtx; 525 526 #define ISN_LOCK_INIT() mtx_init(&isn_mtx, "isn_mtx", NULL, MTX_DEF) 527 #define ISN_LOCK() mtx_lock(&isn_mtx) 528 #define ISN_UNLOCK() mtx_unlock(&isn_mtx) 529 530 /* 531 * TCP initialization. 532 */ 533 static void 534 tcp_zone_change(void *tag) 535 { 536 537 uma_zone_set_max(V_tcbinfo.ipi_zone, maxsockets); 538 uma_zone_set_max(V_tcpcb_zone, maxsockets); 539 tcp_tw_zone_change(); 540 } 541 542 static int 543 tcp_inpcb_init(void *mem, int size, int flags) 544 { 545 struct inpcb *inp = mem; 546 547 INP_LOCK_INIT(inp, "inp", "tcpinp"); 548 return (0); 549 } 550 551 /* 552 * Take a value and get the next power of 2 that doesn't overflow. 553 * Used to size the tcp_inpcb hash buckets. 554 */ 555 static int 556 maketcp_hashsize(int size) 557 { 558 int hashsize; 559 560 /* 561 * auto tune. 562 * get the next power of 2 higher than maxsockets. 563 */ 564 hashsize = 1 << fls(size); 565 /* catch overflow, and just go one power of 2 smaller */ 566 if (hashsize < size) { 567 hashsize = 1 << (fls(size) - 1); 568 } 569 return (hashsize); 570 } 571 572 static volatile int next_tcp_stack_id = 1; 573 574 /* 575 * Register a TCP function block with the name provided in the names 576 * array. (Note that this function does NOT automatically register 577 * blk->tfb_tcp_block_name as a stack name. Therefore, you should 578 * explicitly include blk->tfb_tcp_block_name in the list of names if 579 * you wish to register the stack with that name.) 580 * 581 * Either all name registrations will succeed or all will fail. If 582 * a name registration fails, the function will update the num_names 583 * argument to point to the array index of the name that encountered 584 * the failure. 585 * 586 * Returns 0 on success, or an error code on failure. 587 */ 588 int 589 register_tcp_functions_as_names(struct tcp_function_block *blk, int wait, 590 const char *names[], int *num_names) 591 { 592 struct tcp_function *n; 593 struct tcp_function_set fs; 594 int error, i; 595 596 KASSERT(names != NULL && *num_names > 0, 597 ("%s: Called with 0-length name list", __func__)); 598 KASSERT(names != NULL, ("%s: Called with NULL name list", __func__)); 599 600 if (t_functions_inited == 0) { 601 init_tcp_functions(); 602 } 603 if ((blk->tfb_tcp_output == NULL) || 604 (blk->tfb_tcp_do_segment == NULL) || 605 (blk->tfb_tcp_ctloutput == NULL) || 606 (strlen(blk->tfb_tcp_block_name) == 0)) { 607 /* 608 * These functions are required and you 609 * need a name. 610 */ 611 *num_names = 0; 612 return (EINVAL); 613 } 614 if (blk->tfb_tcp_timer_stop_all || 615 blk->tfb_tcp_timer_activate || 616 blk->tfb_tcp_timer_active || 617 blk->tfb_tcp_timer_stop) { 618 /* 619 * If you define one timer function you 620 * must have them all. 621 */ 622 if ((blk->tfb_tcp_timer_stop_all == NULL) || 623 (blk->tfb_tcp_timer_activate == NULL) || 624 (blk->tfb_tcp_timer_active == NULL) || 625 (blk->tfb_tcp_timer_stop == NULL)) { 626 *num_names = 0; 627 return (EINVAL); 628 } 629 } 630 631 refcount_init(&blk->tfb_refcnt, 0); 632 blk->tfb_flags = 0; 633 blk->tfb_id = atomic_fetchadd_int(&next_tcp_stack_id, 1); 634 for (i = 0; i < *num_names; i++) { 635 n = malloc(sizeof(struct tcp_function), M_TCPFUNCTIONS, wait); 636 if (n == NULL) { 637 error = ENOMEM; 638 goto cleanup; 639 } 640 n->tf_fb = blk; 641 642 (void)strncpy(fs.function_set_name, names[i], 643 TCP_FUNCTION_NAME_LEN_MAX); 644 fs.function_set_name[TCP_FUNCTION_NAME_LEN_MAX - 1] = '\0'; 645 rw_wlock(&tcp_function_lock); 646 if (find_tcp_functions_locked(&fs) != NULL) { 647 /* Duplicate name space not allowed */ 648 rw_wunlock(&tcp_function_lock); 649 free(n, M_TCPFUNCTIONS); 650 error = EALREADY; 651 goto cleanup; 652 } 653 (void)strncpy(n->tf_name, names[i], TCP_FUNCTION_NAME_LEN_MAX); 654 n->tf_name[TCP_FUNCTION_NAME_LEN_MAX - 1] = '\0'; 655 TAILQ_INSERT_TAIL(&t_functions, n, tf_next); 656 rw_wunlock(&tcp_function_lock); 657 } 658 return(0); 659 660 cleanup: 661 /* 662 * Deregister the names we just added. Because registration failed 663 * for names[i], we don't need to deregister that name. 664 */ 665 *num_names = i; 666 rw_wlock(&tcp_function_lock); 667 while (--i >= 0) { 668 TAILQ_FOREACH(n, &t_functions, tf_next) { 669 if (!strncmp(n->tf_name, names[i], 670 TCP_FUNCTION_NAME_LEN_MAX)) { 671 TAILQ_REMOVE(&t_functions, n, tf_next); 672 n->tf_fb = NULL; 673 free(n, M_TCPFUNCTIONS); 674 break; 675 } 676 } 677 } 678 rw_wunlock(&tcp_function_lock); 679 return (error); 680 } 681 682 /* 683 * Register a TCP function block using the name provided in the name 684 * argument. 685 * 686 * Returns 0 on success, or an error code on failure. 687 */ 688 int 689 register_tcp_functions_as_name(struct tcp_function_block *blk, const char *name, 690 int wait) 691 { 692 const char *name_list[1]; 693 int num_names, rv; 694 695 num_names = 1; 696 if (name != NULL) 697 name_list[0] = name; 698 else 699 name_list[0] = blk->tfb_tcp_block_name; 700 rv = register_tcp_functions_as_names(blk, wait, name_list, &num_names); 701 return (rv); 702 } 703 704 /* 705 * Register a TCP function block using the name defined in 706 * blk->tfb_tcp_block_name. 707 * 708 * Returns 0 on success, or an error code on failure. 709 */ 710 int 711 register_tcp_functions(struct tcp_function_block *blk, int wait) 712 { 713 714 return (register_tcp_functions_as_name(blk, NULL, wait)); 715 } 716 717 int 718 deregister_tcp_functions(struct tcp_function_block *blk) 719 { 720 struct tcp_function *f; 721 int error=ENOENT; 722 723 if (strcmp(blk->tfb_tcp_block_name, "default") == 0) { 724 /* You can't un-register the default */ 725 return (EPERM); 726 } 727 rw_wlock(&tcp_function_lock); 728 if (blk == tcp_func_set_ptr) { 729 /* You can't free the current default */ 730 rw_wunlock(&tcp_function_lock); 731 return (EBUSY); 732 } 733 if (blk->tfb_refcnt) { 734 /* Still tcb attached, mark it. */ 735 blk->tfb_flags |= TCP_FUNC_BEING_REMOVED; 736 rw_wunlock(&tcp_function_lock); 737 return (EBUSY); 738 } 739 while (find_tcp_fb_locked(blk, &f) != NULL) { 740 /* Found */ 741 TAILQ_REMOVE(&t_functions, f, tf_next); 742 f->tf_fb = NULL; 743 free(f, M_TCPFUNCTIONS); 744 error = 0; 745 } 746 rw_wunlock(&tcp_function_lock); 747 return (error); 748 } 749 750 void 751 tcp_init(void) 752 { 753 const char *tcbhash_tuneable; 754 int hashsize; 755 756 tcbhash_tuneable = "net.inet.tcp.tcbhashsize"; 757 758 #ifdef TCP_HHOOK 759 if (hhook_head_register(HHOOK_TYPE_TCP, HHOOK_TCP_EST_IN, 760 &V_tcp_hhh[HHOOK_TCP_EST_IN], HHOOK_NOWAIT|HHOOK_HEADISINVNET) != 0) 761 printf("%s: WARNING: unable to register helper hook\n", __func__); 762 if (hhook_head_register(HHOOK_TYPE_TCP, HHOOK_TCP_EST_OUT, 763 &V_tcp_hhh[HHOOK_TCP_EST_OUT], HHOOK_NOWAIT|HHOOK_HEADISINVNET) != 0) 764 printf("%s: WARNING: unable to register helper hook\n", __func__); 765 #endif 766 hashsize = TCBHASHSIZE; 767 TUNABLE_INT_FETCH(tcbhash_tuneable, &hashsize); 768 if (hashsize == 0) { 769 /* 770 * Auto tune the hash size based on maxsockets. 771 * A perfect hash would have a 1:1 mapping 772 * (hashsize = maxsockets) however it's been 773 * suggested that O(2) average is better. 774 */ 775 hashsize = maketcp_hashsize(maxsockets / 4); 776 /* 777 * Our historical default is 512, 778 * do not autotune lower than this. 779 */ 780 if (hashsize < 512) 781 hashsize = 512; 782 if (bootverbose && IS_DEFAULT_VNET(curvnet)) 783 printf("%s: %s auto tuned to %d\n", __func__, 784 tcbhash_tuneable, hashsize); 785 } 786 /* 787 * We require a hashsize to be a power of two. 788 * Previously if it was not a power of two we would just reset it 789 * back to 512, which could be a nasty surprise if you did not notice 790 * the error message. 791 * Instead what we do is clip it to the closest power of two lower 792 * than the specified hash value. 793 */ 794 if (!powerof2(hashsize)) { 795 int oldhashsize = hashsize; 796 797 hashsize = maketcp_hashsize(hashsize); 798 /* prevent absurdly low value */ 799 if (hashsize < 16) 800 hashsize = 16; 801 printf("%s: WARNING: TCB hash size not a power of 2, " 802 "clipped from %d to %d.\n", __func__, oldhashsize, 803 hashsize); 804 } 805 in_pcbinfo_init(&V_tcbinfo, "tcp", &V_tcb, hashsize, hashsize, 806 "tcp_inpcb", tcp_inpcb_init, IPI_HASHFIELDS_4TUPLE); 807 808 /* 809 * These have to be type stable for the benefit of the timers. 810 */ 811 V_tcpcb_zone = uma_zcreate("tcpcb", sizeof(struct tcpcb_mem), 812 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0); 813 uma_zone_set_max(V_tcpcb_zone, maxsockets); 814 uma_zone_set_warning(V_tcpcb_zone, "kern.ipc.maxsockets limit reached"); 815 816 tcp_tw_init(); 817 syncache_init(); 818 tcp_hc_init(); 819 820 TUNABLE_INT_FETCH("net.inet.tcp.sack.enable", &V_tcp_do_sack); 821 V_sack_hole_zone = uma_zcreate("sackhole", sizeof(struct sackhole), 822 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0); 823 824 tcp_fastopen_init(); 825 826 /* Skip initialization of globals for non-default instances. */ 827 if (!IS_DEFAULT_VNET(curvnet)) 828 return; 829 830 tcp_reass_global_init(); 831 832 /* XXX virtualize those bellow? */ 833 tcp_delacktime = TCPTV_DELACK; 834 tcp_keepinit = TCPTV_KEEP_INIT; 835 tcp_keepidle = TCPTV_KEEP_IDLE; 836 tcp_keepintvl = TCPTV_KEEPINTVL; 837 tcp_maxpersistidle = TCPTV_KEEP_IDLE; 838 tcp_msl = TCPTV_MSL; 839 tcp_rexmit_min = TCPTV_MIN; 840 if (tcp_rexmit_min < 1) 841 tcp_rexmit_min = 1; 842 tcp_persmin = TCPTV_PERSMIN; 843 tcp_persmax = TCPTV_PERSMAX; 844 tcp_rexmit_slop = TCPTV_CPU_VAR; 845 tcp_finwait2_timeout = TCPTV_FINWAIT2_TIMEOUT; 846 tcp_tcbhashsize = hashsize; 847 /* Setup the tcp function block list */ 848 init_tcp_functions(); 849 register_tcp_functions(&tcp_def_funcblk, M_WAITOK); 850 #ifdef TCP_BLACKBOX 851 /* Initialize the TCP logging data. */ 852 tcp_log_init(); 853 #endif 854 855 if (tcp_soreceive_stream) { 856 #ifdef INET 857 tcp_usrreqs.pru_soreceive = soreceive_stream; 858 #endif 859 #ifdef INET6 860 tcp6_usrreqs.pru_soreceive = soreceive_stream; 861 #endif /* INET6 */ 862 } 863 864 #ifdef INET6 865 #define TCP_MINPROTOHDR (sizeof(struct ip6_hdr) + sizeof(struct tcphdr)) 866 #else /* INET6 */ 867 #define TCP_MINPROTOHDR (sizeof(struct tcpiphdr)) 868 #endif /* INET6 */ 869 if (max_protohdr < TCP_MINPROTOHDR) 870 max_protohdr = TCP_MINPROTOHDR; 871 if (max_linkhdr + TCP_MINPROTOHDR > MHLEN) 872 panic("tcp_init"); 873 #undef TCP_MINPROTOHDR 874 875 ISN_LOCK_INIT(); 876 EVENTHANDLER_REGISTER(shutdown_pre_sync, tcp_fini, NULL, 877 SHUTDOWN_PRI_DEFAULT); 878 EVENTHANDLER_REGISTER(maxsockets_change, tcp_zone_change, NULL, 879 EVENTHANDLER_PRI_ANY); 880 #ifdef TCPPCAP 881 tcp_pcap_init(); 882 #endif 883 } 884 885 #ifdef VIMAGE 886 static void 887 tcp_destroy(void *unused __unused) 888 { 889 int n; 890 #ifdef TCP_HHOOK 891 int error; 892 #endif 893 894 /* 895 * All our processes are gone, all our sockets should be cleaned 896 * up, which means, we should be past the tcp_discardcb() calls. 897 * Sleep to let all tcpcb timers really disappear and cleanup. 898 */ 899 for (;;) { 900 INP_LIST_RLOCK(&V_tcbinfo); 901 n = V_tcbinfo.ipi_count; 902 INP_LIST_RUNLOCK(&V_tcbinfo); 903 if (n == 0) 904 break; 905 pause("tcpdes", hz / 10); 906 } 907 tcp_hc_destroy(); 908 syncache_destroy(); 909 tcp_tw_destroy(); 910 in_pcbinfo_destroy(&V_tcbinfo); 911 /* tcp_discardcb() clears the sack_holes up. */ 912 uma_zdestroy(V_sack_hole_zone); 913 uma_zdestroy(V_tcpcb_zone); 914 915 /* 916 * Cannot free the zone until all tcpcbs are released as we attach 917 * the allocations to them. 918 */ 919 tcp_fastopen_destroy(); 920 921 #ifdef TCP_HHOOK 922 error = hhook_head_deregister(V_tcp_hhh[HHOOK_TCP_EST_IN]); 923 if (error != 0) { 924 printf("%s: WARNING: unable to deregister helper hook " 925 "type=%d, id=%d: error %d returned\n", __func__, 926 HHOOK_TYPE_TCP, HHOOK_TCP_EST_IN, error); 927 } 928 error = hhook_head_deregister(V_tcp_hhh[HHOOK_TCP_EST_OUT]); 929 if (error != 0) { 930 printf("%s: WARNING: unable to deregister helper hook " 931 "type=%d, id=%d: error %d returned\n", __func__, 932 HHOOK_TYPE_TCP, HHOOK_TCP_EST_OUT, error); 933 } 934 #endif 935 } 936 VNET_SYSUNINIT(tcp, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH, tcp_destroy, NULL); 937 #endif 938 939 void 940 tcp_fini(void *xtp) 941 { 942 943 } 944 945 /* 946 * Fill in the IP and TCP headers for an outgoing packet, given the tcpcb. 947 * tcp_template used to store this data in mbufs, but we now recopy it out 948 * of the tcpcb each time to conserve mbufs. 949 */ 950 void 951 tcpip_fillheaders(struct inpcb *inp, void *ip_ptr, void *tcp_ptr) 952 { 953 struct tcphdr *th = (struct tcphdr *)tcp_ptr; 954 955 INP_WLOCK_ASSERT(inp); 956 957 #ifdef INET6 958 if ((inp->inp_vflag & INP_IPV6) != 0) { 959 struct ip6_hdr *ip6; 960 961 ip6 = (struct ip6_hdr *)ip_ptr; 962 ip6->ip6_flow = (ip6->ip6_flow & ~IPV6_FLOWINFO_MASK) | 963 (inp->inp_flow & IPV6_FLOWINFO_MASK); 964 ip6->ip6_vfc = (ip6->ip6_vfc & ~IPV6_VERSION_MASK) | 965 (IPV6_VERSION & IPV6_VERSION_MASK); 966 ip6->ip6_nxt = IPPROTO_TCP; 967 ip6->ip6_plen = htons(sizeof(struct tcphdr)); 968 ip6->ip6_src = inp->in6p_laddr; 969 ip6->ip6_dst = inp->in6p_faddr; 970 } 971 #endif /* INET6 */ 972 #if defined(INET6) && defined(INET) 973 else 974 #endif 975 #ifdef INET 976 { 977 struct ip *ip; 978 979 ip = (struct ip *)ip_ptr; 980 ip->ip_v = IPVERSION; 981 ip->ip_hl = 5; 982 ip->ip_tos = inp->inp_ip_tos; 983 ip->ip_len = 0; 984 ip->ip_id = 0; 985 ip->ip_off = 0; 986 ip->ip_ttl = inp->inp_ip_ttl; 987 ip->ip_sum = 0; 988 ip->ip_p = IPPROTO_TCP; 989 ip->ip_src = inp->inp_laddr; 990 ip->ip_dst = inp->inp_faddr; 991 } 992 #endif /* INET */ 993 th->th_sport = inp->inp_lport; 994 th->th_dport = inp->inp_fport; 995 th->th_seq = 0; 996 th->th_ack = 0; 997 th->th_x2 = 0; 998 th->th_off = 5; 999 th->th_flags = 0; 1000 th->th_win = 0; 1001 th->th_urp = 0; 1002 th->th_sum = 0; /* in_pseudo() is called later for ipv4 */ 1003 } 1004 1005 /* 1006 * Create template to be used to send tcp packets on a connection. 1007 * Allocates an mbuf and fills in a skeletal tcp/ip header. The only 1008 * use for this function is in keepalives, which use tcp_respond. 1009 */ 1010 struct tcptemp * 1011 tcpip_maketemplate(struct inpcb *inp) 1012 { 1013 struct tcptemp *t; 1014 1015 t = malloc(sizeof(*t), M_TEMP, M_NOWAIT); 1016 if (t == NULL) 1017 return (NULL); 1018 tcpip_fillheaders(inp, (void *)&t->tt_ipgen, (void *)&t->tt_t); 1019 return (t); 1020 } 1021 1022 /* 1023 * Send a single message to the TCP at address specified by 1024 * the given TCP/IP header. If m == NULL, then we make a copy 1025 * of the tcpiphdr at th and send directly to the addressed host. 1026 * This is used to force keep alive messages out using the TCP 1027 * template for a connection. If flags are given then we send 1028 * a message back to the TCP which originated the segment th, 1029 * and discard the mbuf containing it and any other attached mbufs. 1030 * 1031 * In any case the ack and sequence number of the transmitted 1032 * segment are as specified by the parameters. 1033 * 1034 * NOTE: If m != NULL, then th must point to *inside* the mbuf. 1035 */ 1036 void 1037 tcp_respond(struct tcpcb *tp, void *ipgen, struct tcphdr *th, struct mbuf *m, 1038 tcp_seq ack, tcp_seq seq, int flags) 1039 { 1040 struct tcpopt to; 1041 struct inpcb *inp; 1042 struct ip *ip; 1043 struct mbuf *optm; 1044 struct tcphdr *nth; 1045 u_char *optp; 1046 #ifdef INET6 1047 struct ip6_hdr *ip6; 1048 int isipv6; 1049 #endif /* INET6 */ 1050 int optlen, tlen, win; 1051 bool incl_opts; 1052 1053 KASSERT(tp != NULL || m != NULL, ("tcp_respond: tp and m both NULL")); 1054 1055 #ifdef INET6 1056 isipv6 = ((struct ip *)ipgen)->ip_v == (IPV6_VERSION >> 4); 1057 ip6 = ipgen; 1058 #endif /* INET6 */ 1059 ip = ipgen; 1060 1061 if (tp != NULL) { 1062 inp = tp->t_inpcb; 1063 KASSERT(inp != NULL, ("tcp control block w/o inpcb")); 1064 INP_WLOCK_ASSERT(inp); 1065 } else 1066 inp = NULL; 1067 1068 incl_opts = false; 1069 win = 0; 1070 if (tp != NULL) { 1071 if (!(flags & TH_RST)) { 1072 win = sbspace(&inp->inp_socket->so_rcv); 1073 if (win > TCP_MAXWIN << tp->rcv_scale) 1074 win = TCP_MAXWIN << tp->rcv_scale; 1075 } 1076 if ((tp->t_flags & TF_NOOPT) == 0) 1077 incl_opts = true; 1078 } 1079 if (m == NULL) { 1080 m = m_gethdr(M_NOWAIT, MT_DATA); 1081 if (m == NULL) 1082 return; 1083 m->m_data += max_linkhdr; 1084 #ifdef INET6 1085 if (isipv6) { 1086 bcopy((caddr_t)ip6, mtod(m, caddr_t), 1087 sizeof(struct ip6_hdr)); 1088 ip6 = mtod(m, struct ip6_hdr *); 1089 nth = (struct tcphdr *)(ip6 + 1); 1090 } else 1091 #endif /* INET6 */ 1092 { 1093 bcopy((caddr_t)ip, mtod(m, caddr_t), sizeof(struct ip)); 1094 ip = mtod(m, struct ip *); 1095 nth = (struct tcphdr *)(ip + 1); 1096 } 1097 bcopy((caddr_t)th, (caddr_t)nth, sizeof(struct tcphdr)); 1098 flags = TH_ACK; 1099 } else if (!M_WRITABLE(m)) { 1100 struct mbuf *n; 1101 1102 /* Can't reuse 'm', allocate a new mbuf. */ 1103 n = m_gethdr(M_NOWAIT, MT_DATA); 1104 if (n == NULL) { 1105 m_freem(m); 1106 return; 1107 } 1108 1109 if (!m_dup_pkthdr(n, m, M_NOWAIT)) { 1110 m_freem(m); 1111 m_freem(n); 1112 return; 1113 } 1114 1115 n->m_data += max_linkhdr; 1116 /* m_len is set later */ 1117 #define xchg(a,b,type) { type t; t=a; a=b; b=t; } 1118 #ifdef INET6 1119 if (isipv6) { 1120 bcopy((caddr_t)ip6, mtod(n, caddr_t), 1121 sizeof(struct ip6_hdr)); 1122 ip6 = mtod(n, struct ip6_hdr *); 1123 xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr); 1124 nth = (struct tcphdr *)(ip6 + 1); 1125 } else 1126 #endif /* INET6 */ 1127 { 1128 bcopy((caddr_t)ip, mtod(n, caddr_t), sizeof(struct ip)); 1129 ip = mtod(n, struct ip *); 1130 xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, uint32_t); 1131 nth = (struct tcphdr *)(ip + 1); 1132 } 1133 bcopy((caddr_t)th, (caddr_t)nth, sizeof(struct tcphdr)); 1134 xchg(nth->th_dport, nth->th_sport, uint16_t); 1135 th = nth; 1136 m_freem(m); 1137 m = n; 1138 } else { 1139 /* 1140 * reuse the mbuf. 1141 * XXX MRT We inherit the FIB, which is lucky. 1142 */ 1143 m_freem(m->m_next); 1144 m->m_next = NULL; 1145 m->m_data = (caddr_t)ipgen; 1146 /* m_len is set later */ 1147 #ifdef INET6 1148 if (isipv6) { 1149 xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr); 1150 nth = (struct tcphdr *)(ip6 + 1); 1151 } else 1152 #endif /* INET6 */ 1153 { 1154 xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, uint32_t); 1155 nth = (struct tcphdr *)(ip + 1); 1156 } 1157 if (th != nth) { 1158 /* 1159 * this is usually a case when an extension header 1160 * exists between the IPv6 header and the 1161 * TCP header. 1162 */ 1163 nth->th_sport = th->th_sport; 1164 nth->th_dport = th->th_dport; 1165 } 1166 xchg(nth->th_dport, nth->th_sport, uint16_t); 1167 #undef xchg 1168 } 1169 tlen = 0; 1170 #ifdef INET6 1171 if (isipv6) 1172 tlen = sizeof (struct ip6_hdr) + sizeof (struct tcphdr); 1173 #endif 1174 #if defined(INET) && defined(INET6) 1175 else 1176 #endif 1177 #ifdef INET 1178 tlen = sizeof (struct tcpiphdr); 1179 #endif 1180 #ifdef INVARIANTS 1181 m->m_len = 0; 1182 KASSERT(M_TRAILINGSPACE(m) >= tlen, 1183 ("Not enough trailing space for message (m=%p, need=%d, have=%ld)", 1184 m, tlen, (long)M_TRAILINGSPACE(m))); 1185 #endif 1186 m->m_len = tlen; 1187 to.to_flags = 0; 1188 if (incl_opts) { 1189 /* Make sure we have room. */ 1190 if (M_TRAILINGSPACE(m) < TCP_MAXOLEN) { 1191 m->m_next = m_get(M_NOWAIT, MT_DATA); 1192 if (m->m_next) { 1193 optp = mtod(m->m_next, u_char *); 1194 optm = m->m_next; 1195 } else 1196 incl_opts = false; 1197 } else { 1198 optp = (u_char *) (nth + 1); 1199 optm = m; 1200 } 1201 } 1202 if (incl_opts) { 1203 /* Timestamps. */ 1204 if (tp->t_flags & TF_RCVD_TSTMP) { 1205 to.to_tsval = tcp_ts_getticks() + tp->ts_offset; 1206 to.to_tsecr = tp->ts_recent; 1207 to.to_flags |= TOF_TS; 1208 } 1209 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE) 1210 /* TCP-MD5 (RFC2385). */ 1211 if (tp->t_flags & TF_SIGNATURE) 1212 to.to_flags |= TOF_SIGNATURE; 1213 #endif 1214 /* Add the options. */ 1215 tlen += optlen = tcp_addoptions(&to, optp); 1216 1217 /* Update m_len in the correct mbuf. */ 1218 optm->m_len += optlen; 1219 } else 1220 optlen = 0; 1221 #ifdef INET6 1222 if (isipv6) { 1223 ip6->ip6_flow = 0; 1224 ip6->ip6_vfc = IPV6_VERSION; 1225 ip6->ip6_nxt = IPPROTO_TCP; 1226 ip6->ip6_plen = htons(tlen - sizeof(*ip6)); 1227 } 1228 #endif 1229 #if defined(INET) && defined(INET6) 1230 else 1231 #endif 1232 #ifdef INET 1233 { 1234 ip->ip_len = htons(tlen); 1235 ip->ip_ttl = V_ip_defttl; 1236 if (V_path_mtu_discovery) 1237 ip->ip_off |= htons(IP_DF); 1238 } 1239 #endif 1240 m->m_pkthdr.len = tlen; 1241 m->m_pkthdr.rcvif = NULL; 1242 #ifdef MAC 1243 if (inp != NULL) { 1244 /* 1245 * Packet is associated with a socket, so allow the 1246 * label of the response to reflect the socket label. 1247 */ 1248 INP_WLOCK_ASSERT(inp); 1249 mac_inpcb_create_mbuf(inp, m); 1250 } else { 1251 /* 1252 * Packet is not associated with a socket, so possibly 1253 * update the label in place. 1254 */ 1255 mac_netinet_tcp_reply(m); 1256 } 1257 #endif 1258 nth->th_seq = htonl(seq); 1259 nth->th_ack = htonl(ack); 1260 nth->th_x2 = 0; 1261 nth->th_off = (sizeof (struct tcphdr) + optlen) >> 2; 1262 nth->th_flags = flags; 1263 if (tp != NULL) 1264 nth->th_win = htons((u_short) (win >> tp->rcv_scale)); 1265 else 1266 nth->th_win = htons((u_short)win); 1267 nth->th_urp = 0; 1268 1269 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE) 1270 if (to.to_flags & TOF_SIGNATURE) { 1271 if (!TCPMD5_ENABLED() || 1272 TCPMD5_OUTPUT(m, nth, to.to_signature) != 0) { 1273 m_freem(m); 1274 return; 1275 } 1276 } 1277 #endif 1278 1279 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum); 1280 #ifdef INET6 1281 if (isipv6) { 1282 m->m_pkthdr.csum_flags = CSUM_TCP_IPV6; 1283 nth->th_sum = in6_cksum_pseudo(ip6, 1284 tlen - sizeof(struct ip6_hdr), IPPROTO_TCP, 0); 1285 ip6->ip6_hlim = in6_selecthlim(tp != NULL ? tp->t_inpcb : 1286 NULL, NULL); 1287 } 1288 #endif /* INET6 */ 1289 #if defined(INET6) && defined(INET) 1290 else 1291 #endif 1292 #ifdef INET 1293 { 1294 m->m_pkthdr.csum_flags = CSUM_TCP; 1295 nth->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr, 1296 htons((u_short)(tlen - sizeof(struct ip) + ip->ip_p))); 1297 } 1298 #endif /* INET */ 1299 #ifdef TCPDEBUG 1300 if (tp == NULL || (inp->inp_socket->so_options & SO_DEBUG)) 1301 tcp_trace(TA_OUTPUT, 0, tp, mtod(m, void *), th, 0); 1302 #endif 1303 TCP_PROBE3(debug__output, tp, th, m); 1304 if (flags & TH_RST) 1305 TCP_PROBE5(accept__refused, NULL, NULL, m, tp, nth); 1306 1307 #ifdef INET6 1308 if (isipv6) { 1309 TCP_PROBE5(send, NULL, tp, ip6, tp, nth); 1310 (void)ip6_output(m, NULL, NULL, 0, NULL, NULL, inp); 1311 } 1312 #endif /* INET6 */ 1313 #if defined(INET) && defined(INET6) 1314 else 1315 #endif 1316 #ifdef INET 1317 { 1318 TCP_PROBE5(send, NULL, tp, ip, tp, nth); 1319 (void)ip_output(m, NULL, NULL, 0, NULL, inp); 1320 } 1321 #endif 1322 } 1323 1324 /* 1325 * Create a new TCP control block, making an 1326 * empty reassembly queue and hooking it to the argument 1327 * protocol control block. The `inp' parameter must have 1328 * come from the zone allocator set up in tcp_init(). 1329 */ 1330 struct tcpcb * 1331 tcp_newtcpcb(struct inpcb *inp) 1332 { 1333 struct tcpcb_mem *tm; 1334 struct tcpcb *tp; 1335 #ifdef INET6 1336 int isipv6 = (inp->inp_vflag & INP_IPV6) != 0; 1337 #endif /* INET6 */ 1338 1339 tm = uma_zalloc(V_tcpcb_zone, M_NOWAIT | M_ZERO); 1340 if (tm == NULL) 1341 return (NULL); 1342 tp = &tm->tcb; 1343 1344 /* Initialise cc_var struct for this tcpcb. */ 1345 tp->ccv = &tm->ccv; 1346 tp->ccv->type = IPPROTO_TCP; 1347 tp->ccv->ccvc.tcp = tp; 1348 rw_rlock(&tcp_function_lock); 1349 tp->t_fb = tcp_func_set_ptr; 1350 refcount_acquire(&tp->t_fb->tfb_refcnt); 1351 rw_runlock(&tcp_function_lock); 1352 /* 1353 * Use the current system default CC algorithm. 1354 */ 1355 CC_LIST_RLOCK(); 1356 KASSERT(!STAILQ_EMPTY(&cc_list), ("cc_list is empty!")); 1357 CC_ALGO(tp) = CC_DEFAULT(); 1358 CC_LIST_RUNLOCK(); 1359 1360 if (CC_ALGO(tp)->cb_init != NULL) 1361 if (CC_ALGO(tp)->cb_init(tp->ccv) > 0) { 1362 if (tp->t_fb->tfb_tcp_fb_fini) 1363 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 1); 1364 refcount_release(&tp->t_fb->tfb_refcnt); 1365 uma_zfree(V_tcpcb_zone, tm); 1366 return (NULL); 1367 } 1368 1369 #ifdef TCP_HHOOK 1370 tp->osd = &tm->osd; 1371 if (khelp_init_osd(HELPER_CLASS_TCP, tp->osd)) { 1372 if (tp->t_fb->tfb_tcp_fb_fini) 1373 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 1); 1374 refcount_release(&tp->t_fb->tfb_refcnt); 1375 uma_zfree(V_tcpcb_zone, tm); 1376 return (NULL); 1377 } 1378 #endif 1379 1380 #ifdef VIMAGE 1381 tp->t_vnet = inp->inp_vnet; 1382 #endif 1383 tp->t_timers = &tm->tt; 1384 /* LIST_INIT(&tp->t_segq); */ /* XXX covered by M_ZERO */ 1385 tp->t_maxseg = 1386 #ifdef INET6 1387 isipv6 ? V_tcp_v6mssdflt : 1388 #endif /* INET6 */ 1389 V_tcp_mssdflt; 1390 1391 /* Set up our timeouts. */ 1392 callout_init(&tp->t_timers->tt_rexmt, 1); 1393 callout_init(&tp->t_timers->tt_persist, 1); 1394 callout_init(&tp->t_timers->tt_keep, 1); 1395 callout_init(&tp->t_timers->tt_2msl, 1); 1396 callout_init(&tp->t_timers->tt_delack, 1); 1397 1398 if (V_tcp_do_rfc1323) 1399 tp->t_flags = (TF_REQ_SCALE|TF_REQ_TSTMP); 1400 if (V_tcp_do_sack) 1401 tp->t_flags |= TF_SACK_PERMIT; 1402 TAILQ_INIT(&tp->snd_holes); 1403 /* 1404 * The tcpcb will hold a reference on its inpcb until tcp_discardcb() 1405 * is called. 1406 */ 1407 in_pcbref(inp); /* Reference for tcpcb */ 1408 tp->t_inpcb = inp; 1409 1410 /* 1411 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no 1412 * rtt estimate. Set rttvar so that srtt + 4 * rttvar gives 1413 * reasonable initial retransmit time. 1414 */ 1415 tp->t_srtt = TCPTV_SRTTBASE; 1416 tp->t_rttvar = ((TCPTV_RTOBASE - TCPTV_SRTTBASE) << TCP_RTTVAR_SHIFT) / 4; 1417 tp->t_rttmin = tcp_rexmit_min; 1418 tp->t_rxtcur = TCPTV_RTOBASE; 1419 tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT; 1420 tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT; 1421 tp->t_rcvtime = ticks; 1422 /* 1423 * IPv4 TTL initialization is necessary for an IPv6 socket as well, 1424 * because the socket may be bound to an IPv6 wildcard address, 1425 * which may match an IPv4-mapped IPv6 address. 1426 */ 1427 inp->inp_ip_ttl = V_ip_defttl; 1428 inp->inp_ppcb = tp; 1429 #ifdef TCPPCAP 1430 /* 1431 * Init the TCP PCAP queues. 1432 */ 1433 tcp_pcap_tcpcb_init(tp); 1434 #endif 1435 #ifdef TCP_BLACKBOX 1436 /* Initialize the per-TCPCB log data. */ 1437 tcp_log_tcpcbinit(tp); 1438 #endif 1439 if (tp->t_fb->tfb_tcp_fb_init) { 1440 (*tp->t_fb->tfb_tcp_fb_init)(tp); 1441 } 1442 return (tp); /* XXX */ 1443 } 1444 1445 /* 1446 * Switch the congestion control algorithm back to NewReno for any active 1447 * control blocks using an algorithm which is about to go away. 1448 * This ensures the CC framework can allow the unload to proceed without leaving 1449 * any dangling pointers which would trigger a panic. 1450 * Returning non-zero would inform the CC framework that something went wrong 1451 * and it would be unsafe to allow the unload to proceed. However, there is no 1452 * way for this to occur with this implementation so we always return zero. 1453 */ 1454 int 1455 tcp_ccalgounload(struct cc_algo *unload_algo) 1456 { 1457 struct cc_algo *tmpalgo; 1458 struct inpcb *inp; 1459 struct tcpcb *tp; 1460 VNET_ITERATOR_DECL(vnet_iter); 1461 1462 /* 1463 * Check all active control blocks across all network stacks and change 1464 * any that are using "unload_algo" back to NewReno. If "unload_algo" 1465 * requires cleanup code to be run, call it. 1466 */ 1467 VNET_LIST_RLOCK(); 1468 VNET_FOREACH(vnet_iter) { 1469 CURVNET_SET(vnet_iter); 1470 INP_INFO_WLOCK(&V_tcbinfo); 1471 /* 1472 * New connections already part way through being initialised 1473 * with the CC algo we're removing will not race with this code 1474 * because the INP_INFO_WLOCK is held during initialisation. We 1475 * therefore don't enter the loop below until the connection 1476 * list has stabilised. 1477 */ 1478 LIST_FOREACH(inp, &V_tcb, inp_list) { 1479 INP_WLOCK(inp); 1480 /* Important to skip tcptw structs. */ 1481 if (!(inp->inp_flags & INP_TIMEWAIT) && 1482 (tp = intotcpcb(inp)) != NULL) { 1483 /* 1484 * By holding INP_WLOCK here, we are assured 1485 * that the connection is not currently 1486 * executing inside the CC module's functions 1487 * i.e. it is safe to make the switch back to 1488 * NewReno. 1489 */ 1490 if (CC_ALGO(tp) == unload_algo) { 1491 tmpalgo = CC_ALGO(tp); 1492 /* NewReno does not require any init. */ 1493 CC_ALGO(tp) = &newreno_cc_algo; 1494 if (tmpalgo->cb_destroy != NULL) 1495 tmpalgo->cb_destroy(tp->ccv); 1496 } 1497 } 1498 INP_WUNLOCK(inp); 1499 } 1500 INP_INFO_WUNLOCK(&V_tcbinfo); 1501 CURVNET_RESTORE(); 1502 } 1503 VNET_LIST_RUNLOCK(); 1504 1505 return (0); 1506 } 1507 1508 /* 1509 * Drop a TCP connection, reporting 1510 * the specified error. If connection is synchronized, 1511 * then send a RST to peer. 1512 */ 1513 struct tcpcb * 1514 tcp_drop(struct tcpcb *tp, int errno) 1515 { 1516 struct socket *so = tp->t_inpcb->inp_socket; 1517 1518 INP_INFO_LOCK_ASSERT(&V_tcbinfo); 1519 INP_WLOCK_ASSERT(tp->t_inpcb); 1520 1521 if (TCPS_HAVERCVDSYN(tp->t_state)) { 1522 tcp_state_change(tp, TCPS_CLOSED); 1523 (void) tp->t_fb->tfb_tcp_output(tp); 1524 TCPSTAT_INC(tcps_drops); 1525 } else 1526 TCPSTAT_INC(tcps_conndrops); 1527 if (errno == ETIMEDOUT && tp->t_softerror) 1528 errno = tp->t_softerror; 1529 so->so_error = errno; 1530 return (tcp_close(tp)); 1531 } 1532 1533 void 1534 tcp_discardcb(struct tcpcb *tp) 1535 { 1536 struct inpcb *inp = tp->t_inpcb; 1537 struct socket *so = inp->inp_socket; 1538 #ifdef INET6 1539 int isipv6 = (inp->inp_vflag & INP_IPV6) != 0; 1540 #endif /* INET6 */ 1541 int released; 1542 1543 INP_WLOCK_ASSERT(inp); 1544 1545 /* 1546 * Make sure that all of our timers are stopped before we delete the 1547 * PCB. 1548 * 1549 * If stopping a timer fails, we schedule a discard function in same 1550 * callout, and the last discard function called will take care of 1551 * deleting the tcpcb. 1552 */ 1553 tp->t_timers->tt_draincnt = 0; 1554 tcp_timer_stop(tp, TT_REXMT); 1555 tcp_timer_stop(tp, TT_PERSIST); 1556 tcp_timer_stop(tp, TT_KEEP); 1557 tcp_timer_stop(tp, TT_2MSL); 1558 tcp_timer_stop(tp, TT_DELACK); 1559 if (tp->t_fb->tfb_tcp_timer_stop_all) { 1560 /* 1561 * Call the stop-all function of the methods, 1562 * this function should call the tcp_timer_stop() 1563 * method with each of the function specific timeouts. 1564 * That stop will be called via the tfb_tcp_timer_stop() 1565 * which should use the async drain function of the 1566 * callout system (see tcp_var.h). 1567 */ 1568 tp->t_fb->tfb_tcp_timer_stop_all(tp); 1569 } 1570 1571 /* 1572 * If we got enough samples through the srtt filter, 1573 * save the rtt and rttvar in the routing entry. 1574 * 'Enough' is arbitrarily defined as 4 rtt samples. 1575 * 4 samples is enough for the srtt filter to converge 1576 * to within enough % of the correct value; fewer samples 1577 * and we could save a bogus rtt. The danger is not high 1578 * as tcp quickly recovers from everything. 1579 * XXX: Works very well but needs some more statistics! 1580 */ 1581 if (tp->t_rttupdated >= 4) { 1582 struct hc_metrics_lite metrics; 1583 uint32_t ssthresh; 1584 1585 bzero(&metrics, sizeof(metrics)); 1586 /* 1587 * Update the ssthresh always when the conditions below 1588 * are satisfied. This gives us better new start value 1589 * for the congestion avoidance for new connections. 1590 * ssthresh is only set if packet loss occurred on a session. 1591 * 1592 * XXXRW: 'so' may be NULL here, and/or socket buffer may be 1593 * being torn down. Ideally this code would not use 'so'. 1594 */ 1595 ssthresh = tp->snd_ssthresh; 1596 if (ssthresh != 0 && ssthresh < so->so_snd.sb_hiwat / 2) { 1597 /* 1598 * convert the limit from user data bytes to 1599 * packets then to packet data bytes. 1600 */ 1601 ssthresh = (ssthresh + tp->t_maxseg / 2) / tp->t_maxseg; 1602 if (ssthresh < 2) 1603 ssthresh = 2; 1604 ssthresh *= (tp->t_maxseg + 1605 #ifdef INET6 1606 (isipv6 ? sizeof (struct ip6_hdr) + 1607 sizeof (struct tcphdr) : 1608 #endif 1609 sizeof (struct tcpiphdr) 1610 #ifdef INET6 1611 ) 1612 #endif 1613 ); 1614 } else 1615 ssthresh = 0; 1616 metrics.rmx_ssthresh = ssthresh; 1617 1618 metrics.rmx_rtt = tp->t_srtt; 1619 metrics.rmx_rttvar = tp->t_rttvar; 1620 metrics.rmx_cwnd = tp->snd_cwnd; 1621 metrics.rmx_sendpipe = 0; 1622 metrics.rmx_recvpipe = 0; 1623 1624 tcp_hc_update(&inp->inp_inc, &metrics); 1625 } 1626 1627 /* free the reassembly queue, if any */ 1628 tcp_reass_flush(tp); 1629 1630 #ifdef TCP_OFFLOAD 1631 /* Disconnect offload device, if any. */ 1632 if (tp->t_flags & TF_TOE) 1633 tcp_offload_detach(tp); 1634 #endif 1635 1636 tcp_free_sackholes(tp); 1637 1638 #ifdef TCPPCAP 1639 /* Free the TCP PCAP queues. */ 1640 tcp_pcap_drain(&(tp->t_inpkts)); 1641 tcp_pcap_drain(&(tp->t_outpkts)); 1642 #endif 1643 1644 /* Allow the CC algorithm to clean up after itself. */ 1645 if (CC_ALGO(tp)->cb_destroy != NULL) 1646 CC_ALGO(tp)->cb_destroy(tp->ccv); 1647 1648 #ifdef TCP_HHOOK 1649 khelp_destroy_osd(tp->osd); 1650 #endif 1651 1652 CC_ALGO(tp) = NULL; 1653 inp->inp_ppcb = NULL; 1654 if (tp->t_timers->tt_draincnt == 0) { 1655 /* We own the last reference on tcpcb, let's free it. */ 1656 #ifdef TCP_BLACKBOX 1657 tcp_log_tcpcbfini(tp); 1658 #endif 1659 TCPSTATES_DEC(tp->t_state); 1660 if (tp->t_fb->tfb_tcp_fb_fini) 1661 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 1); 1662 refcount_release(&tp->t_fb->tfb_refcnt); 1663 tp->t_inpcb = NULL; 1664 uma_zfree(V_tcpcb_zone, tp); 1665 released = in_pcbrele_wlocked(inp); 1666 KASSERT(!released, ("%s: inp %p should not have been released " 1667 "here", __func__, inp)); 1668 } 1669 } 1670 1671 void 1672 tcp_timer_discard(void *ptp) 1673 { 1674 struct inpcb *inp; 1675 struct tcpcb *tp; 1676 1677 tp = (struct tcpcb *)ptp; 1678 CURVNET_SET(tp->t_vnet); 1679 INP_INFO_RLOCK(&V_tcbinfo); 1680 inp = tp->t_inpcb; 1681 KASSERT(inp != NULL, ("%s: tp %p tp->t_inpcb == NULL", 1682 __func__, tp)); 1683 INP_WLOCK(inp); 1684 KASSERT((tp->t_timers->tt_flags & TT_STOPPED) != 0, 1685 ("%s: tcpcb has to be stopped here", __func__)); 1686 tp->t_timers->tt_draincnt--; 1687 if (tp->t_timers->tt_draincnt == 0) { 1688 /* We own the last reference on this tcpcb, let's free it. */ 1689 #ifdef TCP_BLACKBOX 1690 tcp_log_tcpcbfini(tp); 1691 #endif 1692 TCPSTATES_DEC(tp->t_state); 1693 if (tp->t_fb->tfb_tcp_fb_fini) 1694 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 1); 1695 refcount_release(&tp->t_fb->tfb_refcnt); 1696 tp->t_inpcb = NULL; 1697 uma_zfree(V_tcpcb_zone, tp); 1698 if (in_pcbrele_wlocked(inp)) { 1699 INP_INFO_RUNLOCK(&V_tcbinfo); 1700 CURVNET_RESTORE(); 1701 return; 1702 } 1703 } 1704 INP_WUNLOCK(inp); 1705 INP_INFO_RUNLOCK(&V_tcbinfo); 1706 CURVNET_RESTORE(); 1707 } 1708 1709 /* 1710 * Attempt to close a TCP control block, marking it as dropped, and freeing 1711 * the socket if we hold the only reference. 1712 */ 1713 struct tcpcb * 1714 tcp_close(struct tcpcb *tp) 1715 { 1716 struct inpcb *inp = tp->t_inpcb; 1717 struct socket *so; 1718 1719 INP_INFO_LOCK_ASSERT(&V_tcbinfo); 1720 INP_WLOCK_ASSERT(inp); 1721 1722 #ifdef TCP_OFFLOAD 1723 if (tp->t_state == TCPS_LISTEN) 1724 tcp_offload_listen_stop(tp); 1725 #endif 1726 /* 1727 * This releases the TFO pending counter resource for TFO listen 1728 * sockets as well as passively-created TFO sockets that transition 1729 * from SYN_RECEIVED to CLOSED. 1730 */ 1731 if (tp->t_tfo_pending) { 1732 tcp_fastopen_decrement_counter(tp->t_tfo_pending); 1733 tp->t_tfo_pending = NULL; 1734 } 1735 in_pcbdrop(inp); 1736 TCPSTAT_INC(tcps_closed); 1737 if (tp->t_state != TCPS_CLOSED) 1738 tcp_state_change(tp, TCPS_CLOSED); 1739 KASSERT(inp->inp_socket != NULL, ("tcp_close: inp_socket NULL")); 1740 so = inp->inp_socket; 1741 soisdisconnected(so); 1742 if (inp->inp_flags & INP_SOCKREF) { 1743 KASSERT(so->so_state & SS_PROTOREF, 1744 ("tcp_close: !SS_PROTOREF")); 1745 inp->inp_flags &= ~INP_SOCKREF; 1746 INP_WUNLOCK(inp); 1747 SOCK_LOCK(so); 1748 so->so_state &= ~SS_PROTOREF; 1749 sofree(so); 1750 return (NULL); 1751 } 1752 return (tp); 1753 } 1754 1755 void 1756 tcp_drain(void) 1757 { 1758 VNET_ITERATOR_DECL(vnet_iter); 1759 1760 if (!do_tcpdrain) 1761 return; 1762 1763 VNET_LIST_RLOCK_NOSLEEP(); 1764 VNET_FOREACH(vnet_iter) { 1765 CURVNET_SET(vnet_iter); 1766 struct inpcb *inpb; 1767 struct tcpcb *tcpb; 1768 1769 /* 1770 * Walk the tcpbs, if existing, and flush the reassembly queue, 1771 * if there is one... 1772 * XXX: The "Net/3" implementation doesn't imply that the TCP 1773 * reassembly queue should be flushed, but in a situation 1774 * where we're really low on mbufs, this is potentially 1775 * useful. 1776 */ 1777 INP_INFO_WLOCK(&V_tcbinfo); 1778 LIST_FOREACH(inpb, V_tcbinfo.ipi_listhead, inp_list) { 1779 if (inpb->inp_flags & INP_TIMEWAIT) 1780 continue; 1781 INP_WLOCK(inpb); 1782 if ((tcpb = intotcpcb(inpb)) != NULL) { 1783 tcp_reass_flush(tcpb); 1784 tcp_clean_sackreport(tcpb); 1785 #ifdef TCP_BLACKBOX 1786 tcp_log_drain(tcpb); 1787 #endif 1788 #ifdef TCPPCAP 1789 if (tcp_pcap_aggressive_free) { 1790 /* Free the TCP PCAP queues. */ 1791 tcp_pcap_drain(&(tcpb->t_inpkts)); 1792 tcp_pcap_drain(&(tcpb->t_outpkts)); 1793 } 1794 #endif 1795 } 1796 INP_WUNLOCK(inpb); 1797 } 1798 INP_INFO_WUNLOCK(&V_tcbinfo); 1799 CURVNET_RESTORE(); 1800 } 1801 VNET_LIST_RUNLOCK_NOSLEEP(); 1802 } 1803 1804 /* 1805 * Notify a tcp user of an asynchronous error; 1806 * store error as soft error, but wake up user 1807 * (for now, won't do anything until can select for soft error). 1808 * 1809 * Do not wake up user since there currently is no mechanism for 1810 * reporting soft errors (yet - a kqueue filter may be added). 1811 */ 1812 static struct inpcb * 1813 tcp_notify(struct inpcb *inp, int error) 1814 { 1815 struct tcpcb *tp; 1816 1817 INP_INFO_LOCK_ASSERT(&V_tcbinfo); 1818 INP_WLOCK_ASSERT(inp); 1819 1820 if ((inp->inp_flags & INP_TIMEWAIT) || 1821 (inp->inp_flags & INP_DROPPED)) 1822 return (inp); 1823 1824 tp = intotcpcb(inp); 1825 KASSERT(tp != NULL, ("tcp_notify: tp == NULL")); 1826 1827 /* 1828 * Ignore some errors if we are hooked up. 1829 * If connection hasn't completed, has retransmitted several times, 1830 * and receives a second error, give up now. This is better 1831 * than waiting a long time to establish a connection that 1832 * can never complete. 1833 */ 1834 if (tp->t_state == TCPS_ESTABLISHED && 1835 (error == EHOSTUNREACH || error == ENETUNREACH || 1836 error == EHOSTDOWN)) { 1837 if (inp->inp_route.ro_rt) { 1838 RTFREE(inp->inp_route.ro_rt); 1839 inp->inp_route.ro_rt = (struct rtentry *)NULL; 1840 } 1841 return (inp); 1842 } else if (tp->t_state < TCPS_ESTABLISHED && tp->t_rxtshift > 3 && 1843 tp->t_softerror) { 1844 tp = tcp_drop(tp, error); 1845 if (tp != NULL) 1846 return (inp); 1847 else 1848 return (NULL); 1849 } else { 1850 tp->t_softerror = error; 1851 return (inp); 1852 } 1853 #if 0 1854 wakeup( &so->so_timeo); 1855 sorwakeup(so); 1856 sowwakeup(so); 1857 #endif 1858 } 1859 1860 static int 1861 tcp_pcblist(SYSCTL_HANDLER_ARGS) 1862 { 1863 int error, i, m, n, pcb_count; 1864 struct inpcb *inp, **inp_list; 1865 inp_gen_t gencnt; 1866 struct xinpgen xig; 1867 1868 /* 1869 * The process of preparing the TCB list is too time-consuming and 1870 * resource-intensive to repeat twice on every request. 1871 */ 1872 if (req->oldptr == NULL) { 1873 n = V_tcbinfo.ipi_count + 1874 counter_u64_fetch(V_tcps_states[TCPS_SYN_RECEIVED]); 1875 n += imax(n / 8, 10); 1876 req->oldidx = 2 * (sizeof xig) + n * sizeof(struct xtcpcb); 1877 return (0); 1878 } 1879 1880 if (req->newptr != NULL) 1881 return (EPERM); 1882 1883 /* 1884 * OK, now we're committed to doing something. 1885 */ 1886 INP_LIST_RLOCK(&V_tcbinfo); 1887 gencnt = V_tcbinfo.ipi_gencnt; 1888 n = V_tcbinfo.ipi_count; 1889 INP_LIST_RUNLOCK(&V_tcbinfo); 1890 1891 m = counter_u64_fetch(V_tcps_states[TCPS_SYN_RECEIVED]); 1892 1893 error = sysctl_wire_old_buffer(req, 2 * (sizeof xig) 1894 + (n + m) * sizeof(struct xtcpcb)); 1895 if (error != 0) 1896 return (error); 1897 1898 xig.xig_len = sizeof xig; 1899 xig.xig_count = n + m; 1900 xig.xig_gen = gencnt; 1901 xig.xig_sogen = so_gencnt; 1902 error = SYSCTL_OUT(req, &xig, sizeof xig); 1903 if (error) 1904 return (error); 1905 1906 error = syncache_pcblist(req, m, &pcb_count); 1907 if (error) 1908 return (error); 1909 1910 inp_list = malloc(n * sizeof *inp_list, M_TEMP, M_WAITOK); 1911 1912 INP_INFO_WLOCK(&V_tcbinfo); 1913 for (inp = LIST_FIRST(V_tcbinfo.ipi_listhead), i = 0; 1914 inp != NULL && i < n; inp = LIST_NEXT(inp, inp_list)) { 1915 INP_WLOCK(inp); 1916 if (inp->inp_gencnt <= gencnt) { 1917 /* 1918 * XXX: This use of cr_cansee(), introduced with 1919 * TCP state changes, is not quite right, but for 1920 * now, better than nothing. 1921 */ 1922 if (inp->inp_flags & INP_TIMEWAIT) { 1923 if (intotw(inp) != NULL) 1924 error = cr_cansee(req->td->td_ucred, 1925 intotw(inp)->tw_cred); 1926 else 1927 error = EINVAL; /* Skip this inp. */ 1928 } else 1929 error = cr_canseeinpcb(req->td->td_ucred, inp); 1930 if (error == 0) { 1931 in_pcbref(inp); 1932 inp_list[i++] = inp; 1933 } 1934 } 1935 INP_WUNLOCK(inp); 1936 } 1937 INP_INFO_WUNLOCK(&V_tcbinfo); 1938 n = i; 1939 1940 error = 0; 1941 for (i = 0; i < n; i++) { 1942 inp = inp_list[i]; 1943 INP_RLOCK(inp); 1944 if (inp->inp_gencnt <= gencnt) { 1945 struct xtcpcb xt; 1946 1947 tcp_inptoxtp(inp, &xt); 1948 INP_RUNLOCK(inp); 1949 error = SYSCTL_OUT(req, &xt, sizeof xt); 1950 } else 1951 INP_RUNLOCK(inp); 1952 } 1953 INP_INFO_RLOCK(&V_tcbinfo); 1954 for (i = 0; i < n; i++) { 1955 inp = inp_list[i]; 1956 INP_RLOCK(inp); 1957 if (!in_pcbrele_rlocked(inp)) 1958 INP_RUNLOCK(inp); 1959 } 1960 INP_INFO_RUNLOCK(&V_tcbinfo); 1961 1962 if (!error) { 1963 /* 1964 * Give the user an updated idea of our state. 1965 * If the generation differs from what we told 1966 * her before, she knows that something happened 1967 * while we were processing this request, and it 1968 * might be necessary to retry. 1969 */ 1970 INP_LIST_RLOCK(&V_tcbinfo); 1971 xig.xig_gen = V_tcbinfo.ipi_gencnt; 1972 xig.xig_sogen = so_gencnt; 1973 xig.xig_count = V_tcbinfo.ipi_count + pcb_count; 1974 INP_LIST_RUNLOCK(&V_tcbinfo); 1975 error = SYSCTL_OUT(req, &xig, sizeof xig); 1976 } 1977 free(inp_list, M_TEMP); 1978 return (error); 1979 } 1980 1981 SYSCTL_PROC(_net_inet_tcp, TCPCTL_PCBLIST, pcblist, 1982 CTLTYPE_OPAQUE | CTLFLAG_RD, NULL, 0, 1983 tcp_pcblist, "S,xtcpcb", "List of active TCP connections"); 1984 1985 #ifdef INET 1986 static int 1987 tcp_getcred(SYSCTL_HANDLER_ARGS) 1988 { 1989 struct xucred xuc; 1990 struct sockaddr_in addrs[2]; 1991 struct inpcb *inp; 1992 int error; 1993 1994 error = priv_check(req->td, PRIV_NETINET_GETCRED); 1995 if (error) 1996 return (error); 1997 error = SYSCTL_IN(req, addrs, sizeof(addrs)); 1998 if (error) 1999 return (error); 2000 inp = in_pcblookup(&V_tcbinfo, addrs[1].sin_addr, addrs[1].sin_port, 2001 addrs[0].sin_addr, addrs[0].sin_port, INPLOOKUP_RLOCKPCB, NULL); 2002 if (inp != NULL) { 2003 if (inp->inp_socket == NULL) 2004 error = ENOENT; 2005 if (error == 0) 2006 error = cr_canseeinpcb(req->td->td_ucred, inp); 2007 if (error == 0) 2008 cru2x(inp->inp_cred, &xuc); 2009 INP_RUNLOCK(inp); 2010 } else 2011 error = ENOENT; 2012 if (error == 0) 2013 error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred)); 2014 return (error); 2015 } 2016 2017 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, getcred, 2018 CTLTYPE_OPAQUE|CTLFLAG_RW|CTLFLAG_PRISON, 0, 0, 2019 tcp_getcred, "S,xucred", "Get the xucred of a TCP connection"); 2020 #endif /* INET */ 2021 2022 #ifdef INET6 2023 static int 2024 tcp6_getcred(SYSCTL_HANDLER_ARGS) 2025 { 2026 struct xucred xuc; 2027 struct sockaddr_in6 addrs[2]; 2028 struct inpcb *inp; 2029 int error; 2030 #ifdef INET 2031 int mapped = 0; 2032 #endif 2033 2034 error = priv_check(req->td, PRIV_NETINET_GETCRED); 2035 if (error) 2036 return (error); 2037 error = SYSCTL_IN(req, addrs, sizeof(addrs)); 2038 if (error) 2039 return (error); 2040 if ((error = sa6_embedscope(&addrs[0], V_ip6_use_defzone)) != 0 || 2041 (error = sa6_embedscope(&addrs[1], V_ip6_use_defzone)) != 0) { 2042 return (error); 2043 } 2044 if (IN6_IS_ADDR_V4MAPPED(&addrs[0].sin6_addr)) { 2045 #ifdef INET 2046 if (IN6_IS_ADDR_V4MAPPED(&addrs[1].sin6_addr)) 2047 mapped = 1; 2048 else 2049 #endif 2050 return (EINVAL); 2051 } 2052 2053 #ifdef INET 2054 if (mapped == 1) 2055 inp = in_pcblookup(&V_tcbinfo, 2056 *(struct in_addr *)&addrs[1].sin6_addr.s6_addr[12], 2057 addrs[1].sin6_port, 2058 *(struct in_addr *)&addrs[0].sin6_addr.s6_addr[12], 2059 addrs[0].sin6_port, INPLOOKUP_RLOCKPCB, NULL); 2060 else 2061 #endif 2062 inp = in6_pcblookup(&V_tcbinfo, 2063 &addrs[1].sin6_addr, addrs[1].sin6_port, 2064 &addrs[0].sin6_addr, addrs[0].sin6_port, 2065 INPLOOKUP_RLOCKPCB, NULL); 2066 if (inp != NULL) { 2067 if (inp->inp_socket == NULL) 2068 error = ENOENT; 2069 if (error == 0) 2070 error = cr_canseeinpcb(req->td->td_ucred, inp); 2071 if (error == 0) 2072 cru2x(inp->inp_cred, &xuc); 2073 INP_RUNLOCK(inp); 2074 } else 2075 error = ENOENT; 2076 if (error == 0) 2077 error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred)); 2078 return (error); 2079 } 2080 2081 SYSCTL_PROC(_net_inet6_tcp6, OID_AUTO, getcred, 2082 CTLTYPE_OPAQUE|CTLFLAG_RW|CTLFLAG_PRISON, 0, 0, 2083 tcp6_getcred, "S,xucred", "Get the xucred of a TCP6 connection"); 2084 #endif /* INET6 */ 2085 2086 2087 #ifdef INET 2088 void 2089 tcp_ctlinput(int cmd, struct sockaddr *sa, void *vip) 2090 { 2091 struct ip *ip = vip; 2092 struct tcphdr *th; 2093 struct in_addr faddr; 2094 struct inpcb *inp; 2095 struct tcpcb *tp; 2096 struct inpcb *(*notify)(struct inpcb *, int) = tcp_notify; 2097 struct icmp *icp; 2098 struct in_conninfo inc; 2099 tcp_seq icmp_tcp_seq; 2100 int mtu; 2101 2102 faddr = ((struct sockaddr_in *)sa)->sin_addr; 2103 if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY) 2104 return; 2105 2106 if (cmd == PRC_MSGSIZE) 2107 notify = tcp_mtudisc_notify; 2108 else if (V_icmp_may_rst && (cmd == PRC_UNREACH_ADMIN_PROHIB || 2109 cmd == PRC_UNREACH_PORT || cmd == PRC_UNREACH_PROTOCOL || 2110 cmd == PRC_TIMXCEED_INTRANS) && ip) 2111 notify = tcp_drop_syn_sent; 2112 2113 /* 2114 * Hostdead is ugly because it goes linearly through all PCBs. 2115 * XXX: We never get this from ICMP, otherwise it makes an 2116 * excellent DoS attack on machines with many connections. 2117 */ 2118 else if (cmd == PRC_HOSTDEAD) 2119 ip = NULL; 2120 else if ((unsigned)cmd >= PRC_NCMDS || inetctlerrmap[cmd] == 0) 2121 return; 2122 2123 if (ip == NULL) { 2124 in_pcbnotifyall(&V_tcbinfo, faddr, inetctlerrmap[cmd], notify); 2125 return; 2126 } 2127 2128 icp = (struct icmp *)((caddr_t)ip - offsetof(struct icmp, icmp_ip)); 2129 th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2)); 2130 INP_INFO_RLOCK(&V_tcbinfo); 2131 inp = in_pcblookup(&V_tcbinfo, faddr, th->th_dport, ip->ip_src, 2132 th->th_sport, INPLOOKUP_WLOCKPCB, NULL); 2133 if (inp != NULL && PRC_IS_REDIRECT(cmd)) { 2134 /* signal EHOSTDOWN, as it flushes the cached route */ 2135 inp = (*notify)(inp, EHOSTDOWN); 2136 goto out; 2137 } 2138 icmp_tcp_seq = th->th_seq; 2139 if (inp != NULL) { 2140 if (!(inp->inp_flags & INP_TIMEWAIT) && 2141 !(inp->inp_flags & INP_DROPPED) && 2142 !(inp->inp_socket == NULL)) { 2143 tp = intotcpcb(inp); 2144 if (SEQ_GEQ(ntohl(icmp_tcp_seq), tp->snd_una) && 2145 SEQ_LT(ntohl(icmp_tcp_seq), tp->snd_max)) { 2146 if (cmd == PRC_MSGSIZE) { 2147 /* 2148 * MTU discovery: 2149 * If we got a needfrag set the MTU 2150 * in the route to the suggested new 2151 * value (if given) and then notify. 2152 */ 2153 mtu = ntohs(icp->icmp_nextmtu); 2154 /* 2155 * If no alternative MTU was 2156 * proposed, try the next smaller 2157 * one. 2158 */ 2159 if (!mtu) 2160 mtu = ip_next_mtu( 2161 ntohs(ip->ip_len), 1); 2162 if (mtu < V_tcp_minmss + 2163 sizeof(struct tcpiphdr)) 2164 mtu = V_tcp_minmss + 2165 sizeof(struct tcpiphdr); 2166 /* 2167 * Only process the offered MTU if it 2168 * is smaller than the current one. 2169 */ 2170 if (mtu < tp->t_maxseg + 2171 sizeof(struct tcpiphdr)) { 2172 bzero(&inc, sizeof(inc)); 2173 inc.inc_faddr = faddr; 2174 inc.inc_fibnum = 2175 inp->inp_inc.inc_fibnum; 2176 tcp_hc_updatemtu(&inc, mtu); 2177 tcp_mtudisc(inp, mtu); 2178 } 2179 } else 2180 inp = (*notify)(inp, 2181 inetctlerrmap[cmd]); 2182 } 2183 } 2184 } else { 2185 bzero(&inc, sizeof(inc)); 2186 inc.inc_fport = th->th_dport; 2187 inc.inc_lport = th->th_sport; 2188 inc.inc_faddr = faddr; 2189 inc.inc_laddr = ip->ip_src; 2190 syncache_unreach(&inc, icmp_tcp_seq); 2191 } 2192 out: 2193 if (inp != NULL) 2194 INP_WUNLOCK(inp); 2195 INP_INFO_RUNLOCK(&V_tcbinfo); 2196 } 2197 #endif /* INET */ 2198 2199 #ifdef INET6 2200 void 2201 tcp6_ctlinput(int cmd, struct sockaddr *sa, void *d) 2202 { 2203 struct in6_addr *dst; 2204 struct inpcb *(*notify)(struct inpcb *, int) = tcp_notify; 2205 struct ip6_hdr *ip6; 2206 struct mbuf *m; 2207 struct inpcb *inp; 2208 struct tcpcb *tp; 2209 struct icmp6_hdr *icmp6; 2210 struct ip6ctlparam *ip6cp = NULL; 2211 const struct sockaddr_in6 *sa6_src = NULL; 2212 struct in_conninfo inc; 2213 struct tcp_ports { 2214 uint16_t th_sport; 2215 uint16_t th_dport; 2216 } t_ports; 2217 tcp_seq icmp_tcp_seq; 2218 unsigned int mtu; 2219 unsigned int off; 2220 2221 if (sa->sa_family != AF_INET6 || 2222 sa->sa_len != sizeof(struct sockaddr_in6)) 2223 return; 2224 2225 /* if the parameter is from icmp6, decode it. */ 2226 if (d != NULL) { 2227 ip6cp = (struct ip6ctlparam *)d; 2228 icmp6 = ip6cp->ip6c_icmp6; 2229 m = ip6cp->ip6c_m; 2230 ip6 = ip6cp->ip6c_ip6; 2231 off = ip6cp->ip6c_off; 2232 sa6_src = ip6cp->ip6c_src; 2233 dst = ip6cp->ip6c_finaldst; 2234 } else { 2235 m = NULL; 2236 ip6 = NULL; 2237 off = 0; /* fool gcc */ 2238 sa6_src = &sa6_any; 2239 dst = NULL; 2240 } 2241 2242 if (cmd == PRC_MSGSIZE) 2243 notify = tcp_mtudisc_notify; 2244 else if (V_icmp_may_rst && (cmd == PRC_UNREACH_ADMIN_PROHIB || 2245 cmd == PRC_UNREACH_PORT || cmd == PRC_UNREACH_PROTOCOL || 2246 cmd == PRC_TIMXCEED_INTRANS) && ip6 != NULL) 2247 notify = tcp_drop_syn_sent; 2248 2249 /* 2250 * Hostdead is ugly because it goes linearly through all PCBs. 2251 * XXX: We never get this from ICMP, otherwise it makes an 2252 * excellent DoS attack on machines with many connections. 2253 */ 2254 else if (cmd == PRC_HOSTDEAD) 2255 ip6 = NULL; 2256 else if ((unsigned)cmd >= PRC_NCMDS || inet6ctlerrmap[cmd] == 0) 2257 return; 2258 2259 if (ip6 == NULL) { 2260 in6_pcbnotify(&V_tcbinfo, sa, 0, 2261 (const struct sockaddr *)sa6_src, 2262 0, cmd, NULL, notify); 2263 return; 2264 } 2265 2266 /* Check if we can safely get the ports from the tcp hdr */ 2267 if (m == NULL || 2268 (m->m_pkthdr.len < 2269 (int32_t) (off + sizeof(struct tcp_ports)))) { 2270 return; 2271 } 2272 bzero(&t_ports, sizeof(struct tcp_ports)); 2273 m_copydata(m, off, sizeof(struct tcp_ports), (caddr_t)&t_ports); 2274 INP_INFO_RLOCK(&V_tcbinfo); 2275 inp = in6_pcblookup(&V_tcbinfo, &ip6->ip6_dst, t_ports.th_dport, 2276 &ip6->ip6_src, t_ports.th_sport, INPLOOKUP_WLOCKPCB, NULL); 2277 if (inp != NULL && PRC_IS_REDIRECT(cmd)) { 2278 /* signal EHOSTDOWN, as it flushes the cached route */ 2279 inp = (*notify)(inp, EHOSTDOWN); 2280 goto out; 2281 } 2282 off += sizeof(struct tcp_ports); 2283 if (m->m_pkthdr.len < (int32_t) (off + sizeof(tcp_seq))) { 2284 goto out; 2285 } 2286 m_copydata(m, off, sizeof(tcp_seq), (caddr_t)&icmp_tcp_seq); 2287 if (inp != NULL) { 2288 if (!(inp->inp_flags & INP_TIMEWAIT) && 2289 !(inp->inp_flags & INP_DROPPED) && 2290 !(inp->inp_socket == NULL)) { 2291 tp = intotcpcb(inp); 2292 if (SEQ_GEQ(ntohl(icmp_tcp_seq), tp->snd_una) && 2293 SEQ_LT(ntohl(icmp_tcp_seq), tp->snd_max)) { 2294 if (cmd == PRC_MSGSIZE) { 2295 /* 2296 * MTU discovery: 2297 * If we got a needfrag set the MTU 2298 * in the route to the suggested new 2299 * value (if given) and then notify. 2300 */ 2301 mtu = ntohl(icmp6->icmp6_mtu); 2302 /* 2303 * If no alternative MTU was 2304 * proposed, or the proposed 2305 * MTU was too small, set to 2306 * the min. 2307 */ 2308 if (mtu < IPV6_MMTU) 2309 mtu = IPV6_MMTU - 8; 2310 bzero(&inc, sizeof(inc)); 2311 inc.inc_fibnum = M_GETFIB(m); 2312 inc.inc_flags |= INC_ISIPV6; 2313 inc.inc6_faddr = *dst; 2314 if (in6_setscope(&inc.inc6_faddr, 2315 m->m_pkthdr.rcvif, NULL)) 2316 goto out; 2317 /* 2318 * Only process the offered MTU if it 2319 * is smaller than the current one. 2320 */ 2321 if (mtu < tp->t_maxseg + 2322 sizeof (struct tcphdr) + 2323 sizeof (struct ip6_hdr)) { 2324 tcp_hc_updatemtu(&inc, mtu); 2325 tcp_mtudisc(inp, mtu); 2326 ICMP6STAT_INC(icp6s_pmtuchg); 2327 } 2328 } else 2329 inp = (*notify)(inp, 2330 inet6ctlerrmap[cmd]); 2331 } 2332 } 2333 } else { 2334 bzero(&inc, sizeof(inc)); 2335 inc.inc_fibnum = M_GETFIB(m); 2336 inc.inc_flags |= INC_ISIPV6; 2337 inc.inc_fport = t_ports.th_dport; 2338 inc.inc_lport = t_ports.th_sport; 2339 inc.inc6_faddr = *dst; 2340 inc.inc6_laddr = ip6->ip6_src; 2341 syncache_unreach(&inc, icmp_tcp_seq); 2342 } 2343 out: 2344 if (inp != NULL) 2345 INP_WUNLOCK(inp); 2346 INP_INFO_RUNLOCK(&V_tcbinfo); 2347 } 2348 #endif /* INET6 */ 2349 2350 2351 /* 2352 * Following is where TCP initial sequence number generation occurs. 2353 * 2354 * There are two places where we must use initial sequence numbers: 2355 * 1. In SYN-ACK packets. 2356 * 2. In SYN packets. 2357 * 2358 * All ISNs for SYN-ACK packets are generated by the syncache. See 2359 * tcp_syncache.c for details. 2360 * 2361 * The ISNs in SYN packets must be monotonic; TIME_WAIT recycling 2362 * depends on this property. In addition, these ISNs should be 2363 * unguessable so as to prevent connection hijacking. To satisfy 2364 * the requirements of this situation, the algorithm outlined in 2365 * RFC 1948 is used, with only small modifications. 2366 * 2367 * Implementation details: 2368 * 2369 * Time is based off the system timer, and is corrected so that it 2370 * increases by one megabyte per second. This allows for proper 2371 * recycling on high speed LANs while still leaving over an hour 2372 * before rollover. 2373 * 2374 * As reading the *exact* system time is too expensive to be done 2375 * whenever setting up a TCP connection, we increment the time 2376 * offset in two ways. First, a small random positive increment 2377 * is added to isn_offset for each connection that is set up. 2378 * Second, the function tcp_isn_tick fires once per clock tick 2379 * and increments isn_offset as necessary so that sequence numbers 2380 * are incremented at approximately ISN_BYTES_PER_SECOND. The 2381 * random positive increments serve only to ensure that the same 2382 * exact sequence number is never sent out twice (as could otherwise 2383 * happen when a port is recycled in less than the system tick 2384 * interval.) 2385 * 2386 * net.inet.tcp.isn_reseed_interval controls the number of seconds 2387 * between seeding of isn_secret. This is normally set to zero, 2388 * as reseeding should not be necessary. 2389 * 2390 * Locking of the global variables isn_secret, isn_last_reseed, isn_offset, 2391 * isn_offset_old, and isn_ctx is performed using the TCP pcbinfo lock. In 2392 * general, this means holding an exclusive (write) lock. 2393 */ 2394 2395 #define ISN_BYTES_PER_SECOND 1048576 2396 #define ISN_STATIC_INCREMENT 4096 2397 #define ISN_RANDOM_INCREMENT (4096 - 1) 2398 2399 static VNET_DEFINE(u_char, isn_secret[32]); 2400 static VNET_DEFINE(int, isn_last); 2401 static VNET_DEFINE(int, isn_last_reseed); 2402 static VNET_DEFINE(u_int32_t, isn_offset); 2403 static VNET_DEFINE(u_int32_t, isn_offset_old); 2404 2405 #define V_isn_secret VNET(isn_secret) 2406 #define V_isn_last VNET(isn_last) 2407 #define V_isn_last_reseed VNET(isn_last_reseed) 2408 #define V_isn_offset VNET(isn_offset) 2409 #define V_isn_offset_old VNET(isn_offset_old) 2410 2411 tcp_seq 2412 tcp_new_isn(struct tcpcb *tp) 2413 { 2414 MD5_CTX isn_ctx; 2415 u_int32_t md5_buffer[4]; 2416 tcp_seq new_isn; 2417 u_int32_t projected_offset; 2418 2419 INP_WLOCK_ASSERT(tp->t_inpcb); 2420 2421 ISN_LOCK(); 2422 /* Seed if this is the first use, reseed if requested. */ 2423 if ((V_isn_last_reseed == 0) || ((V_tcp_isn_reseed_interval > 0) && 2424 (((u_int)V_isn_last_reseed + (u_int)V_tcp_isn_reseed_interval*hz) 2425 < (u_int)ticks))) { 2426 read_random(&V_isn_secret, sizeof(V_isn_secret)); 2427 V_isn_last_reseed = ticks; 2428 } 2429 2430 /* Compute the md5 hash and return the ISN. */ 2431 MD5Init(&isn_ctx); 2432 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_fport, sizeof(u_short)); 2433 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_lport, sizeof(u_short)); 2434 #ifdef INET6 2435 if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0) { 2436 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->in6p_faddr, 2437 sizeof(struct in6_addr)); 2438 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->in6p_laddr, 2439 sizeof(struct in6_addr)); 2440 } else 2441 #endif 2442 { 2443 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_faddr, 2444 sizeof(struct in_addr)); 2445 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_laddr, 2446 sizeof(struct in_addr)); 2447 } 2448 MD5Update(&isn_ctx, (u_char *) &V_isn_secret, sizeof(V_isn_secret)); 2449 MD5Final((u_char *) &md5_buffer, &isn_ctx); 2450 new_isn = (tcp_seq) md5_buffer[0]; 2451 V_isn_offset += ISN_STATIC_INCREMENT + 2452 (arc4random() & ISN_RANDOM_INCREMENT); 2453 if (ticks != V_isn_last) { 2454 projected_offset = V_isn_offset_old + 2455 ISN_BYTES_PER_SECOND / hz * (ticks - V_isn_last); 2456 if (SEQ_GT(projected_offset, V_isn_offset)) 2457 V_isn_offset = projected_offset; 2458 V_isn_offset_old = V_isn_offset; 2459 V_isn_last = ticks; 2460 } 2461 new_isn += V_isn_offset; 2462 ISN_UNLOCK(); 2463 return (new_isn); 2464 } 2465 2466 /* 2467 * When a specific ICMP unreachable message is received and the 2468 * connection state is SYN-SENT, drop the connection. This behavior 2469 * is controlled by the icmp_may_rst sysctl. 2470 */ 2471 struct inpcb * 2472 tcp_drop_syn_sent(struct inpcb *inp, int errno) 2473 { 2474 struct tcpcb *tp; 2475 2476 INP_INFO_RLOCK_ASSERT(&V_tcbinfo); 2477 INP_WLOCK_ASSERT(inp); 2478 2479 if ((inp->inp_flags & INP_TIMEWAIT) || 2480 (inp->inp_flags & INP_DROPPED)) 2481 return (inp); 2482 2483 tp = intotcpcb(inp); 2484 if (tp->t_state != TCPS_SYN_SENT) 2485 return (inp); 2486 2487 if (IS_FASTOPEN(tp->t_flags)) 2488 tcp_fastopen_disable_path(tp); 2489 2490 tp = tcp_drop(tp, errno); 2491 if (tp != NULL) 2492 return (inp); 2493 else 2494 return (NULL); 2495 } 2496 2497 /* 2498 * When `need fragmentation' ICMP is received, update our idea of the MSS 2499 * based on the new value. Also nudge TCP to send something, since we 2500 * know the packet we just sent was dropped. 2501 * This duplicates some code in the tcp_mss() function in tcp_input.c. 2502 */ 2503 static struct inpcb * 2504 tcp_mtudisc_notify(struct inpcb *inp, int error) 2505 { 2506 2507 tcp_mtudisc(inp, -1); 2508 return (inp); 2509 } 2510 2511 static void 2512 tcp_mtudisc(struct inpcb *inp, int mtuoffer) 2513 { 2514 struct tcpcb *tp; 2515 struct socket *so; 2516 2517 INP_WLOCK_ASSERT(inp); 2518 if ((inp->inp_flags & INP_TIMEWAIT) || 2519 (inp->inp_flags & INP_DROPPED)) 2520 return; 2521 2522 tp = intotcpcb(inp); 2523 KASSERT(tp != NULL, ("tcp_mtudisc: tp == NULL")); 2524 2525 tcp_mss_update(tp, -1, mtuoffer, NULL, NULL); 2526 2527 so = inp->inp_socket; 2528 SOCKBUF_LOCK(&so->so_snd); 2529 /* If the mss is larger than the socket buffer, decrease the mss. */ 2530 if (so->so_snd.sb_hiwat < tp->t_maxseg) 2531 tp->t_maxseg = so->so_snd.sb_hiwat; 2532 SOCKBUF_UNLOCK(&so->so_snd); 2533 2534 TCPSTAT_INC(tcps_mturesent); 2535 tp->t_rtttime = 0; 2536 tp->snd_nxt = tp->snd_una; 2537 tcp_free_sackholes(tp); 2538 tp->snd_recover = tp->snd_max; 2539 if (tp->t_flags & TF_SACK_PERMIT) 2540 EXIT_FASTRECOVERY(tp->t_flags); 2541 tp->t_fb->tfb_tcp_output(tp); 2542 } 2543 2544 #ifdef INET 2545 /* 2546 * Look-up the routing entry to the peer of this inpcb. If no route 2547 * is found and it cannot be allocated, then return 0. This routine 2548 * is called by TCP routines that access the rmx structure and by 2549 * tcp_mss_update to get the peer/interface MTU. 2550 */ 2551 uint32_t 2552 tcp_maxmtu(struct in_conninfo *inc, struct tcp_ifcap *cap) 2553 { 2554 struct nhop4_extended nh4; 2555 struct ifnet *ifp; 2556 uint32_t maxmtu = 0; 2557 2558 KASSERT(inc != NULL, ("tcp_maxmtu with NULL in_conninfo pointer")); 2559 2560 if (inc->inc_faddr.s_addr != INADDR_ANY) { 2561 2562 if (fib4_lookup_nh_ext(inc->inc_fibnum, inc->inc_faddr, 2563 NHR_REF, 0, &nh4) != 0) 2564 return (0); 2565 2566 ifp = nh4.nh_ifp; 2567 maxmtu = nh4.nh_mtu; 2568 2569 /* Report additional interface capabilities. */ 2570 if (cap != NULL) { 2571 if (ifp->if_capenable & IFCAP_TSO4 && 2572 ifp->if_hwassist & CSUM_TSO) { 2573 cap->ifcap |= CSUM_TSO; 2574 cap->tsomax = ifp->if_hw_tsomax; 2575 cap->tsomaxsegcount = ifp->if_hw_tsomaxsegcount; 2576 cap->tsomaxsegsize = ifp->if_hw_tsomaxsegsize; 2577 } 2578 } 2579 fib4_free_nh_ext(inc->inc_fibnum, &nh4); 2580 } 2581 return (maxmtu); 2582 } 2583 #endif /* INET */ 2584 2585 #ifdef INET6 2586 uint32_t 2587 tcp_maxmtu6(struct in_conninfo *inc, struct tcp_ifcap *cap) 2588 { 2589 struct nhop6_extended nh6; 2590 struct in6_addr dst6; 2591 uint32_t scopeid; 2592 struct ifnet *ifp; 2593 uint32_t maxmtu = 0; 2594 2595 KASSERT(inc != NULL, ("tcp_maxmtu6 with NULL in_conninfo pointer")); 2596 2597 if (!IN6_IS_ADDR_UNSPECIFIED(&inc->inc6_faddr)) { 2598 in6_splitscope(&inc->inc6_faddr, &dst6, &scopeid); 2599 if (fib6_lookup_nh_ext(inc->inc_fibnum, &dst6, scopeid, 0, 2600 0, &nh6) != 0) 2601 return (0); 2602 2603 ifp = nh6.nh_ifp; 2604 maxmtu = nh6.nh_mtu; 2605 2606 /* Report additional interface capabilities. */ 2607 if (cap != NULL) { 2608 if (ifp->if_capenable & IFCAP_TSO6 && 2609 ifp->if_hwassist & CSUM_TSO) { 2610 cap->ifcap |= CSUM_TSO; 2611 cap->tsomax = ifp->if_hw_tsomax; 2612 cap->tsomaxsegcount = ifp->if_hw_tsomaxsegcount; 2613 cap->tsomaxsegsize = ifp->if_hw_tsomaxsegsize; 2614 } 2615 } 2616 fib6_free_nh_ext(inc->inc_fibnum, &nh6); 2617 } 2618 2619 return (maxmtu); 2620 } 2621 #endif /* INET6 */ 2622 2623 /* 2624 * Calculate effective SMSS per RFC5681 definition for a given TCP 2625 * connection at its current state, taking into account SACK and etc. 2626 */ 2627 u_int 2628 tcp_maxseg(const struct tcpcb *tp) 2629 { 2630 u_int optlen; 2631 2632 if (tp->t_flags & TF_NOOPT) 2633 return (tp->t_maxseg); 2634 2635 /* 2636 * Here we have a simplified code from tcp_addoptions(), 2637 * without a proper loop, and having most of paddings hardcoded. 2638 * We might make mistakes with padding here in some edge cases, 2639 * but this is harmless, since result of tcp_maxseg() is used 2640 * only in cwnd and ssthresh estimations. 2641 */ 2642 #define PAD(len) ((((len) / 4) + !!((len) % 4)) * 4) 2643 if (TCPS_HAVEESTABLISHED(tp->t_state)) { 2644 if (tp->t_flags & TF_RCVD_TSTMP) 2645 optlen = TCPOLEN_TSTAMP_APPA; 2646 else 2647 optlen = 0; 2648 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE) 2649 if (tp->t_flags & TF_SIGNATURE) 2650 optlen += PAD(TCPOLEN_SIGNATURE); 2651 #endif 2652 if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks > 0) { 2653 optlen += TCPOLEN_SACKHDR; 2654 optlen += tp->rcv_numsacks * TCPOLEN_SACK; 2655 optlen = PAD(optlen); 2656 } 2657 } else { 2658 if (tp->t_flags & TF_REQ_TSTMP) 2659 optlen = TCPOLEN_TSTAMP_APPA; 2660 else 2661 optlen = PAD(TCPOLEN_MAXSEG); 2662 if (tp->t_flags & TF_REQ_SCALE) 2663 optlen += PAD(TCPOLEN_WINDOW); 2664 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE) 2665 if (tp->t_flags & TF_SIGNATURE) 2666 optlen += PAD(TCPOLEN_SIGNATURE); 2667 #endif 2668 if (tp->t_flags & TF_SACK_PERMIT) 2669 optlen += PAD(TCPOLEN_SACK_PERMITTED); 2670 } 2671 #undef PAD 2672 optlen = min(optlen, TCP_MAXOLEN); 2673 return (tp->t_maxseg - optlen); 2674 } 2675 2676 static int 2677 sysctl_drop(SYSCTL_HANDLER_ARGS) 2678 { 2679 /* addrs[0] is a foreign socket, addrs[1] is a local one. */ 2680 struct sockaddr_storage addrs[2]; 2681 struct inpcb *inp; 2682 struct tcpcb *tp; 2683 struct tcptw *tw; 2684 struct sockaddr_in *fin, *lin; 2685 #ifdef INET6 2686 struct sockaddr_in6 *fin6, *lin6; 2687 #endif 2688 int error; 2689 2690 inp = NULL; 2691 fin = lin = NULL; 2692 #ifdef INET6 2693 fin6 = lin6 = NULL; 2694 #endif 2695 error = 0; 2696 2697 if (req->oldptr != NULL || req->oldlen != 0) 2698 return (EINVAL); 2699 if (req->newptr == NULL) 2700 return (EPERM); 2701 if (req->newlen < sizeof(addrs)) 2702 return (ENOMEM); 2703 error = SYSCTL_IN(req, &addrs, sizeof(addrs)); 2704 if (error) 2705 return (error); 2706 2707 switch (addrs[0].ss_family) { 2708 #ifdef INET6 2709 case AF_INET6: 2710 fin6 = (struct sockaddr_in6 *)&addrs[0]; 2711 lin6 = (struct sockaddr_in6 *)&addrs[1]; 2712 if (fin6->sin6_len != sizeof(struct sockaddr_in6) || 2713 lin6->sin6_len != sizeof(struct sockaddr_in6)) 2714 return (EINVAL); 2715 if (IN6_IS_ADDR_V4MAPPED(&fin6->sin6_addr)) { 2716 if (!IN6_IS_ADDR_V4MAPPED(&lin6->sin6_addr)) 2717 return (EINVAL); 2718 in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[0]); 2719 in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[1]); 2720 fin = (struct sockaddr_in *)&addrs[0]; 2721 lin = (struct sockaddr_in *)&addrs[1]; 2722 break; 2723 } 2724 error = sa6_embedscope(fin6, V_ip6_use_defzone); 2725 if (error) 2726 return (error); 2727 error = sa6_embedscope(lin6, V_ip6_use_defzone); 2728 if (error) 2729 return (error); 2730 break; 2731 #endif 2732 #ifdef INET 2733 case AF_INET: 2734 fin = (struct sockaddr_in *)&addrs[0]; 2735 lin = (struct sockaddr_in *)&addrs[1]; 2736 if (fin->sin_len != sizeof(struct sockaddr_in) || 2737 lin->sin_len != sizeof(struct sockaddr_in)) 2738 return (EINVAL); 2739 break; 2740 #endif 2741 default: 2742 return (EINVAL); 2743 } 2744 INP_INFO_RLOCK(&V_tcbinfo); 2745 switch (addrs[0].ss_family) { 2746 #ifdef INET6 2747 case AF_INET6: 2748 inp = in6_pcblookup(&V_tcbinfo, &fin6->sin6_addr, 2749 fin6->sin6_port, &lin6->sin6_addr, lin6->sin6_port, 2750 INPLOOKUP_WLOCKPCB, NULL); 2751 break; 2752 #endif 2753 #ifdef INET 2754 case AF_INET: 2755 inp = in_pcblookup(&V_tcbinfo, fin->sin_addr, fin->sin_port, 2756 lin->sin_addr, lin->sin_port, INPLOOKUP_WLOCKPCB, NULL); 2757 break; 2758 #endif 2759 } 2760 if (inp != NULL) { 2761 if (inp->inp_flags & INP_TIMEWAIT) { 2762 /* 2763 * XXXRW: There currently exists a state where an 2764 * inpcb is present, but its timewait state has been 2765 * discarded. For now, don't allow dropping of this 2766 * type of inpcb. 2767 */ 2768 tw = intotw(inp); 2769 if (tw != NULL) 2770 tcp_twclose(tw, 0); 2771 else 2772 INP_WUNLOCK(inp); 2773 } else if (!(inp->inp_flags & INP_DROPPED) && 2774 !(inp->inp_socket->so_options & SO_ACCEPTCONN)) { 2775 tp = intotcpcb(inp); 2776 tp = tcp_drop(tp, ECONNABORTED); 2777 if (tp != NULL) 2778 INP_WUNLOCK(inp); 2779 } else 2780 INP_WUNLOCK(inp); 2781 } else 2782 error = ESRCH; 2783 INP_INFO_RUNLOCK(&V_tcbinfo); 2784 return (error); 2785 } 2786 2787 SYSCTL_PROC(_net_inet_tcp, TCPCTL_DROP, drop, 2788 CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP, NULL, 2789 0, sysctl_drop, "", "Drop TCP connection"); 2790 2791 /* 2792 * Generate a standardized TCP log line for use throughout the 2793 * tcp subsystem. Memory allocation is done with M_NOWAIT to 2794 * allow use in the interrupt context. 2795 * 2796 * NB: The caller MUST free(s, M_TCPLOG) the returned string. 2797 * NB: The function may return NULL if memory allocation failed. 2798 * 2799 * Due to header inclusion and ordering limitations the struct ip 2800 * and ip6_hdr pointers have to be passed as void pointers. 2801 */ 2802 char * 2803 tcp_log_vain(struct in_conninfo *inc, struct tcphdr *th, void *ip4hdr, 2804 const void *ip6hdr) 2805 { 2806 2807 /* Is logging enabled? */ 2808 if (tcp_log_in_vain == 0) 2809 return (NULL); 2810 2811 return (tcp_log_addr(inc, th, ip4hdr, ip6hdr)); 2812 } 2813 2814 char * 2815 tcp_log_addrs(struct in_conninfo *inc, struct tcphdr *th, void *ip4hdr, 2816 const void *ip6hdr) 2817 { 2818 2819 /* Is logging enabled? */ 2820 if (tcp_log_debug == 0) 2821 return (NULL); 2822 2823 return (tcp_log_addr(inc, th, ip4hdr, ip6hdr)); 2824 } 2825 2826 static char * 2827 tcp_log_addr(struct in_conninfo *inc, struct tcphdr *th, void *ip4hdr, 2828 const void *ip6hdr) 2829 { 2830 char *s, *sp; 2831 size_t size; 2832 struct ip *ip; 2833 #ifdef INET6 2834 const struct ip6_hdr *ip6; 2835 2836 ip6 = (const struct ip6_hdr *)ip6hdr; 2837 #endif /* INET6 */ 2838 ip = (struct ip *)ip4hdr; 2839 2840 /* 2841 * The log line looks like this: 2842 * "TCP: [1.2.3.4]:50332 to [1.2.3.4]:80 tcpflags 0x2<SYN>" 2843 */ 2844 size = sizeof("TCP: []:12345 to []:12345 tcpflags 0x2<>") + 2845 sizeof(PRINT_TH_FLAGS) + 1 + 2846 #ifdef INET6 2847 2 * INET6_ADDRSTRLEN; 2848 #else 2849 2 * INET_ADDRSTRLEN; 2850 #endif /* INET6 */ 2851 2852 s = malloc(size, M_TCPLOG, M_ZERO|M_NOWAIT); 2853 if (s == NULL) 2854 return (NULL); 2855 2856 strcat(s, "TCP: ["); 2857 sp = s + strlen(s); 2858 2859 if (inc && ((inc->inc_flags & INC_ISIPV6) == 0)) { 2860 inet_ntoa_r(inc->inc_faddr, sp); 2861 sp = s + strlen(s); 2862 sprintf(sp, "]:%i to [", ntohs(inc->inc_fport)); 2863 sp = s + strlen(s); 2864 inet_ntoa_r(inc->inc_laddr, sp); 2865 sp = s + strlen(s); 2866 sprintf(sp, "]:%i", ntohs(inc->inc_lport)); 2867 #ifdef INET6 2868 } else if (inc) { 2869 ip6_sprintf(sp, &inc->inc6_faddr); 2870 sp = s + strlen(s); 2871 sprintf(sp, "]:%i to [", ntohs(inc->inc_fport)); 2872 sp = s + strlen(s); 2873 ip6_sprintf(sp, &inc->inc6_laddr); 2874 sp = s + strlen(s); 2875 sprintf(sp, "]:%i", ntohs(inc->inc_lport)); 2876 } else if (ip6 && th) { 2877 ip6_sprintf(sp, &ip6->ip6_src); 2878 sp = s + strlen(s); 2879 sprintf(sp, "]:%i to [", ntohs(th->th_sport)); 2880 sp = s + strlen(s); 2881 ip6_sprintf(sp, &ip6->ip6_dst); 2882 sp = s + strlen(s); 2883 sprintf(sp, "]:%i", ntohs(th->th_dport)); 2884 #endif /* INET6 */ 2885 #ifdef INET 2886 } else if (ip && th) { 2887 inet_ntoa_r(ip->ip_src, sp); 2888 sp = s + strlen(s); 2889 sprintf(sp, "]:%i to [", ntohs(th->th_sport)); 2890 sp = s + strlen(s); 2891 inet_ntoa_r(ip->ip_dst, sp); 2892 sp = s + strlen(s); 2893 sprintf(sp, "]:%i", ntohs(th->th_dport)); 2894 #endif /* INET */ 2895 } else { 2896 free(s, M_TCPLOG); 2897 return (NULL); 2898 } 2899 sp = s + strlen(s); 2900 if (th) 2901 sprintf(sp, " tcpflags 0x%b", th->th_flags, PRINT_TH_FLAGS); 2902 if (*(s + size - 1) != '\0') 2903 panic("%s: string too long", __func__); 2904 return (s); 2905 } 2906 2907 /* 2908 * A subroutine which makes it easy to track TCP state changes with DTrace. 2909 * This function shouldn't be called for t_state initializations that don't 2910 * correspond to actual TCP state transitions. 2911 */ 2912 void 2913 tcp_state_change(struct tcpcb *tp, int newstate) 2914 { 2915 #if defined(KDTRACE_HOOKS) 2916 int pstate = tp->t_state; 2917 #endif 2918 2919 TCPSTATES_DEC(tp->t_state); 2920 TCPSTATES_INC(newstate); 2921 tp->t_state = newstate; 2922 TCP_PROBE6(state__change, NULL, tp, NULL, tp, NULL, pstate); 2923 } 2924 2925 /* 2926 * Create an external-format (``xtcpcb'') structure using the information in 2927 * the kernel-format tcpcb structure pointed to by tp. This is done to 2928 * reduce the spew of irrelevant information over this interface, to isolate 2929 * user code from changes in the kernel structure, and potentially to provide 2930 * information-hiding if we decide that some of this information should be 2931 * hidden from users. 2932 */ 2933 void 2934 tcp_inptoxtp(const struct inpcb *inp, struct xtcpcb *xt) 2935 { 2936 struct tcpcb *tp = intotcpcb(inp); 2937 sbintime_t now; 2938 2939 if (inp->inp_flags & INP_TIMEWAIT) { 2940 bzero(xt, sizeof(struct xtcpcb)); 2941 xt->t_state = TCPS_TIME_WAIT; 2942 } else { 2943 xt->t_state = tp->t_state; 2944 xt->t_logstate = tp->t_logstate; 2945 xt->t_flags = tp->t_flags; 2946 xt->t_sndzerowin = tp->t_sndzerowin; 2947 xt->t_sndrexmitpack = tp->t_sndrexmitpack; 2948 xt->t_rcvoopack = tp->t_rcvoopack; 2949 2950 now = getsbinuptime(); 2951 #define COPYTIMER(ttt) do { \ 2952 if (callout_active(&tp->t_timers->ttt)) \ 2953 xt->ttt = (tp->t_timers->ttt.c_time - now) / \ 2954 SBT_1MS; \ 2955 else \ 2956 xt->ttt = 0; \ 2957 } while (0) 2958 COPYTIMER(tt_delack); 2959 COPYTIMER(tt_rexmt); 2960 COPYTIMER(tt_persist); 2961 COPYTIMER(tt_keep); 2962 COPYTIMER(tt_2msl); 2963 #undef COPYTIMER 2964 xt->t_rcvtime = 1000 * (ticks - tp->t_rcvtime) / hz; 2965 2966 bcopy(tp->t_fb->tfb_tcp_block_name, xt->xt_stack, 2967 TCP_FUNCTION_NAME_LEN_MAX); 2968 bzero(xt->xt_logid, TCP_LOG_ID_LEN); 2969 #ifdef TCP_BLACKBOX 2970 (void)tcp_log_get_id(tp, xt->xt_logid); 2971 #endif 2972 } 2973 2974 xt->xt_len = sizeof(struct xtcpcb); 2975 in_pcbtoxinpcb(inp, &xt->xt_inp); 2976 if (inp->inp_socket == NULL) 2977 xt->xt_inp.xi_socket.xso_protocol = IPPROTO_TCP; 2978 } 2979