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