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