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