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