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