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