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 32 #include "opt_inet.h" 33 #include "opt_inet6.h" 34 #include "opt_ipsec.h" 35 #include "opt_kern_tls.h" 36 37 #include <sys/param.h> 38 #include <sys/systm.h> 39 #include <sys/arb.h> 40 #include <sys/callout.h> 41 #include <sys/eventhandler.h> 42 #ifdef TCP_HHOOK 43 #include <sys/hhook.h> 44 #endif 45 #include <sys/kernel.h> 46 #ifdef TCP_HHOOK 47 #include <sys/khelp.h> 48 #endif 49 #ifdef KERN_TLS 50 #include <sys/ktls.h> 51 #endif 52 #include <sys/qmath.h> 53 #include <sys/stats.h> 54 #include <sys/sysctl.h> 55 #include <sys/jail.h> 56 #include <sys/malloc.h> 57 #include <sys/refcount.h> 58 #include <sys/mbuf.h> 59 #include <sys/priv.h> 60 #include <sys/sdt.h> 61 #include <sys/socket.h> 62 #include <sys/socketvar.h> 63 #include <sys/protosw.h> 64 #include <sys/random.h> 65 66 #include <vm/uma.h> 67 68 #include <net/route.h> 69 #include <net/route/nhop.h> 70 #include <net/if.h> 71 #include <net/if_var.h> 72 #include <net/if_private.h> 73 #include <net/vnet.h> 74 75 #include <netinet/in.h> 76 #include <netinet/in_fib.h> 77 #include <netinet/in_kdtrace.h> 78 #include <netinet/in_pcb.h> 79 #include <netinet/in_systm.h> 80 #include <netinet/in_var.h> 81 #include <netinet/ip.h> 82 #include <netinet/ip_icmp.h> 83 #include <netinet/ip_var.h> 84 #include <netinet/icmp_var.h> 85 #ifdef INET6 86 #include <netinet/icmp6.h> 87 #include <netinet/ip6.h> 88 #include <netinet6/in6_fib.h> 89 #include <netinet6/in6_pcb.h> 90 #include <netinet6/ip6_var.h> 91 #include <netinet6/scope6_var.h> 92 #include <netinet6/nd6.h> 93 #endif 94 95 #include <netinet/tcp.h> 96 #ifdef INVARIANTS 97 #define TCPSTATES 98 #endif 99 #include <netinet/tcp_fsm.h> 100 #include <netinet/tcp_seq.h> 101 #include <netinet/tcp_timer.h> 102 #include <netinet/tcp_var.h> 103 #include <netinet/tcp_ecn.h> 104 #include <netinet/tcp_log_buf.h> 105 #include <netinet/tcp_syncache.h> 106 #include <netinet/tcp_hpts.h> 107 #include <netinet/tcp_lro.h> 108 #include <netinet/cc/cc.h> 109 #include <netinet/tcpip.h> 110 #include <netinet/tcp_fastopen.h> 111 #include <netinet/tcp_accounting.h> 112 #ifdef TCP_OFFLOAD 113 #include <netinet/tcp_offload.h> 114 #endif 115 #include <netinet/udp.h> 116 #include <netinet/udp_var.h> 117 #ifdef INET6 118 #include <netinet6/tcp6_var.h> 119 #endif 120 121 #include <netipsec/ipsec_support.h> 122 123 #include <machine/in_cksum.h> 124 #include <crypto/siphash/siphash.h> 125 126 #include <security/mac/mac_framework.h> 127 128 #ifdef INET6 129 static ip6proto_ctlinput_t tcp6_ctlinput; 130 static udp_tun_icmp_t tcp6_ctlinput_viaudp; 131 #endif 132 133 VNET_DEFINE(int, tcp_mssdflt) = TCP_MSS; 134 #ifdef INET6 135 VNET_DEFINE(int, tcp_v6mssdflt) = TCP6_MSS; 136 #endif 137 138 VNET_DEFINE(uint32_t, tcp_ack_war_time_window) = 1000; 139 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, ack_war_timewindow, 140 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(tcp_ack_war_time_window), 0, 141 "Time interval in ms used to limit the number (ack_war_cnt) of challenge ACKs sent per TCP connection"); 142 VNET_DEFINE(uint32_t, tcp_ack_war_cnt) = 5; 143 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, ack_war_cnt, CTLFLAG_VNET | CTLFLAG_RW, 144 &VNET_NAME(tcp_ack_war_cnt), 0, 145 "Maximum number of challenge ACKs sent per TCP connection during the time interval (ack_war_timewindow)"); 146 147 struct rwlock tcp_function_lock; 148 149 static int 150 sysctl_net_inet_tcp_mss_check(SYSCTL_HANDLER_ARGS) 151 { 152 int error, new; 153 154 new = V_tcp_mssdflt; 155 error = sysctl_handle_int(oidp, &new, 0, req); 156 if (error == 0 && req->newptr) { 157 if (new < TCP_MINMSS) 158 error = EINVAL; 159 else 160 V_tcp_mssdflt = new; 161 } 162 return (error); 163 } 164 165 SYSCTL_PROC(_net_inet_tcp, TCPCTL_MSSDFLT, mssdflt, 166 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, 167 &VNET_NAME(tcp_mssdflt), 0, &sysctl_net_inet_tcp_mss_check, "I", 168 "Default TCP Maximum Segment Size"); 169 170 #ifdef INET6 171 static int 172 sysctl_net_inet_tcp_mss_v6_check(SYSCTL_HANDLER_ARGS) 173 { 174 int error, new; 175 176 new = V_tcp_v6mssdflt; 177 error = sysctl_handle_int(oidp, &new, 0, req); 178 if (error == 0 && req->newptr) { 179 if (new < TCP_MINMSS) 180 error = EINVAL; 181 else 182 V_tcp_v6mssdflt = new; 183 } 184 return (error); 185 } 186 187 SYSCTL_PROC(_net_inet_tcp, TCPCTL_V6MSSDFLT, v6mssdflt, 188 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, 189 &VNET_NAME(tcp_v6mssdflt), 0, &sysctl_net_inet_tcp_mss_v6_check, "I", 190 "Default TCP Maximum Segment Size for IPv6"); 191 #endif /* INET6 */ 192 193 /* 194 * Minimum MSS we accept and use. This prevents DoS attacks where 195 * we are forced to a ridiculous low MSS like 20 and send hundreds 196 * of packets instead of one. The effect scales with the available 197 * bandwidth and quickly saturates the CPU and network interface 198 * with packet generation and sending. Set to zero to disable MINMSS 199 * checking. This setting prevents us from sending too small packets. 200 */ 201 VNET_DEFINE(int, tcp_minmss) = TCP_MINMSS; 202 SYSCTL_INT(_net_inet_tcp, OID_AUTO, minmss, CTLFLAG_VNET | CTLFLAG_RW, 203 &VNET_NAME(tcp_minmss), 0, 204 "Minimum TCP Maximum Segment Size"); 205 206 VNET_DEFINE(int, tcp_do_rfc1323) = 1; 207 SYSCTL_INT(_net_inet_tcp, TCPCTL_DO_RFC1323, rfc1323, CTLFLAG_VNET | CTLFLAG_RW, 208 &VNET_NAME(tcp_do_rfc1323), 0, 209 "Enable rfc1323 (high performance TCP) extensions"); 210 211 /* 212 * As of June 2021, several TCP stacks violate RFC 7323 from September 2014. 213 * Some stacks negotiate TS, but never send them after connection setup. Some 214 * stacks negotiate TS, but don't send them when sending keep-alive segments. 215 * These include modern widely deployed TCP stacks. 216 * Therefore tolerating violations for now... 217 */ 218 VNET_DEFINE(int, tcp_tolerate_missing_ts) = 1; 219 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tolerate_missing_ts, CTLFLAG_VNET | CTLFLAG_RW, 220 &VNET_NAME(tcp_tolerate_missing_ts), 0, 221 "Tolerate missing TCP timestamps"); 222 223 VNET_DEFINE(int, tcp_ts_offset_per_conn) = 1; 224 SYSCTL_INT(_net_inet_tcp, OID_AUTO, ts_offset_per_conn, CTLFLAG_VNET | CTLFLAG_RW, 225 &VNET_NAME(tcp_ts_offset_per_conn), 0, 226 "Initialize TCP timestamps per connection instead of per host pair"); 227 228 /* How many connections are pacing */ 229 static volatile uint32_t number_of_tcp_connections_pacing = 0; 230 static uint32_t shadow_num_connections = 0; 231 static counter_u64_t tcp_pacing_failures; 232 static counter_u64_t tcp_dgp_failures; 233 static uint32_t shadow_tcp_pacing_dgp = 0; 234 static volatile uint32_t number_of_dgp_connections = 0; 235 236 static int tcp_pacing_limit = 10000; 237 SYSCTL_INT(_net_inet_tcp, OID_AUTO, pacing_limit, CTLFLAG_RW, 238 &tcp_pacing_limit, 1000, 239 "If the TCP stack does pacing, is there a limit (-1 = no, 0 = no pacing N = number of connections)"); 240 241 static int tcp_dgp_limit = -1; 242 SYSCTL_INT(_net_inet_tcp, OID_AUTO, dgp_limit, CTLFLAG_RW, 243 &tcp_dgp_limit, -1, 244 "If the TCP stack does DGP, is there a limit (-1 = no, 0 = no dgp N = number of connections)"); 245 246 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, pacing_count, CTLFLAG_RD, 247 &shadow_num_connections, 0, "Number of TCP connections being paced"); 248 249 SYSCTL_COUNTER_U64(_net_inet_tcp, OID_AUTO, pacing_failures, CTLFLAG_RD, 250 &tcp_pacing_failures, "Number of times we failed to enable pacing to avoid exceeding the limit"); 251 252 SYSCTL_COUNTER_U64(_net_inet_tcp, OID_AUTO, dgp_failures, CTLFLAG_RD, 253 &tcp_dgp_failures, "Number of times we failed to enable dgp to avoid exceeding the limit"); 254 255 static int tcp_log_debug = 0; 256 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_debug, CTLFLAG_RW, 257 &tcp_log_debug, 0, "Log errors caused by incoming TCP segments"); 258 259 /* 260 * Target size of TCP PCB hash tables. Must be a power of two. 261 * 262 * Note that this can be overridden by the kernel environment 263 * variable net.inet.tcp.tcbhashsize 264 */ 265 #ifndef TCBHASHSIZE 266 #define TCBHASHSIZE 0 267 #endif 268 static int tcp_tcbhashsize = TCBHASHSIZE; 269 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tcbhashsize, CTLFLAG_RDTUN, 270 &tcp_tcbhashsize, 0, "Size of TCP control-block hashtable"); 271 272 static int do_tcpdrain = 1; 273 SYSCTL_INT(_net_inet_tcp, OID_AUTO, do_tcpdrain, CTLFLAG_RW, &do_tcpdrain, 0, 274 "Enable tcp_drain routine for extra help when low on mbufs"); 275 276 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, pcbcount, CTLFLAG_VNET | CTLFLAG_RD, 277 &VNET_NAME(tcbinfo.ipi_count), 0, "Number of active PCBs"); 278 279 VNET_DEFINE_STATIC(int, icmp_may_rst) = 1; 280 #define V_icmp_may_rst VNET(icmp_may_rst) 281 SYSCTL_INT(_net_inet_tcp, OID_AUTO, icmp_may_rst, CTLFLAG_VNET | CTLFLAG_RW, 282 &VNET_NAME(icmp_may_rst), 0, 283 "Certain ICMP unreachable messages may abort connections in SYN_SENT"); 284 285 VNET_DEFINE_STATIC(int, tcp_isn_reseed_interval) = 0; 286 #define V_tcp_isn_reseed_interval VNET(tcp_isn_reseed_interval) 287 SYSCTL_INT(_net_inet_tcp, OID_AUTO, isn_reseed_interval, CTLFLAG_VNET | CTLFLAG_RW, 288 &VNET_NAME(tcp_isn_reseed_interval), 0, 289 "Seconds between reseeding of ISN secret"); 290 291 static int tcp_soreceive_stream; 292 SYSCTL_INT(_net_inet_tcp, OID_AUTO, soreceive_stream, CTLFLAG_RDTUN, 293 &tcp_soreceive_stream, 0, "Using soreceive_stream for TCP sockets"); 294 295 VNET_DEFINE(uma_zone_t, sack_hole_zone); 296 #define V_sack_hole_zone VNET(sack_hole_zone) 297 VNET_DEFINE(uint32_t, tcp_map_entries_limit) = 0; /* unlimited */ 298 static int 299 sysctl_net_inet_tcp_map_limit_check(SYSCTL_HANDLER_ARGS) 300 { 301 int error; 302 uint32_t new; 303 304 new = V_tcp_map_entries_limit; 305 error = sysctl_handle_int(oidp, &new, 0, req); 306 if (error == 0 && req->newptr) { 307 /* only allow "0" and value > minimum */ 308 if (new > 0 && new < TCP_MIN_MAP_ENTRIES_LIMIT) 309 error = EINVAL; 310 else 311 V_tcp_map_entries_limit = new; 312 } 313 return (error); 314 } 315 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, map_limit, 316 CTLFLAG_VNET | CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, 317 &VNET_NAME(tcp_map_entries_limit), 0, 318 &sysctl_net_inet_tcp_map_limit_check, "IU", 319 "Total sendmap entries limit"); 320 321 VNET_DEFINE(uint32_t, tcp_map_split_limit) = 0; /* unlimited */ 322 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, split_limit, CTLFLAG_VNET | CTLFLAG_RW, 323 &VNET_NAME(tcp_map_split_limit), 0, 324 "Total sendmap split entries limit"); 325 326 #ifdef TCP_HHOOK 327 VNET_DEFINE(struct hhook_head *, tcp_hhh[HHOOK_TCP_LAST+1]); 328 #endif 329 330 #define TS_OFFSET_SECRET_LENGTH SIPHASH_KEY_LENGTH 331 VNET_DEFINE_STATIC(u_char, ts_offset_secret[TS_OFFSET_SECRET_LENGTH]); 332 #define V_ts_offset_secret VNET(ts_offset_secret) 333 334 static int tcp_default_fb_init(struct tcpcb *tp, void **ptr); 335 static void tcp_default_fb_fini(struct tcpcb *tp, int tcb_is_purged); 336 static int tcp_default_handoff_ok(struct tcpcb *tp); 337 static struct inpcb *tcp_notify(struct inpcb *, int); 338 static struct inpcb *tcp_mtudisc_notify(struct inpcb *, int); 339 static struct inpcb *tcp_mtudisc(struct inpcb *, int); 340 static struct inpcb *tcp_drop_syn_sent(struct inpcb *, int); 341 static char * tcp_log_addr(struct in_conninfo *inc, struct tcphdr *th, 342 const void *ip4hdr, const void *ip6hdr); 343 static void tcp_default_switch_failed(struct tcpcb *tp); 344 345 #ifdef INET 346 static ipproto_ctlinput_t tcp_ctlinput; 347 static udp_tun_icmp_t tcp_ctlinput_viaudp; 348 #endif 349 350 static struct tcp_function_block tcp_def_funcblk = { 351 .tfb_tcp_block_name = "freebsd", 352 .tfb_tcp_output = tcp_default_output, 353 .tfb_tcp_do_segment = tcp_do_segment, 354 .tfb_tcp_ctloutput = tcp_default_ctloutput, 355 .tfb_tcp_handoff_ok = tcp_default_handoff_ok, 356 .tfb_tcp_fb_init = tcp_default_fb_init, 357 .tfb_tcp_fb_fini = tcp_default_fb_fini, 358 .tfb_switch_failed = tcp_default_switch_failed, 359 .tfb_flags = TCP_FUNC_DEFAULT_OK, 360 }; 361 362 static int tcp_fb_cnt = 0; 363 struct tcp_funchead t_functions; 364 VNET_DEFINE_STATIC(struct tcp_function_block *, tcp_func_set_ptr) = &tcp_def_funcblk; 365 #define V_tcp_func_set_ptr VNET(tcp_func_set_ptr) 366 367 void 368 tcp_record_dsack(struct tcpcb *tp, tcp_seq start, tcp_seq end, int tlp) 369 { 370 TCPSTAT_INC(tcps_dsack_count); 371 tp->t_dsack_pack++; 372 if (tlp == 0) { 373 if (SEQ_GT(end, start)) { 374 tp->t_dsack_bytes += (end - start); 375 TCPSTAT_ADD(tcps_dsack_bytes, (end - start)); 376 } else { 377 tp->t_dsack_tlp_bytes += (start - end); 378 TCPSTAT_ADD(tcps_dsack_bytes, (start - end)); 379 } 380 } else { 381 if (SEQ_GT(end, start)) { 382 tp->t_dsack_bytes += (end - start); 383 TCPSTAT_ADD(tcps_dsack_tlp_bytes, (end - start)); 384 } else { 385 tp->t_dsack_tlp_bytes += (start - end); 386 TCPSTAT_ADD(tcps_dsack_tlp_bytes, (start - end)); 387 } 388 } 389 } 390 391 static struct tcp_function_block * 392 find_tcp_functions_locked(struct tcp_function_set *fs) 393 { 394 struct tcp_function *f; 395 struct tcp_function_block *blk = NULL; 396 397 rw_assert(&tcp_function_lock, RA_LOCKED); 398 TAILQ_FOREACH(f, &t_functions, tf_next) { 399 if (strcmp(f->tf_name, fs->function_set_name) == 0) { 400 blk = f->tf_fb; 401 break; 402 } 403 } 404 return (blk); 405 } 406 407 static struct tcp_function_block * 408 find_tcp_fb_locked(struct tcp_function_block *blk, struct tcp_function **s) 409 { 410 struct tcp_function_block *rblk = NULL; 411 struct tcp_function *f; 412 413 rw_assert(&tcp_function_lock, RA_LOCKED); 414 TAILQ_FOREACH(f, &t_functions, tf_next) { 415 if (f->tf_fb == blk) { 416 rblk = blk; 417 if (s) { 418 *s = f; 419 } 420 break; 421 } 422 } 423 return (rblk); 424 } 425 426 struct tcp_function_block * 427 find_and_ref_tcp_functions(struct tcp_function_set *fs) 428 { 429 struct tcp_function_block *blk; 430 431 rw_rlock(&tcp_function_lock); 432 blk = find_tcp_functions_locked(fs); 433 if (blk) 434 refcount_acquire(&blk->tfb_refcnt); 435 rw_runlock(&tcp_function_lock); 436 return (blk); 437 } 438 439 struct tcp_function_block * 440 find_and_ref_tcp_fb(struct tcp_function_block *blk) 441 { 442 struct tcp_function_block *rblk; 443 444 rw_rlock(&tcp_function_lock); 445 rblk = find_tcp_fb_locked(blk, NULL); 446 if (rblk) 447 refcount_acquire(&rblk->tfb_refcnt); 448 rw_runlock(&tcp_function_lock); 449 return (rblk); 450 } 451 452 /* Find a matching alias for the given tcp_function_block. */ 453 int 454 find_tcp_function_alias(struct tcp_function_block *blk, 455 struct tcp_function_set *fs) 456 { 457 struct tcp_function *f; 458 int found; 459 460 found = 0; 461 rw_rlock(&tcp_function_lock); 462 TAILQ_FOREACH(f, &t_functions, tf_next) { 463 if ((f->tf_fb == blk) && 464 (strncmp(f->tf_name, blk->tfb_tcp_block_name, 465 TCP_FUNCTION_NAME_LEN_MAX) != 0)) { 466 /* Matching function block with different name. */ 467 strncpy(fs->function_set_name, f->tf_name, 468 TCP_FUNCTION_NAME_LEN_MAX); 469 found = 1; 470 break; 471 } 472 } 473 /* Null terminate the string appropriately. */ 474 if (found) { 475 fs->function_set_name[TCP_FUNCTION_NAME_LEN_MAX - 1] = '\0'; 476 } else { 477 fs->function_set_name[0] = '\0'; 478 } 479 rw_runlock(&tcp_function_lock); 480 return (found); 481 } 482 483 static struct tcp_function_block * 484 find_and_ref_tcp_default_fb(void) 485 { 486 struct tcp_function_block *rblk; 487 488 rw_rlock(&tcp_function_lock); 489 rblk = V_tcp_func_set_ptr; 490 refcount_acquire(&rblk->tfb_refcnt); 491 rw_runlock(&tcp_function_lock); 492 return (rblk); 493 } 494 495 void 496 tcp_switch_back_to_default(struct tcpcb *tp) 497 { 498 struct tcp_function_block *tfb; 499 void *ptr = NULL; 500 501 KASSERT(tp->t_fb != &tcp_def_funcblk, 502 ("%s: called by the built-in default stack", __func__)); 503 504 if (tp->t_fb->tfb_tcp_timer_stop_all != NULL) 505 tp->t_fb->tfb_tcp_timer_stop_all(tp); 506 507 /* 508 * Now, we'll find a new function block to use. 509 * Start by trying the current user-selected 510 * default, unless this stack is the user-selected 511 * default. 512 */ 513 tfb = find_and_ref_tcp_default_fb(); 514 if (tfb == tp->t_fb) { 515 refcount_release(&tfb->tfb_refcnt); 516 tfb = NULL; 517 } 518 /* Does the stack accept this connection? */ 519 if (tfb != NULL && (*tfb->tfb_tcp_handoff_ok)(tp)) { 520 refcount_release(&tfb->tfb_refcnt); 521 tfb = NULL; 522 } 523 /* Try to use that stack. */ 524 if (tfb != NULL) { 525 /* Initialize the new stack. If it succeeds, we are done. */ 526 if (tfb->tfb_tcp_fb_init == NULL || 527 (*tfb->tfb_tcp_fb_init)(tp, &ptr) == 0) { 528 /* Release the old stack */ 529 if (tp->t_fb->tfb_tcp_fb_fini != NULL) 530 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 0); 531 refcount_release(&tp->t_fb->tfb_refcnt); 532 /* Now set in all the pointers */ 533 tp->t_fb = tfb; 534 tp->t_fb_ptr = ptr; 535 return; 536 } 537 /* 538 * Initialization failed. Release the reference count on 539 * the looked up default stack. 540 */ 541 refcount_release(&tfb->tfb_refcnt); 542 } 543 544 /* 545 * If that wasn't feasible, use the built-in default 546 * stack which is not allowed to reject anyone. 547 */ 548 tfb = find_and_ref_tcp_fb(&tcp_def_funcblk); 549 if (tfb == NULL) { 550 /* there always should be a default */ 551 panic("Can't refer to tcp_def_funcblk"); 552 } 553 if ((*tfb->tfb_tcp_handoff_ok)(tp)) { 554 /* The default stack cannot say no */ 555 panic("Default stack rejects a new session?"); 556 } 557 if (tfb->tfb_tcp_fb_init != NULL && 558 (*tfb->tfb_tcp_fb_init)(tp, &ptr)) { 559 /* The default stack cannot fail */ 560 panic("Default stack initialization failed"); 561 } 562 /* Now release the old stack */ 563 if (tp->t_fb->tfb_tcp_fb_fini != NULL) 564 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 0); 565 refcount_release(&tp->t_fb->tfb_refcnt); 566 /* And set in the pointers to the new */ 567 tp->t_fb = tfb; 568 tp->t_fb_ptr = ptr; 569 } 570 571 static bool 572 tcp_recv_udp_tunneled_packet(struct mbuf *m, int off, struct inpcb *inp, 573 const struct sockaddr *sa, void *ctx) 574 { 575 struct ip *iph; 576 #ifdef INET6 577 struct ip6_hdr *ip6; 578 #endif 579 struct udphdr *uh; 580 struct tcphdr *th; 581 int len, thlen; 582 uint16_t port; 583 584 TCPSTAT_INC(tcps_tunneled_pkts); 585 if ((m->m_flags & M_PKTHDR) == 0) { 586 /* Can't handle one that is not a pkt hdr */ 587 TCPSTAT_INC(tcps_tunneled_errs); 588 m_freem(m); 589 return (true); 590 } 591 thlen = sizeof(struct tcphdr); 592 if (m->m_len < off + sizeof(struct udphdr) + thlen && 593 (m = m_pullup(m, off + sizeof(struct udphdr) + thlen)) == NULL) { 594 TCPSTAT_INC(tcps_tunneled_errs); 595 return (true); 596 } 597 iph = mtod(m, struct ip *); 598 uh = (struct udphdr *)((caddr_t)iph + off); 599 th = (struct tcphdr *)(uh + 1); 600 thlen = th->th_off << 2; 601 if (m->m_len < off + sizeof(struct udphdr) + thlen) { 602 m = m_pullup(m, off + sizeof(struct udphdr) + thlen); 603 if (m == NULL) { 604 TCPSTAT_INC(tcps_tunneled_errs); 605 return (true); 606 } else { 607 iph = mtod(m, struct ip *); 608 uh = (struct udphdr *)((caddr_t)iph + off); 609 th = (struct tcphdr *)(uh + 1); 610 } 611 } 612 m->m_pkthdr.tcp_tun_port = port = uh->uh_sport; 613 bcopy(th, uh, m->m_len - off - sizeof(struct udphdr)); 614 m->m_len -= sizeof(struct udphdr); 615 m->m_pkthdr.len -= sizeof(struct udphdr); 616 /* 617 * We use the same algorithm for 618 * both UDP and TCP for c-sum. So 619 * the code in tcp_input will skip 620 * the checksum. So we do nothing 621 * with the flag (m->m_pkthdr.csum_flags). 622 */ 623 switch (iph->ip_v) { 624 #ifdef INET 625 case IPVERSION: 626 len = ntohs(iph->ip_len) - sizeof(struct udphdr); 627 if (__predict_false(len != m->m_pkthdr.len)) { 628 TCPSTAT_INC(tcps_tunneled_errs); 629 m_freem(m); 630 return (true); 631 } else { 632 iph->ip_len = htons(len); 633 tcp_input_with_port(&m, &off, IPPROTO_TCP, port); 634 } 635 break; 636 #endif 637 #ifdef INET6 638 case IPV6_VERSION >> 4: 639 ip6 = mtod(m, struct ip6_hdr *); 640 len = ntohs(ip6->ip6_plen) - sizeof(struct udphdr); 641 if (__predict_false(len + sizeof(struct ip6_hdr) != 642 m->m_pkthdr.len)) { 643 TCPSTAT_INC(tcps_tunneled_errs); 644 m_freem(m); 645 return (true); 646 } else { 647 ip6->ip6_plen = htons(len); 648 tcp6_input_with_port(&m, &off, IPPROTO_TCP, port); 649 } 650 break; 651 #endif 652 default: 653 m_freem(m); 654 break; 655 } 656 return (true); 657 } 658 659 static int 660 sysctl_net_inet_default_tcp_functions(SYSCTL_HANDLER_ARGS) 661 { 662 struct tcp_function_set fs; 663 struct tcp_function_block *blk; 664 int error; 665 666 memset(&fs, 0, sizeof(struct tcp_function_set)); 667 rw_rlock(&tcp_function_lock); 668 blk = find_tcp_fb_locked(V_tcp_func_set_ptr, NULL); 669 if (blk != NULL) { 670 /* Found him */ 671 strcpy(fs.function_set_name, blk->tfb_tcp_block_name); 672 fs.pcbcnt = blk->tfb_refcnt; 673 } 674 rw_runlock(&tcp_function_lock); 675 error = sysctl_handle_string(oidp, fs.function_set_name, 676 sizeof(fs.function_set_name), req); 677 678 /* Check for error or no change */ 679 if (error != 0 || req->newptr == NULL) 680 return (error); 681 682 rw_wlock(&tcp_function_lock); 683 blk = find_tcp_functions_locked(&fs); 684 if ((blk == NULL) || 685 (blk->tfb_flags & TCP_FUNC_BEING_REMOVED)) { 686 error = ENOENT; 687 goto done; 688 } 689 if ((blk->tfb_flags & TCP_FUNC_DEFAULT_OK) == 0) { 690 error = EINVAL; 691 goto done; 692 } 693 V_tcp_func_set_ptr = blk; 694 done: 695 rw_wunlock(&tcp_function_lock); 696 return (error); 697 } 698 699 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, functions_default, 700 CTLFLAG_VNET | CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_NEEDGIANT, 701 NULL, 0, sysctl_net_inet_default_tcp_functions, "A", 702 "Set/get the default TCP functions"); 703 704 static int 705 sysctl_net_inet_list_available(SYSCTL_HANDLER_ARGS) 706 { 707 int error, cnt, linesz; 708 struct tcp_function *f; 709 char *buffer, *cp; 710 size_t bufsz, outsz; 711 bool alias; 712 713 cnt = 0; 714 rw_rlock(&tcp_function_lock); 715 TAILQ_FOREACH(f, &t_functions, tf_next) { 716 cnt++; 717 } 718 rw_runlock(&tcp_function_lock); 719 720 bufsz = (cnt+2) * ((TCP_FUNCTION_NAME_LEN_MAX * 2) + 13) + 1; 721 buffer = malloc(bufsz, M_TEMP, M_WAITOK); 722 723 error = 0; 724 cp = buffer; 725 726 linesz = snprintf(cp, bufsz, "\n%-32s%c %-32s %s\n", "Stack", 'D', 727 "Alias", "PCB count"); 728 cp += linesz; 729 bufsz -= linesz; 730 outsz = linesz; 731 732 rw_rlock(&tcp_function_lock); 733 TAILQ_FOREACH(f, &t_functions, tf_next) { 734 alias = (f->tf_name != f->tf_fb->tfb_tcp_block_name); 735 linesz = snprintf(cp, bufsz, "%-32s%c %-32s %u\n", 736 f->tf_fb->tfb_tcp_block_name, 737 (f->tf_fb == V_tcp_func_set_ptr) ? '*' : ' ', 738 alias ? f->tf_name : "-", 739 f->tf_fb->tfb_refcnt); 740 if (linesz >= bufsz) { 741 error = EOVERFLOW; 742 break; 743 } 744 cp += linesz; 745 bufsz -= linesz; 746 outsz += linesz; 747 } 748 rw_runlock(&tcp_function_lock); 749 if (error == 0) 750 error = sysctl_handle_string(oidp, buffer, outsz + 1, req); 751 free(buffer, M_TEMP); 752 return (error); 753 } 754 755 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, functions_available, 756 CTLFLAG_VNET | CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT, 757 NULL, 0, sysctl_net_inet_list_available, "A", 758 "list available TCP Function sets"); 759 760 VNET_DEFINE(int, tcp_udp_tunneling_port) = TCP_TUNNELING_PORT_DEFAULT; 761 762 #ifdef INET 763 VNET_DEFINE(struct socket *, udp4_tun_socket) = NULL; 764 #define V_udp4_tun_socket VNET(udp4_tun_socket) 765 #endif 766 #ifdef INET6 767 VNET_DEFINE(struct socket *, udp6_tun_socket) = NULL; 768 #define V_udp6_tun_socket VNET(udp6_tun_socket) 769 #endif 770 771 static struct sx tcpoudp_lock; 772 773 static void 774 tcp_over_udp_stop(void) 775 { 776 777 sx_assert(&tcpoudp_lock, SA_XLOCKED); 778 779 #ifdef INET 780 if (V_udp4_tun_socket != NULL) { 781 soclose(V_udp4_tun_socket); 782 V_udp4_tun_socket = NULL; 783 } 784 #endif 785 #ifdef INET6 786 if (V_udp6_tun_socket != NULL) { 787 soclose(V_udp6_tun_socket); 788 V_udp6_tun_socket = NULL; 789 } 790 #endif 791 } 792 793 static int 794 tcp_over_udp_start(void) 795 { 796 uint16_t port; 797 int ret; 798 #ifdef INET 799 struct sockaddr_in sin; 800 #endif 801 #ifdef INET6 802 struct sockaddr_in6 sin6; 803 #endif 804 805 sx_assert(&tcpoudp_lock, SA_XLOCKED); 806 807 port = V_tcp_udp_tunneling_port; 808 if (ntohs(port) == 0) { 809 /* Must have a port set */ 810 return (EINVAL); 811 } 812 #ifdef INET 813 if (V_udp4_tun_socket != NULL) { 814 /* Already running -- must stop first */ 815 return (EALREADY); 816 } 817 #endif 818 #ifdef INET6 819 if (V_udp6_tun_socket != NULL) { 820 /* Already running -- must stop first */ 821 return (EALREADY); 822 } 823 #endif 824 #ifdef INET 825 if ((ret = socreate(PF_INET, &V_udp4_tun_socket, 826 SOCK_DGRAM, IPPROTO_UDP, 827 curthread->td_ucred, curthread))) { 828 tcp_over_udp_stop(); 829 return (ret); 830 } 831 /* Call the special UDP hook. */ 832 if ((ret = udp_set_kernel_tunneling(V_udp4_tun_socket, 833 tcp_recv_udp_tunneled_packet, 834 tcp_ctlinput_viaudp, 835 NULL))) { 836 tcp_over_udp_stop(); 837 return (ret); 838 } 839 /* Ok, we have a socket, bind it to the port. */ 840 memset(&sin, 0, sizeof(struct sockaddr_in)); 841 sin.sin_len = sizeof(struct sockaddr_in); 842 sin.sin_family = AF_INET; 843 sin.sin_port = htons(port); 844 if ((ret = sobind(V_udp4_tun_socket, 845 (struct sockaddr *)&sin, curthread))) { 846 tcp_over_udp_stop(); 847 return (ret); 848 } 849 #endif 850 #ifdef INET6 851 if ((ret = socreate(PF_INET6, &V_udp6_tun_socket, 852 SOCK_DGRAM, IPPROTO_UDP, 853 curthread->td_ucred, curthread))) { 854 tcp_over_udp_stop(); 855 return (ret); 856 } 857 /* Call the special UDP hook. */ 858 if ((ret = udp_set_kernel_tunneling(V_udp6_tun_socket, 859 tcp_recv_udp_tunneled_packet, 860 tcp6_ctlinput_viaudp, 861 NULL))) { 862 tcp_over_udp_stop(); 863 return (ret); 864 } 865 /* Ok, we have a socket, bind it to the port. */ 866 memset(&sin6, 0, sizeof(struct sockaddr_in6)); 867 sin6.sin6_len = sizeof(struct sockaddr_in6); 868 sin6.sin6_family = AF_INET6; 869 sin6.sin6_port = htons(port); 870 if ((ret = sobind(V_udp6_tun_socket, 871 (struct sockaddr *)&sin6, curthread))) { 872 tcp_over_udp_stop(); 873 return (ret); 874 } 875 #endif 876 return (0); 877 } 878 879 static int 880 sysctl_net_inet_tcp_udp_tunneling_port_check(SYSCTL_HANDLER_ARGS) 881 { 882 int error; 883 uint32_t old, new; 884 885 old = V_tcp_udp_tunneling_port; 886 new = old; 887 error = sysctl_handle_int(oidp, &new, 0, req); 888 if ((error == 0) && 889 (req->newptr != NULL)) { 890 if ((new < TCP_TUNNELING_PORT_MIN) || 891 (new > TCP_TUNNELING_PORT_MAX)) { 892 error = EINVAL; 893 } else { 894 sx_xlock(&tcpoudp_lock); 895 V_tcp_udp_tunneling_port = new; 896 if (old != 0) { 897 tcp_over_udp_stop(); 898 } 899 if (new != 0) { 900 error = tcp_over_udp_start(); 901 if (error != 0) { 902 V_tcp_udp_tunneling_port = 0; 903 } 904 } 905 sx_xunlock(&tcpoudp_lock); 906 } 907 } 908 return (error); 909 } 910 911 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, udp_tunneling_port, 912 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, 913 &VNET_NAME(tcp_udp_tunneling_port), 914 0, &sysctl_net_inet_tcp_udp_tunneling_port_check, "IU", 915 "Tunneling port for tcp over udp"); 916 917 VNET_DEFINE(int, tcp_udp_tunneling_overhead) = TCP_TUNNELING_OVERHEAD_DEFAULT; 918 919 static int 920 sysctl_net_inet_tcp_udp_tunneling_overhead_check(SYSCTL_HANDLER_ARGS) 921 { 922 int error, new; 923 924 new = V_tcp_udp_tunneling_overhead; 925 error = sysctl_handle_int(oidp, &new, 0, req); 926 if (error == 0 && req->newptr) { 927 if ((new < TCP_TUNNELING_OVERHEAD_MIN) || 928 (new > TCP_TUNNELING_OVERHEAD_MAX)) 929 error = EINVAL; 930 else 931 V_tcp_udp_tunneling_overhead = new; 932 } 933 return (error); 934 } 935 936 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, udp_tunneling_overhead, 937 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, 938 &VNET_NAME(tcp_udp_tunneling_overhead), 939 0, &sysctl_net_inet_tcp_udp_tunneling_overhead_check, "IU", 940 "MSS reduction when using tcp over udp"); 941 942 /* 943 * Exports one (struct tcp_function_info) for each alias/name. 944 */ 945 static int 946 sysctl_net_inet_list_func_info(SYSCTL_HANDLER_ARGS) 947 { 948 int cnt, error; 949 struct tcp_function *f; 950 struct tcp_function_info tfi; 951 952 /* 953 * We don't allow writes. 954 */ 955 if (req->newptr != NULL) 956 return (EINVAL); 957 958 /* 959 * Wire the old buffer so we can directly copy the functions to 960 * user space without dropping the lock. 961 */ 962 if (req->oldptr != NULL) { 963 error = sysctl_wire_old_buffer(req, 0); 964 if (error) 965 return (error); 966 } 967 968 /* 969 * Walk the list and copy out matching entries. If INVARIANTS 970 * is compiled in, also walk the list to verify the length of 971 * the list matches what we have recorded. 972 */ 973 rw_rlock(&tcp_function_lock); 974 975 cnt = 0; 976 #ifndef INVARIANTS 977 if (req->oldptr == NULL) { 978 cnt = tcp_fb_cnt; 979 goto skip_loop; 980 } 981 #endif 982 TAILQ_FOREACH(f, &t_functions, tf_next) { 983 #ifdef INVARIANTS 984 cnt++; 985 #endif 986 if (req->oldptr != NULL) { 987 bzero(&tfi, sizeof(tfi)); 988 tfi.tfi_refcnt = f->tf_fb->tfb_refcnt; 989 tfi.tfi_id = f->tf_fb->tfb_id; 990 (void)strlcpy(tfi.tfi_alias, f->tf_name, 991 sizeof(tfi.tfi_alias)); 992 (void)strlcpy(tfi.tfi_name, 993 f->tf_fb->tfb_tcp_block_name, sizeof(tfi.tfi_name)); 994 error = SYSCTL_OUT(req, &tfi, sizeof(tfi)); 995 /* 996 * Don't stop on error, as that is the 997 * mechanism we use to accumulate length 998 * information if the buffer was too short. 999 */ 1000 } 1001 } 1002 KASSERT(cnt == tcp_fb_cnt, 1003 ("%s: cnt (%d) != tcp_fb_cnt (%d)", __func__, cnt, tcp_fb_cnt)); 1004 #ifndef INVARIANTS 1005 skip_loop: 1006 #endif 1007 rw_runlock(&tcp_function_lock); 1008 if (req->oldptr == NULL) 1009 error = SYSCTL_OUT(req, NULL, 1010 (cnt + 1) * sizeof(struct tcp_function_info)); 1011 1012 return (error); 1013 } 1014 1015 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, function_info, 1016 CTLTYPE_OPAQUE | CTLFLAG_SKIP | CTLFLAG_RD | CTLFLAG_MPSAFE, 1017 NULL, 0, sysctl_net_inet_list_func_info, "S,tcp_function_info", 1018 "List TCP function block name-to-ID mappings"); 1019 1020 /* 1021 * tfb_tcp_handoff_ok() function for the default stack. 1022 * Note that we'll basically try to take all comers. 1023 */ 1024 static int 1025 tcp_default_handoff_ok(struct tcpcb *tp) 1026 { 1027 1028 return (0); 1029 } 1030 1031 /* 1032 * tfb_tcp_fb_init() function for the default stack. 1033 * 1034 * This handles making sure we have appropriate timers set if you are 1035 * transitioning a socket that has some amount of setup done. 1036 * 1037 * The init() fuction from the default can *never* return non-zero i.e. 1038 * it is required to always succeed since it is the stack of last resort! 1039 */ 1040 static int 1041 tcp_default_fb_init(struct tcpcb *tp, void **ptr) 1042 { 1043 struct socket *so = tptosocket(tp); 1044 int rexmt; 1045 1046 INP_WLOCK_ASSERT(tptoinpcb(tp)); 1047 /* We don't use the pointer */ 1048 *ptr = NULL; 1049 1050 /* Make sure we get no interesting mbuf queuing behavior */ 1051 /* All mbuf queue/ack compress flags should be off */ 1052 tcp_lro_features_off(tp); 1053 1054 /* Cancel the GP measurement in progress */ 1055 tp->t_flags &= ~TF_GPUTINPROG; 1056 /* Validate the timers are not in usec, if they are convert */ 1057 tcp_change_time_units(tp, TCP_TMR_GRANULARITY_TICKS); 1058 if ((tp->t_state == TCPS_SYN_SENT) || 1059 (tp->t_state == TCPS_SYN_RECEIVED)) 1060 rexmt = tcp_rexmit_initial * tcp_backoff[tp->t_rxtshift]; 1061 else 1062 rexmt = TCP_REXMTVAL(tp) * tcp_backoff[tp->t_rxtshift]; 1063 if (tp->t_rxtshift == 0) 1064 tp->t_rxtcur = rexmt; 1065 else 1066 TCPT_RANGESET(tp->t_rxtcur, rexmt, tp->t_rttmin, 1067 tcp_rexmit_max); 1068 1069 /* 1070 * Nothing to do for ESTABLISHED or LISTEN states. And, we don't 1071 * know what to do for unexpected states (which includes TIME_WAIT). 1072 */ 1073 if (tp->t_state <= TCPS_LISTEN || tp->t_state >= TCPS_TIME_WAIT) 1074 return (0); 1075 1076 /* 1077 * Make sure some kind of transmission timer is set if there is 1078 * outstanding data. 1079 */ 1080 if ((!TCPS_HAVEESTABLISHED(tp->t_state) || sbavail(&so->so_snd) || 1081 tp->snd_una != tp->snd_max) && !(tcp_timer_active(tp, TT_REXMT) || 1082 tcp_timer_active(tp, TT_PERSIST))) { 1083 /* 1084 * If the session has established and it looks like it should 1085 * be in the persist state, set the persist timer. Otherwise, 1086 * set the retransmit timer. 1087 */ 1088 if (TCPS_HAVEESTABLISHED(tp->t_state) && tp->snd_wnd == 0 && 1089 (int32_t)(tp->snd_nxt - tp->snd_una) < 1090 (int32_t)sbavail(&so->so_snd)) 1091 tcp_setpersist(tp); 1092 else 1093 tcp_timer_activate(tp, TT_REXMT, TP_RXTCUR(tp)); 1094 } 1095 1096 /* All non-embryonic sessions get a keepalive timer. */ 1097 if (!tcp_timer_active(tp, TT_KEEP)) 1098 tcp_timer_activate(tp, TT_KEEP, 1099 TCPS_HAVEESTABLISHED(tp->t_state) ? TP_KEEPIDLE(tp) : 1100 TP_KEEPINIT(tp)); 1101 1102 /* 1103 * Make sure critical variables are initialized 1104 * if transitioning while in Recovery. 1105 */ 1106 if IN_FASTRECOVERY(tp->t_flags) { 1107 if (tp->sackhint.recover_fs == 0) 1108 tp->sackhint.recover_fs = max(1, 1109 tp->snd_nxt - tp->snd_una); 1110 } 1111 1112 return (0); 1113 } 1114 1115 /* 1116 * tfb_tcp_fb_fini() function for the default stack. 1117 * 1118 * This changes state as necessary (or prudent) to prepare for another stack 1119 * to assume responsibility for the connection. 1120 */ 1121 static void 1122 tcp_default_fb_fini(struct tcpcb *tp, int tcb_is_purged) 1123 { 1124 1125 INP_WLOCK_ASSERT(tptoinpcb(tp)); 1126 1127 #ifdef TCP_BLACKBOX 1128 tcp_log_flowend(tp); 1129 #endif 1130 tp->t_acktime = 0; 1131 return; 1132 } 1133 1134 MALLOC_DEFINE(M_TCPLOG, "tcplog", "TCP address and flags print buffers"); 1135 MALLOC_DEFINE(M_TCPFUNCTIONS, "tcpfunc", "TCP function set memory"); 1136 1137 static struct mtx isn_mtx; 1138 1139 #define ISN_LOCK_INIT() mtx_init(&isn_mtx, "isn_mtx", NULL, MTX_DEF) 1140 #define ISN_LOCK() mtx_lock(&isn_mtx) 1141 #define ISN_UNLOCK() mtx_unlock(&isn_mtx) 1142 1143 INPCBSTORAGE_DEFINE(tcpcbstor, tcpcb, "tcpinp", "tcp_inpcb", "tcp", "tcphash"); 1144 1145 /* 1146 * Take a value and get the next power of 2 that doesn't overflow. 1147 * Used to size the tcp_inpcb hash buckets. 1148 */ 1149 static int 1150 maketcp_hashsize(int size) 1151 { 1152 int hashsize; 1153 1154 /* 1155 * auto tune. 1156 * get the next power of 2 higher than maxsockets. 1157 */ 1158 hashsize = 1 << fls(size); 1159 /* catch overflow, and just go one power of 2 smaller */ 1160 if (hashsize < size) { 1161 hashsize = 1 << (fls(size) - 1); 1162 } 1163 return (hashsize); 1164 } 1165 1166 static volatile int next_tcp_stack_id = 1; 1167 1168 /* 1169 * Register a TCP function block with the name provided in the names 1170 * array. (Note that this function does NOT automatically register 1171 * blk->tfb_tcp_block_name as a stack name. Therefore, you should 1172 * explicitly include blk->tfb_tcp_block_name in the list of names if 1173 * you wish to register the stack with that name.) 1174 * 1175 * Either all name registrations will succeed or all will fail. If 1176 * a name registration fails, the function will update the num_names 1177 * argument to point to the array index of the name that encountered 1178 * the failure. 1179 * 1180 * Returns 0 on success, or an error code on failure. 1181 */ 1182 int 1183 register_tcp_functions_as_names(struct tcp_function_block *blk, int wait, 1184 const char *names[], int *num_names) 1185 { 1186 struct tcp_function *f[TCP_FUNCTION_NAME_NUM_MAX]; 1187 struct tcp_function_set fs; 1188 int error, i, num_registered; 1189 1190 KASSERT(names != NULL, ("%s: Called with NULL name list", __func__)); 1191 KASSERT(*num_names > 0, 1192 ("%s: Called with non-positive length of name list", __func__)); 1193 KASSERT(rw_initialized(&tcp_function_lock), 1194 ("%s: called too early", __func__)); 1195 1196 if (*num_names > TCP_FUNCTION_NAME_NUM_MAX) { 1197 /* Too many names. */ 1198 *num_names = 0; 1199 return (E2BIG); 1200 } 1201 if ((blk->tfb_tcp_output == NULL) || 1202 (blk->tfb_tcp_do_segment == NULL) || 1203 (blk->tfb_tcp_ctloutput == NULL) || 1204 (blk->tfb_tcp_handoff_ok == NULL) || 1205 (strlen(blk->tfb_tcp_block_name) == 0)) { 1206 /* These functions are required and a name is needed. */ 1207 *num_names = 0; 1208 return (EINVAL); 1209 } 1210 1211 for (i = 0; i < *num_names; i++) { 1212 f[i] = malloc(sizeof(struct tcp_function), M_TCPFUNCTIONS, wait); 1213 if (f[i] == NULL) { 1214 while (--i >= 0) 1215 free(f[i], M_TCPFUNCTIONS); 1216 *num_names = 0; 1217 return (ENOMEM); 1218 } 1219 } 1220 1221 num_registered = 0; 1222 rw_wlock(&tcp_function_lock); 1223 if (find_tcp_fb_locked(blk, NULL) != NULL) { 1224 /* A TCP function block can only be registered once. */ 1225 error = EALREADY; 1226 goto cleanup; 1227 } 1228 if (blk->tfb_flags & TCP_FUNC_BEING_REMOVED) { 1229 error = EINVAL; 1230 goto cleanup; 1231 } 1232 refcount_init(&blk->tfb_refcnt, 0); 1233 blk->tfb_id = atomic_fetchadd_int(&next_tcp_stack_id, 1); 1234 for (i = 0; i < *num_names; i++) { 1235 (void)strlcpy(fs.function_set_name, names[i], 1236 sizeof(fs.function_set_name)); 1237 if (find_tcp_functions_locked(&fs) != NULL) { 1238 /* Duplicate name space not allowed */ 1239 error = EALREADY; 1240 goto cleanup; 1241 } 1242 f[i]->tf_fb = blk; 1243 (void)strlcpy(f[i]->tf_name, names[i], sizeof(f[i]->tf_name)); 1244 TAILQ_INSERT_TAIL(&t_functions, f[i], tf_next); 1245 tcp_fb_cnt++; 1246 num_registered++; 1247 } 1248 rw_wunlock(&tcp_function_lock); 1249 return (0); 1250 1251 cleanup: 1252 /* Remove the entries just added. */ 1253 for (i = 0; i < *num_names; i++) { 1254 if (i < num_registered) { 1255 TAILQ_REMOVE(&t_functions, f[i], tf_next); 1256 tcp_fb_cnt--; 1257 } 1258 f[i]->tf_fb = NULL; 1259 free(f[i], M_TCPFUNCTIONS); 1260 } 1261 rw_wunlock(&tcp_function_lock); 1262 *num_names = num_registered; 1263 return (error); 1264 } 1265 1266 /* 1267 * Register a TCP function block using the name provided in the name 1268 * argument. 1269 * 1270 * Returns 0 on success, or an error code on failure. 1271 */ 1272 int 1273 register_tcp_functions_as_name(struct tcp_function_block *blk, const char *name, 1274 int wait) 1275 { 1276 const char *name_list[1]; 1277 int num_names, rv; 1278 1279 num_names = 1; 1280 if (name != NULL) 1281 name_list[0] = name; 1282 else 1283 name_list[0] = blk->tfb_tcp_block_name; 1284 rv = register_tcp_functions_as_names(blk, wait, name_list, &num_names); 1285 return (rv); 1286 } 1287 1288 /* 1289 * Register a TCP function block using the name defined in 1290 * blk->tfb_tcp_block_name. 1291 * 1292 * Returns 0 on success, or an error code on failure. 1293 */ 1294 int 1295 register_tcp_functions(struct tcp_function_block *blk, int wait) 1296 { 1297 1298 return (register_tcp_functions_as_name(blk, NULL, wait)); 1299 } 1300 1301 /* 1302 * Deregister all names associated with a function block. This 1303 * functionally removes the function block from use within the system. 1304 * 1305 * When called with a true quiesce argument, mark the function block 1306 * as being removed so no more stacks will use it and determine 1307 * whether the removal would succeed. 1308 * 1309 * When called with a false quiesce argument, actually attempt the 1310 * removal. 1311 * 1312 * When called with a force argument, attempt to switch all TCBs to 1313 * use the default stack instead of returning EBUSY. 1314 * 1315 * Returns 0 on success (or if the removal would succeed), or an error 1316 * code on failure. 1317 */ 1318 int 1319 deregister_tcp_functions(struct tcp_function_block *blk, bool quiesce, 1320 bool force) 1321 { 1322 struct tcp_function *f; 1323 VNET_ITERATOR_DECL(vnet_iter); 1324 1325 if (blk == &tcp_def_funcblk) { 1326 /* You can't un-register the default */ 1327 return (EPERM); 1328 } 1329 rw_wlock(&tcp_function_lock); 1330 VNET_LIST_RLOCK_NOSLEEP(); 1331 VNET_FOREACH(vnet_iter) { 1332 CURVNET_SET(vnet_iter); 1333 if (blk == V_tcp_func_set_ptr) { 1334 /* You can't free the current default in some vnet. */ 1335 CURVNET_RESTORE(); 1336 VNET_LIST_RUNLOCK_NOSLEEP(); 1337 rw_wunlock(&tcp_function_lock); 1338 return (EBUSY); 1339 } 1340 CURVNET_RESTORE(); 1341 } 1342 VNET_LIST_RUNLOCK_NOSLEEP(); 1343 /* Mark the block so no more stacks can use it. */ 1344 blk->tfb_flags |= TCP_FUNC_BEING_REMOVED; 1345 /* 1346 * If TCBs are still attached to the stack, attempt to switch them 1347 * to the default stack. 1348 */ 1349 if (force && blk->tfb_refcnt) { 1350 struct inpcb *inp; 1351 struct tcpcb *tp; 1352 VNET_ITERATOR_DECL(vnet_iter); 1353 1354 rw_wunlock(&tcp_function_lock); 1355 1356 VNET_LIST_RLOCK(); 1357 VNET_FOREACH(vnet_iter) { 1358 CURVNET_SET(vnet_iter); 1359 struct inpcb_iterator inpi = INP_ALL_ITERATOR(&V_tcbinfo, 1360 INPLOOKUP_WLOCKPCB); 1361 1362 while ((inp = inp_next(&inpi)) != NULL) { 1363 tp = intotcpcb(inp); 1364 if (tp == NULL || tp->t_fb != blk) 1365 continue; 1366 tcp_switch_back_to_default(tp); 1367 } 1368 CURVNET_RESTORE(); 1369 } 1370 VNET_LIST_RUNLOCK(); 1371 1372 rw_wlock(&tcp_function_lock); 1373 } 1374 if (blk->tfb_refcnt) { 1375 /* TCBs still attached. */ 1376 rw_wunlock(&tcp_function_lock); 1377 return (EBUSY); 1378 } 1379 if (quiesce) { 1380 /* Skip removal. */ 1381 rw_wunlock(&tcp_function_lock); 1382 return (0); 1383 } 1384 /* Remove any function names that map to this function block. */ 1385 while (find_tcp_fb_locked(blk, &f) != NULL) { 1386 TAILQ_REMOVE(&t_functions, f, tf_next); 1387 tcp_fb_cnt--; 1388 f->tf_fb = NULL; 1389 free(f, M_TCPFUNCTIONS); 1390 } 1391 rw_wunlock(&tcp_function_lock); 1392 return (0); 1393 } 1394 1395 static void 1396 tcp_drain(void *ctx __unused, int flags __unused) 1397 { 1398 struct epoch_tracker et; 1399 VNET_ITERATOR_DECL(vnet_iter); 1400 1401 if (!do_tcpdrain) 1402 return; 1403 1404 NET_EPOCH_ENTER(et); 1405 VNET_LIST_RLOCK_NOSLEEP(); 1406 VNET_FOREACH(vnet_iter) { 1407 CURVNET_SET(vnet_iter); 1408 struct inpcb_iterator inpi = INP_ALL_ITERATOR(&V_tcbinfo, 1409 INPLOOKUP_WLOCKPCB); 1410 struct inpcb *inpb; 1411 struct tcpcb *tcpb; 1412 1413 /* 1414 * Walk the tcpbs, if existing, and flush the reassembly queue, 1415 * if there is one... 1416 * XXX: The "Net/3" implementation doesn't imply that the TCP 1417 * reassembly queue should be flushed, but in a situation 1418 * where we're really low on mbufs, this is potentially 1419 * useful. 1420 */ 1421 while ((inpb = inp_next(&inpi)) != NULL) { 1422 if ((tcpb = intotcpcb(inpb)) != NULL) { 1423 tcp_reass_flush(tcpb); 1424 tcp_clean_sackreport(tcpb); 1425 #ifdef TCP_BLACKBOX 1426 tcp_log_drain(tcpb); 1427 #endif 1428 } 1429 } 1430 CURVNET_RESTORE(); 1431 } 1432 VNET_LIST_RUNLOCK_NOSLEEP(); 1433 NET_EPOCH_EXIT(et); 1434 } 1435 1436 static void 1437 tcp_vnet_init(void *arg __unused) 1438 { 1439 1440 #ifdef TCP_HHOOK 1441 if (hhook_head_register(HHOOK_TYPE_TCP, HHOOK_TCP_EST_IN, 1442 &V_tcp_hhh[HHOOK_TCP_EST_IN], HHOOK_NOWAIT|HHOOK_HEADISINVNET) != 0) 1443 printf("%s: WARNING: unable to register helper hook\n", __func__); 1444 if (hhook_head_register(HHOOK_TYPE_TCP, HHOOK_TCP_EST_OUT, 1445 &V_tcp_hhh[HHOOK_TCP_EST_OUT], HHOOK_NOWAIT|HHOOK_HEADISINVNET) != 0) 1446 printf("%s: WARNING: unable to register helper hook\n", __func__); 1447 #endif 1448 #ifdef STATS 1449 if (tcp_stats_init()) 1450 printf("%s: WARNING: unable to initialise TCP stats\n", 1451 __func__); 1452 #endif 1453 in_pcbinfo_init(&V_tcbinfo, &tcpcbstor, tcp_tcbhashsize, 1454 tcp_tcbhashsize); 1455 1456 syncache_init(); 1457 tcp_hc_init(); 1458 1459 TUNABLE_INT_FETCH("net.inet.tcp.sack.enable", &V_tcp_do_sack); 1460 V_sack_hole_zone = uma_zcreate("sackhole", sizeof(struct sackhole), 1461 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0); 1462 1463 tcp_fastopen_init(); 1464 1465 COUNTER_ARRAY_ALLOC(V_tcps_states, TCP_NSTATES, M_WAITOK); 1466 VNET_PCPUSTAT_ALLOC(tcpstat, M_WAITOK); 1467 1468 V_tcp_msl = TCPTV_MSL; 1469 V_tcp_msl_local = TCPTV_MSL_LOCAL; 1470 arc4rand(&V_ts_offset_secret, sizeof(V_ts_offset_secret), 0); 1471 } 1472 VNET_SYSINIT(tcp_vnet_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH, 1473 tcp_vnet_init, NULL); 1474 1475 static void 1476 tcp_init(void *arg __unused) 1477 { 1478 int hashsize; 1479 1480 tcp_reass_global_init(); 1481 1482 /* XXX virtualize those below? */ 1483 tcp_delacktime = TCPTV_DELACK; 1484 tcp_keepinit = TCPTV_KEEP_INIT; 1485 tcp_keepidle = TCPTV_KEEP_IDLE; 1486 tcp_keepintvl = TCPTV_KEEPINTVL; 1487 tcp_maxpersistidle = TCPTV_KEEP_IDLE; 1488 tcp_rexmit_initial = TCPTV_RTOBASE; 1489 tcp_rexmit_min = TCPTV_MIN; 1490 tcp_rexmit_max = TCPTV_REXMTMAX; 1491 tcp_persmin = TCPTV_PERSMIN; 1492 tcp_persmax = TCPTV_PERSMAX; 1493 tcp_rexmit_slop = TCPTV_CPU_VAR; 1494 tcp_finwait2_timeout = TCPTV_FINWAIT2_TIMEOUT; 1495 1496 /* Setup the tcp function block list */ 1497 TAILQ_INIT(&t_functions); 1498 rw_init(&tcp_function_lock, "tcp_func_lock"); 1499 register_tcp_functions(&tcp_def_funcblk, M_WAITOK); 1500 sx_init(&tcpoudp_lock, "TCP over UDP configuration"); 1501 #ifdef TCP_BLACKBOX 1502 /* Initialize the TCP logging data. */ 1503 tcp_log_init(); 1504 #endif 1505 1506 if (tcp_soreceive_stream) { 1507 #ifdef INET 1508 tcp_protosw.pr_soreceive = soreceive_stream; 1509 #endif 1510 #ifdef INET6 1511 tcp6_protosw.pr_soreceive = soreceive_stream; 1512 #endif /* INET6 */ 1513 } 1514 1515 #ifdef INET6 1516 max_protohdr_grow(sizeof(struct ip6_hdr) + sizeof(struct tcphdr)); 1517 #else /* INET6 */ 1518 max_protohdr_grow(sizeof(struct tcpiphdr)); 1519 #endif /* INET6 */ 1520 1521 ISN_LOCK_INIT(); 1522 EVENTHANDLER_REGISTER(shutdown_pre_sync, tcp_fini, NULL, 1523 SHUTDOWN_PRI_DEFAULT); 1524 EVENTHANDLER_REGISTER(vm_lowmem, tcp_drain, NULL, LOWMEM_PRI_DEFAULT); 1525 EVENTHANDLER_REGISTER(mbuf_lowmem, tcp_drain, NULL, LOWMEM_PRI_DEFAULT); 1526 1527 tcp_inp_lro_direct_queue = counter_u64_alloc(M_WAITOK); 1528 tcp_inp_lro_wokeup_queue = counter_u64_alloc(M_WAITOK); 1529 tcp_inp_lro_compressed = counter_u64_alloc(M_WAITOK); 1530 tcp_inp_lro_locks_taken = counter_u64_alloc(M_WAITOK); 1531 tcp_extra_mbuf = counter_u64_alloc(M_WAITOK); 1532 tcp_would_have_but = counter_u64_alloc(M_WAITOK); 1533 tcp_comp_total = counter_u64_alloc(M_WAITOK); 1534 tcp_uncomp_total = counter_u64_alloc(M_WAITOK); 1535 tcp_bad_csums = counter_u64_alloc(M_WAITOK); 1536 tcp_pacing_failures = counter_u64_alloc(M_WAITOK); 1537 tcp_dgp_failures = counter_u64_alloc(M_WAITOK); 1538 1539 hashsize = tcp_tcbhashsize; 1540 if (hashsize == 0) { 1541 /* 1542 * Auto tune the hash size based on maxsockets. 1543 * A perfect hash would have a 1:1 mapping 1544 * (hashsize = maxsockets) however it's been 1545 * suggested that O(2) average is better. 1546 */ 1547 hashsize = maketcp_hashsize(maxsockets / 4); 1548 /* 1549 * Our historical default is 512, 1550 * do not autotune lower than this. 1551 */ 1552 if (hashsize < 512) 1553 hashsize = 512; 1554 if (bootverbose) 1555 printf("%s: %s auto tuned to %d\n", __func__, 1556 "net.inet.tcp.tcbhashsize", hashsize); 1557 } 1558 /* 1559 * We require a hashsize to be a power of two. 1560 * Previously if it was not a power of two we would just reset it 1561 * back to 512, which could be a nasty surprise if you did not notice 1562 * the error message. 1563 * Instead what we do is clip it to the closest power of two lower 1564 * than the specified hash value. 1565 */ 1566 if (!powerof2(hashsize)) { 1567 int oldhashsize = hashsize; 1568 1569 hashsize = maketcp_hashsize(hashsize); 1570 /* prevent absurdly low value */ 1571 if (hashsize < 16) 1572 hashsize = 16; 1573 printf("%s: WARNING: TCB hash size not a power of 2, " 1574 "clipped from %d to %d.\n", __func__, oldhashsize, 1575 hashsize); 1576 } 1577 tcp_tcbhashsize = hashsize; 1578 1579 #ifdef INET 1580 IPPROTO_REGISTER(IPPROTO_TCP, tcp_input, tcp_ctlinput); 1581 #endif 1582 #ifdef INET6 1583 IP6PROTO_REGISTER(IPPROTO_TCP, tcp6_input, tcp6_ctlinput); 1584 #endif 1585 } 1586 SYSINIT(tcp_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD, tcp_init, NULL); 1587 1588 #ifdef VIMAGE 1589 static void 1590 tcp_destroy(void *unused __unused) 1591 { 1592 #ifdef TCP_HHOOK 1593 int error; 1594 #endif 1595 1596 tcp_hc_destroy(); 1597 syncache_destroy(); 1598 in_pcbinfo_destroy(&V_tcbinfo); 1599 /* tcp_discardcb() clears the sack_holes up. */ 1600 uma_zdestroy(V_sack_hole_zone); 1601 1602 /* 1603 * Cannot free the zone until all tcpcbs are released as we attach 1604 * the allocations to them. 1605 */ 1606 tcp_fastopen_destroy(); 1607 1608 COUNTER_ARRAY_FREE(V_tcps_states, TCP_NSTATES); 1609 VNET_PCPUSTAT_FREE(tcpstat); 1610 1611 #ifdef TCP_HHOOK 1612 error = hhook_head_deregister(V_tcp_hhh[HHOOK_TCP_EST_IN]); 1613 if (error != 0) { 1614 printf("%s: WARNING: unable to deregister helper hook " 1615 "type=%d, id=%d: error %d returned\n", __func__, 1616 HHOOK_TYPE_TCP, HHOOK_TCP_EST_IN, error); 1617 } 1618 error = hhook_head_deregister(V_tcp_hhh[HHOOK_TCP_EST_OUT]); 1619 if (error != 0) { 1620 printf("%s: WARNING: unable to deregister helper hook " 1621 "type=%d, id=%d: error %d returned\n", __func__, 1622 HHOOK_TYPE_TCP, HHOOK_TCP_EST_OUT, error); 1623 } 1624 #endif 1625 } 1626 VNET_SYSUNINIT(tcp, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH, tcp_destroy, NULL); 1627 #endif 1628 1629 void 1630 tcp_fini(void *xtp) 1631 { 1632 1633 } 1634 1635 /* 1636 * Fill in the IP and TCP headers for an outgoing packet, given the tcpcb. 1637 * tcp_template used to store this data in mbufs, but we now recopy it out 1638 * of the tcpcb each time to conserve mbufs. 1639 */ 1640 void 1641 tcpip_fillheaders(struct inpcb *inp, uint16_t port, void *ip_ptr, void *tcp_ptr) 1642 { 1643 struct tcphdr *th = (struct tcphdr *)tcp_ptr; 1644 1645 INP_WLOCK_ASSERT(inp); 1646 1647 #ifdef INET6 1648 if ((inp->inp_vflag & INP_IPV6) != 0) { 1649 struct ip6_hdr *ip6; 1650 1651 ip6 = (struct ip6_hdr *)ip_ptr; 1652 ip6->ip6_flow = (ip6->ip6_flow & ~IPV6_FLOWINFO_MASK) | 1653 (inp->inp_flow & IPV6_FLOWINFO_MASK); 1654 ip6->ip6_vfc = (ip6->ip6_vfc & ~IPV6_VERSION_MASK) | 1655 (IPV6_VERSION & IPV6_VERSION_MASK); 1656 if (port == 0) 1657 ip6->ip6_nxt = IPPROTO_TCP; 1658 else 1659 ip6->ip6_nxt = IPPROTO_UDP; 1660 ip6->ip6_plen = htons(sizeof(struct tcphdr)); 1661 ip6->ip6_src = inp->in6p_laddr; 1662 ip6->ip6_dst = inp->in6p_faddr; 1663 } 1664 #endif /* INET6 */ 1665 #if defined(INET6) && defined(INET) 1666 else 1667 #endif 1668 #ifdef INET 1669 { 1670 struct ip *ip; 1671 1672 ip = (struct ip *)ip_ptr; 1673 ip->ip_v = IPVERSION; 1674 ip->ip_hl = 5; 1675 ip->ip_tos = inp->inp_ip_tos; 1676 ip->ip_len = 0; 1677 ip->ip_id = 0; 1678 ip->ip_off = 0; 1679 ip->ip_ttl = inp->inp_ip_ttl; 1680 ip->ip_sum = 0; 1681 if (port == 0) 1682 ip->ip_p = IPPROTO_TCP; 1683 else 1684 ip->ip_p = IPPROTO_UDP; 1685 ip->ip_src = inp->inp_laddr; 1686 ip->ip_dst = inp->inp_faddr; 1687 } 1688 #endif /* INET */ 1689 th->th_sport = inp->inp_lport; 1690 th->th_dport = inp->inp_fport; 1691 th->th_seq = 0; 1692 th->th_ack = 0; 1693 th->th_off = 5; 1694 tcp_set_flags(th, 0); 1695 th->th_win = 0; 1696 th->th_urp = 0; 1697 th->th_sum = 0; /* in_pseudo() is called later for ipv4 */ 1698 } 1699 1700 /* 1701 * Create template to be used to send tcp packets on a connection. 1702 * Allocates an mbuf and fills in a skeletal tcp/ip header. The only 1703 * use for this function is in keepalives, which use tcp_respond. 1704 */ 1705 struct tcptemp * 1706 tcpip_maketemplate(struct inpcb *inp) 1707 { 1708 struct tcptemp *t; 1709 1710 t = malloc(sizeof(*t), M_TEMP, M_NOWAIT); 1711 if (t == NULL) 1712 return (NULL); 1713 tcpip_fillheaders(inp, 0, (void *)&t->tt_ipgen, (void *)&t->tt_t); 1714 return (t); 1715 } 1716 1717 /* 1718 * Send a single message to the TCP at address specified by 1719 * the given TCP/IP header. If m == NULL, then we make a copy 1720 * of the tcpiphdr at th and send directly to the addressed host. 1721 * This is used to force keep alive messages out using the TCP 1722 * template for a connection. If flags are given then we send 1723 * a message back to the TCP which originated the segment th, 1724 * and discard the mbuf containing it and any other attached mbufs. 1725 * 1726 * In any case the ack and sequence number of the transmitted 1727 * segment are as specified by the parameters. 1728 * 1729 * NOTE: If m != NULL, then th must point to *inside* the mbuf. 1730 */ 1731 1732 void 1733 tcp_respond(struct tcpcb *tp, void *ipgen, struct tcphdr *th, struct mbuf *m, 1734 tcp_seq ack, tcp_seq seq, uint16_t flags) 1735 { 1736 struct tcpopt to; 1737 struct inpcb *inp; 1738 struct ip *ip; 1739 struct mbuf *optm; 1740 struct udphdr *uh = NULL; 1741 struct tcphdr *nth; 1742 struct tcp_log_buffer *lgb; 1743 u_char *optp; 1744 #ifdef INET6 1745 struct ip6_hdr *ip6; 1746 int isipv6; 1747 #endif /* INET6 */ 1748 int optlen, tlen, win, ulen; 1749 int ect = 0; 1750 bool incl_opts; 1751 uint16_t port; 1752 int output_ret; 1753 #ifdef INVARIANTS 1754 int thflags = tcp_get_flags(th); 1755 #endif 1756 1757 KASSERT(tp != NULL || m != NULL, ("tcp_respond: tp and m both NULL")); 1758 NET_EPOCH_ASSERT(); 1759 1760 #ifdef INET6 1761 isipv6 = ((struct ip *)ipgen)->ip_v == (IPV6_VERSION >> 4); 1762 ip6 = ipgen; 1763 #endif /* INET6 */ 1764 ip = ipgen; 1765 1766 if (tp != NULL) { 1767 inp = tptoinpcb(tp); 1768 INP_LOCK_ASSERT(inp); 1769 } else 1770 inp = NULL; 1771 1772 if (m != NULL) { 1773 #ifdef INET6 1774 if (isipv6 && ip6 && (ip6->ip6_nxt == IPPROTO_UDP)) 1775 port = m->m_pkthdr.tcp_tun_port; 1776 else 1777 #endif 1778 if (ip && (ip->ip_p == IPPROTO_UDP)) 1779 port = m->m_pkthdr.tcp_tun_port; 1780 else 1781 port = 0; 1782 } else 1783 port = tp->t_port; 1784 1785 incl_opts = false; 1786 win = 0; 1787 if (tp != NULL) { 1788 if (!(flags & TH_RST)) { 1789 win = sbspace(&inp->inp_socket->so_rcv); 1790 if (win > TCP_MAXWIN << tp->rcv_scale) 1791 win = TCP_MAXWIN << tp->rcv_scale; 1792 } 1793 if ((tp->t_flags & TF_NOOPT) == 0) 1794 incl_opts = true; 1795 } 1796 if (m == NULL) { 1797 m = m_gethdr(M_NOWAIT, MT_DATA); 1798 if (m == NULL) 1799 return; 1800 m->m_data += max_linkhdr; 1801 #ifdef INET6 1802 if (isipv6) { 1803 bcopy((caddr_t)ip6, mtod(m, caddr_t), 1804 sizeof(struct ip6_hdr)); 1805 ip6 = mtod(m, struct ip6_hdr *); 1806 nth = (struct tcphdr *)(ip6 + 1); 1807 if (port) { 1808 /* Insert a UDP header */ 1809 uh = (struct udphdr *)nth; 1810 uh->uh_sport = htons(V_tcp_udp_tunneling_port); 1811 uh->uh_dport = port; 1812 nth = (struct tcphdr *)(uh + 1); 1813 } 1814 } else 1815 #endif /* INET6 */ 1816 { 1817 bcopy((caddr_t)ip, mtod(m, caddr_t), sizeof(struct ip)); 1818 ip = mtod(m, struct ip *); 1819 nth = (struct tcphdr *)(ip + 1); 1820 if (port) { 1821 /* Insert a UDP header */ 1822 uh = (struct udphdr *)nth; 1823 uh->uh_sport = htons(V_tcp_udp_tunneling_port); 1824 uh->uh_dport = port; 1825 nth = (struct tcphdr *)(uh + 1); 1826 } 1827 } 1828 bcopy((caddr_t)th, (caddr_t)nth, sizeof(struct tcphdr)); 1829 flags = TH_ACK; 1830 } else if ((!M_WRITABLE(m)) || (port != 0)) { 1831 struct mbuf *n; 1832 1833 /* Can't reuse 'm', allocate a new mbuf. */ 1834 n = m_gethdr(M_NOWAIT, MT_DATA); 1835 if (n == NULL) { 1836 m_freem(m); 1837 return; 1838 } 1839 1840 if (!m_dup_pkthdr(n, m, M_NOWAIT)) { 1841 m_freem(m); 1842 m_freem(n); 1843 return; 1844 } 1845 1846 n->m_data += max_linkhdr; 1847 /* m_len is set later */ 1848 #define xchg(a,b,type) { type t; t=a; a=b; b=t; } 1849 #ifdef INET6 1850 if (isipv6) { 1851 bcopy((caddr_t)ip6, mtod(n, caddr_t), 1852 sizeof(struct ip6_hdr)); 1853 ip6 = mtod(n, struct ip6_hdr *); 1854 xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr); 1855 nth = (struct tcphdr *)(ip6 + 1); 1856 if (port) { 1857 /* Insert a UDP header */ 1858 uh = (struct udphdr *)nth; 1859 uh->uh_sport = htons(V_tcp_udp_tunneling_port); 1860 uh->uh_dport = port; 1861 nth = (struct tcphdr *)(uh + 1); 1862 } 1863 } else 1864 #endif /* INET6 */ 1865 { 1866 bcopy((caddr_t)ip, mtod(n, caddr_t), sizeof(struct ip)); 1867 ip = mtod(n, struct ip *); 1868 xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, uint32_t); 1869 nth = (struct tcphdr *)(ip + 1); 1870 if (port) { 1871 /* Insert a UDP header */ 1872 uh = (struct udphdr *)nth; 1873 uh->uh_sport = htons(V_tcp_udp_tunneling_port); 1874 uh->uh_dport = port; 1875 nth = (struct tcphdr *)(uh + 1); 1876 } 1877 } 1878 bcopy((caddr_t)th, (caddr_t)nth, sizeof(struct tcphdr)); 1879 xchg(nth->th_dport, nth->th_sport, uint16_t); 1880 th = nth; 1881 m_freem(m); 1882 m = n; 1883 } else { 1884 /* 1885 * reuse the mbuf. 1886 * XXX MRT We inherit the FIB, which is lucky. 1887 */ 1888 m_freem(m->m_next); 1889 m->m_next = NULL; 1890 m->m_data = (caddr_t)ipgen; 1891 /* clear any receive flags for proper bpf timestamping */ 1892 m->m_flags &= ~(M_TSTMP | M_TSTMP_LRO); 1893 /* m_len is set later */ 1894 #ifdef INET6 1895 if (isipv6) { 1896 xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr); 1897 nth = (struct tcphdr *)(ip6 + 1); 1898 } else 1899 #endif /* INET6 */ 1900 { 1901 xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, uint32_t); 1902 nth = (struct tcphdr *)(ip + 1); 1903 } 1904 if (th != nth) { 1905 /* 1906 * this is usually a case when an extension header 1907 * exists between the IPv6 header and the 1908 * TCP header. 1909 */ 1910 nth->th_sport = th->th_sport; 1911 nth->th_dport = th->th_dport; 1912 } 1913 xchg(nth->th_dport, nth->th_sport, uint16_t); 1914 #undef xchg 1915 } 1916 tlen = 0; 1917 #ifdef INET6 1918 if (isipv6) 1919 tlen = sizeof (struct ip6_hdr) + sizeof (struct tcphdr); 1920 #endif 1921 #if defined(INET) && defined(INET6) 1922 else 1923 #endif 1924 #ifdef INET 1925 tlen = sizeof (struct tcpiphdr); 1926 #endif 1927 if (port) 1928 tlen += sizeof (struct udphdr); 1929 #ifdef INVARIANTS 1930 m->m_len = 0; 1931 KASSERT(M_TRAILINGSPACE(m) >= tlen, 1932 ("Not enough trailing space for message (m=%p, need=%d, have=%ld)", 1933 m, tlen, (long)M_TRAILINGSPACE(m))); 1934 #endif 1935 m->m_len = tlen; 1936 to.to_flags = 0; 1937 if (incl_opts) { 1938 ect = tcp_ecn_output_established(tp, &flags, 0, false); 1939 /* Make sure we have room. */ 1940 if (M_TRAILINGSPACE(m) < TCP_MAXOLEN) { 1941 m->m_next = m_get(M_NOWAIT, MT_DATA); 1942 if (m->m_next) { 1943 optp = mtod(m->m_next, u_char *); 1944 optm = m->m_next; 1945 } else 1946 incl_opts = false; 1947 } else { 1948 optp = (u_char *) (nth + 1); 1949 optm = m; 1950 } 1951 } 1952 if (incl_opts) { 1953 /* Timestamps. */ 1954 if (tp->t_flags & TF_RCVD_TSTMP) { 1955 to.to_tsval = tcp_ts_getticks() + tp->ts_offset; 1956 to.to_tsecr = tp->ts_recent; 1957 to.to_flags |= TOF_TS; 1958 } 1959 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE) 1960 /* TCP-MD5 (RFC2385). */ 1961 if (tp->t_flags & TF_SIGNATURE) 1962 to.to_flags |= TOF_SIGNATURE; 1963 #endif 1964 /* Add the options. */ 1965 tlen += optlen = tcp_addoptions(&to, optp); 1966 1967 /* Update m_len in the correct mbuf. */ 1968 optm->m_len += optlen; 1969 } else 1970 optlen = 0; 1971 #ifdef INET6 1972 if (isipv6) { 1973 if (uh) { 1974 ulen = tlen - sizeof(struct ip6_hdr); 1975 uh->uh_ulen = htons(ulen); 1976 } 1977 ip6->ip6_flow = htonl(ect << IPV6_FLOWLABEL_LEN); 1978 ip6->ip6_vfc = IPV6_VERSION; 1979 if (port) 1980 ip6->ip6_nxt = IPPROTO_UDP; 1981 else 1982 ip6->ip6_nxt = IPPROTO_TCP; 1983 ip6->ip6_plen = htons(tlen - sizeof(*ip6)); 1984 } 1985 #endif 1986 #if defined(INET) && defined(INET6) 1987 else 1988 #endif 1989 #ifdef INET 1990 { 1991 if (uh) { 1992 ulen = tlen - sizeof(struct ip); 1993 uh->uh_ulen = htons(ulen); 1994 } 1995 ip->ip_len = htons(tlen); 1996 if (inp != NULL) { 1997 ip->ip_tos = inp->inp_ip_tos & ~IPTOS_ECN_MASK; 1998 ip->ip_ttl = inp->inp_ip_ttl; 1999 } else { 2000 ip->ip_tos = 0; 2001 ip->ip_ttl = V_ip_defttl; 2002 } 2003 ip->ip_tos |= ect; 2004 if (port) { 2005 ip->ip_p = IPPROTO_UDP; 2006 } else { 2007 ip->ip_p = IPPROTO_TCP; 2008 } 2009 if (V_path_mtu_discovery) 2010 ip->ip_off |= htons(IP_DF); 2011 } 2012 #endif 2013 m->m_pkthdr.len = tlen; 2014 m->m_pkthdr.rcvif = NULL; 2015 #ifdef MAC 2016 if (inp != NULL) { 2017 /* 2018 * Packet is associated with a socket, so allow the 2019 * label of the response to reflect the socket label. 2020 */ 2021 INP_LOCK_ASSERT(inp); 2022 mac_inpcb_create_mbuf(inp, m); 2023 } else { 2024 /* 2025 * Packet is not associated with a socket, so possibly 2026 * update the label in place. 2027 */ 2028 mac_netinet_tcp_reply(m); 2029 } 2030 #endif 2031 nth->th_seq = htonl(seq); 2032 nth->th_ack = htonl(ack); 2033 nth->th_off = (sizeof (struct tcphdr) + optlen) >> 2; 2034 tcp_set_flags(nth, flags); 2035 if (tp && (flags & TH_RST)) { 2036 /* Log the reset */ 2037 tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST); 2038 } 2039 if (tp != NULL) 2040 nth->th_win = htons((u_short) (win >> tp->rcv_scale)); 2041 else 2042 nth->th_win = htons((u_short)win); 2043 nth->th_urp = 0; 2044 2045 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE) 2046 if (to.to_flags & TOF_SIGNATURE) { 2047 if (!TCPMD5_ENABLED() || 2048 TCPMD5_OUTPUT(m, nth, to.to_signature) != 0) { 2049 m_freem(m); 2050 return; 2051 } 2052 } 2053 #endif 2054 2055 #ifdef INET6 2056 if (isipv6) { 2057 if (port) { 2058 m->m_pkthdr.csum_flags = CSUM_UDP_IPV6; 2059 m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum); 2060 uh->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0); 2061 nth->th_sum = 0; 2062 } else { 2063 m->m_pkthdr.csum_flags = CSUM_TCP_IPV6; 2064 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum); 2065 nth->th_sum = in6_cksum_pseudo(ip6, 2066 tlen - sizeof(struct ip6_hdr), IPPROTO_TCP, 0); 2067 } 2068 ip6->ip6_hlim = in6_selecthlim(inp, NULL); 2069 } 2070 #endif /* INET6 */ 2071 #if defined(INET6) && defined(INET) 2072 else 2073 #endif 2074 #ifdef INET 2075 { 2076 if (port) { 2077 uh->uh_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr, 2078 htons(ulen + IPPROTO_UDP)); 2079 m->m_pkthdr.csum_flags = CSUM_UDP; 2080 m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum); 2081 nth->th_sum = 0; 2082 } else { 2083 m->m_pkthdr.csum_flags = CSUM_TCP; 2084 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum); 2085 nth->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr, 2086 htons((u_short)(tlen - sizeof(struct ip) + ip->ip_p))); 2087 } 2088 } 2089 #endif /* INET */ 2090 TCP_PROBE3(debug__output, tp, th, m); 2091 if (flags & TH_RST) 2092 TCP_PROBE5(accept__refused, NULL, NULL, m, tp, nth); 2093 lgb = NULL; 2094 if ((tp != NULL) && tcp_bblogging_on(tp)) { 2095 if (INP_WLOCKED(inp)) { 2096 union tcp_log_stackspecific log; 2097 struct timeval tv; 2098 2099 memset(&log, 0, sizeof(log)); 2100 log.u_bbr.inhpts = tcp_in_hpts(tp); 2101 log.u_bbr.flex8 = 4; 2102 log.u_bbr.pkts_out = tp->t_maxseg; 2103 log.u_bbr.timeStamp = tcp_get_usecs(&tv); 2104 log.u_bbr.delivered = 0; 2105 lgb = tcp_log_event(tp, nth, NULL, NULL, TCP_LOG_OUT, 2106 ERRNO_UNK, 0, &log, false, NULL, NULL, 0, &tv); 2107 } else { 2108 /* 2109 * We can not log the packet, since we only own the 2110 * read lock, but a write lock is needed. The read lock 2111 * is not upgraded to a write lock, since only getting 2112 * the read lock was done intentionally to improve the 2113 * handling of SYN flooding attacks. 2114 * This happens only for pure SYN segments received in 2115 * the initial CLOSED state, or received in a more 2116 * advanced state than listen and the UDP encapsulation 2117 * port is unexpected. 2118 * The incoming SYN segments do not really belong to 2119 * the TCP connection and the handling does not change 2120 * the state of the TCP connection. Therefore, the 2121 * sending of the RST segments is not logged. Please 2122 * note that also the incoming SYN segments are not 2123 * logged. 2124 * 2125 * The following code ensures that the above description 2126 * is and stays correct. 2127 */ 2128 KASSERT((thflags & (TH_ACK|TH_SYN)) == TH_SYN && 2129 (tp->t_state == TCPS_CLOSED || 2130 (tp->t_state > TCPS_LISTEN && tp->t_port != port)), 2131 ("%s: Logging of TCP segment with flags 0x%b and " 2132 "UDP encapsulation port %u skipped in state %s", 2133 __func__, thflags, PRINT_TH_FLAGS, 2134 ntohs(port), tcpstates[tp->t_state])); 2135 } 2136 } 2137 2138 if (flags & TH_ACK) 2139 TCPSTAT_INC(tcps_sndacks); 2140 else if (flags & (TH_SYN|TH_FIN|TH_RST)) 2141 TCPSTAT_INC(tcps_sndctrl); 2142 TCPSTAT_INC(tcps_sndtotal); 2143 2144 #ifdef INET6 2145 if (isipv6) { 2146 TCP_PROBE5(send, NULL, tp, ip6, tp, nth); 2147 output_ret = ip6_output(m, inp ? inp->in6p_outputopts : NULL, 2148 NULL, 0, NULL, NULL, inp); 2149 } 2150 #endif /* INET6 */ 2151 #if defined(INET) && defined(INET6) 2152 else 2153 #endif 2154 #ifdef INET 2155 { 2156 TCP_PROBE5(send, NULL, tp, ip, tp, nth); 2157 output_ret = ip_output(m, NULL, NULL, 0, NULL, inp); 2158 } 2159 #endif 2160 if (lgb != NULL) 2161 lgb->tlb_errno = output_ret; 2162 } 2163 2164 /* 2165 * Check that no more than V_tcp_ack_war_cnt per V_tcp_ack_war_time_window 2166 * are sent. *epoch_end is the end of the current epoch and is updated, if the 2167 * current epoch ended in the past. *ack_cnt is the counter used during the 2168 * current epoch. It might be reset and incremented. 2169 * The function returns true if a challenge ACK should be sent. 2170 */ 2171 bool 2172 tcp_challenge_ack_check(sbintime_t *epoch_end, uint32_t *ack_cnt) 2173 { 2174 sbintime_t now; 2175 2176 /* 2177 * The sending of a challenge ACK could be triggered by a blind attacker 2178 * to detect an existing TCP connection. To mitigate that, increment 2179 * also the global counter which would be incremented if the attacker 2180 * would have guessed wrongly. 2181 */ 2182 (void)badport_bandlim(BANDLIM_TCP_RST); 2183 2184 if (V_tcp_ack_war_time_window == 0 || V_tcp_ack_war_cnt == 0) { 2185 /* ACK war protection is disabled. */ 2186 return (true); 2187 } else { 2188 /* Start new epoch, if the previous one is already over. */ 2189 now = getsbinuptime(); 2190 if (*epoch_end < now) { 2191 *ack_cnt = 0; 2192 *epoch_end = now + V_tcp_ack_war_time_window * SBT_1MS; 2193 } 2194 /* 2195 * Send a challenge ACK, if less than tcp_ack_war_cnt have been 2196 * sent in the current epoch. 2197 */ 2198 if (*ack_cnt < V_tcp_ack_war_cnt) { 2199 (*ack_cnt)++; 2200 return (true); 2201 } else { 2202 return (false); 2203 } 2204 } 2205 } 2206 2207 /* 2208 * Send a challenge ack (no data, no SACK option), but not more than 2209 * V_tcp_ack_war_cnt per V_tcp_ack_war_time_window (per TCP connection). 2210 */ 2211 void 2212 tcp_send_challenge_ack(struct tcpcb *tp, struct tcphdr *th, struct mbuf *m) 2213 { 2214 if (tcp_challenge_ack_check(&tp->t_challenge_ack_end, 2215 &tp->t_challenge_ack_cnt)) { 2216 tcp_respond(tp, mtod(m, void *), th, m, tp->rcv_nxt, 2217 tp->snd_nxt, TH_ACK); 2218 tp->last_ack_sent = tp->rcv_nxt; 2219 } 2220 } 2221 2222 /* 2223 * Create a new TCP control block, making an empty reassembly queue and hooking 2224 * it to the argument protocol control block. The `inp' parameter must have 2225 * come from the zone allocator set up by tcpcbstor declaration. 2226 * The caller can provide a pointer to a tcpcb of the listener to inherit the 2227 * TCP function block from the listener. 2228 */ 2229 struct tcpcb * 2230 tcp_newtcpcb(struct inpcb *inp, struct tcpcb *listening_tcb) 2231 { 2232 struct tcpcb *tp = intotcpcb(inp); 2233 #ifdef INET6 2234 int isipv6 = (inp->inp_vflag & INP_IPV6) != 0; 2235 #endif /* INET6 */ 2236 2237 /* 2238 * Historically allocation was done with M_ZERO. There is a lot of 2239 * code that rely on that. For now take safe approach and zero whole 2240 * tcpcb. This definitely can be optimized. 2241 */ 2242 bzero(&tp->t_start_zero, t_zero_size); 2243 2244 /* Initialise cc_var struct for this tcpcb. */ 2245 tp->t_ccv.tp = tp; 2246 rw_rlock(&tcp_function_lock); 2247 if (listening_tcb != NULL) { 2248 INP_LOCK_ASSERT(tptoinpcb(listening_tcb)); 2249 KASSERT(listening_tcb->t_fb != NULL, 2250 ("tcp_newtcpcb: listening_tcb->t_fb is NULL")); 2251 if (listening_tcb->t_fb->tfb_flags & TCP_FUNC_BEING_REMOVED) { 2252 rw_runlock(&tcp_function_lock); 2253 return (NULL); 2254 } 2255 tp->t_fb = listening_tcb->t_fb; 2256 } else { 2257 tp->t_fb = V_tcp_func_set_ptr; 2258 } 2259 refcount_acquire(&tp->t_fb->tfb_refcnt); 2260 KASSERT((tp->t_fb->tfb_flags & TCP_FUNC_BEING_REMOVED) == 0, 2261 ("tcp_newtcpcb: using TFB being removed")); 2262 rw_runlock(&tcp_function_lock); 2263 CC_LIST_RLOCK(); 2264 if (listening_tcb != NULL) { 2265 if (CC_ALGO(listening_tcb)->flags & CC_MODULE_BEING_REMOVED) { 2266 CC_LIST_RUNLOCK(); 2267 if (tp->t_fb->tfb_tcp_fb_fini) 2268 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 1); 2269 refcount_release(&tp->t_fb->tfb_refcnt); 2270 return (NULL); 2271 } 2272 CC_ALGO(tp) = CC_ALGO(listening_tcb); 2273 } else 2274 CC_ALGO(tp) = CC_DEFAULT_ALGO(); 2275 cc_refer(CC_ALGO(tp)); 2276 CC_LIST_RUNLOCK(); 2277 if (CC_ALGO(tp)->cb_init != NULL) 2278 if (CC_ALGO(tp)->cb_init(&tp->t_ccv, NULL) > 0) { 2279 cc_detach(tp); 2280 if (tp->t_fb->tfb_tcp_fb_fini) 2281 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 1); 2282 refcount_release(&tp->t_fb->tfb_refcnt); 2283 return (NULL); 2284 } 2285 2286 #ifdef TCP_HHOOK 2287 if (khelp_init_osd(HELPER_CLASS_TCP, &tp->t_osd)) { 2288 if (CC_ALGO(tp)->cb_destroy != NULL) 2289 CC_ALGO(tp)->cb_destroy(&tp->t_ccv); 2290 CC_DATA(tp) = NULL; 2291 cc_detach(tp); 2292 if (tp->t_fb->tfb_tcp_fb_fini) 2293 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 1); 2294 refcount_release(&tp->t_fb->tfb_refcnt); 2295 return (NULL); 2296 } 2297 #endif 2298 2299 TAILQ_INIT(&tp->t_segq); 2300 STAILQ_INIT(&tp->t_inqueue); 2301 tp->t_maxseg = 2302 #ifdef INET6 2303 isipv6 ? V_tcp_v6mssdflt : 2304 #endif /* INET6 */ 2305 V_tcp_mssdflt; 2306 2307 /* All mbuf queue/ack compress flags should be off */ 2308 tcp_lro_features_off(tp); 2309 2310 tp->t_hpts_cpu = HPTS_CPU_NONE; 2311 tp->t_lro_cpu = HPTS_CPU_NONE; 2312 2313 callout_init_rw(&tp->t_callout, &inp->inp_lock, 2314 CALLOUT_TRYLOCK | CALLOUT_RETURNUNLOCKED); 2315 for (int i = 0; i < TT_N; i++) 2316 tp->t_timers[i] = SBT_MAX; 2317 2318 switch (V_tcp_do_rfc1323) { 2319 case 0: 2320 break; 2321 default: 2322 case 1: 2323 tp->t_flags = (TF_REQ_SCALE|TF_REQ_TSTMP); 2324 break; 2325 case 2: 2326 tp->t_flags = TF_REQ_SCALE; 2327 break; 2328 case 3: 2329 tp->t_flags = TF_REQ_TSTMP; 2330 break; 2331 } 2332 if (V_tcp_do_sack) 2333 tp->t_flags |= TF_SACK_PERMIT; 2334 TAILQ_INIT(&tp->snd_holes); 2335 2336 /* 2337 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no 2338 * rtt estimate. Set rttvar so that srtt + 4 * rttvar gives 2339 * reasonable initial retransmit time. 2340 */ 2341 tp->t_srtt = TCPTV_SRTTBASE; 2342 tp->t_rttvar = ((tcp_rexmit_initial - TCPTV_SRTTBASE) << TCP_RTTVAR_SHIFT) / 4; 2343 tp->t_rttmin = tcp_rexmit_min; 2344 tp->t_rxtcur = tcp_rexmit_initial; 2345 tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT; 2346 tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT; 2347 tp->t_rcvtime = ticks; 2348 /* We always start with ticks granularity */ 2349 tp->t_tmr_granularity = TCP_TMR_GRANULARITY_TICKS; 2350 /* 2351 * IPv4 TTL initialization is necessary for an IPv6 socket as well, 2352 * because the socket may be bound to an IPv6 wildcard address, 2353 * which may match an IPv4-mapped IPv6 address. 2354 */ 2355 inp->inp_ip_ttl = V_ip_defttl; 2356 #ifdef TCP_BLACKBOX 2357 /* Initialize the per-TCPCB log data. */ 2358 tcp_log_tcpcbinit(tp); 2359 #endif 2360 tp->t_pacing_rate = -1; 2361 if (tp->t_fb->tfb_tcp_fb_init) { 2362 if ((*tp->t_fb->tfb_tcp_fb_init)(tp, &tp->t_fb_ptr)) { 2363 if (CC_ALGO(tp)->cb_destroy != NULL) 2364 CC_ALGO(tp)->cb_destroy(&tp->t_ccv); 2365 CC_DATA(tp) = NULL; 2366 cc_detach(tp); 2367 #ifdef TCP_HHOOK 2368 khelp_destroy_osd(&tp->t_osd); 2369 #endif 2370 refcount_release(&tp->t_fb->tfb_refcnt); 2371 return (NULL); 2372 } 2373 } 2374 #ifdef STATS 2375 if (V_tcp_perconn_stats_enable == 1) 2376 tp->t_stats = stats_blob_alloc(V_tcp_perconn_stats_dflt_tpl, 0); 2377 #endif 2378 if (V_tcp_do_lrd) 2379 tp->t_flags |= TF_LRD; 2380 2381 return (tp); 2382 } 2383 2384 /* 2385 * Drop a TCP connection, reporting 2386 * the specified error. If connection is synchronized, 2387 * then send a RST to peer. 2388 */ 2389 struct tcpcb * 2390 tcp_drop(struct tcpcb *tp, int errno) 2391 { 2392 struct socket *so = tptosocket(tp); 2393 2394 NET_EPOCH_ASSERT(); 2395 INP_WLOCK_ASSERT(tptoinpcb(tp)); 2396 2397 if (TCPS_HAVERCVDSYN(tp->t_state)) { 2398 tcp_state_change(tp, TCPS_CLOSED); 2399 /* Don't use tcp_output() here due to possible recursion. */ 2400 (void)tcp_output_nodrop(tp); 2401 TCPSTAT_INC(tcps_drops); 2402 } else 2403 TCPSTAT_INC(tcps_conndrops); 2404 if (errno == ETIMEDOUT && tp->t_softerror) 2405 errno = tp->t_softerror; 2406 so->so_error = errno; 2407 return (tcp_close(tp)); 2408 } 2409 2410 void 2411 tcp_discardcb(struct tcpcb *tp) 2412 { 2413 struct inpcb *inp = tptoinpcb(tp); 2414 struct socket *so = tptosocket(tp); 2415 struct mbuf *m; 2416 #ifdef INET6 2417 bool isipv6 = (inp->inp_vflag & INP_IPV6) != 0; 2418 #endif 2419 2420 INP_WLOCK_ASSERT(inp); 2421 MPASS(!callout_active(&tp->t_callout)); 2422 MPASS(TAILQ_EMPTY(&tp->snd_holes)); 2423 2424 /* free the reassembly queue, if any */ 2425 tcp_reass_flush(tp); 2426 2427 #ifdef TCP_OFFLOAD 2428 /* Disconnect offload device, if any. */ 2429 if (tp->t_flags & TF_TOE) 2430 tcp_offload_detach(tp); 2431 #endif 2432 2433 /* Allow the CC algorithm to clean up after itself. */ 2434 if (CC_ALGO(tp)->cb_destroy != NULL) 2435 CC_ALGO(tp)->cb_destroy(&tp->t_ccv); 2436 CC_DATA(tp) = NULL; 2437 /* Detach from the CC algorithm */ 2438 cc_detach(tp); 2439 2440 #ifdef TCP_HHOOK 2441 khelp_destroy_osd(&tp->t_osd); 2442 #endif 2443 #ifdef STATS 2444 stats_blob_destroy(tp->t_stats); 2445 #endif 2446 2447 CC_ALGO(tp) = NULL; 2448 if ((m = STAILQ_FIRST(&tp->t_inqueue)) != NULL) { 2449 struct mbuf *prev; 2450 2451 STAILQ_INIT(&tp->t_inqueue); 2452 STAILQ_FOREACH_FROM_SAFE(m, &tp->t_inqueue, m_stailqpkt, prev) 2453 m_freem(m); 2454 } 2455 TCPSTATES_DEC(tp->t_state); 2456 2457 if (tp->t_fb->tfb_tcp_fb_fini) 2458 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 1); 2459 MPASS(!tcp_in_hpts(tp)); 2460 #ifdef TCP_BLACKBOX 2461 tcp_log_tcpcbfini(tp); 2462 #endif 2463 2464 /* 2465 * If we got enough samples through the srtt filter, 2466 * save the rtt and rttvar in the routing entry. 2467 * 'Enough' is arbitrarily defined as 4 rtt samples. 2468 * 4 samples is enough for the srtt filter to converge 2469 * to within enough % of the correct value; fewer samples 2470 * and we could save a bogus rtt. The danger is not high 2471 * as tcp quickly recovers from everything. 2472 * XXX: Works very well but needs some more statistics! 2473 * 2474 * XXXRRS: Updating must be after the stack fini() since 2475 * that may be converting some internal representation of 2476 * say srtt etc into the general one used by other stacks. 2477 */ 2478 if (tp->t_rttupdated >= 4) { 2479 struct hc_metrics_lite metrics; 2480 uint32_t ssthresh; 2481 2482 bzero(&metrics, sizeof(metrics)); 2483 /* 2484 * Update the ssthresh always when the conditions below 2485 * are satisfied. This gives us better new start value 2486 * for the congestion avoidance for new connections. 2487 * ssthresh is only set if packet loss occurred on a session. 2488 */ 2489 ssthresh = tp->snd_ssthresh; 2490 if (ssthresh != 0 && ssthresh < so->so_snd.sb_hiwat / 2) { 2491 /* 2492 * convert the limit from user data bytes to 2493 * packets then to packet data bytes. 2494 */ 2495 ssthresh = (ssthresh + tp->t_maxseg / 2) / tp->t_maxseg; 2496 if (ssthresh < 2) 2497 ssthresh = 2; 2498 ssthresh *= (tp->t_maxseg + 2499 #ifdef INET6 2500 (isipv6 ? sizeof (struct ip6_hdr) + 2501 sizeof (struct tcphdr) : 2502 #endif 2503 sizeof (struct tcpiphdr) 2504 #ifdef INET6 2505 ) 2506 #endif 2507 ); 2508 } else 2509 ssthresh = 0; 2510 metrics.hc_ssthresh = ssthresh; 2511 2512 metrics.hc_rtt = tp->t_srtt; 2513 metrics.hc_rttvar = tp->t_rttvar; 2514 metrics.hc_cwnd = tp->snd_cwnd; 2515 metrics.hc_sendpipe = 0; 2516 metrics.hc_recvpipe = 0; 2517 2518 tcp_hc_update(&inp->inp_inc, &metrics); 2519 } 2520 2521 refcount_release(&tp->t_fb->tfb_refcnt); 2522 } 2523 2524 /* 2525 * Attempt to close a TCP control block, marking it as dropped, and freeing 2526 * the socket if we hold the only reference. 2527 */ 2528 struct tcpcb * 2529 tcp_close(struct tcpcb *tp) 2530 { 2531 struct inpcb *inp = tptoinpcb(tp); 2532 struct socket *so = tptosocket(tp); 2533 2534 INP_WLOCK_ASSERT(inp); 2535 2536 #ifdef TCP_OFFLOAD 2537 if (tp->t_state == TCPS_LISTEN) 2538 tcp_offload_listen_stop(tp); 2539 #endif 2540 /* 2541 * This releases the TFO pending counter resource for TFO listen 2542 * sockets as well as passively-created TFO sockets that transition 2543 * from SYN_RECEIVED to CLOSED. 2544 */ 2545 if (tp->t_tfo_pending) { 2546 tcp_fastopen_decrement_counter(tp->t_tfo_pending); 2547 tp->t_tfo_pending = NULL; 2548 } 2549 tcp_timer_stop(tp); 2550 if (tp->t_fb->tfb_tcp_timer_stop_all != NULL) 2551 tp->t_fb->tfb_tcp_timer_stop_all(tp); 2552 in_pcbdrop(inp); 2553 TCPSTAT_INC(tcps_closed); 2554 if (tp->t_state != TCPS_CLOSED) 2555 tcp_state_change(tp, TCPS_CLOSED); 2556 KASSERT(inp->inp_socket != NULL, ("tcp_close: inp_socket NULL")); 2557 tcp_free_sackholes(tp); 2558 soisdisconnected(so); 2559 if (inp->inp_flags & INP_SOCKREF) { 2560 inp->inp_flags &= ~INP_SOCKREF; 2561 INP_WUNLOCK(inp); 2562 sorele(so); 2563 return (NULL); 2564 } 2565 return (tp); 2566 } 2567 2568 /* 2569 * Notify a tcp user of an asynchronous error; 2570 * store error as soft error, but wake up user 2571 * (for now, won't do anything until can select for soft error). 2572 * 2573 * Do not wake up user since there currently is no mechanism for 2574 * reporting soft errors (yet - a kqueue filter may be added). 2575 */ 2576 static struct inpcb * 2577 tcp_notify(struct inpcb *inp, int error) 2578 { 2579 struct tcpcb *tp; 2580 2581 INP_WLOCK_ASSERT(inp); 2582 2583 tp = intotcpcb(inp); 2584 KASSERT(tp != NULL, ("tcp_notify: tp == NULL")); 2585 2586 /* 2587 * Ignore some errors if we are hooked up. 2588 * If connection hasn't completed, has retransmitted several times, 2589 * and receives a second error, give up now. This is better 2590 * than waiting a long time to establish a connection that 2591 * can never complete. 2592 */ 2593 if (tp->t_state == TCPS_ESTABLISHED && 2594 (error == EHOSTUNREACH || error == ENETUNREACH || 2595 error == EHOSTDOWN)) { 2596 if (inp->inp_route.ro_nh) { 2597 NH_FREE(inp->inp_route.ro_nh); 2598 inp->inp_route.ro_nh = (struct nhop_object *)NULL; 2599 } 2600 return (inp); 2601 } else if (tp->t_state < TCPS_ESTABLISHED && tp->t_rxtshift > 3 && 2602 tp->t_softerror) { 2603 tp = tcp_drop(tp, error); 2604 if (tp != NULL) 2605 return (inp); 2606 else 2607 return (NULL); 2608 } else { 2609 tp->t_softerror = error; 2610 return (inp); 2611 } 2612 #if 0 2613 wakeup( &so->so_timeo); 2614 sorwakeup(so); 2615 sowwakeup(so); 2616 #endif 2617 } 2618 2619 static int 2620 tcp_pcblist(SYSCTL_HANDLER_ARGS) 2621 { 2622 struct inpcb_iterator inpi = INP_ALL_ITERATOR(&V_tcbinfo, 2623 INPLOOKUP_RLOCKPCB); 2624 struct xinpgen xig; 2625 struct inpcb *inp; 2626 int error; 2627 2628 if (req->newptr != NULL) 2629 return (EPERM); 2630 2631 if (req->oldptr == NULL) { 2632 int n; 2633 2634 n = V_tcbinfo.ipi_count + 2635 counter_u64_fetch(V_tcps_states[TCPS_SYN_RECEIVED]); 2636 n += imax(n / 8, 10); 2637 req->oldidx = 2 * (sizeof xig) + n * sizeof(struct xtcpcb); 2638 return (0); 2639 } 2640 2641 if ((error = sysctl_wire_old_buffer(req, 0)) != 0) 2642 return (error); 2643 2644 bzero(&xig, sizeof(xig)); 2645 xig.xig_len = sizeof xig; 2646 xig.xig_count = V_tcbinfo.ipi_count + 2647 counter_u64_fetch(V_tcps_states[TCPS_SYN_RECEIVED]); 2648 xig.xig_gen = V_tcbinfo.ipi_gencnt; 2649 xig.xig_sogen = so_gencnt; 2650 error = SYSCTL_OUT(req, &xig, sizeof xig); 2651 if (error) 2652 return (error); 2653 2654 error = syncache_pcblist(req); 2655 if (error) 2656 return (error); 2657 2658 while ((inp = inp_next(&inpi)) != NULL) { 2659 if (inp->inp_gencnt <= xig.xig_gen && 2660 cr_canseeinpcb(req->td->td_ucred, inp) == 0) { 2661 struct xtcpcb xt; 2662 2663 tcp_inptoxtp(inp, &xt); 2664 error = SYSCTL_OUT(req, &xt, sizeof xt); 2665 if (error) { 2666 INP_RUNLOCK(inp); 2667 break; 2668 } else 2669 continue; 2670 } 2671 } 2672 2673 if (!error) { 2674 /* 2675 * Give the user an updated idea of our state. 2676 * If the generation differs from what we told 2677 * her before, she knows that something happened 2678 * while we were processing this request, and it 2679 * might be necessary to retry. 2680 */ 2681 xig.xig_gen = V_tcbinfo.ipi_gencnt; 2682 xig.xig_sogen = so_gencnt; 2683 xig.xig_count = V_tcbinfo.ipi_count + 2684 counter_u64_fetch(V_tcps_states[TCPS_SYN_RECEIVED]); 2685 error = SYSCTL_OUT(req, &xig, sizeof xig); 2686 } 2687 2688 return (error); 2689 } 2690 2691 SYSCTL_PROC(_net_inet_tcp, TCPCTL_PCBLIST, pcblist, 2692 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_NEEDGIANT, 2693 NULL, 0, tcp_pcblist, "S,xtcpcb", 2694 "List of active TCP connections"); 2695 2696 #define SND_TAG_STATUS_MAXLEN 128 2697 2698 #ifdef KERN_TLS 2699 2700 static struct sx ktlslist_lock; 2701 SX_SYSINIT(ktlslistlock, &ktlslist_lock, "ktlslist"); 2702 static uint64_t ktls_glob_gen = 1; 2703 2704 static int 2705 tcp_ktlslist_locked(SYSCTL_HANDLER_ARGS, bool export_keys) 2706 { 2707 struct xinpgen xig; 2708 struct inpcb *inp; 2709 struct socket *so; 2710 struct ktls_session *ksr, *kss; 2711 char *buf; 2712 struct xktls_session *xktls; 2713 uint64_t ipi_gencnt; 2714 size_t buflen, len, sz; 2715 u_int cnt; 2716 int error; 2717 bool ek, p; 2718 2719 sx_assert(&ktlslist_lock, SA_XLOCKED); 2720 if (req->newptr != NULL) 2721 return (EPERM); 2722 2723 len = 0; 2724 cnt = 0; 2725 ipi_gencnt = V_tcbinfo.ipi_gencnt; 2726 bzero(&xig, sizeof(xig)); 2727 xig.xig_len = sizeof(xig); 2728 xig.xig_gen = ktls_glob_gen++; 2729 xig.xig_sogen = so_gencnt; 2730 2731 struct inpcb_iterator inpi = INP_ALL_ITERATOR(&V_tcbinfo, 2732 INPLOOKUP_RLOCKPCB); 2733 while ((inp = inp_next(&inpi)) != NULL) { 2734 if (inp->inp_gencnt > ipi_gencnt || 2735 cr_canseeinpcb(req->td->td_ucred, inp) != 0) 2736 continue; 2737 2738 so = inp->inp_socket; 2739 if (so != NULL && so->so_gencnt <= xig.xig_sogen) { 2740 p = false; 2741 ek = export_keys && cr_canexport_ktlskeys( 2742 req->td, inp); 2743 ksr = so->so_rcv.sb_tls_info; 2744 if (ksr != NULL) { 2745 ksr->gen = xig.xig_gen; 2746 p = true; 2747 if (ek) { 2748 sz = SIZE_T_MAX; 2749 ktls_session_copy_keys(ksr, 2750 NULL, &sz); 2751 len += sz; 2752 } 2753 if (ksr->snd_tag != NULL && 2754 ksr->snd_tag->sw->snd_tag_status_str != 2755 NULL) { 2756 sz = SND_TAG_STATUS_MAXLEN; 2757 in_pcbref(inp); 2758 INP_RUNLOCK(inp); 2759 error = ksr->snd_tag->sw-> 2760 snd_tag_status_str( 2761 ksr->snd_tag, NULL, &sz); 2762 if (in_pcbrele_rlock(inp)) 2763 return (EDEADLK); 2764 if (error == 0) 2765 len += sz; 2766 } 2767 } 2768 kss = so->so_snd.sb_tls_info; 2769 if (kss != NULL) { 2770 kss->gen = xig.xig_gen; 2771 p = true; 2772 if (ek) { 2773 sz = SIZE_T_MAX; 2774 ktls_session_copy_keys(kss, 2775 NULL, &sz); 2776 len += sz; 2777 } 2778 if (kss->snd_tag != NULL && 2779 kss->snd_tag->sw->snd_tag_status_str != 2780 NULL) { 2781 sz = SND_TAG_STATUS_MAXLEN; 2782 in_pcbref(inp); 2783 INP_RUNLOCK(inp); 2784 error = kss->snd_tag->sw-> 2785 snd_tag_status_str( 2786 kss->snd_tag, NULL, &sz); 2787 if (in_pcbrele_rlock(inp)) 2788 return (EDEADLK); 2789 if (error == 0) 2790 len += sz; 2791 } 2792 } 2793 if (p) { 2794 len += sizeof(*xktls); 2795 len = roundup2(len, __alignof(struct 2796 xktls_session)); 2797 } 2798 } 2799 } 2800 if (req->oldptr == NULL) { 2801 len += 2 * sizeof(xig); 2802 len += 3 * len / 4; 2803 req->oldidx = len; 2804 return (0); 2805 } 2806 2807 if ((error = sysctl_wire_old_buffer(req, 0)) != 0) 2808 return (error); 2809 2810 error = SYSCTL_OUT(req, &xig, sizeof xig); 2811 if (error != 0) 2812 return (error); 2813 2814 buflen = roundup2(sizeof(*xktls) + 2 * TLS_MAX_PARAM_SIZE + 2815 2 * SND_TAG_STATUS_MAXLEN, __alignof(struct xktls_session)); 2816 buf = malloc(buflen, M_TEMP, M_WAITOK | M_ZERO); 2817 struct inpcb_iterator inpi1 = INP_ALL_ITERATOR(&V_tcbinfo, 2818 INPLOOKUP_RLOCKPCB); 2819 while ((inp = inp_next(&inpi1)) != NULL) { 2820 if (inp->inp_gencnt > ipi_gencnt || 2821 cr_canseeinpcb(req->td->td_ucred, inp) != 0) 2822 continue; 2823 2824 so = inp->inp_socket; 2825 if (so == NULL) 2826 continue; 2827 2828 p = false; 2829 ek = export_keys && cr_canexport_ktlskeys(req->td, inp); 2830 ksr = so->so_rcv.sb_tls_info; 2831 kss = so->so_snd.sb_tls_info; 2832 xktls = (struct xktls_session *)buf; 2833 if (ksr != NULL && ksr->gen == xig.xig_gen) { 2834 p = true; 2835 ktls_session_to_xktls_onedir(ksr, ek, &xktls->rcv); 2836 } 2837 if (kss != NULL && kss->gen == xig.xig_gen) { 2838 p = true; 2839 ktls_session_to_xktls_onedir(kss, ek, &xktls->snd); 2840 } 2841 if (!p) 2842 continue; 2843 2844 xktls->inp_gencnt = inp->inp_gencnt; 2845 xktls->so_pcb = (kvaddr_t)inp; 2846 memcpy(&xktls->coninf, &inp->inp_inc, sizeof(xktls->coninf)); 2847 len = sizeof(*xktls); 2848 if (ksr != NULL && ksr->gen == xig.xig_gen) { 2849 if (ek) { 2850 sz = buflen - len; 2851 ktls_session_copy_keys(ksr, buf + len, &sz); 2852 len += sz; 2853 } else { 2854 xktls->rcv.cipher_key_len = 0; 2855 xktls->rcv.auth_key_len = 0; 2856 } 2857 if (ksr->snd_tag != NULL && 2858 ksr->snd_tag->sw->snd_tag_status_str != NULL) { 2859 sz = SND_TAG_STATUS_MAXLEN; 2860 in_pcbref(inp); 2861 INP_RUNLOCK(inp); 2862 error = ksr->snd_tag->sw->snd_tag_status_str( 2863 ksr->snd_tag, buf + len, &sz); 2864 if (in_pcbrele_rlock(inp)) 2865 return (EDEADLK); 2866 if (error == 0) { 2867 xktls->rcv.drv_st_len = sz; 2868 len += sz; 2869 } 2870 } 2871 } 2872 if (kss != NULL && kss->gen == xig.xig_gen) { 2873 if (ek) { 2874 sz = buflen - len; 2875 ktls_session_copy_keys(kss, buf + len, &sz); 2876 len += sz; 2877 } else { 2878 xktls->snd.cipher_key_len = 0; 2879 xktls->snd.auth_key_len = 0; 2880 } 2881 if (kss->snd_tag != NULL && 2882 kss->snd_tag->sw->snd_tag_status_str != NULL) { 2883 sz = SND_TAG_STATUS_MAXLEN; 2884 in_pcbref(inp); 2885 INP_RUNLOCK(inp); 2886 error = kss->snd_tag->sw->snd_tag_status_str( 2887 kss->snd_tag, buf + len, &sz); 2888 if (in_pcbrele_rlock(inp)) 2889 return (EDEADLK); 2890 if (error == 0) { 2891 xktls->snd.drv_st_len = sz; 2892 len += sz; 2893 } 2894 } 2895 } 2896 len = roundup2(len, __alignof(*xktls)); 2897 xktls->tsz = len; 2898 xktls->fsz = sizeof(*xktls); 2899 2900 error = SYSCTL_OUT(req, xktls, len); 2901 if (error != 0) { 2902 INP_RUNLOCK(inp); 2903 break; 2904 } 2905 cnt++; 2906 } 2907 2908 if (error == 0) { 2909 xig.xig_sogen = so_gencnt; 2910 xig.xig_count = cnt; 2911 error = SYSCTL_OUT(req, &xig, sizeof(xig)); 2912 } 2913 2914 zfree(buf, M_TEMP); 2915 return (error); 2916 } 2917 2918 static int 2919 tcp_ktlslist1(SYSCTL_HANDLER_ARGS, bool export_keys) 2920 { 2921 int repeats, error; 2922 2923 for (repeats = 0; repeats < 100; repeats++) { 2924 if (sx_xlock_sig(&ktlslist_lock)) 2925 return (EINTR); 2926 error = tcp_ktlslist_locked(oidp, arg1, arg2, req, 2927 export_keys); 2928 sx_xunlock(&ktlslist_lock); 2929 if (error != EDEADLK) 2930 break; 2931 if (sig_intr() != 0) { 2932 error = EINTR; 2933 break; 2934 } 2935 req->oldidx = 0; 2936 } 2937 return (error); 2938 } 2939 2940 static int 2941 tcp_ktlslist_nokeys(SYSCTL_HANDLER_ARGS) 2942 { 2943 return (tcp_ktlslist1(oidp, arg1, arg2, req, false)); 2944 } 2945 2946 static int 2947 tcp_ktlslist_wkeys(SYSCTL_HANDLER_ARGS) 2948 { 2949 return (tcp_ktlslist1(oidp, arg1, arg2, req, true)); 2950 } 2951 2952 SYSCTL_PROC(_net_inet_tcp, TCPCTL_KTLSLIST, ktlslist, 2953 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE, 2954 NULL, 0, tcp_ktlslist_nokeys, "S,xktls_session", 2955 "List of active kTLS sessions for TCP connections"); 2956 SYSCTL_PROC(_net_inet_tcp, TCPCTL_KTLSLIST_WKEYS, ktlslist_wkeys, 2957 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE, 2958 NULL, 0, tcp_ktlslist_wkeys, "S,xktls_session", 2959 "List of active kTLS sessions for TCP connections with keys"); 2960 #endif /* KERN_TLS */ 2961 2962 #ifdef INET 2963 static int 2964 tcp_getcred(SYSCTL_HANDLER_ARGS) 2965 { 2966 struct xucred xuc; 2967 struct sockaddr_in addrs[2]; 2968 struct epoch_tracker et; 2969 struct inpcb *inp; 2970 int error; 2971 2972 if (req->newptr == NULL) 2973 return (EINVAL); 2974 error = priv_check(req->td, PRIV_NETINET_GETCRED); 2975 if (error) 2976 return (error); 2977 error = SYSCTL_IN(req, addrs, sizeof(addrs)); 2978 if (error) 2979 return (error); 2980 NET_EPOCH_ENTER(et); 2981 inp = in_pcblookup(&V_tcbinfo, addrs[1].sin_addr, addrs[1].sin_port, 2982 addrs[0].sin_addr, addrs[0].sin_port, INPLOOKUP_RLOCKPCB, NULL); 2983 NET_EPOCH_EXIT(et); 2984 if (inp != NULL) { 2985 if (error == 0) 2986 error = cr_canseeinpcb(req->td->td_ucred, inp); 2987 if (error == 0) 2988 cru2x(inp->inp_cred, &xuc); 2989 INP_RUNLOCK(inp); 2990 } else 2991 error = ENOENT; 2992 if (error == 0) 2993 error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred)); 2994 return (error); 2995 } 2996 2997 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, getcred, 2998 CTLTYPE_OPAQUE | CTLFLAG_RW | CTLFLAG_PRISON | CTLFLAG_NEEDGIANT, 2999 0, 0, tcp_getcred, "S,xucred", 3000 "Get the xucred of a TCP connection"); 3001 #endif /* INET */ 3002 3003 #ifdef INET6 3004 static int 3005 tcp6_getcred(SYSCTL_HANDLER_ARGS) 3006 { 3007 struct epoch_tracker et; 3008 struct xucred xuc; 3009 struct sockaddr_in6 addrs[2]; 3010 struct inpcb *inp; 3011 int error; 3012 #ifdef INET 3013 int mapped = 0; 3014 #endif 3015 3016 if (req->newptr == NULL) 3017 return (EINVAL); 3018 error = priv_check(req->td, PRIV_NETINET_GETCRED); 3019 if (error) 3020 return (error); 3021 error = SYSCTL_IN(req, addrs, sizeof(addrs)); 3022 if (error) 3023 return (error); 3024 if ((error = sa6_embedscope(&addrs[0], V_ip6_use_defzone)) != 0 || 3025 (error = sa6_embedscope(&addrs[1], V_ip6_use_defzone)) != 0) { 3026 return (error); 3027 } 3028 if (IN6_IS_ADDR_V4MAPPED(&addrs[0].sin6_addr)) { 3029 #ifdef INET 3030 if (IN6_IS_ADDR_V4MAPPED(&addrs[1].sin6_addr)) 3031 mapped = 1; 3032 else 3033 #endif 3034 return (EINVAL); 3035 } 3036 3037 NET_EPOCH_ENTER(et); 3038 #ifdef INET 3039 if (mapped == 1) 3040 inp = in_pcblookup(&V_tcbinfo, 3041 *(struct in_addr *)&addrs[1].sin6_addr.s6_addr[12], 3042 addrs[1].sin6_port, 3043 *(struct in_addr *)&addrs[0].sin6_addr.s6_addr[12], 3044 addrs[0].sin6_port, INPLOOKUP_RLOCKPCB, NULL); 3045 else 3046 #endif 3047 inp = in6_pcblookup(&V_tcbinfo, 3048 &addrs[1].sin6_addr, addrs[1].sin6_port, 3049 &addrs[0].sin6_addr, addrs[0].sin6_port, 3050 INPLOOKUP_RLOCKPCB, NULL); 3051 NET_EPOCH_EXIT(et); 3052 if (inp != NULL) { 3053 if (error == 0) 3054 error = cr_canseeinpcb(req->td->td_ucred, inp); 3055 if (error == 0) 3056 cru2x(inp->inp_cred, &xuc); 3057 INP_RUNLOCK(inp); 3058 } else 3059 error = ENOENT; 3060 if (error == 0) 3061 error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred)); 3062 return (error); 3063 } 3064 3065 SYSCTL_PROC(_net_inet6_tcp6, OID_AUTO, getcred, 3066 CTLTYPE_OPAQUE | CTLFLAG_RW | CTLFLAG_PRISON | CTLFLAG_NEEDGIANT, 3067 0, 0, tcp6_getcred, "S,xucred", 3068 "Get the xucred of a TCP6 connection"); 3069 #endif /* INET6 */ 3070 3071 #ifdef INET 3072 /* Path MTU to try next when a fragmentation-needed message is received. */ 3073 static inline int 3074 tcp_next_pmtu(const struct icmp *icp, const struct ip *ip) 3075 { 3076 int mtu = ntohs(icp->icmp_nextmtu); 3077 3078 /* If no alternative MTU was proposed, try the next smaller one. */ 3079 if (!mtu) 3080 mtu = ip_next_mtu(ntohs(ip->ip_len), 1); 3081 if (mtu < V_tcp_minmss + sizeof(struct tcpiphdr)) 3082 mtu = V_tcp_minmss + sizeof(struct tcpiphdr); 3083 3084 return (mtu); 3085 } 3086 3087 static void 3088 tcp_ctlinput_with_port(struct icmp *icp, uint16_t port) 3089 { 3090 struct ip *ip; 3091 struct tcphdr *th; 3092 struct inpcb *inp; 3093 struct tcpcb *tp; 3094 struct inpcb *(*notify)(struct inpcb *, int); 3095 struct in_conninfo inc; 3096 tcp_seq icmp_tcp_seq; 3097 int errno, mtu; 3098 3099 errno = icmp_errmap(icp); 3100 switch (errno) { 3101 case 0: 3102 return; 3103 case EMSGSIZE: 3104 notify = tcp_mtudisc_notify; 3105 break; 3106 case ECONNREFUSED: 3107 if (V_icmp_may_rst) 3108 notify = tcp_drop_syn_sent; 3109 else 3110 notify = tcp_notify; 3111 break; 3112 case EHOSTUNREACH: 3113 if (V_icmp_may_rst && icp->icmp_type == ICMP_TIMXCEED) 3114 notify = tcp_drop_syn_sent; 3115 else 3116 notify = tcp_notify; 3117 break; 3118 default: 3119 notify = tcp_notify; 3120 } 3121 3122 ip = &icp->icmp_ip; 3123 th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2)); 3124 icmp_tcp_seq = th->th_seq; 3125 inp = in_pcblookup(&V_tcbinfo, ip->ip_dst, th->th_dport, ip->ip_src, 3126 th->th_sport, INPLOOKUP_WLOCKPCB, NULL); 3127 if (inp != NULL) { 3128 tp = intotcpcb(inp); 3129 #ifdef TCP_OFFLOAD 3130 if (tp->t_flags & TF_TOE && errno == EMSGSIZE) { 3131 /* 3132 * MTU discovery for offloaded connections. Let 3133 * the TOE driver verify seq# and process it. 3134 */ 3135 mtu = tcp_next_pmtu(icp, ip); 3136 tcp_offload_pmtu_update(tp, icmp_tcp_seq, mtu); 3137 goto out; 3138 } 3139 #endif 3140 if (tp->t_port != port) 3141 goto out; 3142 if (SEQ_GEQ(ntohl(icmp_tcp_seq), tp->snd_una) && 3143 SEQ_LT(ntohl(icmp_tcp_seq), tp->snd_max)) { 3144 if (errno == EMSGSIZE) { 3145 /* 3146 * MTU discovery: we got a needfrag and 3147 * will potentially try a lower MTU. 3148 */ 3149 mtu = tcp_next_pmtu(icp, ip); 3150 3151 /* 3152 * Only process the offered MTU if it 3153 * is smaller than the current one. 3154 */ 3155 if (mtu < tp->t_maxseg + 3156 sizeof(struct tcpiphdr)) { 3157 bzero(&inc, sizeof(inc)); 3158 inc.inc_faddr = ip->ip_dst; 3159 inc.inc_fibnum = 3160 inp->inp_inc.inc_fibnum; 3161 tcp_hc_updatemtu(&inc, mtu); 3162 inp = tcp_mtudisc(inp, mtu); 3163 } 3164 } else 3165 inp = (*notify)(inp, errno); 3166 } 3167 } else { 3168 bzero(&inc, sizeof(inc)); 3169 inc.inc_fport = th->th_dport; 3170 inc.inc_lport = th->th_sport; 3171 inc.inc_faddr = ip->ip_dst; 3172 inc.inc_laddr = ip->ip_src; 3173 syncache_unreach(&inc, icmp_tcp_seq, port); 3174 } 3175 out: 3176 if (inp != NULL) 3177 INP_WUNLOCK(inp); 3178 } 3179 3180 static void 3181 tcp_ctlinput(struct icmp *icmp) 3182 { 3183 tcp_ctlinput_with_port(icmp, htons(0)); 3184 } 3185 3186 static void 3187 tcp_ctlinput_viaudp(udp_tun_icmp_param_t param) 3188 { 3189 /* Its a tunneled TCP over UDP icmp */ 3190 struct icmp *icmp = param.icmp; 3191 struct ip *outer_ip, *inner_ip; 3192 struct udphdr *udp; 3193 struct tcphdr *th, ttemp; 3194 int i_hlen, o_len; 3195 uint16_t port; 3196 3197 outer_ip = (struct ip *)((caddr_t)icmp - sizeof(struct ip)); 3198 inner_ip = &icmp->icmp_ip; 3199 i_hlen = inner_ip->ip_hl << 2; 3200 o_len = ntohs(outer_ip->ip_len); 3201 if (o_len < 3202 (sizeof(struct ip) + 8 + i_hlen + sizeof(struct udphdr) + offsetof(struct tcphdr, th_ack))) { 3203 /* Not enough data present */ 3204 return; 3205 } 3206 /* Ok lets strip out the inner udphdr header by copying up on top of it the tcp hdr */ 3207 udp = (struct udphdr *)(((caddr_t)inner_ip) + i_hlen); 3208 if (ntohs(udp->uh_sport) != V_tcp_udp_tunneling_port) { 3209 return; 3210 } 3211 port = udp->uh_dport; 3212 th = (struct tcphdr *)(udp + 1); 3213 memcpy(&ttemp, th, sizeof(struct tcphdr)); 3214 memcpy(udp, &ttemp, sizeof(struct tcphdr)); 3215 /* Now adjust down the size of the outer IP header */ 3216 o_len -= sizeof(struct udphdr); 3217 outer_ip->ip_len = htons(o_len); 3218 /* Now call in to the normal handling code */ 3219 tcp_ctlinput_with_port(icmp, port); 3220 } 3221 #endif /* INET */ 3222 3223 #ifdef INET6 3224 static inline int 3225 tcp6_next_pmtu(const struct icmp6_hdr *icmp6) 3226 { 3227 int mtu = ntohl(icmp6->icmp6_mtu); 3228 3229 /* 3230 * If no alternative MTU was proposed, or the proposed MTU was too 3231 * small, set to the min. 3232 */ 3233 if (mtu < IPV6_MMTU) 3234 mtu = IPV6_MMTU; 3235 return (mtu); 3236 } 3237 3238 static void 3239 tcp6_ctlinput_with_port(struct ip6ctlparam *ip6cp, uint16_t port) 3240 { 3241 struct in6_addr *dst; 3242 struct inpcb *(*notify)(struct inpcb *, int); 3243 struct ip6_hdr *ip6; 3244 struct mbuf *m; 3245 struct inpcb *inp; 3246 struct tcpcb *tp; 3247 struct icmp6_hdr *icmp6; 3248 struct in_conninfo inc; 3249 struct tcp_ports { 3250 uint16_t th_sport; 3251 uint16_t th_dport; 3252 } t_ports; 3253 tcp_seq icmp_tcp_seq; 3254 unsigned int mtu; 3255 unsigned int off; 3256 int errno; 3257 3258 icmp6 = ip6cp->ip6c_icmp6; 3259 m = ip6cp->ip6c_m; 3260 ip6 = ip6cp->ip6c_ip6; 3261 off = ip6cp->ip6c_off; 3262 dst = &ip6cp->ip6c_finaldst->sin6_addr; 3263 3264 errno = icmp6_errmap(icmp6); 3265 switch (errno) { 3266 case 0: 3267 return; 3268 case EMSGSIZE: 3269 notify = tcp_mtudisc_notify; 3270 break; 3271 case ECONNREFUSED: 3272 if (V_icmp_may_rst) 3273 notify = tcp_drop_syn_sent; 3274 else 3275 notify = tcp_notify; 3276 break; 3277 case EHOSTUNREACH: 3278 /* 3279 * There are only four ICMPs that may reset connection: 3280 * - administratively prohibited 3281 * - port unreachable 3282 * - time exceeded in transit 3283 * - unknown next header 3284 */ 3285 if (V_icmp_may_rst && 3286 ((icmp6->icmp6_type == ICMP6_DST_UNREACH && 3287 (icmp6->icmp6_code == ICMP6_DST_UNREACH_ADMIN || 3288 icmp6->icmp6_code == ICMP6_DST_UNREACH_NOPORT)) || 3289 (icmp6->icmp6_type == ICMP6_TIME_EXCEEDED && 3290 icmp6->icmp6_code == ICMP6_TIME_EXCEED_TRANSIT) || 3291 (icmp6->icmp6_type == ICMP6_PARAM_PROB && 3292 icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER))) 3293 notify = tcp_drop_syn_sent; 3294 else 3295 notify = tcp_notify; 3296 break; 3297 default: 3298 notify = tcp_notify; 3299 } 3300 3301 /* Check if we can safely get the ports from the tcp hdr */ 3302 if (m == NULL || 3303 (m->m_pkthdr.len < 3304 (int32_t) (off + sizeof(struct tcp_ports)))) { 3305 return; 3306 } 3307 bzero(&t_ports, sizeof(struct tcp_ports)); 3308 m_copydata(m, off, sizeof(struct tcp_ports), (caddr_t)&t_ports); 3309 inp = in6_pcblookup(&V_tcbinfo, &ip6->ip6_dst, t_ports.th_dport, 3310 &ip6->ip6_src, t_ports.th_sport, INPLOOKUP_WLOCKPCB, NULL); 3311 off += sizeof(struct tcp_ports); 3312 if (m->m_pkthdr.len < (int32_t) (off + sizeof(tcp_seq))) { 3313 goto out; 3314 } 3315 m_copydata(m, off, sizeof(tcp_seq), (caddr_t)&icmp_tcp_seq); 3316 if (inp != NULL) { 3317 tp = intotcpcb(inp); 3318 #ifdef TCP_OFFLOAD 3319 if (tp->t_flags & TF_TOE && errno == EMSGSIZE) { 3320 /* MTU discovery for offloaded connections. */ 3321 mtu = tcp6_next_pmtu(icmp6); 3322 tcp_offload_pmtu_update(tp, icmp_tcp_seq, mtu); 3323 goto out; 3324 } 3325 #endif 3326 if (tp->t_port != port) 3327 goto out; 3328 if (SEQ_GEQ(ntohl(icmp_tcp_seq), tp->snd_una) && 3329 SEQ_LT(ntohl(icmp_tcp_seq), tp->snd_max)) { 3330 if (errno == EMSGSIZE) { 3331 /* 3332 * MTU discovery: 3333 * If we got a needfrag set the MTU 3334 * in the route to the suggested new 3335 * value (if given) and then notify. 3336 */ 3337 mtu = tcp6_next_pmtu(icmp6); 3338 3339 bzero(&inc, sizeof(inc)); 3340 inc.inc_fibnum = M_GETFIB(m); 3341 inc.inc_flags |= INC_ISIPV6; 3342 inc.inc6_faddr = *dst; 3343 if (in6_setscope(&inc.inc6_faddr, 3344 m->m_pkthdr.rcvif, NULL)) 3345 goto out; 3346 /* 3347 * Only process the offered MTU if it 3348 * is smaller than the current one. 3349 */ 3350 if (mtu < tp->t_maxseg + 3351 sizeof (struct tcphdr) + 3352 sizeof (struct ip6_hdr)) { 3353 tcp_hc_updatemtu(&inc, mtu); 3354 tcp_mtudisc(inp, mtu); 3355 ICMP6STAT_INC(icp6s_pmtuchg); 3356 } 3357 } else 3358 inp = (*notify)(inp, errno); 3359 } 3360 } else { 3361 bzero(&inc, sizeof(inc)); 3362 inc.inc_fibnum = M_GETFIB(m); 3363 inc.inc_flags |= INC_ISIPV6; 3364 inc.inc_fport = t_ports.th_dport; 3365 inc.inc_lport = t_ports.th_sport; 3366 inc.inc6_faddr = *dst; 3367 inc.inc6_laddr = ip6->ip6_src; 3368 syncache_unreach(&inc, icmp_tcp_seq, port); 3369 } 3370 out: 3371 if (inp != NULL) 3372 INP_WUNLOCK(inp); 3373 } 3374 3375 static void 3376 tcp6_ctlinput(struct ip6ctlparam *ctl) 3377 { 3378 tcp6_ctlinput_with_port(ctl, htons(0)); 3379 } 3380 3381 static void 3382 tcp6_ctlinput_viaudp(udp_tun_icmp_param_t param) 3383 { 3384 struct ip6ctlparam *ip6cp = param.ip6cp; 3385 struct mbuf *m; 3386 struct udphdr *udp; 3387 uint16_t port; 3388 3389 m = m_pulldown(ip6cp->ip6c_m, ip6cp->ip6c_off, sizeof(struct udphdr), NULL); 3390 if (m == NULL) { 3391 return; 3392 } 3393 udp = mtod(m, struct udphdr *); 3394 if (ntohs(udp->uh_sport) != V_tcp_udp_tunneling_port) { 3395 return; 3396 } 3397 port = udp->uh_dport; 3398 m_adj(m, sizeof(struct udphdr)); 3399 if ((m->m_flags & M_PKTHDR) == 0) { 3400 ip6cp->ip6c_m->m_pkthdr.len -= sizeof(struct udphdr); 3401 } 3402 /* Now call in to the normal handling code */ 3403 tcp6_ctlinput_with_port(ip6cp, port); 3404 } 3405 3406 #endif /* INET6 */ 3407 3408 static uint32_t 3409 tcp_keyed_hash(struct in_conninfo *inc, u_char *key, u_int len) 3410 { 3411 SIPHASH_CTX ctx; 3412 uint32_t hash[2]; 3413 3414 KASSERT(len >= SIPHASH_KEY_LENGTH, 3415 ("%s: keylen %u too short ", __func__, len)); 3416 SipHash24_Init(&ctx); 3417 SipHash_SetKey(&ctx, (uint8_t *)key); 3418 SipHash_Update(&ctx, &inc->inc_fport, sizeof(uint16_t)); 3419 SipHash_Update(&ctx, &inc->inc_lport, sizeof(uint16_t)); 3420 switch (inc->inc_flags & INC_ISIPV6) { 3421 #ifdef INET 3422 case 0: 3423 SipHash_Update(&ctx, &inc->inc_faddr, sizeof(struct in_addr)); 3424 SipHash_Update(&ctx, &inc->inc_laddr, sizeof(struct in_addr)); 3425 break; 3426 #endif 3427 #ifdef INET6 3428 case INC_ISIPV6: 3429 SipHash_Update(&ctx, &inc->inc6_faddr, sizeof(struct in6_addr)); 3430 SipHash_Update(&ctx, &inc->inc6_laddr, sizeof(struct in6_addr)); 3431 break; 3432 #endif 3433 } 3434 SipHash_Final((uint8_t *)hash, &ctx); 3435 3436 return (hash[0] ^ hash[1]); 3437 } 3438 3439 uint32_t 3440 tcp_new_ts_offset(struct in_conninfo *inc) 3441 { 3442 struct in_conninfo inc_store, *local_inc; 3443 3444 if (!V_tcp_ts_offset_per_conn) { 3445 memcpy(&inc_store, inc, sizeof(struct in_conninfo)); 3446 inc_store.inc_lport = 0; 3447 inc_store.inc_fport = 0; 3448 local_inc = &inc_store; 3449 } else { 3450 local_inc = inc; 3451 } 3452 return (tcp_keyed_hash(local_inc, V_ts_offset_secret, 3453 sizeof(V_ts_offset_secret))); 3454 } 3455 3456 /* 3457 * Following is where TCP initial sequence number generation occurs. 3458 * 3459 * There are two places where we must use initial sequence numbers: 3460 * 1. In SYN-ACK packets. 3461 * 2. In SYN packets. 3462 * 3463 * All ISNs for SYN-ACK packets are generated by the syncache. See 3464 * tcp_syncache.c for details. 3465 * 3466 * The ISNs in SYN packets must be monotonic; TIME_WAIT recycling 3467 * depends on this property. In addition, these ISNs should be 3468 * unguessable so as to prevent connection hijacking. To satisfy 3469 * the requirements of this situation, the algorithm outlined in 3470 * RFC 1948 is used, with only small modifications. 3471 * 3472 * Implementation details: 3473 * 3474 * Time is based off the system timer, and is corrected so that it 3475 * increases by one megabyte per second. This allows for proper 3476 * recycling on high speed LANs while still leaving over an hour 3477 * before rollover. 3478 * 3479 * As reading the *exact* system time is too expensive to be done 3480 * whenever setting up a TCP connection, we increment the time 3481 * offset in two ways. First, a small random positive increment 3482 * is added to isn_offset for each connection that is set up. 3483 * Second, the function tcp_isn_tick fires once per clock tick 3484 * and increments isn_offset as necessary so that sequence numbers 3485 * are incremented at approximately ISN_BYTES_PER_SECOND. The 3486 * random positive increments serve only to ensure that the same 3487 * exact sequence number is never sent out twice (as could otherwise 3488 * happen when a port is recycled in less than the system tick 3489 * interval.) 3490 * 3491 * net.inet.tcp.isn_reseed_interval controls the number of seconds 3492 * between seeding of isn_secret. This is normally set to zero, 3493 * as reseeding should not be necessary. 3494 * 3495 * Locking of the global variables isn_secret, isn_last_reseed, isn_offset, 3496 * isn_offset_old, and isn_ctx is performed using the ISN lock. In 3497 * general, this means holding an exclusive (write) lock. 3498 */ 3499 3500 #define ISN_BYTES_PER_SECOND 1048576 3501 #define ISN_STATIC_INCREMENT 4096 3502 #define ISN_RANDOM_INCREMENT (4096 - 1) 3503 #define ISN_SECRET_LENGTH SIPHASH_KEY_LENGTH 3504 3505 VNET_DEFINE_STATIC(u_char, isn_secret[ISN_SECRET_LENGTH]); 3506 VNET_DEFINE_STATIC(int, isn_last); 3507 VNET_DEFINE_STATIC(int, isn_last_reseed); 3508 VNET_DEFINE_STATIC(u_int32_t, isn_offset); 3509 VNET_DEFINE_STATIC(u_int32_t, isn_offset_old); 3510 3511 #define V_isn_secret VNET(isn_secret) 3512 #define V_isn_last VNET(isn_last) 3513 #define V_isn_last_reseed VNET(isn_last_reseed) 3514 #define V_isn_offset VNET(isn_offset) 3515 #define V_isn_offset_old VNET(isn_offset_old) 3516 3517 tcp_seq 3518 tcp_new_isn(struct in_conninfo *inc) 3519 { 3520 tcp_seq new_isn; 3521 u_int32_t projected_offset; 3522 3523 ISN_LOCK(); 3524 /* Seed if this is the first use, reseed if requested. */ 3525 if ((V_isn_last_reseed == 0) || ((V_tcp_isn_reseed_interval > 0) && 3526 (((u_int)V_isn_last_reseed + (u_int)V_tcp_isn_reseed_interval*hz) 3527 < (u_int)ticks))) { 3528 arc4rand(&V_isn_secret, sizeof(V_isn_secret), 0); 3529 V_isn_last_reseed = ticks; 3530 } 3531 3532 /* Compute the hash and return the ISN. */ 3533 new_isn = (tcp_seq)tcp_keyed_hash(inc, V_isn_secret, 3534 sizeof(V_isn_secret)); 3535 V_isn_offset += ISN_STATIC_INCREMENT + 3536 (arc4random() & ISN_RANDOM_INCREMENT); 3537 if (ticks != V_isn_last) { 3538 projected_offset = V_isn_offset_old + 3539 ISN_BYTES_PER_SECOND / hz * (ticks - V_isn_last); 3540 if (SEQ_GT(projected_offset, V_isn_offset)) 3541 V_isn_offset = projected_offset; 3542 V_isn_offset_old = V_isn_offset; 3543 V_isn_last = ticks; 3544 } 3545 new_isn += V_isn_offset; 3546 ISN_UNLOCK(); 3547 return (new_isn); 3548 } 3549 3550 /* 3551 * When a specific ICMP unreachable message is received and the 3552 * connection state is SYN-SENT, drop the connection. This behavior 3553 * is controlled by the icmp_may_rst sysctl. 3554 */ 3555 static struct inpcb * 3556 tcp_drop_syn_sent(struct inpcb *inp, int errno) 3557 { 3558 struct tcpcb *tp; 3559 3560 NET_EPOCH_ASSERT(); 3561 INP_WLOCK_ASSERT(inp); 3562 3563 tp = intotcpcb(inp); 3564 if (tp->t_state != TCPS_SYN_SENT) 3565 return (inp); 3566 3567 if (tp->t_flags & TF_FASTOPEN) 3568 tcp_fastopen_disable_path(tp); 3569 3570 tp = tcp_drop(tp, errno); 3571 if (tp != NULL) 3572 return (inp); 3573 else 3574 return (NULL); 3575 } 3576 3577 /* 3578 * When `need fragmentation' ICMP is received, update our idea of the MSS 3579 * based on the new value. Also nudge TCP to send something, since we 3580 * know the packet we just sent was dropped. 3581 * This duplicates some code in the tcp_mss() function in tcp_input.c. 3582 */ 3583 static struct inpcb * 3584 tcp_mtudisc_notify(struct inpcb *inp, int error) 3585 { 3586 3587 return (tcp_mtudisc(inp, -1)); 3588 } 3589 3590 static struct inpcb * 3591 tcp_mtudisc(struct inpcb *inp, int mtuoffer) 3592 { 3593 struct tcpcb *tp; 3594 struct socket *so; 3595 3596 INP_WLOCK_ASSERT(inp); 3597 3598 tp = intotcpcb(inp); 3599 KASSERT(tp != NULL, ("tcp_mtudisc: tp == NULL")); 3600 3601 tcp_mss_update(tp, -1, mtuoffer, NULL, NULL); 3602 3603 so = inp->inp_socket; 3604 SOCK_SENDBUF_LOCK(so); 3605 /* If the mss is larger than the socket buffer, decrease the mss. */ 3606 if (so->so_snd.sb_hiwat < tp->t_maxseg) { 3607 tp->t_maxseg = so->so_snd.sb_hiwat; 3608 if (tp->t_maxseg < V_tcp_mssdflt) { 3609 /* 3610 * The MSS is so small we should not process incoming 3611 * SACK's since we are subject to attack in such a 3612 * case. 3613 */ 3614 tp->t_flags2 |= TF2_PROC_SACK_PROHIBIT; 3615 } else { 3616 tp->t_flags2 &= ~TF2_PROC_SACK_PROHIBIT; 3617 } 3618 } 3619 SOCK_SENDBUF_UNLOCK(so); 3620 3621 TCPSTAT_INC(tcps_mturesent); 3622 tp->t_rtttime = 0; 3623 tp->snd_nxt = tp->snd_una; 3624 tcp_free_sackholes(tp); 3625 tp->snd_recover = tp->snd_max; 3626 if (tp->t_flags & TF_SACK_PERMIT) 3627 EXIT_FASTRECOVERY(tp->t_flags); 3628 if (tp->t_fb->tfb_tcp_mtu_chg != NULL) { 3629 /* 3630 * Conceptually the snd_nxt setting 3631 * and freeing sack holes should 3632 * be done by the default stacks 3633 * own tfb_tcp_mtu_chg(). 3634 */ 3635 tp->t_fb->tfb_tcp_mtu_chg(tp); 3636 } 3637 if (tcp_output(tp) < 0) 3638 return (NULL); 3639 else 3640 return (inp); 3641 } 3642 3643 #ifdef INET 3644 /* 3645 * Look-up the routing entry to the peer of this inpcb. If no route 3646 * is found and it cannot be allocated, then return 0. This routine 3647 * is called by TCP routines that access the rmx structure and by 3648 * tcp_mss_update to get the peer/interface MTU. 3649 */ 3650 uint32_t 3651 tcp_maxmtu(struct in_conninfo *inc, struct tcp_ifcap *cap) 3652 { 3653 struct nhop_object *nh; 3654 struct ifnet *ifp; 3655 uint32_t maxmtu = 0; 3656 3657 KASSERT(inc != NULL, ("tcp_maxmtu with NULL in_conninfo pointer")); 3658 3659 if (inc->inc_faddr.s_addr != INADDR_ANY) { 3660 nh = fib4_lookup(inc->inc_fibnum, inc->inc_faddr, 0, NHR_NONE, 0); 3661 if (nh == NULL) 3662 return (0); 3663 3664 ifp = nh->nh_ifp; 3665 maxmtu = nh->nh_mtu; 3666 3667 /* Report additional interface capabilities. */ 3668 if (cap != NULL) { 3669 if (ifp->if_capenable & IFCAP_TSO4 && 3670 ifp->if_hwassist & CSUM_TSO) { 3671 cap->ifcap |= CSUM_TSO; 3672 cap->tsomax = ifp->if_hw_tsomax; 3673 cap->tsomaxsegcount = ifp->if_hw_tsomaxsegcount; 3674 cap->tsomaxsegsize = ifp->if_hw_tsomaxsegsize; 3675 /* XXXKIB IFCAP2_IPSEC_OFFLOAD_TSO */ 3676 cap->ipsec_tso = (ifp->if_capenable2 & 3677 IFCAP2_BIT(IFCAP2_IPSEC_OFFLOAD)) != 0; 3678 } 3679 } 3680 } 3681 return (maxmtu); 3682 } 3683 #endif /* INET */ 3684 3685 #ifdef INET6 3686 uint32_t 3687 tcp_maxmtu6(struct in_conninfo *inc, struct tcp_ifcap *cap) 3688 { 3689 struct nhop_object *nh; 3690 struct in6_addr dst6; 3691 uint32_t scopeid; 3692 struct ifnet *ifp; 3693 uint32_t maxmtu = 0; 3694 3695 KASSERT(inc != NULL, ("tcp_maxmtu6 with NULL in_conninfo pointer")); 3696 3697 if (inc->inc_flags & INC_IPV6MINMTU) 3698 return (IPV6_MMTU); 3699 3700 if (!IN6_IS_ADDR_UNSPECIFIED(&inc->inc6_faddr)) { 3701 in6_splitscope(&inc->inc6_faddr, &dst6, &scopeid); 3702 nh = fib6_lookup(inc->inc_fibnum, &dst6, scopeid, NHR_NONE, 0); 3703 if (nh == NULL) 3704 return (0); 3705 3706 ifp = nh->nh_ifp; 3707 maxmtu = nh->nh_mtu; 3708 3709 /* Report additional interface capabilities. */ 3710 if (cap != NULL) { 3711 if (ifp->if_capenable & IFCAP_TSO6 && 3712 ifp->if_hwassist & CSUM_TSO) { 3713 cap->ifcap |= CSUM_TSO; 3714 cap->tsomax = ifp->if_hw_tsomax; 3715 cap->tsomaxsegcount = ifp->if_hw_tsomaxsegcount; 3716 cap->tsomaxsegsize = ifp->if_hw_tsomaxsegsize; 3717 cap->ipsec_tso = false; /* XXXKIB */ 3718 } 3719 } 3720 } 3721 3722 return (maxmtu); 3723 } 3724 3725 /* 3726 * Handle setsockopt(IPV6_USE_MIN_MTU) by a TCP stack. 3727 * 3728 * XXXGL: we are updating inpcb here with INC_IPV6MINMTU flag. 3729 * The right place to do that is ip6_setpktopt() that has just been 3730 * executed. By the way it just filled ip6po_minmtu for us. 3731 */ 3732 void 3733 tcp6_use_min_mtu(struct tcpcb *tp) 3734 { 3735 struct inpcb *inp = tptoinpcb(tp); 3736 3737 INP_WLOCK_ASSERT(inp); 3738 /* 3739 * In case of the IPV6_USE_MIN_MTU socket 3740 * option, the INC_IPV6MINMTU flag to announce 3741 * a corresponding MSS during the initial 3742 * handshake. If the TCP connection is not in 3743 * the front states, just reduce the MSS being 3744 * used. This avoids the sending of TCP 3745 * segments which will be fragmented at the 3746 * IPv6 layer. 3747 */ 3748 inp->inp_inc.inc_flags |= INC_IPV6MINMTU; 3749 if ((tp->t_state >= TCPS_SYN_SENT) && 3750 (inp->inp_inc.inc_flags & INC_ISIPV6)) { 3751 struct ip6_pktopts *opt; 3752 3753 opt = inp->in6p_outputopts; 3754 if (opt != NULL && opt->ip6po_minmtu == IP6PO_MINMTU_ALL && 3755 tp->t_maxseg > TCP6_MSS) { 3756 tp->t_maxseg = TCP6_MSS; 3757 if (tp->t_maxseg < V_tcp_mssdflt) { 3758 /* 3759 * The MSS is so small we should not process incoming 3760 * SACK's since we are subject to attack in such a 3761 * case. 3762 */ 3763 tp->t_flags2 |= TF2_PROC_SACK_PROHIBIT; 3764 } else { 3765 tp->t_flags2 &= ~TF2_PROC_SACK_PROHIBIT; 3766 } 3767 } 3768 } 3769 } 3770 #endif /* INET6 */ 3771 3772 /* 3773 * Calculate effective SMSS per RFC5681 definition for a given TCP 3774 * connection at its current state, taking into account SACK and etc. 3775 */ 3776 u_int 3777 tcp_maxseg(const struct tcpcb *tp) 3778 { 3779 u_int optlen; 3780 3781 if (tp->t_flags & TF_NOOPT) 3782 return (tp->t_maxseg); 3783 3784 /* 3785 * Here we have a simplified code from tcp_addoptions(), 3786 * without a proper loop, and having most of paddings hardcoded. 3787 * We might make mistakes with padding here in some edge cases, 3788 * but this is harmless, since result of tcp_maxseg() is used 3789 * only in cwnd and ssthresh estimations. 3790 */ 3791 if (TCPS_HAVEESTABLISHED(tp->t_state)) { 3792 if (tp->t_flags & TF_RCVD_TSTMP) 3793 optlen = TCPOLEN_TSTAMP_APPA; 3794 else 3795 optlen = 0; 3796 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE) 3797 if (tp->t_flags & TF_SIGNATURE) 3798 optlen += PADTCPOLEN(TCPOLEN_SIGNATURE); 3799 #endif 3800 if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks > 0) { 3801 optlen += TCPOLEN_SACKHDR; 3802 optlen += tp->rcv_numsacks * TCPOLEN_SACK; 3803 optlen = PADTCPOLEN(optlen); 3804 } 3805 } else { 3806 if (tp->t_flags & TF_REQ_TSTMP) 3807 optlen = TCPOLEN_TSTAMP_APPA; 3808 else 3809 optlen = PADTCPOLEN(TCPOLEN_MAXSEG); 3810 if (tp->t_flags & TF_REQ_SCALE) 3811 optlen += PADTCPOLEN(TCPOLEN_WINDOW); 3812 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE) 3813 if (tp->t_flags & TF_SIGNATURE) 3814 optlen += PADTCPOLEN(TCPOLEN_SIGNATURE); 3815 #endif 3816 if (tp->t_flags & TF_SACK_PERMIT) 3817 optlen += PADTCPOLEN(TCPOLEN_SACK_PERMITTED); 3818 } 3819 optlen = min(optlen, TCP_MAXOLEN); 3820 return (tp->t_maxseg - optlen); 3821 } 3822 3823 3824 u_int 3825 tcp_fixed_maxseg(const struct tcpcb *tp) 3826 { 3827 int optlen; 3828 3829 if (tp->t_flags & TF_NOOPT) 3830 return (tp->t_maxseg); 3831 3832 /* 3833 * Here we have a simplified code from tcp_addoptions(), 3834 * without a proper loop, and having most of paddings hardcoded. 3835 * We only consider fixed options that we would send every 3836 * time I.e. SACK is not considered. This is important 3837 * for cc modules to figure out what the modulo of the 3838 * cwnd should be. 3839 */ 3840 if (TCPS_HAVEESTABLISHED(tp->t_state)) { 3841 if (tp->t_flags & TF_RCVD_TSTMP) 3842 optlen = TCPOLEN_TSTAMP_APPA; 3843 else 3844 optlen = 0; 3845 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE) 3846 if (tp->t_flags & TF_SIGNATURE) 3847 optlen += PADTCPOLEN(TCPOLEN_SIGNATURE); 3848 #endif 3849 } else { 3850 if (tp->t_flags & TF_REQ_TSTMP) 3851 optlen = TCPOLEN_TSTAMP_APPA; 3852 else 3853 optlen = PADTCPOLEN(TCPOLEN_MAXSEG); 3854 if (tp->t_flags & TF_REQ_SCALE) 3855 optlen += PADTCPOLEN(TCPOLEN_WINDOW); 3856 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE) 3857 if (tp->t_flags & TF_SIGNATURE) 3858 optlen += PADTCPOLEN(TCPOLEN_SIGNATURE); 3859 #endif 3860 if (tp->t_flags & TF_SACK_PERMIT) 3861 optlen += PADTCPOLEN(TCPOLEN_SACK_PERMITTED); 3862 } 3863 optlen = min(optlen, TCP_MAXOLEN); 3864 return (tp->t_maxseg - optlen); 3865 } 3866 3867 3868 3869 static int 3870 sysctl_drop(SYSCTL_HANDLER_ARGS) 3871 { 3872 /* addrs[0] is a foreign socket, addrs[1] is a local one. */ 3873 struct sockaddr_storage addrs[2]; 3874 struct inpcb *inp; 3875 struct tcpcb *tp; 3876 #ifdef INET 3877 struct sockaddr_in *fin = NULL, *lin = NULL; 3878 #endif 3879 struct epoch_tracker et; 3880 #ifdef INET6 3881 struct sockaddr_in6 *fin6, *lin6; 3882 #endif 3883 int error; 3884 3885 inp = NULL; 3886 #ifdef INET6 3887 fin6 = lin6 = NULL; 3888 #endif 3889 error = 0; 3890 3891 if (req->oldptr != NULL || req->oldlen != 0) 3892 return (EINVAL); 3893 if (req->newptr == NULL) 3894 return (EPERM); 3895 if (req->newlen < sizeof(addrs)) 3896 return (ENOMEM); 3897 error = SYSCTL_IN(req, &addrs, sizeof(addrs)); 3898 if (error) 3899 return (error); 3900 3901 switch (addrs[0].ss_family) { 3902 #ifdef INET6 3903 case AF_INET6: 3904 fin6 = (struct sockaddr_in6 *)&addrs[0]; 3905 lin6 = (struct sockaddr_in6 *)&addrs[1]; 3906 if (fin6->sin6_len != sizeof(struct sockaddr_in6) || 3907 lin6->sin6_len != sizeof(struct sockaddr_in6)) 3908 return (EINVAL); 3909 if (IN6_IS_ADDR_V4MAPPED(&fin6->sin6_addr)) { 3910 if (!IN6_IS_ADDR_V4MAPPED(&lin6->sin6_addr)) 3911 return (EINVAL); 3912 in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[0]); 3913 in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[1]); 3914 #ifdef INET 3915 fin = (struct sockaddr_in *)&addrs[0]; 3916 lin = (struct sockaddr_in *)&addrs[1]; 3917 #endif 3918 break; 3919 } 3920 error = sa6_embedscope(fin6, V_ip6_use_defzone); 3921 if (error) 3922 return (error); 3923 error = sa6_embedscope(lin6, V_ip6_use_defzone); 3924 if (error) 3925 return (error); 3926 break; 3927 #endif 3928 #ifdef INET 3929 case AF_INET: 3930 fin = (struct sockaddr_in *)&addrs[0]; 3931 lin = (struct sockaddr_in *)&addrs[1]; 3932 if (fin->sin_len != sizeof(struct sockaddr_in) || 3933 lin->sin_len != sizeof(struct sockaddr_in)) 3934 return (EINVAL); 3935 break; 3936 #endif 3937 default: 3938 return (EINVAL); 3939 } 3940 NET_EPOCH_ENTER(et); 3941 switch (addrs[0].ss_family) { 3942 #ifdef INET6 3943 case AF_INET6: 3944 inp = in6_pcblookup(&V_tcbinfo, &fin6->sin6_addr, 3945 fin6->sin6_port, &lin6->sin6_addr, lin6->sin6_port, 3946 INPLOOKUP_WLOCKPCB, NULL); 3947 break; 3948 #endif 3949 #ifdef INET 3950 case AF_INET: 3951 inp = in_pcblookup(&V_tcbinfo, fin->sin_addr, fin->sin_port, 3952 lin->sin_addr, lin->sin_port, INPLOOKUP_WLOCKPCB, NULL); 3953 break; 3954 #endif 3955 } 3956 if (inp != NULL) { 3957 if (!SOLISTENING(inp->inp_socket)) { 3958 tp = intotcpcb(inp); 3959 tp = tcp_drop(tp, ECONNABORTED); 3960 if (tp != NULL) 3961 INP_WUNLOCK(inp); 3962 } else 3963 INP_WUNLOCK(inp); 3964 } else 3965 error = ESRCH; 3966 NET_EPOCH_EXIT(et); 3967 return (error); 3968 } 3969 3970 SYSCTL_PROC(_net_inet_tcp, TCPCTL_DROP, drop, 3971 CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP | 3972 CTLFLAG_NEEDGIANT, NULL, 0, sysctl_drop, "", 3973 "Drop TCP connection"); 3974 3975 static int 3976 tcp_sysctl_setsockopt(SYSCTL_HANDLER_ARGS) 3977 { 3978 return (sysctl_setsockopt(oidp, arg1, arg2, req, &V_tcbinfo, 3979 &tcp_ctloutput_set)); 3980 } 3981 3982 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, setsockopt, 3983 CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP | 3984 CTLFLAG_MPSAFE, NULL, 0, tcp_sysctl_setsockopt, "", 3985 "Set socket option for TCP endpoint"); 3986 3987 #ifdef KERN_TLS 3988 static int 3989 sysctl_switch_tls(SYSCTL_HANDLER_ARGS) 3990 { 3991 /* addrs[0] is a foreign socket, addrs[1] is a local one. */ 3992 struct sockaddr_storage addrs[2]; 3993 struct inpcb *inp; 3994 #ifdef INET 3995 struct sockaddr_in *fin = NULL, *lin = NULL; 3996 #endif 3997 struct epoch_tracker et; 3998 #ifdef INET6 3999 struct sockaddr_in6 *fin6, *lin6; 4000 #endif 4001 int error; 4002 4003 inp = NULL; 4004 #ifdef INET6 4005 fin6 = lin6 = NULL; 4006 #endif 4007 error = 0; 4008 4009 if (req->oldptr != NULL || req->oldlen != 0) 4010 return (EINVAL); 4011 if (req->newptr == NULL) 4012 return (EPERM); 4013 if (req->newlen < sizeof(addrs)) 4014 return (ENOMEM); 4015 error = SYSCTL_IN(req, &addrs, sizeof(addrs)); 4016 if (error) 4017 return (error); 4018 4019 switch (addrs[0].ss_family) { 4020 #ifdef INET6 4021 case AF_INET6: 4022 fin6 = (struct sockaddr_in6 *)&addrs[0]; 4023 lin6 = (struct sockaddr_in6 *)&addrs[1]; 4024 if (fin6->sin6_len != sizeof(struct sockaddr_in6) || 4025 lin6->sin6_len != sizeof(struct sockaddr_in6)) 4026 return (EINVAL); 4027 if (IN6_IS_ADDR_V4MAPPED(&fin6->sin6_addr)) { 4028 if (!IN6_IS_ADDR_V4MAPPED(&lin6->sin6_addr)) 4029 return (EINVAL); 4030 in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[0]); 4031 in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[1]); 4032 #ifdef INET 4033 fin = (struct sockaddr_in *)&addrs[0]; 4034 lin = (struct sockaddr_in *)&addrs[1]; 4035 #endif 4036 break; 4037 } 4038 error = sa6_embedscope(fin6, V_ip6_use_defzone); 4039 if (error) 4040 return (error); 4041 error = sa6_embedscope(lin6, V_ip6_use_defzone); 4042 if (error) 4043 return (error); 4044 break; 4045 #endif 4046 #ifdef INET 4047 case AF_INET: 4048 fin = (struct sockaddr_in *)&addrs[0]; 4049 lin = (struct sockaddr_in *)&addrs[1]; 4050 if (fin->sin_len != sizeof(struct sockaddr_in) || 4051 lin->sin_len != sizeof(struct sockaddr_in)) 4052 return (EINVAL); 4053 break; 4054 #endif 4055 default: 4056 return (EINVAL); 4057 } 4058 NET_EPOCH_ENTER(et); 4059 switch (addrs[0].ss_family) { 4060 #ifdef INET6 4061 case AF_INET6: 4062 inp = in6_pcblookup(&V_tcbinfo, &fin6->sin6_addr, 4063 fin6->sin6_port, &lin6->sin6_addr, lin6->sin6_port, 4064 INPLOOKUP_WLOCKPCB, NULL); 4065 break; 4066 #endif 4067 #ifdef INET 4068 case AF_INET: 4069 inp = in_pcblookup(&V_tcbinfo, fin->sin_addr, fin->sin_port, 4070 lin->sin_addr, lin->sin_port, INPLOOKUP_WLOCKPCB, NULL); 4071 break; 4072 #endif 4073 } 4074 NET_EPOCH_EXIT(et); 4075 if (inp != NULL) { 4076 struct socket *so; 4077 4078 so = inp->inp_socket; 4079 soref(so); 4080 error = ktls_set_tx_mode(so, 4081 arg2 == 0 ? TCP_TLS_MODE_SW : TCP_TLS_MODE_IFNET); 4082 INP_WUNLOCK(inp); 4083 sorele(so); 4084 } else 4085 error = ESRCH; 4086 return (error); 4087 } 4088 4089 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, switch_to_sw_tls, 4090 CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP | 4091 CTLFLAG_NEEDGIANT, NULL, 0, sysctl_switch_tls, "", 4092 "Switch TCP connection to SW TLS"); 4093 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, switch_to_ifnet_tls, 4094 CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP | 4095 CTLFLAG_NEEDGIANT, NULL, 1, sysctl_switch_tls, "", 4096 "Switch TCP connection to ifnet TLS"); 4097 #endif 4098 4099 /* 4100 * Generate a standardized TCP log line for use throughout the 4101 * tcp subsystem. Memory allocation is done with M_NOWAIT to 4102 * allow use in the interrupt context. 4103 * 4104 * NB: The caller MUST free(s, M_TCPLOG) the returned string. 4105 * NB: The function may return NULL if memory allocation failed. 4106 * 4107 * Due to header inclusion and ordering limitations the struct ip 4108 * and ip6_hdr pointers have to be passed as void pointers. 4109 */ 4110 char * 4111 tcp_log_vain(struct in_conninfo *inc, struct tcphdr *th, const void *ip4hdr, 4112 const void *ip6hdr) 4113 { 4114 4115 /* Is logging enabled? */ 4116 if (V_tcp_log_in_vain == 0) 4117 return (NULL); 4118 4119 return (tcp_log_addr(inc, th, ip4hdr, ip6hdr)); 4120 } 4121 4122 char * 4123 tcp_log_addrs(struct in_conninfo *inc, struct tcphdr *th, const void *ip4hdr, 4124 const void *ip6hdr) 4125 { 4126 4127 /* Is logging enabled? */ 4128 if (tcp_log_debug == 0) 4129 return (NULL); 4130 4131 return (tcp_log_addr(inc, th, ip4hdr, ip6hdr)); 4132 } 4133 4134 static char * 4135 tcp_log_addr(struct in_conninfo *inc, struct tcphdr *th, const void *ip4hdr, 4136 const void *ip6hdr) 4137 { 4138 char *s, *sp; 4139 size_t size; 4140 #ifdef INET 4141 const struct ip *ip = (const struct ip *)ip4hdr; 4142 #endif 4143 #ifdef INET6 4144 const struct ip6_hdr *ip6 = (const struct ip6_hdr *)ip6hdr; 4145 #endif /* INET6 */ 4146 4147 /* 4148 * The log line looks like this: 4149 * "TCP: [1.2.3.4]:50332 to [1.2.3.4]:80 tcpflags 0x2<SYN>" 4150 */ 4151 size = sizeof("TCP: []:12345 to []:12345 tcpflags 0x2<>") + 4152 sizeof(PRINT_TH_FLAGS) + 1 + 4153 #ifdef INET6 4154 2 * INET6_ADDRSTRLEN; 4155 #else 4156 2 * INET_ADDRSTRLEN; 4157 #endif /* INET6 */ 4158 4159 s = malloc(size, M_TCPLOG, M_ZERO|M_NOWAIT); 4160 if (s == NULL) 4161 return (NULL); 4162 4163 strcat(s, "TCP: ["); 4164 sp = s + strlen(s); 4165 4166 if (inc && ((inc->inc_flags & INC_ISIPV6) == 0)) { 4167 inet_ntoa_r(inc->inc_faddr, sp); 4168 sp = s + strlen(s); 4169 sprintf(sp, "]:%i to [", ntohs(inc->inc_fport)); 4170 sp = s + strlen(s); 4171 inet_ntoa_r(inc->inc_laddr, sp); 4172 sp = s + strlen(s); 4173 sprintf(sp, "]:%i", ntohs(inc->inc_lport)); 4174 #ifdef INET6 4175 } else if (inc) { 4176 ip6_sprintf(sp, &inc->inc6_faddr); 4177 sp = s + strlen(s); 4178 sprintf(sp, "]:%i to [", ntohs(inc->inc_fport)); 4179 sp = s + strlen(s); 4180 ip6_sprintf(sp, &inc->inc6_laddr); 4181 sp = s + strlen(s); 4182 sprintf(sp, "]:%i", ntohs(inc->inc_lport)); 4183 } else if (ip6 && th) { 4184 ip6_sprintf(sp, &ip6->ip6_src); 4185 sp = s + strlen(s); 4186 sprintf(sp, "]:%i to [", ntohs(th->th_sport)); 4187 sp = s + strlen(s); 4188 ip6_sprintf(sp, &ip6->ip6_dst); 4189 sp = s + strlen(s); 4190 sprintf(sp, "]:%i", ntohs(th->th_dport)); 4191 #endif /* INET6 */ 4192 #ifdef INET 4193 } else if (ip && th) { 4194 inet_ntoa_r(ip->ip_src, sp); 4195 sp = s + strlen(s); 4196 sprintf(sp, "]:%i to [", ntohs(th->th_sport)); 4197 sp = s + strlen(s); 4198 inet_ntoa_r(ip->ip_dst, sp); 4199 sp = s + strlen(s); 4200 sprintf(sp, "]:%i", ntohs(th->th_dport)); 4201 #endif /* INET */ 4202 } else { 4203 free(s, M_TCPLOG); 4204 return (NULL); 4205 } 4206 sp = s + strlen(s); 4207 if (th) 4208 sprintf(sp, " tcpflags 0x%b", tcp_get_flags(th), PRINT_TH_FLAGS); 4209 if (*(s + size - 1) != '\0') 4210 panic("%s: string too long", __func__); 4211 return (s); 4212 } 4213 4214 /* 4215 * A subroutine which makes it easy to track TCP state changes with DTrace. 4216 * This function shouldn't be called for t_state initializations that don't 4217 * correspond to actual TCP state transitions. 4218 */ 4219 void 4220 tcp_state_change(struct tcpcb *tp, int newstate) 4221 { 4222 #if defined(KDTRACE_HOOKS) 4223 int pstate = tp->t_state; 4224 #endif 4225 4226 TCPSTATES_DEC(tp->t_state); 4227 TCPSTATES_INC(newstate); 4228 tp->t_state = newstate; 4229 TCP_PROBE6(state__change, NULL, tp, NULL, tp, NULL, pstate); 4230 } 4231 4232 /* 4233 * Create an external-format (``xtcpcb'') structure using the information in 4234 * the kernel-format tcpcb structure pointed to by tp. This is done to 4235 * reduce the spew of irrelevant information over this interface, to isolate 4236 * user code from changes in the kernel structure, and potentially to provide 4237 * information-hiding if we decide that some of this information should be 4238 * hidden from users. 4239 */ 4240 void 4241 tcp_inptoxtp(const struct inpcb *inp, struct xtcpcb *xt) 4242 { 4243 struct tcpcb *tp = intotcpcb(inp); 4244 sbintime_t now; 4245 4246 bzero(xt, sizeof(*xt)); 4247 xt->t_state = tp->t_state; 4248 xt->t_logstate = tcp_get_bblog_state(tp); 4249 xt->t_flags = tp->t_flags; 4250 xt->t_sndzerowin = tp->t_sndzerowin; 4251 xt->t_sndrexmitpack = tp->t_sndrexmitpack; 4252 xt->t_rcvoopack = tp->t_rcvoopack; 4253 xt->t_rcv_wnd = tp->rcv_wnd; 4254 xt->t_snd_wnd = tp->snd_wnd; 4255 xt->t_snd_cwnd = tp->snd_cwnd; 4256 xt->t_snd_ssthresh = tp->snd_ssthresh; 4257 xt->t_dsack_bytes = tp->t_dsack_bytes; 4258 xt->t_dsack_tlp_bytes = tp->t_dsack_tlp_bytes; 4259 xt->t_dsack_pack = tp->t_dsack_pack; 4260 xt->t_maxseg = tp->t_maxseg; 4261 xt->xt_ecn = (tp->t_flags2 & TF2_ECN_PERMIT) ? 1 : 0 + 4262 (tp->t_flags2 & TF2_ACE_PERMIT) ? 2 : 0; 4263 4264 now = getsbinuptime(); 4265 #define COPYTIMER(which,where) do { \ 4266 if (tp->t_timers[which] != SBT_MAX) \ 4267 xt->where = (tp->t_timers[which] - now) / SBT_1MS; \ 4268 else \ 4269 xt->where = 0; \ 4270 } while (0) 4271 COPYTIMER(TT_DELACK, tt_delack); 4272 COPYTIMER(TT_REXMT, tt_rexmt); 4273 COPYTIMER(TT_PERSIST, tt_persist); 4274 COPYTIMER(TT_KEEP, tt_keep); 4275 COPYTIMER(TT_2MSL, tt_2msl); 4276 #undef COPYTIMER 4277 xt->t_rcvtime = 1000 * (ticks - tp->t_rcvtime) / hz; 4278 4279 xt->xt_encaps_port = tp->t_port; 4280 bcopy(tp->t_fb->tfb_tcp_block_name, xt->xt_stack, 4281 TCP_FUNCTION_NAME_LEN_MAX); 4282 bcopy(CC_ALGO(tp)->name, xt->xt_cc, TCP_CA_NAME_MAX); 4283 #ifdef TCP_BLACKBOX 4284 (void)tcp_log_get_id(tp, xt->xt_logid); 4285 #endif 4286 4287 xt->xt_len = sizeof(struct xtcpcb); 4288 in_pcbtoxinpcb(inp, &xt->xt_inp); 4289 } 4290 4291 void 4292 tcp_log_end_status(struct tcpcb *tp, uint8_t status) 4293 { 4294 uint32_t bit, i; 4295 4296 if ((tp == NULL) || 4297 (status > TCP_EI_STATUS_MAX_VALUE) || 4298 (status == 0)) { 4299 /* Invalid */ 4300 return; 4301 } 4302 if (status > (sizeof(uint32_t) * 8)) { 4303 /* Should this be a KASSERT? */ 4304 return; 4305 } 4306 bit = 1U << (status - 1); 4307 if (bit & tp->t_end_info_status) { 4308 /* already logged */ 4309 return; 4310 } 4311 for (i = 0; i < TCP_END_BYTE_INFO; i++) { 4312 if (tp->t_end_info_bytes[i] == TCP_EI_EMPTY_SLOT) { 4313 tp->t_end_info_bytes[i] = status; 4314 tp->t_end_info_status |= bit; 4315 break; 4316 } 4317 } 4318 } 4319 4320 int 4321 tcp_can_enable_pacing(void) 4322 { 4323 4324 if ((tcp_pacing_limit == -1) || 4325 (tcp_pacing_limit > number_of_tcp_connections_pacing)) { 4326 atomic_fetchadd_int(&number_of_tcp_connections_pacing, 1); 4327 shadow_num_connections = number_of_tcp_connections_pacing; 4328 return (1); 4329 } else { 4330 counter_u64_add(tcp_pacing_failures, 1); 4331 return (0); 4332 } 4333 } 4334 4335 int 4336 tcp_incr_dgp_pacing_cnt(void) 4337 { 4338 if ((tcp_dgp_limit == -1) || 4339 (tcp_dgp_limit > number_of_dgp_connections)) { 4340 atomic_fetchadd_int(&number_of_dgp_connections, 1); 4341 shadow_tcp_pacing_dgp = number_of_dgp_connections; 4342 return (1); 4343 } else { 4344 counter_u64_add(tcp_dgp_failures, 1); 4345 return (0); 4346 } 4347 } 4348 4349 static uint8_t tcp_dgp_warning = 0; 4350 4351 void 4352 tcp_dec_dgp_pacing_cnt(void) 4353 { 4354 uint32_t ret; 4355 4356 ret = atomic_fetchadd_int(&number_of_dgp_connections, -1); 4357 shadow_tcp_pacing_dgp = number_of_dgp_connections; 4358 KASSERT(ret != 0, ("number_of_dgp_connections -1 would cause wrap?")); 4359 if (ret == 0) { 4360 if (tcp_dgp_limit != -1) { 4361 printf("Warning all DGP is now disabled, count decrements invalidly!\n"); 4362 tcp_dgp_limit = 0; 4363 tcp_dgp_warning = 1; 4364 } else if (tcp_dgp_warning == 0) { 4365 printf("Warning DGP pacing is invalid, invalid decrement\n"); 4366 tcp_dgp_warning = 1; 4367 } 4368 } 4369 4370 } 4371 4372 static uint8_t tcp_pacing_warning = 0; 4373 4374 void 4375 tcp_decrement_paced_conn(void) 4376 { 4377 uint32_t ret; 4378 4379 ret = atomic_fetchadd_int(&number_of_tcp_connections_pacing, -1); 4380 shadow_num_connections = number_of_tcp_connections_pacing; 4381 KASSERT(ret != 0, ("tcp_paced_connection_exits -1 would cause wrap?")); 4382 if (ret == 0) { 4383 if (tcp_pacing_limit != -1) { 4384 printf("Warning all pacing is now disabled, count decrements invalidly!\n"); 4385 tcp_pacing_limit = 0; 4386 } else if (tcp_pacing_warning == 0) { 4387 printf("Warning pacing count is invalid, invalid decrement\n"); 4388 tcp_pacing_warning = 1; 4389 } 4390 } 4391 } 4392 4393 static void 4394 tcp_default_switch_failed(struct tcpcb *tp) 4395 { 4396 /* 4397 * If a switch fails we only need to 4398 * care about two things: 4399 * a) The t_flags2 4400 * and 4401 * b) The timer granularity. 4402 * Timeouts, at least for now, don't use the 4403 * old callout system in the other stacks so 4404 * those are hopefully safe. 4405 */ 4406 tcp_lro_features_off(tp); 4407 tcp_change_time_units(tp, TCP_TMR_GRANULARITY_TICKS); 4408 } 4409 4410 #ifdef TCP_ACCOUNTING 4411 int 4412 tcp_do_ack_accounting(struct tcpcb *tp, struct tcphdr *th, struct tcpopt *to, uint32_t tiwin, int mss) 4413 { 4414 if (SEQ_LT(th->th_ack, tp->snd_una)) { 4415 /* Do we have a SACK? */ 4416 if (to->to_flags & TOF_SACK) { 4417 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) { 4418 tp->tcp_cnt_counters[ACK_SACK]++; 4419 } 4420 return (ACK_SACK); 4421 } else { 4422 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) { 4423 tp->tcp_cnt_counters[ACK_BEHIND]++; 4424 } 4425 return (ACK_BEHIND); 4426 } 4427 } else if (th->th_ack == tp->snd_una) { 4428 /* Do we have a SACK? */ 4429 if (to->to_flags & TOF_SACK) { 4430 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) { 4431 tp->tcp_cnt_counters[ACK_SACK]++; 4432 } 4433 return (ACK_SACK); 4434 } else if (tiwin != tp->snd_wnd) { 4435 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) { 4436 tp->tcp_cnt_counters[ACK_RWND]++; 4437 } 4438 return (ACK_RWND); 4439 } else { 4440 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) { 4441 tp->tcp_cnt_counters[ACK_DUPACK]++; 4442 } 4443 return (ACK_DUPACK); 4444 } 4445 } else { 4446 if (!SEQ_GT(th->th_ack, tp->snd_max)) { 4447 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) { 4448 tp->tcp_cnt_counters[CNT_OF_ACKS_IN] += (((th->th_ack - tp->snd_una) + mss - 1)/mss); 4449 } 4450 } 4451 if (to->to_flags & TOF_SACK) { 4452 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) { 4453 tp->tcp_cnt_counters[ACK_CUMACK_SACK]++; 4454 } 4455 return (ACK_CUMACK_SACK); 4456 } else { 4457 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) { 4458 tp->tcp_cnt_counters[ACK_CUMACK]++; 4459 } 4460 return (ACK_CUMACK); 4461 } 4462 } 4463 } 4464 #endif 4465 4466 void 4467 tcp_change_time_units(struct tcpcb *tp, int granularity) 4468 { 4469 if (tp->t_tmr_granularity == granularity) { 4470 /* We are there */ 4471 return; 4472 } 4473 if (granularity == TCP_TMR_GRANULARITY_USEC) { 4474 KASSERT((tp->t_tmr_granularity == TCP_TMR_GRANULARITY_TICKS), 4475 ("Granularity is not TICKS its %u in tp:%p", 4476 tp->t_tmr_granularity, tp)); 4477 tp->t_rttlow = TICKS_2_USEC(tp->t_rttlow); 4478 if (tp->t_srtt > 1) { 4479 uint32_t val, frac; 4480 4481 val = tp->t_srtt >> TCP_RTT_SHIFT; 4482 frac = tp->t_srtt & 0x1f; 4483 tp->t_srtt = TICKS_2_USEC(val); 4484 /* 4485 * frac is the fractional part of the srtt (if any) 4486 * but its in ticks and every bit represents 4487 * 1/32nd of a hz. 4488 */ 4489 if (frac) { 4490 if (hz == 1000) { 4491 frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_MSEC) / (uint64_t)TCP_RTT_SCALE); 4492 } else { 4493 frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_SEC) / ((uint64_t)(hz) * (uint64_t)TCP_RTT_SCALE)); 4494 } 4495 tp->t_srtt += frac; 4496 } 4497 } 4498 if (tp->t_rttvar) { 4499 uint32_t val, frac; 4500 4501 val = tp->t_rttvar >> TCP_RTTVAR_SHIFT; 4502 frac = tp->t_rttvar & 0x1f; 4503 tp->t_rttvar = TICKS_2_USEC(val); 4504 /* 4505 * frac is the fractional part of the srtt (if any) 4506 * but its in ticks and every bit represents 4507 * 1/32nd of a hz. 4508 */ 4509 if (frac) { 4510 if (hz == 1000) { 4511 frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_MSEC) / (uint64_t)TCP_RTT_SCALE); 4512 } else { 4513 frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_SEC) / ((uint64_t)(hz) * (uint64_t)TCP_RTT_SCALE)); 4514 } 4515 tp->t_rttvar += frac; 4516 } 4517 } 4518 tp->t_tmr_granularity = TCP_TMR_GRANULARITY_USEC; 4519 } else if (granularity == TCP_TMR_GRANULARITY_TICKS) { 4520 /* Convert back to ticks, with */ 4521 KASSERT((tp->t_tmr_granularity == TCP_TMR_GRANULARITY_USEC), 4522 ("Granularity is not USEC its %u in tp:%p", 4523 tp->t_tmr_granularity, tp)); 4524 if (tp->t_srtt > 1) { 4525 uint32_t val, frac; 4526 4527 val = USEC_2_TICKS(tp->t_srtt); 4528 frac = tp->t_srtt % (HPTS_USEC_IN_SEC / hz); 4529 tp->t_srtt = val << TCP_RTT_SHIFT; 4530 /* 4531 * frac is the fractional part here is left 4532 * over from converting to hz and shifting. 4533 * We need to convert this to the 5 bit 4534 * remainder. 4535 */ 4536 if (frac) { 4537 if (hz == 1000) { 4538 frac = (((uint64_t)frac * (uint64_t)TCP_RTT_SCALE) / (uint64_t)HPTS_USEC_IN_MSEC); 4539 } else { 4540 frac = (((uint64_t)frac * (uint64_t)(hz) * (uint64_t)TCP_RTT_SCALE) /(uint64_t)HPTS_USEC_IN_SEC); 4541 } 4542 tp->t_srtt += frac; 4543 } 4544 } 4545 if (tp->t_rttvar) { 4546 uint32_t val, frac; 4547 4548 val = USEC_2_TICKS(tp->t_rttvar); 4549 frac = tp->t_rttvar % (HPTS_USEC_IN_SEC / hz); 4550 tp->t_rttvar = val << TCP_RTTVAR_SHIFT; 4551 /* 4552 * frac is the fractional part here is left 4553 * over from converting to hz and shifting. 4554 * We need to convert this to the 4 bit 4555 * remainder. 4556 */ 4557 if (frac) { 4558 if (hz == 1000) { 4559 frac = (((uint64_t)frac * (uint64_t)TCP_RTTVAR_SCALE) / (uint64_t)HPTS_USEC_IN_MSEC); 4560 } else { 4561 frac = (((uint64_t)frac * (uint64_t)(hz) * (uint64_t)TCP_RTTVAR_SCALE) /(uint64_t)HPTS_USEC_IN_SEC); 4562 } 4563 tp->t_rttvar += frac; 4564 } 4565 } 4566 tp->t_rttlow = USEC_2_TICKS(tp->t_rttlow); 4567 tp->t_tmr_granularity = TCP_TMR_GRANULARITY_TICKS; 4568 } 4569 #ifdef INVARIANTS 4570 else { 4571 panic("Unknown granularity:%d tp:%p", 4572 granularity, tp); 4573 } 4574 #endif 4575 } 4576 4577 void 4578 tcp_handle_orphaned_packets(struct tcpcb *tp) 4579 { 4580 struct mbuf *save, *m, *prev; 4581 /* 4582 * Called when a stack switch is occuring from the fini() 4583 * of the old stack. We assue the init() as already been 4584 * run of the new stack and it has set the t_flags2 to 4585 * what it supports. This function will then deal with any 4586 * differences i.e. cleanup packets that maybe queued that 4587 * the newstack does not support. 4588 */ 4589 4590 if (tp->t_flags2 & TF2_MBUF_L_ACKS) 4591 return; 4592 if ((tp->t_flags2 & TF2_SUPPORTS_MBUFQ) == 0 && 4593 !STAILQ_EMPTY(&tp->t_inqueue)) { 4594 /* 4595 * It is unsafe to process the packets since a 4596 * reset may be lurking in them (its rare but it 4597 * can occur). If we were to find a RST, then we 4598 * would end up dropping the connection and the 4599 * INP lock, so when we return the caller (tcp_usrreq) 4600 * will blow up when it trys to unlock the inp. 4601 * This new stack does not do any fancy LRO features 4602 * so all we can do is toss the packets. 4603 */ 4604 m = STAILQ_FIRST(&tp->t_inqueue); 4605 STAILQ_INIT(&tp->t_inqueue); 4606 STAILQ_FOREACH_FROM_SAFE(m, &tp->t_inqueue, m_stailqpkt, save) 4607 m_freem(m); 4608 } else { 4609 /* 4610 * Here we have a stack that does mbuf queuing but 4611 * does not support compressed ack's. We must 4612 * walk all the mbufs and discard any compressed acks. 4613 */ 4614 STAILQ_FOREACH_SAFE(m, &tp->t_inqueue, m_stailqpkt, save) { 4615 if (m->m_flags & M_ACKCMP) { 4616 if (m == STAILQ_FIRST(&tp->t_inqueue)) 4617 STAILQ_REMOVE_HEAD(&tp->t_inqueue, 4618 m_stailqpkt); 4619 else 4620 STAILQ_REMOVE_AFTER(&tp->t_inqueue, 4621 prev, m_stailqpkt); 4622 m_freem(m); 4623 } else 4624 prev = m; 4625 } 4626 } 4627 } 4628 4629 #ifdef TCP_REQUEST_TRK 4630 uint32_t 4631 tcp_estimate_tls_overhead(struct socket *so, uint64_t tls_usr_bytes) 4632 { 4633 #ifdef KERN_TLS 4634 struct ktls_session *tls; 4635 uint32_t rec_oh, records; 4636 4637 tls = so->so_snd.sb_tls_info; 4638 if (tls == NULL) 4639 return (0); 4640 4641 rec_oh = tls->params.tls_hlen + tls->params.tls_tlen; 4642 records = ((tls_usr_bytes + tls->params.max_frame_len - 1)/tls->params.max_frame_len); 4643 return (records * rec_oh); 4644 #else 4645 return (0); 4646 #endif 4647 } 4648 4649 extern uint32_t tcp_stale_entry_time; 4650 uint32_t tcp_stale_entry_time = 250000; 4651 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, usrlog_stale, CTLFLAG_RW, 4652 &tcp_stale_entry_time, 250000, "Time that a tcpreq entry without a sendfile ages out"); 4653 4654 void 4655 tcp_req_log_req_info(struct tcpcb *tp, struct tcp_sendfile_track *req, 4656 uint16_t slot, uint8_t val, uint64_t offset, uint64_t nbytes) 4657 { 4658 if (tcp_bblogging_on(tp)) { 4659 union tcp_log_stackspecific log; 4660 struct timeval tv; 4661 4662 memset(&log, 0, sizeof(log)); 4663 log.u_bbr.inhpts = tcp_in_hpts(tp); 4664 log.u_bbr.flex8 = val; 4665 log.u_bbr.rttProp = req->timestamp; 4666 log.u_bbr.delRate = req->start; 4667 log.u_bbr.cur_del_rate = req->end; 4668 log.u_bbr.flex1 = req->start_seq; 4669 log.u_bbr.flex2 = req->end_seq; 4670 log.u_bbr.flex3 = req->flags; 4671 log.u_bbr.flex4 = ((req->localtime >> 32) & 0x00000000ffffffff); 4672 log.u_bbr.flex5 = (req->localtime & 0x00000000ffffffff); 4673 log.u_bbr.flex7 = slot; 4674 log.u_bbr.bw_inuse = offset; 4675 /* nbytes = flex6 | epoch */ 4676 log.u_bbr.flex6 = ((nbytes >> 32) & 0x00000000ffffffff); 4677 log.u_bbr.epoch = (nbytes & 0x00000000ffffffff); 4678 /* cspr = lt_epoch | pkts_out */ 4679 log.u_bbr.lt_epoch = ((req->cspr >> 32) & 0x00000000ffffffff); 4680 log.u_bbr.pkts_out |= (req->cspr & 0x00000000ffffffff); 4681 log.u_bbr.applimited = tp->t_tcpreq_closed; 4682 log.u_bbr.applimited <<= 8; 4683 log.u_bbr.applimited |= tp->t_tcpreq_open; 4684 log.u_bbr.applimited <<= 8; 4685 log.u_bbr.applimited |= tp->t_tcpreq_req; 4686 log.u_bbr.timeStamp = tcp_get_usecs(&tv); 4687 TCP_LOG_EVENTP(tp, NULL, 4688 &tptosocket(tp)->so_rcv, 4689 &tptosocket(tp)->so_snd, 4690 TCP_LOG_REQ_T, 0, 4691 0, &log, false, &tv); 4692 } 4693 } 4694 4695 void 4696 tcp_req_free_a_slot(struct tcpcb *tp, struct tcp_sendfile_track *ent) 4697 { 4698 if (tp->t_tcpreq_req > 0) 4699 tp->t_tcpreq_req--; 4700 if (ent->flags & TCP_TRK_TRACK_FLG_OPEN) { 4701 if (tp->t_tcpreq_open > 0) 4702 tp->t_tcpreq_open--; 4703 } else { 4704 if (tp->t_tcpreq_closed > 0) 4705 tp->t_tcpreq_closed--; 4706 } 4707 ent->flags = TCP_TRK_TRACK_FLG_EMPTY; 4708 } 4709 4710 static void 4711 tcp_req_check_for_stale_entries(struct tcpcb *tp, uint64_t ts, int rm_oldest) 4712 { 4713 struct tcp_sendfile_track *ent; 4714 uint64_t time_delta, oldest_delta; 4715 int i, oldest, oldest_set = 0, cnt_rm = 0; 4716 4717 for (i = 0; i < MAX_TCP_TRK_REQ; i++) { 4718 ent = &tp->t_tcpreq_info[i]; 4719 if (ent->flags != TCP_TRK_TRACK_FLG_USED) { 4720 /* 4721 * We only care about closed end ranges 4722 * that are allocated and have no sendfile 4723 * ever touching them. They would be in 4724 * state USED. 4725 */ 4726 continue; 4727 } 4728 if (ts >= ent->localtime) 4729 time_delta = ts - ent->localtime; 4730 else 4731 time_delta = 0; 4732 if (time_delta && 4733 ((oldest_delta < time_delta) || (oldest_set == 0))) { 4734 oldest_set = 1; 4735 oldest = i; 4736 oldest_delta = time_delta; 4737 } 4738 if (tcp_stale_entry_time && (time_delta >= tcp_stale_entry_time)) { 4739 /* 4740 * No sendfile in a our time-limit 4741 * time to purge it. 4742 */ 4743 cnt_rm++; 4744 tcp_req_log_req_info(tp, &tp->t_tcpreq_info[i], i, TCP_TRK_REQ_LOG_STALE, 4745 time_delta, 0); 4746 tcp_req_free_a_slot(tp, ent); 4747 } 4748 } 4749 if ((cnt_rm == 0) && rm_oldest && oldest_set) { 4750 ent = &tp->t_tcpreq_info[oldest]; 4751 tcp_req_log_req_info(tp, &tp->t_tcpreq_info[i], i, TCP_TRK_REQ_LOG_STALE, 4752 oldest_delta, 1); 4753 tcp_req_free_a_slot(tp, ent); 4754 } 4755 } 4756 4757 int 4758 tcp_req_check_for_comp(struct tcpcb *tp, tcp_seq ack_point) 4759 { 4760 int i, ret = 0; 4761 struct tcp_sendfile_track *ent; 4762 4763 /* Clean up any old closed end requests that are now completed */ 4764 if (tp->t_tcpreq_req == 0) 4765 return (0); 4766 if (tp->t_tcpreq_closed == 0) 4767 return (0); 4768 for (i = 0; i < MAX_TCP_TRK_REQ; i++) { 4769 ent = &tp->t_tcpreq_info[i]; 4770 /* Skip empty ones */ 4771 if (ent->flags == TCP_TRK_TRACK_FLG_EMPTY) 4772 continue; 4773 /* Skip open ones */ 4774 if (ent->flags & TCP_TRK_TRACK_FLG_OPEN) 4775 continue; 4776 if (SEQ_GEQ(ack_point, ent->end_seq)) { 4777 /* We are past it -- free it */ 4778 tcp_req_log_req_info(tp, ent, 4779 i, TCP_TRK_REQ_LOG_FREED, 0, 0); 4780 tcp_req_free_a_slot(tp, ent); 4781 ret++; 4782 } 4783 } 4784 return (ret); 4785 } 4786 4787 int 4788 tcp_req_is_entry_comp(struct tcpcb *tp, struct tcp_sendfile_track *ent, tcp_seq ack_point) 4789 { 4790 if (tp->t_tcpreq_req == 0) 4791 return (-1); 4792 if (tp->t_tcpreq_closed == 0) 4793 return (-1); 4794 if (ent->flags == TCP_TRK_TRACK_FLG_EMPTY) 4795 return (-1); 4796 if (SEQ_GEQ(ack_point, ent->end_seq)) { 4797 return (1); 4798 } 4799 return (0); 4800 } 4801 4802 struct tcp_sendfile_track * 4803 tcp_req_find_a_req_that_is_completed_by(struct tcpcb *tp, tcp_seq th_ack, int *ip) 4804 { 4805 /* 4806 * Given an ack point (th_ack) walk through our entries and 4807 * return the first one found that th_ack goes past the 4808 * end_seq. 4809 */ 4810 struct tcp_sendfile_track *ent; 4811 int i; 4812 4813 if (tp->t_tcpreq_req == 0) { 4814 /* none open */ 4815 return (NULL); 4816 } 4817 for (i = 0; i < MAX_TCP_TRK_REQ; i++) { 4818 ent = &tp->t_tcpreq_info[i]; 4819 if (ent->flags == TCP_TRK_TRACK_FLG_EMPTY) 4820 continue; 4821 if ((ent->flags & TCP_TRK_TRACK_FLG_OPEN) == 0) { 4822 if (SEQ_GEQ(th_ack, ent->end_seq)) { 4823 *ip = i; 4824 return (ent); 4825 } 4826 } 4827 } 4828 return (NULL); 4829 } 4830 4831 struct tcp_sendfile_track * 4832 tcp_req_find_req_for_seq(struct tcpcb *tp, tcp_seq seq) 4833 { 4834 struct tcp_sendfile_track *ent; 4835 int i; 4836 4837 if (tp->t_tcpreq_req == 0) { 4838 /* none open */ 4839 return (NULL); 4840 } 4841 for (i = 0; i < MAX_TCP_TRK_REQ; i++) { 4842 ent = &tp->t_tcpreq_info[i]; 4843 tcp_req_log_req_info(tp, ent, i, TCP_TRK_REQ_LOG_SEARCH, 4844 (uint64_t)seq, 0); 4845 if (ent->flags == TCP_TRK_TRACK_FLG_EMPTY) { 4846 continue; 4847 } 4848 if (ent->flags & TCP_TRK_TRACK_FLG_OPEN) { 4849 /* 4850 * An open end request only needs to 4851 * match the beginning seq or be 4852 * all we have (once we keep going on 4853 * a open end request we may have a seq 4854 * wrap). 4855 */ 4856 if ((SEQ_GEQ(seq, ent->start_seq)) || 4857 (tp->t_tcpreq_closed == 0)) 4858 return (ent); 4859 } else { 4860 /* 4861 * For this one we need to 4862 * be a bit more careful if its 4863 * completed at least. 4864 */ 4865 if ((SEQ_GEQ(seq, ent->start_seq)) && 4866 (SEQ_LT(seq, ent->end_seq))) { 4867 return (ent); 4868 } 4869 } 4870 } 4871 return (NULL); 4872 } 4873 4874 /* Should this be in its own file tcp_req.c ? */ 4875 struct tcp_sendfile_track * 4876 tcp_req_alloc_req_full(struct tcpcb *tp, struct tcp_snd_req *req, uint64_t ts, int rec_dups) 4877 { 4878 struct tcp_sendfile_track *fil; 4879 int i, allocated; 4880 4881 /* In case the stack does not check for completions do so now */ 4882 tcp_req_check_for_comp(tp, tp->snd_una); 4883 /* Check for stale entries */ 4884 if (tp->t_tcpreq_req) 4885 tcp_req_check_for_stale_entries(tp, ts, 4886 (tp->t_tcpreq_req >= MAX_TCP_TRK_REQ)); 4887 /* Check to see if this is a duplicate of one not started */ 4888 if (tp->t_tcpreq_req) { 4889 for (i = 0, allocated = 0; i < MAX_TCP_TRK_REQ; i++) { 4890 fil = &tp->t_tcpreq_info[i]; 4891 if ((fil->flags & TCP_TRK_TRACK_FLG_USED) == 0) 4892 continue; 4893 if ((fil->timestamp == req->timestamp) && 4894 (fil->start == req->start) && 4895 ((fil->flags & TCP_TRK_TRACK_FLG_OPEN) || 4896 (fil->end == req->end))) { 4897 /* 4898 * We already have this request 4899 * and it has not been started with sendfile. 4900 * This probably means the user was returned 4901 * a 4xx of some sort and its going to age 4902 * out, lets not duplicate it. 4903 */ 4904 return (fil); 4905 } 4906 } 4907 } 4908 /* Ok if there is no room at the inn we are in trouble */ 4909 if (tp->t_tcpreq_req >= MAX_TCP_TRK_REQ) { 4910 tcp_trace_point(tp, TCP_TP_REQ_LOG_FAIL); 4911 for (i = 0; i < MAX_TCP_TRK_REQ; i++) { 4912 tcp_req_log_req_info(tp, &tp->t_tcpreq_info[i], 4913 i, TCP_TRK_REQ_LOG_ALLOCFAIL, 0, 0); 4914 } 4915 return (NULL); 4916 } 4917 for (i = 0, allocated = 0; i < MAX_TCP_TRK_REQ; i++) { 4918 fil = &tp->t_tcpreq_info[i]; 4919 if (fil->flags == TCP_TRK_TRACK_FLG_EMPTY) { 4920 allocated = 1; 4921 fil->flags = TCP_TRK_TRACK_FLG_USED; 4922 fil->timestamp = req->timestamp; 4923 fil->playout_ms = req->playout_ms; 4924 fil->localtime = ts; 4925 fil->start = req->start; 4926 if (req->flags & TCP_LOG_HTTPD_RANGE_END) { 4927 fil->end = req->end; 4928 } else { 4929 fil->end = 0; 4930 fil->flags |= TCP_TRK_TRACK_FLG_OPEN; 4931 } 4932 /* 4933 * We can set the min boundaries to the TCP Sequence space, 4934 * but it might be found to be further up when sendfile 4935 * actually runs on this range (if it ever does). 4936 */ 4937 fil->sbcc_at_s = tptosocket(tp)->so_snd.sb_ccc; 4938 fil->start_seq = tp->snd_una + 4939 tptosocket(tp)->so_snd.sb_ccc; 4940 if (req->flags & TCP_LOG_HTTPD_RANGE_END) 4941 fil->end_seq = (fil->start_seq + ((uint32_t)(fil->end - fil->start))); 4942 else 4943 fil->end_seq = 0; 4944 if (tptosocket(tp)->so_snd.sb_tls_info) { 4945 /* 4946 * This session is doing TLS. Take a swag guess 4947 * at the overhead. 4948 */ 4949 fil->end_seq += tcp_estimate_tls_overhead( 4950 tptosocket(tp), (fil->end - fil->start)); 4951 } 4952 tp->t_tcpreq_req++; 4953 if (fil->flags & TCP_TRK_TRACK_FLG_OPEN) 4954 tp->t_tcpreq_open++; 4955 else 4956 tp->t_tcpreq_closed++; 4957 tcp_req_log_req_info(tp, fil, i, 4958 TCP_TRK_REQ_LOG_NEW, 0, 0); 4959 break; 4960 } else 4961 fil = NULL; 4962 } 4963 return (fil); 4964 } 4965 4966 void 4967 tcp_req_alloc_req(struct tcpcb *tp, union tcp_log_userdata *user, uint64_t ts) 4968 { 4969 (void)tcp_req_alloc_req_full(tp, &user->tcp_req, ts, 1); 4970 } 4971 #endif 4972 4973 void 4974 tcp_log_socket_option(struct tcpcb *tp, uint32_t option_num, uint32_t option_val, int err) 4975 { 4976 if (tcp_bblogging_on(tp)) { 4977 struct tcp_log_buffer *l; 4978 4979 l = tcp_log_event(tp, NULL, 4980 &tptosocket(tp)->so_rcv, 4981 &tptosocket(tp)->so_snd, 4982 TCP_LOG_SOCKET_OPT, 4983 err, 0, NULL, 1, 4984 NULL, NULL, 0, NULL); 4985 if (l) { 4986 l->tlb_flex1 = option_num; 4987 l->tlb_flex2 = option_val; 4988 } 4989 } 4990 } 4991 4992 uint32_t 4993 tcp_get_srtt(struct tcpcb *tp, int granularity) 4994 { 4995 uint32_t srtt; 4996 4997 KASSERT(granularity == TCP_TMR_GRANULARITY_USEC || 4998 granularity == TCP_TMR_GRANULARITY_TICKS, 4999 ("%s: called with unexpected granularity %d", __func__, 5000 granularity)); 5001 5002 srtt = tp->t_srtt; 5003 5004 /* 5005 * We only support two granularities. If the stored granularity 5006 * does not match the granularity requested by the caller, 5007 * convert the stored value to the requested unit of granularity. 5008 */ 5009 if (tp->t_tmr_granularity != granularity) { 5010 if (granularity == TCP_TMR_GRANULARITY_USEC) 5011 srtt = TICKS_2_USEC(srtt); 5012 else 5013 srtt = USEC_2_TICKS(srtt); 5014 } 5015 5016 /* 5017 * If the srtt is stored with ticks granularity, we need to 5018 * unshift to get the actual value. We do this after the 5019 * conversion above (if one was necessary) in order to maximize 5020 * precision. 5021 */ 5022 if (tp->t_tmr_granularity == TCP_TMR_GRANULARITY_TICKS) 5023 srtt = srtt >> TCP_RTT_SHIFT; 5024 5025 return (srtt); 5026 } 5027 5028 void 5029 tcp_account_for_send(struct tcpcb *tp, uint32_t len, uint8_t is_rxt, 5030 uint8_t is_tlp, bool hw_tls) 5031 { 5032 5033 if (is_tlp) { 5034 tp->t_sndtlppack++; 5035 tp->t_sndtlpbyte += len; 5036 } 5037 /* To get total bytes sent you must add t_snd_rxt_bytes to t_sndbytes */ 5038 if (is_rxt) 5039 tp->t_snd_rxt_bytes += len; 5040 else 5041 tp->t_sndbytes += len; 5042 5043 #ifdef KERN_TLS 5044 if (hw_tls && is_rxt && len != 0) { 5045 uint64_t rexmit_percent; 5046 5047 rexmit_percent = (1000ULL * tp->t_snd_rxt_bytes) / 5048 (10ULL * (tp->t_snd_rxt_bytes + tp->t_sndbytes)); 5049 if (rexmit_percent > ktls_ifnet_max_rexmit_pct) 5050 ktls_disable_ifnet(tp); 5051 } 5052 #endif 5053 } 5054