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 * @(#)tcp_subr.c 8.2 (Berkeley) 5/24/95
32 */
33
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36
37 #include "opt_inet.h"
38 #include "opt_inet6.h"
39 #include "opt_ipsec.h"
40 #include "opt_tcpdebug.h"
41
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/callout.h>
45 #include <sys/eventhandler.h>
46 #ifdef TCP_HHOOK
47 #include <sys/hhook.h>
48 #endif
49 #include <sys/kernel.h>
50 #ifdef TCP_HHOOK
51 #include <sys/khelp.h>
52 #endif
53 #include <sys/sysctl.h>
54 #include <sys/jail.h>
55 #include <sys/malloc.h>
56 #include <sys/refcount.h>
57 #include <sys/mbuf.h>
58 #ifdef INET6
59 #include <sys/domain.h>
60 #endif
61 #include <sys/priv.h>
62 #include <sys/proc.h>
63 #include <sys/sdt.h>
64 #include <sys/socket.h>
65 #include <sys/socketvar.h>
66 #include <sys/protosw.h>
67 #include <sys/random.h>
68
69 #include <vm/uma.h>
70
71 #include <net/route.h>
72 #include <net/if.h>
73 #include <net/if_var.h>
74 #include <net/vnet.h>
75
76 #include <netinet/in.h>
77 #include <netinet/in_fib.h>
78 #include <netinet/in_kdtrace.h>
79 #include <netinet/in_pcb.h>
80 #include <netinet/in_systm.h>
81 #include <netinet/in_var.h>
82 #include <netinet/ip.h>
83 #include <netinet/ip_icmp.h>
84 #include <netinet/ip_var.h>
85 #ifdef INET6
86 #include <netinet/icmp6.h>
87 #include <netinet/ip6.h>
88 #include <netinet6/in6_fib.h>
89 #include <netinet6/in6_pcb.h>
90 #include <netinet6/ip6_var.h>
91 #include <netinet6/scope6_var.h>
92 #include <netinet6/nd6.h>
93 #endif
94
95 #include <netinet/tcp.h>
96 #include <netinet/tcp_fsm.h>
97 #include <netinet/tcp_seq.h>
98 #include <netinet/tcp_timer.h>
99 #include <netinet/tcp_var.h>
100 #include <netinet/tcp_log_buf.h>
101 #include <netinet/tcp_syncache.h>
102 #include <netinet/tcp_hpts.h>
103 #include <netinet/cc/cc.h>
104 #ifdef INET6
105 #include <netinet6/tcp6_var.h>
106 #endif
107 #include <netinet/tcpip.h>
108 #include <netinet/tcp_fastopen.h>
109 #ifdef TCPPCAP
110 #include <netinet/tcp_pcap.h>
111 #endif
112 #ifdef TCPDEBUG
113 #include <netinet/tcp_debug.h>
114 #endif
115 #ifdef INET6
116 #include <netinet6/ip6protosw.h>
117 #endif
118 #ifdef TCP_OFFLOAD
119 #include <netinet/tcp_offload.h>
120 #endif
121
122 #include <netipsec/ipsec_support.h>
123
124 #include <machine/in_cksum.h>
125 #include <sys/md5.h>
126
127 #include <security/mac/mac_framework.h>
128
129 VNET_DEFINE(int, tcp_mssdflt) = TCP_MSS;
130 #ifdef INET6
131 VNET_DEFINE(int, tcp_v6mssdflt) = TCP6_MSS;
132 #endif
133
134 struct rwlock tcp_function_lock;
135
136 static int
137 sysctl_net_inet_tcp_mss_check(SYSCTL_HANDLER_ARGS)
138 {
139 int error, new;
140
141 new = V_tcp_mssdflt;
142 error = sysctl_handle_int(oidp, &new, 0, req);
143 if (error == 0 && req->newptr) {
144 if (new < TCP_MINMSS)
145 error = EINVAL;
146 else
147 V_tcp_mssdflt = new;
148 }
149 return (error);
150 }
151
152 SYSCTL_PROC(_net_inet_tcp, TCPCTL_MSSDFLT, mssdflt,
153 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW, &VNET_NAME(tcp_mssdflt), 0,
154 &sysctl_net_inet_tcp_mss_check, "I",
155 "Default TCP Maximum Segment Size");
156
157 #ifdef INET6
158 static int
159 sysctl_net_inet_tcp_mss_v6_check(SYSCTL_HANDLER_ARGS)
160 {
161 int error, new;
162
163 new = V_tcp_v6mssdflt;
164 error = sysctl_handle_int(oidp, &new, 0, req);
165 if (error == 0 && req->newptr) {
166 if (new < TCP_MINMSS)
167 error = EINVAL;
168 else
169 V_tcp_v6mssdflt = new;
170 }
171 return (error);
172 }
173
174 SYSCTL_PROC(_net_inet_tcp, TCPCTL_V6MSSDFLT, v6mssdflt,
175 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW, &VNET_NAME(tcp_v6mssdflt), 0,
176 &sysctl_net_inet_tcp_mss_v6_check, "I",
177 "Default TCP Maximum Segment Size for IPv6");
178 #endif /* INET6 */
179
180 /*
181 * Minimum MSS we accept and use. This prevents DoS attacks where
182 * we are forced to a ridiculous low MSS like 20 and send hundreds
183 * of packets instead of one. The effect scales with the available
184 * bandwidth and quickly saturates the CPU and network interface
185 * with packet generation and sending. Set to zero to disable MINMSS
186 * checking. This setting prevents us from sending too small packets.
187 */
188 VNET_DEFINE(int, tcp_minmss) = TCP_MINMSS;
189 SYSCTL_INT(_net_inet_tcp, OID_AUTO, minmss, CTLFLAG_VNET | CTLFLAG_RW,
190 &VNET_NAME(tcp_minmss), 0,
191 "Minimum TCP Maximum Segment Size");
192
193 VNET_DEFINE(int, tcp_do_rfc1323) = 1;
194 SYSCTL_INT(_net_inet_tcp, TCPCTL_DO_RFC1323, rfc1323, CTLFLAG_VNET | CTLFLAG_RW,
195 &VNET_NAME(tcp_do_rfc1323), 0,
196 "Enable rfc1323 (high performance TCP) extensions");
197
198 /*
199 * As of June 2021, several TCP stacks violate RFC 7323 from September 2014.
200 * Some stacks negotiate TS, but never send them after connection setup. Some
201 * stacks negotiate TS, but don't send them when sending keep-alive segments.
202 * These include modern widely deployed TCP stacks.
203 * Therefore tolerating violations for now...
204 */
205 VNET_DEFINE(int, tcp_tolerate_missing_ts) = 1;
206 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tolerate_missing_ts, CTLFLAG_VNET | CTLFLAG_RW,
207 &VNET_NAME(tcp_tolerate_missing_ts), 0,
208 "Tolerate missing TCP timestamps");
209
210 VNET_DEFINE(int, tcp_ts_offset_per_conn) = 1;
211 SYSCTL_INT(_net_inet_tcp, OID_AUTO, ts_offset_per_conn, CTLFLAG_VNET | CTLFLAG_RW,
212 &VNET_NAME(tcp_ts_offset_per_conn), 0,
213 "Initialize TCP timestamps per connection instead of per host pair");
214
215 static int tcp_log_debug = 0;
216 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_debug, CTLFLAG_RW,
217 &tcp_log_debug, 0, "Log errors caused by incoming TCP segments");
218
219 static int tcp_tcbhashsize;
220 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tcbhashsize, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
221 &tcp_tcbhashsize, 0, "Size of TCP control-block hashtable");
222
223 static int do_tcpdrain = 1;
224 SYSCTL_INT(_net_inet_tcp, OID_AUTO, do_tcpdrain, CTLFLAG_RW, &do_tcpdrain, 0,
225 "Enable tcp_drain routine for extra help when low on mbufs");
226
227 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, pcbcount, CTLFLAG_VNET | CTLFLAG_RD,
228 &VNET_NAME(tcbinfo.ipi_count), 0, "Number of active PCBs");
229
230 VNET_DEFINE_STATIC(int, icmp_may_rst) = 1;
231 #define V_icmp_may_rst VNET(icmp_may_rst)
232 SYSCTL_INT(_net_inet_tcp, OID_AUTO, icmp_may_rst, CTLFLAG_VNET | CTLFLAG_RW,
233 &VNET_NAME(icmp_may_rst), 0,
234 "Certain ICMP unreachable messages may abort connections in SYN_SENT");
235
236 VNET_DEFINE_STATIC(int, tcp_isn_reseed_interval) = 0;
237 #define V_tcp_isn_reseed_interval VNET(tcp_isn_reseed_interval)
238 SYSCTL_INT(_net_inet_tcp, OID_AUTO, isn_reseed_interval, CTLFLAG_VNET | CTLFLAG_RW,
239 &VNET_NAME(tcp_isn_reseed_interval), 0,
240 "Seconds between reseeding of ISN secret");
241
242 static int tcp_soreceive_stream;
243 SYSCTL_INT(_net_inet_tcp, OID_AUTO, soreceive_stream, CTLFLAG_RDTUN,
244 &tcp_soreceive_stream, 0, "Using soreceive_stream for TCP sockets");
245
246 VNET_DEFINE(uma_zone_t, sack_hole_zone);
247 #define V_sack_hole_zone VNET(sack_hole_zone)
248
249 #ifdef TCP_HHOOK
250 VNET_DEFINE(struct hhook_head *, tcp_hhh[HHOOK_TCP_LAST+1]);
251 #endif
252
253 #define TS_OFFSET_SECRET_LENGTH 32
254 VNET_DEFINE_STATIC(u_char, ts_offset_secret[TS_OFFSET_SECRET_LENGTH]);
255 #define V_ts_offset_secret VNET(ts_offset_secret)
256
257 static int tcp_default_fb_init(struct tcpcb *tp);
258 static void tcp_default_fb_fini(struct tcpcb *tp, int tcb_is_purged);
259 static int tcp_default_handoff_ok(struct tcpcb *tp);
260 static struct inpcb *tcp_notify(struct inpcb *, int);
261 static struct inpcb *tcp_mtudisc_notify(struct inpcb *, int);
262 static void tcp_mtudisc(struct inpcb *, int);
263 static char * tcp_log_addr(struct in_conninfo *inc, struct tcphdr *th,
264 void *ip4hdr, const void *ip6hdr);
265
266
267 static struct tcp_function_block tcp_def_funcblk = {
268 .tfb_tcp_block_name = "freebsd",
269 .tfb_tcp_output = tcp_output,
270 .tfb_tcp_do_segment = tcp_do_segment,
271 .tfb_tcp_ctloutput = tcp_default_ctloutput,
272 .tfb_tcp_handoff_ok = tcp_default_handoff_ok,
273 .tfb_tcp_fb_init = tcp_default_fb_init,
274 .tfb_tcp_fb_fini = tcp_default_fb_fini,
275 };
276
277 int t_functions_inited = 0;
278 static int tcp_fb_cnt = 0;
279 struct tcp_funchead t_functions;
280 static struct tcp_function_block *tcp_func_set_ptr = &tcp_def_funcblk;
281
282 static void
283 init_tcp_functions(void)
284 {
285 if (t_functions_inited == 0) {
286 TAILQ_INIT(&t_functions);
287 rw_init_flags(&tcp_function_lock, "tcp_func_lock" , 0);
288 t_functions_inited = 1;
289 }
290 }
291
292 static struct tcp_function_block *
293 find_tcp_functions_locked(struct tcp_function_set *fs)
294 {
295 struct tcp_function *f;
296 struct tcp_function_block *blk=NULL;
297
298 TAILQ_FOREACH(f, &t_functions, tf_next) {
299 if (strcmp(f->tf_name, fs->function_set_name) == 0) {
300 blk = f->tf_fb;
301 break;
302 }
303 }
304 return(blk);
305 }
306
307 static struct tcp_function_block *
308 find_tcp_fb_locked(struct tcp_function_block *blk, struct tcp_function **s)
309 {
310 struct tcp_function_block *rblk=NULL;
311 struct tcp_function *f;
312
313 TAILQ_FOREACH(f, &t_functions, tf_next) {
314 if (f->tf_fb == blk) {
315 rblk = blk;
316 if (s) {
317 *s = f;
318 }
319 break;
320 }
321 }
322 return (rblk);
323 }
324
325 struct tcp_function_block *
326 find_and_ref_tcp_functions(struct tcp_function_set *fs)
327 {
328 struct tcp_function_block *blk;
329
330 rw_rlock(&tcp_function_lock);
331 blk = find_tcp_functions_locked(fs);
332 if (blk)
333 refcount_acquire(&blk->tfb_refcnt);
334 rw_runlock(&tcp_function_lock);
335 return(blk);
336 }
337
338 struct tcp_function_block *
339 find_and_ref_tcp_fb(struct tcp_function_block *blk)
340 {
341 struct tcp_function_block *rblk;
342
343 rw_rlock(&tcp_function_lock);
344 rblk = find_tcp_fb_locked(blk, NULL);
345 if (rblk)
346 refcount_acquire(&rblk->tfb_refcnt);
347 rw_runlock(&tcp_function_lock);
348 return(rblk);
349 }
350
351 static struct tcp_function_block *
352 find_and_ref_tcp_default_fb(void)
353 {
354 struct tcp_function_block *rblk;
355
356 rw_rlock(&tcp_function_lock);
357 rblk = tcp_func_set_ptr;
358 refcount_acquire(&rblk->tfb_refcnt);
359 rw_runlock(&tcp_function_lock);
360 return (rblk);
361 }
362
363 void
364 tcp_switch_back_to_default(struct tcpcb *tp)
365 {
366 struct tcp_function_block *tfb;
367
368 KASSERT(tp->t_fb != &tcp_def_funcblk,
369 ("%s: called by the built-in default stack", __func__));
370
371 /*
372 * Release the old stack. This function will either find a new one
373 * or panic.
374 */
375 if (tp->t_fb->tfb_tcp_fb_fini != NULL)
376 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 0);
377 refcount_release(&tp->t_fb->tfb_refcnt);
378
379 /*
380 * Now, we'll find a new function block to use.
381 * Start by trying the current user-selected
382 * default, unless this stack is the user-selected
383 * default.
384 */
385 tfb = find_and_ref_tcp_default_fb();
386 if (tfb == tp->t_fb) {
387 refcount_release(&tfb->tfb_refcnt);
388 tfb = NULL;
389 }
390 /* Does the stack accept this connection? */
391 if (tfb != NULL && tfb->tfb_tcp_handoff_ok != NULL &&
392 (*tfb->tfb_tcp_handoff_ok)(tp)) {
393 refcount_release(&tfb->tfb_refcnt);
394 tfb = NULL;
395 }
396 /* Try to use that stack. */
397 if (tfb != NULL) {
398 /* Initialize the new stack. If it succeeds, we are done. */
399 tp->t_fb = tfb;
400 if (tp->t_fb->tfb_tcp_fb_init == NULL ||
401 (*tp->t_fb->tfb_tcp_fb_init)(tp) == 0)
402 return;
403
404 /*
405 * Initialization failed. Release the reference count on
406 * the stack.
407 */
408 refcount_release(&tfb->tfb_refcnt);
409 }
410
411 /*
412 * If that wasn't feasible, use the built-in default
413 * stack which is not allowed to reject anyone.
414 */
415 tfb = find_and_ref_tcp_fb(&tcp_def_funcblk);
416 if (tfb == NULL) {
417 /* there always should be a default */
418 panic("Can't refer to tcp_def_funcblk");
419 }
420 if (tfb->tfb_tcp_handoff_ok != NULL) {
421 if ((*tfb->tfb_tcp_handoff_ok) (tp)) {
422 /* The default stack cannot say no */
423 panic("Default stack rejects a new session?");
424 }
425 }
426 tp->t_fb = tfb;
427 if (tp->t_fb->tfb_tcp_fb_init != NULL &&
428 (*tp->t_fb->tfb_tcp_fb_init)(tp)) {
429 /* The default stack cannot fail */
430 panic("Default stack initialization failed");
431 }
432 }
433
434 static int
435 sysctl_net_inet_default_tcp_functions(SYSCTL_HANDLER_ARGS)
436 {
437 int error=ENOENT;
438 struct tcp_function_set fs;
439 struct tcp_function_block *blk;
440
441 memset(&fs, 0, sizeof(fs));
442 rw_rlock(&tcp_function_lock);
443 blk = find_tcp_fb_locked(tcp_func_set_ptr, NULL);
444 if (blk) {
445 /* Found him */
446 strcpy(fs.function_set_name, blk->tfb_tcp_block_name);
447 fs.pcbcnt = blk->tfb_refcnt;
448 }
449 rw_runlock(&tcp_function_lock);
450 error = sysctl_handle_string(oidp, fs.function_set_name,
451 sizeof(fs.function_set_name), req);
452
453 /* Check for error or no change */
454 if (error != 0 || req->newptr == NULL)
455 return(error);
456
457 rw_wlock(&tcp_function_lock);
458 blk = find_tcp_functions_locked(&fs);
459 if ((blk == NULL) ||
460 (blk->tfb_flags & TCP_FUNC_BEING_REMOVED)) {
461 error = ENOENT;
462 goto done;
463 }
464 tcp_func_set_ptr = blk;
465 done:
466 rw_wunlock(&tcp_function_lock);
467 return (error);
468 }
469
470 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, functions_default,
471 CTLTYPE_STRING | CTLFLAG_RW,
472 NULL, 0, sysctl_net_inet_default_tcp_functions, "A",
473 "Set/get the default TCP functions");
474
475 static int
476 sysctl_net_inet_list_available(SYSCTL_HANDLER_ARGS)
477 {
478 int error, cnt, linesz;
479 struct tcp_function *f;
480 char *buffer, *cp;
481 size_t bufsz, outsz;
482 bool alias;
483
484 cnt = 0;
485 rw_rlock(&tcp_function_lock);
486 TAILQ_FOREACH(f, &t_functions, tf_next) {
487 cnt++;
488 }
489 rw_runlock(&tcp_function_lock);
490
491 bufsz = (cnt+2) * ((TCP_FUNCTION_NAME_LEN_MAX * 2) + 13) + 1;
492 buffer = malloc(bufsz, M_TEMP, M_WAITOK);
493
494 error = 0;
495 cp = buffer;
496
497 linesz = snprintf(cp, bufsz, "\n%-32s%c %-32s %s\n", "Stack", 'D',
498 "Alias", "PCB count");
499 cp += linesz;
500 bufsz -= linesz;
501 outsz = linesz;
502
503 rw_rlock(&tcp_function_lock);
504 TAILQ_FOREACH(f, &t_functions, tf_next) {
505 alias = (f->tf_name != f->tf_fb->tfb_tcp_block_name);
506 linesz = snprintf(cp, bufsz, "%-32s%c %-32s %u\n",
507 f->tf_fb->tfb_tcp_block_name,
508 (f->tf_fb == tcp_func_set_ptr) ? '*' : ' ',
509 alias ? f->tf_name : "-",
510 f->tf_fb->tfb_refcnt);
511 if (linesz >= bufsz) {
512 error = EOVERFLOW;
513 break;
514 }
515 cp += linesz;
516 bufsz -= linesz;
517 outsz += linesz;
518 }
519 rw_runlock(&tcp_function_lock);
520 if (error == 0)
521 error = sysctl_handle_string(oidp, buffer, outsz + 1, req);
522 free(buffer, M_TEMP);
523 return (error);
524 }
525
526 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, functions_available,
527 CTLTYPE_STRING|CTLFLAG_RD,
528 NULL, 0, sysctl_net_inet_list_available, "A",
529 "list available TCP Function sets");
530
531 /*
532 * Exports one (struct tcp_function_info) for each alias/name.
533 */
534 static int
535 sysctl_net_inet_list_func_info(SYSCTL_HANDLER_ARGS)
536 {
537 int cnt, error;
538 struct tcp_function *f;
539 struct tcp_function_info tfi;
540
541 /*
542 * We don't allow writes.
543 */
544 if (req->newptr != NULL)
545 return (EINVAL);
546
547 /*
548 * Wire the old buffer so we can directly copy the functions to
549 * user space without dropping the lock.
550 */
551 if (req->oldptr != NULL) {
552 error = sysctl_wire_old_buffer(req, 0);
553 if (error)
554 return (error);
555 }
556
557 /*
558 * Walk the list and copy out matching entries. If INVARIANTS
559 * is compiled in, also walk the list to verify the length of
560 * the list matches what we have recorded.
561 */
562 rw_rlock(&tcp_function_lock);
563
564 cnt = 0;
565 #ifndef INVARIANTS
566 if (req->oldptr == NULL) {
567 cnt = tcp_fb_cnt;
568 goto skip_loop;
569 }
570 #endif
571 TAILQ_FOREACH(f, &t_functions, tf_next) {
572 #ifdef INVARIANTS
573 cnt++;
574 #endif
575 if (req->oldptr != NULL) {
576 bzero(&tfi, sizeof(tfi));
577 tfi.tfi_refcnt = f->tf_fb->tfb_refcnt;
578 tfi.tfi_id = f->tf_fb->tfb_id;
579 (void)strncpy(tfi.tfi_alias, f->tf_name,
580 TCP_FUNCTION_NAME_LEN_MAX);
581 tfi.tfi_alias[TCP_FUNCTION_NAME_LEN_MAX - 1] = '\0';
582 (void)strncpy(tfi.tfi_name,
583 f->tf_fb->tfb_tcp_block_name,
584 TCP_FUNCTION_NAME_LEN_MAX);
585 tfi.tfi_name[TCP_FUNCTION_NAME_LEN_MAX - 1] = '\0';
586 error = SYSCTL_OUT(req, &tfi, sizeof(tfi));
587 /*
588 * Don't stop on error, as that is the
589 * mechanism we use to accumulate length
590 * information if the buffer was too short.
591 */
592 }
593 }
594 KASSERT(cnt == tcp_fb_cnt,
595 ("%s: cnt (%d) != tcp_fb_cnt (%d)", __func__, cnt, tcp_fb_cnt));
596 #ifndef INVARIANTS
597 skip_loop:
598 #endif
599 rw_runlock(&tcp_function_lock);
600 if (req->oldptr == NULL)
601 error = SYSCTL_OUT(req, NULL,
602 (cnt + 1) * sizeof(struct tcp_function_info));
603
604 return (error);
605 }
606
607 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, function_info,
608 CTLTYPE_OPAQUE | CTLFLAG_SKIP | CTLFLAG_RD | CTLFLAG_MPSAFE,
609 NULL, 0, sysctl_net_inet_list_func_info, "S,tcp_function_info",
610 "List TCP function block name-to-ID mappings");
611
612 /*
613 * tfb_tcp_handoff_ok() function for the default stack.
614 * Note that we'll basically try to take all comers.
615 */
616 static int
617 tcp_default_handoff_ok(struct tcpcb *tp)
618 {
619
620 return (0);
621 }
622
623 /*
624 * tfb_tcp_fb_init() function for the default stack.
625 *
626 * This handles making sure we have appropriate timers set if you are
627 * transitioning a socket that has some amount of setup done.
628 *
629 * The init() fuction from the default can *never* return non-zero i.e.
630 * it is required to always succeed since it is the stack of last resort!
631 */
632 static int
633 tcp_default_fb_init(struct tcpcb *tp)
634 {
635
636 struct socket *so;
637
638 INP_WLOCK_ASSERT(tp->t_inpcb);
639
640 KASSERT(tp->t_state >= 0 && tp->t_state < TCPS_TIME_WAIT,
641 ("%s: connection %p in unexpected state %d", __func__, tp,
642 tp->t_state));
643
644 /*
645 * Nothing to do for ESTABLISHED or LISTEN states. And, we don't
646 * know what to do for unexpected states (which includes TIME_WAIT).
647 */
648 if (tp->t_state <= TCPS_LISTEN || tp->t_state >= TCPS_TIME_WAIT)
649 return (0);
650
651 /*
652 * Make sure some kind of transmission timer is set if there is
653 * outstanding data.
654 */
655 so = tp->t_inpcb->inp_socket;
656 if ((!TCPS_HAVEESTABLISHED(tp->t_state) || sbavail(&so->so_snd) ||
657 tp->snd_una != tp->snd_max) && !(tcp_timer_active(tp, TT_REXMT) ||
658 tcp_timer_active(tp, TT_PERSIST))) {
659 /*
660 * If the session has established and it looks like it should
661 * be in the persist state, set the persist timer. Otherwise,
662 * set the retransmit timer.
663 */
664 if (TCPS_HAVEESTABLISHED(tp->t_state) && tp->snd_wnd == 0 &&
665 (int32_t)(tp->snd_nxt - tp->snd_una) <
666 (int32_t)sbavail(&so->so_snd))
667 tcp_setpersist(tp);
668 else
669 tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
670 }
671
672 /* All non-embryonic sessions get a keepalive timer. */
673 if (!tcp_timer_active(tp, TT_KEEP))
674 tcp_timer_activate(tp, TT_KEEP,
675 TCPS_HAVEESTABLISHED(tp->t_state) ? TP_KEEPIDLE(tp) :
676 TP_KEEPINIT(tp));
677
678 return (0);
679 }
680
681 /*
682 * tfb_tcp_fb_fini() function for the default stack.
683 *
684 * This changes state as necessary (or prudent) to prepare for another stack
685 * to assume responsibility for the connection.
686 */
687 static void
688 tcp_default_fb_fini(struct tcpcb *tp, int tcb_is_purged)
689 {
690
691 INP_WLOCK_ASSERT(tp->t_inpcb);
692 return;
693 }
694
695 /*
696 * Target size of TCP PCB hash tables. Must be a power of two.
697 *
698 * Note that this can be overridden by the kernel environment
699 * variable net.inet.tcp.tcbhashsize
700 */
701 #ifndef TCBHASHSIZE
702 #define TCBHASHSIZE 0
703 #endif
704
705 /*
706 * XXX
707 * Callouts should be moved into struct tcp directly. They are currently
708 * separate because the tcpcb structure is exported to userland for sysctl
709 * parsing purposes, which do not know about callouts.
710 */
711 struct tcpcb_mem {
712 struct tcpcb tcb;
713 struct tcp_timer tt;
714 struct cc_var ccv;
715 #ifdef TCP_HHOOK
716 struct osd osd;
717 #endif
718 };
719
720 VNET_DEFINE_STATIC(uma_zone_t, tcpcb_zone);
721 #define V_tcpcb_zone VNET(tcpcb_zone)
722
723 MALLOC_DEFINE(M_TCPLOG, "tcplog", "TCP address and flags print buffers");
724 MALLOC_DEFINE(M_TCPFUNCTIONS, "tcpfunc", "TCP function set memory");
725
726 static struct mtx isn_mtx;
727
728 #define ISN_LOCK_INIT() mtx_init(&isn_mtx, "isn_mtx", NULL, MTX_DEF)
729 #define ISN_LOCK() mtx_lock(&isn_mtx)
730 #define ISN_UNLOCK() mtx_unlock(&isn_mtx)
731
732 /*
733 * TCP initialization.
734 */
735 static void
736 tcp_zone_change(void *tag)
737 {
738
739 uma_zone_set_max(V_tcbinfo.ipi_zone, maxsockets);
740 uma_zone_set_max(V_tcpcb_zone, maxsockets);
741 tcp_tw_zone_change();
742 }
743
744 static int
745 tcp_inpcb_init(void *mem, int size, int flags)
746 {
747 struct inpcb *inp = mem;
748
749 INP_LOCK_INIT(inp, "inp", "tcpinp");
750 return (0);
751 }
752
753 /*
754 * Take a value and get the next power of 2 that doesn't overflow.
755 * Used to size the tcp_inpcb hash buckets.
756 */
757 static int
758 maketcp_hashsize(int size)
759 {
760 int hashsize;
761
762 /*
763 * auto tune.
764 * get the next power of 2 higher than maxsockets.
765 */
766 hashsize = 1 << fls(size);
767 /* catch overflow, and just go one power of 2 smaller */
768 if (hashsize < size) {
769 hashsize = 1 << (fls(size) - 1);
770 }
771 return (hashsize);
772 }
773
774 static volatile int next_tcp_stack_id = 1;
775
776 /*
777 * Register a TCP function block with the name provided in the names
778 * array. (Note that this function does NOT automatically register
779 * blk->tfb_tcp_block_name as a stack name. Therefore, you should
780 * explicitly include blk->tfb_tcp_block_name in the list of names if
781 * you wish to register the stack with that name.)
782 *
783 * Either all name registrations will succeed or all will fail. If
784 * a name registration fails, the function will update the num_names
785 * argument to point to the array index of the name that encountered
786 * the failure.
787 *
788 * Returns 0 on success, or an error code on failure.
789 */
790 int
791 register_tcp_functions_as_names(struct tcp_function_block *blk, int wait,
792 const char *names[], int *num_names)
793 {
794 struct tcp_function *n;
795 struct tcp_function_set fs;
796 int error, i;
797
798 KASSERT(names != NULL && *num_names > 0,
799 ("%s: Called with 0-length name list", __func__));
800 KASSERT(names != NULL, ("%s: Called with NULL name list", __func__));
801
802 if (t_functions_inited == 0) {
803 init_tcp_functions();
804 }
805 if ((blk->tfb_tcp_output == NULL) ||
806 (blk->tfb_tcp_do_segment == NULL) ||
807 (blk->tfb_tcp_ctloutput == NULL) ||
808 (strlen(blk->tfb_tcp_block_name) == 0)) {
809 /*
810 * These functions are required and you
811 * need a name.
812 */
813 *num_names = 0;
814 return (EINVAL);
815 }
816 if (blk->tfb_tcp_timer_stop_all ||
817 blk->tfb_tcp_timer_activate ||
818 blk->tfb_tcp_timer_active ||
819 blk->tfb_tcp_timer_stop) {
820 /*
821 * If you define one timer function you
822 * must have them all.
823 */
824 if ((blk->tfb_tcp_timer_stop_all == NULL) ||
825 (blk->tfb_tcp_timer_activate == NULL) ||
826 (blk->tfb_tcp_timer_active == NULL) ||
827 (blk->tfb_tcp_timer_stop == NULL)) {
828 *num_names = 0;
829 return (EINVAL);
830 }
831 }
832
833 if (blk->tfb_flags & TCP_FUNC_BEING_REMOVED) {
834 *num_names = 0;
835 return (EINVAL);
836 }
837
838 refcount_init(&blk->tfb_refcnt, 0);
839 blk->tfb_id = atomic_fetchadd_int(&next_tcp_stack_id, 1);
840 for (i = 0; i < *num_names; i++) {
841 n = malloc(sizeof(struct tcp_function), M_TCPFUNCTIONS, wait);
842 if (n == NULL) {
843 error = ENOMEM;
844 goto cleanup;
845 }
846 n->tf_fb = blk;
847
848 (void)strncpy(fs.function_set_name, names[i],
849 TCP_FUNCTION_NAME_LEN_MAX);
850 fs.function_set_name[TCP_FUNCTION_NAME_LEN_MAX - 1] = '\0';
851 rw_wlock(&tcp_function_lock);
852 if (find_tcp_functions_locked(&fs) != NULL) {
853 /* Duplicate name space not allowed */
854 rw_wunlock(&tcp_function_lock);
855 free(n, M_TCPFUNCTIONS);
856 error = EALREADY;
857 goto cleanup;
858 }
859 (void)strncpy(n->tf_name, names[i], TCP_FUNCTION_NAME_LEN_MAX);
860 n->tf_name[TCP_FUNCTION_NAME_LEN_MAX - 1] = '\0';
861 TAILQ_INSERT_TAIL(&t_functions, n, tf_next);
862 tcp_fb_cnt++;
863 rw_wunlock(&tcp_function_lock);
864 }
865 return(0);
866
867 cleanup:
868 /*
869 * Deregister the names we just added. Because registration failed
870 * for names[i], we don't need to deregister that name.
871 */
872 *num_names = i;
873 rw_wlock(&tcp_function_lock);
874 while (--i >= 0) {
875 TAILQ_FOREACH(n, &t_functions, tf_next) {
876 if (!strncmp(n->tf_name, names[i],
877 TCP_FUNCTION_NAME_LEN_MAX)) {
878 TAILQ_REMOVE(&t_functions, n, tf_next);
879 tcp_fb_cnt--;
880 n->tf_fb = NULL;
881 free(n, M_TCPFUNCTIONS);
882 break;
883 }
884 }
885 }
886 rw_wunlock(&tcp_function_lock);
887 return (error);
888 }
889
890 /*
891 * Register a TCP function block using the name provided in the name
892 * argument.
893 *
894 * Returns 0 on success, or an error code on failure.
895 */
896 int
897 register_tcp_functions_as_name(struct tcp_function_block *blk, const char *name,
898 int wait)
899 {
900 const char *name_list[1];
901 int num_names, rv;
902
903 num_names = 1;
904 if (name != NULL)
905 name_list[0] = name;
906 else
907 name_list[0] = blk->tfb_tcp_block_name;
908 rv = register_tcp_functions_as_names(blk, wait, name_list, &num_names);
909 return (rv);
910 }
911
912 /*
913 * Register a TCP function block using the name defined in
914 * blk->tfb_tcp_block_name.
915 *
916 * Returns 0 on success, or an error code on failure.
917 */
918 int
919 register_tcp_functions(struct tcp_function_block *blk, int wait)
920 {
921
922 return (register_tcp_functions_as_name(blk, NULL, wait));
923 }
924
925 /*
926 * Deregister all names associated with a function block. This
927 * functionally removes the function block from use within the system.
928 *
929 * When called with a true quiesce argument, mark the function block
930 * as being removed so no more stacks will use it and determine
931 * whether the removal would succeed.
932 *
933 * When called with a false quiesce argument, actually attempt the
934 * removal.
935 *
936 * When called with a force argument, attempt to switch all TCBs to
937 * use the default stack instead of returning EBUSY.
938 *
939 * Returns 0 on success (or if the removal would succeed, or an error
940 * code on failure.
941 */
942 int
943 deregister_tcp_functions(struct tcp_function_block *blk, bool quiesce,
944 bool force)
945 {
946 struct tcp_function *f;
947
948 if (strcmp(blk->tfb_tcp_block_name, "default") == 0) {
949 /* You can't un-register the default */
950 return (EPERM);
951 }
952 rw_wlock(&tcp_function_lock);
953 if (blk == tcp_func_set_ptr) {
954 /* You can't free the current default */
955 rw_wunlock(&tcp_function_lock);
956 return (EBUSY);
957 }
958 /* Mark the block so no more stacks can use it. */
959 blk->tfb_flags |= TCP_FUNC_BEING_REMOVED;
960 /*
961 * If TCBs are still attached to the stack, attempt to switch them
962 * to the default stack.
963 */
964 if (force && blk->tfb_refcnt) {
965 struct inpcb *inp;
966 struct tcpcb *tp;
967 VNET_ITERATOR_DECL(vnet_iter);
968
969 rw_wunlock(&tcp_function_lock);
970
971 VNET_LIST_RLOCK();
972 VNET_FOREACH(vnet_iter) {
973 CURVNET_SET(vnet_iter);
974 INP_INFO_WLOCK(&V_tcbinfo);
975 CK_LIST_FOREACH(inp, V_tcbinfo.ipi_listhead, inp_list) {
976 INP_WLOCK(inp);
977 if (inp->inp_flags & INP_TIMEWAIT) {
978 INP_WUNLOCK(inp);
979 continue;
980 }
981 tp = intotcpcb(inp);
982 if (tp == NULL || tp->t_fb != blk) {
983 INP_WUNLOCK(inp);
984 continue;
985 }
986 tcp_switch_back_to_default(tp);
987 INP_WUNLOCK(inp);
988 }
989 INP_INFO_WUNLOCK(&V_tcbinfo);
990 CURVNET_RESTORE();
991 }
992 VNET_LIST_RUNLOCK();
993
994 rw_wlock(&tcp_function_lock);
995 }
996 if (blk->tfb_refcnt) {
997 /* TCBs still attached. */
998 rw_wunlock(&tcp_function_lock);
999 return (EBUSY);
1000 }
1001 if (quiesce) {
1002 /* Skip removal. */
1003 rw_wunlock(&tcp_function_lock);
1004 return (0);
1005 }
1006 /* Remove any function names that map to this function block. */
1007 while (find_tcp_fb_locked(blk, &f) != NULL) {
1008 TAILQ_REMOVE(&t_functions, f, tf_next);
1009 tcp_fb_cnt--;
1010 f->tf_fb = NULL;
1011 free(f, M_TCPFUNCTIONS);
1012 }
1013 rw_wunlock(&tcp_function_lock);
1014 return (0);
1015 }
1016
1017 void
1018 tcp_init(void)
1019 {
1020 const char *tcbhash_tuneable;
1021 int hashsize;
1022
1023 tcbhash_tuneable = "net.inet.tcp.tcbhashsize";
1024
1025 #ifdef TCP_HHOOK
1026 if (hhook_head_register(HHOOK_TYPE_TCP, HHOOK_TCP_EST_IN,
1027 &V_tcp_hhh[HHOOK_TCP_EST_IN], HHOOK_NOWAIT|HHOOK_HEADISINVNET) != 0)
1028 printf("%s: WARNING: unable to register helper hook\n", __func__);
1029 if (hhook_head_register(HHOOK_TYPE_TCP, HHOOK_TCP_EST_OUT,
1030 &V_tcp_hhh[HHOOK_TCP_EST_OUT], HHOOK_NOWAIT|HHOOK_HEADISINVNET) != 0)
1031 printf("%s: WARNING: unable to register helper hook\n", __func__);
1032 #endif
1033 hashsize = TCBHASHSIZE;
1034 TUNABLE_INT_FETCH(tcbhash_tuneable, &hashsize);
1035 if (hashsize == 0) {
1036 /*
1037 * Auto tune the hash size based on maxsockets.
1038 * A perfect hash would have a 1:1 mapping
1039 * (hashsize = maxsockets) however it's been
1040 * suggested that O(2) average is better.
1041 */
1042 hashsize = maketcp_hashsize(maxsockets / 4);
1043 /*
1044 * Our historical default is 512,
1045 * do not autotune lower than this.
1046 */
1047 if (hashsize < 512)
1048 hashsize = 512;
1049 if (bootverbose && IS_DEFAULT_VNET(curvnet))
1050 printf("%s: %s auto tuned to %d\n", __func__,
1051 tcbhash_tuneable, hashsize);
1052 }
1053 /*
1054 * We require a hashsize to be a power of two.
1055 * Previously if it was not a power of two we would just reset it
1056 * back to 512, which could be a nasty surprise if you did not notice
1057 * the error message.
1058 * Instead what we do is clip it to the closest power of two lower
1059 * than the specified hash value.
1060 */
1061 if (!powerof2(hashsize)) {
1062 int oldhashsize = hashsize;
1063
1064 hashsize = maketcp_hashsize(hashsize);
1065 /* prevent absurdly low value */
1066 if (hashsize < 16)
1067 hashsize = 16;
1068 printf("%s: WARNING: TCB hash size not a power of 2, "
1069 "clipped from %d to %d.\n", __func__, oldhashsize,
1070 hashsize);
1071 }
1072 in_pcbinfo_init(&V_tcbinfo, "tcp", &V_tcb, hashsize, hashsize,
1073 "tcp_inpcb", tcp_inpcb_init, IPI_HASHFIELDS_4TUPLE);
1074
1075 /*
1076 * These have to be type stable for the benefit of the timers.
1077 */
1078 V_tcpcb_zone = uma_zcreate("tcpcb", sizeof(struct tcpcb_mem),
1079 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1080 uma_zone_set_max(V_tcpcb_zone, maxsockets);
1081 uma_zone_set_warning(V_tcpcb_zone, "kern.ipc.maxsockets limit reached");
1082
1083 tcp_tw_init();
1084 syncache_init();
1085 tcp_hc_init();
1086
1087 TUNABLE_INT_FETCH("net.inet.tcp.sack.enable", &V_tcp_do_sack);
1088 V_sack_hole_zone = uma_zcreate("sackhole", sizeof(struct sackhole),
1089 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1090
1091 tcp_fastopen_init();
1092
1093 /* Skip initialization of globals for non-default instances. */
1094 if (!IS_DEFAULT_VNET(curvnet))
1095 return;
1096
1097 tcp_reass_global_init();
1098
1099 /* XXX virtualize those bellow? */
1100 tcp_delacktime = TCPTV_DELACK;
1101 tcp_keepinit = TCPTV_KEEP_INIT;
1102 tcp_keepidle = TCPTV_KEEP_IDLE;
1103 tcp_keepintvl = TCPTV_KEEPINTVL;
1104 tcp_maxpersistidle = TCPTV_KEEP_IDLE;
1105 tcp_msl = TCPTV_MSL;
1106 tcp_rexmit_initial = TCPTV_RTOBASE;
1107 if (tcp_rexmit_initial < 1)
1108 tcp_rexmit_initial = 1;
1109 tcp_rexmit_min = TCPTV_MIN;
1110 if (tcp_rexmit_min < 1)
1111 tcp_rexmit_min = 1;
1112 tcp_persmin = TCPTV_PERSMIN;
1113 tcp_persmax = TCPTV_PERSMAX;
1114 tcp_rexmit_slop = TCPTV_CPU_VAR;
1115 tcp_finwait2_timeout = TCPTV_FINWAIT2_TIMEOUT;
1116 tcp_tcbhashsize = hashsize;
1117 /* Setup the tcp function block list */
1118 init_tcp_functions();
1119 register_tcp_functions(&tcp_def_funcblk, M_WAITOK);
1120 #ifdef TCP_BLACKBOX
1121 /* Initialize the TCP logging data. */
1122 tcp_log_init();
1123 #endif
1124 arc4rand(&V_ts_offset_secret, sizeof(V_ts_offset_secret), 0);
1125
1126 if (tcp_soreceive_stream) {
1127 #ifdef INET
1128 tcp_usrreqs.pru_soreceive = soreceive_stream;
1129 #endif
1130 #ifdef INET6
1131 tcp6_usrreqs.pru_soreceive = soreceive_stream;
1132 #endif /* INET6 */
1133 }
1134
1135 #ifdef INET6
1136 #define TCP_MINPROTOHDR (sizeof(struct ip6_hdr) + sizeof(struct tcphdr))
1137 #else /* INET6 */
1138 #define TCP_MINPROTOHDR (sizeof(struct tcpiphdr))
1139 #endif /* INET6 */
1140 if (max_protohdr < TCP_MINPROTOHDR)
1141 max_protohdr = TCP_MINPROTOHDR;
1142 if (max_linkhdr + TCP_MINPROTOHDR > MHLEN)
1143 panic("tcp_init");
1144 #undef TCP_MINPROTOHDR
1145
1146 ISN_LOCK_INIT();
1147 EVENTHANDLER_REGISTER(shutdown_pre_sync, tcp_fini, NULL,
1148 SHUTDOWN_PRI_DEFAULT);
1149 EVENTHANDLER_REGISTER(maxsockets_change, tcp_zone_change, NULL,
1150 EVENTHANDLER_PRI_ANY);
1151 #ifdef TCPPCAP
1152 tcp_pcap_init();
1153 #endif
1154 }
1155
1156 #ifdef VIMAGE
1157 static void
1158 tcp_destroy(void *unused __unused)
1159 {
1160 int n;
1161 #ifdef TCP_HHOOK
1162 int error;
1163 #endif
1164
1165 /*
1166 * All our processes are gone, all our sockets should be cleaned
1167 * up, which means, we should be past the tcp_discardcb() calls.
1168 * Sleep to let all tcpcb timers really disappear and cleanup.
1169 */
1170 for (;;) {
1171 INP_LIST_RLOCK(&V_tcbinfo);
1172 n = V_tcbinfo.ipi_count;
1173 INP_LIST_RUNLOCK(&V_tcbinfo);
1174 if (n == 0)
1175 break;
1176 pause("tcpdes", hz / 10);
1177 }
1178 tcp_hc_destroy();
1179 syncache_destroy();
1180 tcp_tw_destroy();
1181 in_pcbinfo_destroy(&V_tcbinfo);
1182 /* tcp_discardcb() clears the sack_holes up. */
1183 uma_zdestroy(V_sack_hole_zone);
1184 uma_zdestroy(V_tcpcb_zone);
1185
1186 /*
1187 * Cannot free the zone until all tcpcbs are released as we attach
1188 * the allocations to them.
1189 */
1190 tcp_fastopen_destroy();
1191
1192 #ifdef TCP_HHOOK
1193 error = hhook_head_deregister(V_tcp_hhh[HHOOK_TCP_EST_IN]);
1194 if (error != 0) {
1195 printf("%s: WARNING: unable to deregister helper hook "
1196 "type=%d, id=%d: error %d returned\n", __func__,
1197 HHOOK_TYPE_TCP, HHOOK_TCP_EST_IN, error);
1198 }
1199 error = hhook_head_deregister(V_tcp_hhh[HHOOK_TCP_EST_OUT]);
1200 if (error != 0) {
1201 printf("%s: WARNING: unable to deregister helper hook "
1202 "type=%d, id=%d: error %d returned\n", __func__,
1203 HHOOK_TYPE_TCP, HHOOK_TCP_EST_OUT, error);
1204 }
1205 #endif
1206 }
1207 VNET_SYSUNINIT(tcp, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH, tcp_destroy, NULL);
1208 #endif
1209
1210 void
1211 tcp_fini(void *xtp)
1212 {
1213
1214 }
1215
1216 /*
1217 * Fill in the IP and TCP headers for an outgoing packet, given the tcpcb.
1218 * tcp_template used to store this data in mbufs, but we now recopy it out
1219 * of the tcpcb each time to conserve mbufs.
1220 */
1221 void
1222 tcpip_fillheaders(struct inpcb *inp, void *ip_ptr, void *tcp_ptr)
1223 {
1224 struct tcphdr *th = (struct tcphdr *)tcp_ptr;
1225
1226 INP_WLOCK_ASSERT(inp);
1227
1228 #ifdef INET6
1229 if ((inp->inp_vflag & INP_IPV6) != 0) {
1230 struct ip6_hdr *ip6;
1231
1232 ip6 = (struct ip6_hdr *)ip_ptr;
1233 ip6->ip6_flow = (ip6->ip6_flow & ~IPV6_FLOWINFO_MASK) |
1234 (inp->inp_flow & IPV6_FLOWINFO_MASK);
1235 ip6->ip6_vfc = (ip6->ip6_vfc & ~IPV6_VERSION_MASK) |
1236 (IPV6_VERSION & IPV6_VERSION_MASK);
1237 ip6->ip6_nxt = IPPROTO_TCP;
1238 ip6->ip6_plen = htons(sizeof(struct tcphdr));
1239 ip6->ip6_src = inp->in6p_laddr;
1240 ip6->ip6_dst = inp->in6p_faddr;
1241 }
1242 #endif /* INET6 */
1243 #if defined(INET6) && defined(INET)
1244 else
1245 #endif
1246 #ifdef INET
1247 {
1248 struct ip *ip;
1249
1250 ip = (struct ip *)ip_ptr;
1251 ip->ip_v = IPVERSION;
1252 ip->ip_hl = 5;
1253 ip->ip_tos = inp->inp_ip_tos;
1254 ip->ip_len = 0;
1255 ip->ip_id = 0;
1256 ip->ip_off = 0;
1257 ip->ip_ttl = inp->inp_ip_ttl;
1258 ip->ip_sum = 0;
1259 ip->ip_p = IPPROTO_TCP;
1260 ip->ip_src = inp->inp_laddr;
1261 ip->ip_dst = inp->inp_faddr;
1262 }
1263 #endif /* INET */
1264 th->th_sport = inp->inp_lport;
1265 th->th_dport = inp->inp_fport;
1266 th->th_seq = 0;
1267 th->th_ack = 0;
1268 th->th_x2 = 0;
1269 th->th_off = 5;
1270 th->th_flags = 0;
1271 th->th_win = 0;
1272 th->th_urp = 0;
1273 th->th_sum = 0; /* in_pseudo() is called later for ipv4 */
1274 }
1275
1276 /*
1277 * Create template to be used to send tcp packets on a connection.
1278 * Allocates an mbuf and fills in a skeletal tcp/ip header. The only
1279 * use for this function is in keepalives, which use tcp_respond.
1280 */
1281 struct tcptemp *
1282 tcpip_maketemplate(struct inpcb *inp)
1283 {
1284 struct tcptemp *t;
1285
1286 t = malloc(sizeof(*t), M_TEMP, M_NOWAIT);
1287 if (t == NULL)
1288 return (NULL);
1289 tcpip_fillheaders(inp, (void *)&t->tt_ipgen, (void *)&t->tt_t);
1290 return (t);
1291 }
1292
1293 /*
1294 * Send a single message to the TCP at address specified by
1295 * the given TCP/IP header. If m == NULL, then we make a copy
1296 * of the tcpiphdr at th and send directly to the addressed host.
1297 * This is used to force keep alive messages out using the TCP
1298 * template for a connection. If flags are given then we send
1299 * a message back to the TCP which originated the segment th,
1300 * and discard the mbuf containing it and any other attached mbufs.
1301 *
1302 * In any case the ack and sequence number of the transmitted
1303 * segment are as specified by the parameters.
1304 *
1305 * NOTE: If m != NULL, then th must point to *inside* the mbuf.
1306 */
1307 void
1308 tcp_respond(struct tcpcb *tp, void *ipgen, struct tcphdr *th, struct mbuf *m,
1309 tcp_seq ack, tcp_seq seq, int flags)
1310 {
1311 struct tcpopt to;
1312 struct inpcb *inp;
1313 struct ip *ip;
1314 struct mbuf *optm;
1315 struct tcphdr *nth;
1316 u_char *optp;
1317 #ifdef INET6
1318 struct ip6_hdr *ip6;
1319 int isipv6;
1320 #endif /* INET6 */
1321 int optlen, tlen, win;
1322 bool incl_opts;
1323
1324 KASSERT(tp != NULL || m != NULL, ("tcp_respond: tp and m both NULL"));
1325
1326 #ifdef INET6
1327 isipv6 = ((struct ip *)ipgen)->ip_v == (IPV6_VERSION >> 4);
1328 ip6 = ipgen;
1329 #endif /* INET6 */
1330 ip = ipgen;
1331
1332 if (tp != NULL) {
1333 inp = tp->t_inpcb;
1334 KASSERT(inp != NULL, ("tcp control block w/o inpcb"));
1335 INP_WLOCK_ASSERT(inp);
1336 } else
1337 inp = NULL;
1338
1339 incl_opts = false;
1340 win = 0;
1341 if (tp != NULL) {
1342 if (!(flags & TH_RST)) {
1343 win = sbspace(&inp->inp_socket->so_rcv);
1344 if (win > TCP_MAXWIN << tp->rcv_scale)
1345 win = TCP_MAXWIN << tp->rcv_scale;
1346 }
1347 if ((tp->t_flags & TF_NOOPT) == 0)
1348 incl_opts = true;
1349 }
1350 if (m == NULL) {
1351 m = m_gethdr(M_NOWAIT, MT_DATA);
1352 if (m == NULL)
1353 return;
1354 m->m_data += max_linkhdr;
1355 #ifdef INET6
1356 if (isipv6) {
1357 bcopy((caddr_t)ip6, mtod(m, caddr_t),
1358 sizeof(struct ip6_hdr));
1359 ip6 = mtod(m, struct ip6_hdr *);
1360 nth = (struct tcphdr *)(ip6 + 1);
1361 } else
1362 #endif /* INET6 */
1363 {
1364 bcopy((caddr_t)ip, mtod(m, caddr_t), sizeof(struct ip));
1365 ip = mtod(m, struct ip *);
1366 nth = (struct tcphdr *)(ip + 1);
1367 }
1368 bcopy((caddr_t)th, (caddr_t)nth, sizeof(struct tcphdr));
1369 flags = TH_ACK;
1370 } else if (!M_WRITABLE(m)) {
1371 struct mbuf *n;
1372
1373 /* Can't reuse 'm', allocate a new mbuf. */
1374 n = m_gethdr(M_NOWAIT, MT_DATA);
1375 if (n == NULL) {
1376 m_freem(m);
1377 return;
1378 }
1379
1380 if (!m_dup_pkthdr(n, m, M_NOWAIT)) {
1381 m_freem(m);
1382 m_freem(n);
1383 return;
1384 }
1385
1386 n->m_data += max_linkhdr;
1387 /* m_len is set later */
1388 #define xchg(a,b,type) { type t; t=a; a=b; b=t; }
1389 #ifdef INET6
1390 if (isipv6) {
1391 bcopy((caddr_t)ip6, mtod(n, caddr_t),
1392 sizeof(struct ip6_hdr));
1393 ip6 = mtod(n, struct ip6_hdr *);
1394 xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
1395 nth = (struct tcphdr *)(ip6 + 1);
1396 } else
1397 #endif /* INET6 */
1398 {
1399 bcopy((caddr_t)ip, mtod(n, caddr_t), sizeof(struct ip));
1400 ip = mtod(n, struct ip *);
1401 xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, uint32_t);
1402 nth = (struct tcphdr *)(ip + 1);
1403 }
1404 bcopy((caddr_t)th, (caddr_t)nth, sizeof(struct tcphdr));
1405 xchg(nth->th_dport, nth->th_sport, uint16_t);
1406 th = nth;
1407 m_freem(m);
1408 m = n;
1409 } else {
1410 /*
1411 * reuse the mbuf.
1412 * XXX MRT We inherit the FIB, which is lucky.
1413 */
1414 m_freem(m->m_next);
1415 m->m_next = NULL;
1416 m->m_data = (caddr_t)ipgen;
1417 /* m_len is set later */
1418 #ifdef INET6
1419 if (isipv6) {
1420 xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
1421 nth = (struct tcphdr *)(ip6 + 1);
1422 } else
1423 #endif /* INET6 */
1424 {
1425 xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, uint32_t);
1426 nth = (struct tcphdr *)(ip + 1);
1427 }
1428 if (th != nth) {
1429 /*
1430 * this is usually a case when an extension header
1431 * exists between the IPv6 header and the
1432 * TCP header.
1433 */
1434 nth->th_sport = th->th_sport;
1435 nth->th_dport = th->th_dport;
1436 }
1437 xchg(nth->th_dport, nth->th_sport, uint16_t);
1438 #undef xchg
1439 }
1440 tlen = 0;
1441 #ifdef INET6
1442 if (isipv6)
1443 tlen = sizeof (struct ip6_hdr) + sizeof (struct tcphdr);
1444 #endif
1445 #if defined(INET) && defined(INET6)
1446 else
1447 #endif
1448 #ifdef INET
1449 tlen = sizeof (struct tcpiphdr);
1450 #endif
1451 #ifdef INVARIANTS
1452 m->m_len = 0;
1453 KASSERT(M_TRAILINGSPACE(m) >= tlen,
1454 ("Not enough trailing space for message (m=%p, need=%d, have=%ld)",
1455 m, tlen, (long)M_TRAILINGSPACE(m)));
1456 #endif
1457 m->m_len = tlen;
1458 to.to_flags = 0;
1459 if (incl_opts) {
1460 /* Make sure we have room. */
1461 if (M_TRAILINGSPACE(m) < TCP_MAXOLEN) {
1462 m->m_next = m_get(M_NOWAIT, MT_DATA);
1463 if (m->m_next) {
1464 optp = mtod(m->m_next, u_char *);
1465 optm = m->m_next;
1466 } else
1467 incl_opts = false;
1468 } else {
1469 optp = (u_char *) (nth + 1);
1470 optm = m;
1471 }
1472 }
1473 if (incl_opts) {
1474 /* Timestamps. */
1475 if (tp->t_flags & TF_RCVD_TSTMP) {
1476 to.to_tsval = tcp_ts_getticks() + tp->ts_offset;
1477 to.to_tsecr = tp->ts_recent;
1478 to.to_flags |= TOF_TS;
1479 }
1480 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1481 /* TCP-MD5 (RFC2385). */
1482 if (tp->t_flags & TF_SIGNATURE)
1483 to.to_flags |= TOF_SIGNATURE;
1484 #endif
1485 /* Add the options. */
1486 tlen += optlen = tcp_addoptions(&to, optp);
1487
1488 /* Update m_len in the correct mbuf. */
1489 optm->m_len += optlen;
1490 } else
1491 optlen = 0;
1492 #ifdef INET6
1493 if (isipv6) {
1494 ip6->ip6_flow = 0;
1495 ip6->ip6_vfc = IPV6_VERSION;
1496 ip6->ip6_nxt = IPPROTO_TCP;
1497 ip6->ip6_plen = htons(tlen - sizeof(*ip6));
1498 }
1499 #endif
1500 #if defined(INET) && defined(INET6)
1501 else
1502 #endif
1503 #ifdef INET
1504 {
1505 ip->ip_len = htons(tlen);
1506 ip->ip_ttl = V_ip_defttl;
1507 if (V_path_mtu_discovery)
1508 ip->ip_off |= htons(IP_DF);
1509 }
1510 #endif
1511 m->m_pkthdr.len = tlen;
1512 m->m_pkthdr.rcvif = NULL;
1513 #ifdef MAC
1514 if (inp != NULL) {
1515 /*
1516 * Packet is associated with a socket, so allow the
1517 * label of the response to reflect the socket label.
1518 */
1519 INP_WLOCK_ASSERT(inp);
1520 mac_inpcb_create_mbuf(inp, m);
1521 } else {
1522 /*
1523 * Packet is not associated with a socket, so possibly
1524 * update the label in place.
1525 */
1526 mac_netinet_tcp_reply(m);
1527 }
1528 #endif
1529 nth->th_seq = htonl(seq);
1530 nth->th_ack = htonl(ack);
1531 nth->th_x2 = 0;
1532 nth->th_off = (sizeof (struct tcphdr) + optlen) >> 2;
1533 nth->th_flags = flags;
1534 if (tp != NULL)
1535 nth->th_win = htons((u_short) (win >> tp->rcv_scale));
1536 else
1537 nth->th_win = htons((u_short)win);
1538 nth->th_urp = 0;
1539
1540 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1541 if (to.to_flags & TOF_SIGNATURE) {
1542 if (!TCPMD5_ENABLED() ||
1543 TCPMD5_OUTPUT(m, nth, to.to_signature) != 0) {
1544 m_freem(m);
1545 return;
1546 }
1547 }
1548 #endif
1549
1550 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
1551 #ifdef INET6
1552 if (isipv6) {
1553 m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
1554 nth->th_sum = in6_cksum_pseudo(ip6,
1555 tlen - sizeof(struct ip6_hdr), IPPROTO_TCP, 0);
1556 ip6->ip6_hlim = in6_selecthlim(tp != NULL ? tp->t_inpcb :
1557 NULL, NULL);
1558 }
1559 #endif /* INET6 */
1560 #if defined(INET6) && defined(INET)
1561 else
1562 #endif
1563 #ifdef INET
1564 {
1565 m->m_pkthdr.csum_flags = CSUM_TCP;
1566 nth->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
1567 htons((u_short)(tlen - sizeof(struct ip) + ip->ip_p)));
1568 }
1569 #endif /* INET */
1570 #ifdef TCPDEBUG
1571 if (tp == NULL || (inp->inp_socket->so_options & SO_DEBUG))
1572 tcp_trace(TA_OUTPUT, 0, tp, mtod(m, void *), th, 0);
1573 #endif
1574 TCP_PROBE3(debug__output, tp, th, m);
1575 if (flags & TH_RST)
1576 TCP_PROBE5(accept__refused, NULL, NULL, m, tp, nth);
1577
1578 #ifdef INET6
1579 if (isipv6) {
1580 TCP_PROBE5(send, NULL, tp, ip6, tp, nth);
1581 (void)ip6_output(m, NULL, NULL, 0, NULL, NULL, inp);
1582 }
1583 #endif /* INET6 */
1584 #if defined(INET) && defined(INET6)
1585 else
1586 #endif
1587 #ifdef INET
1588 {
1589 TCP_PROBE5(send, NULL, tp, ip, tp, nth);
1590 (void)ip_output(m, NULL, NULL, 0, NULL, inp);
1591 }
1592 #endif
1593 }
1594
1595 /*
1596 * Create a new TCP control block, making an
1597 * empty reassembly queue and hooking it to the argument
1598 * protocol control block. The `inp' parameter must have
1599 * come from the zone allocator set up in tcp_init().
1600 */
1601 struct tcpcb *
1602 tcp_newtcpcb(struct inpcb *inp)
1603 {
1604 struct tcpcb_mem *tm;
1605 struct tcpcb *tp;
1606 #ifdef INET6
1607 int isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
1608 #endif /* INET6 */
1609
1610 tm = uma_zalloc(V_tcpcb_zone, M_NOWAIT | M_ZERO);
1611 if (tm == NULL)
1612 return (NULL);
1613 tp = &tm->tcb;
1614
1615 /* Initialise cc_var struct for this tcpcb. */
1616 tp->ccv = &tm->ccv;
1617 tp->ccv->type = IPPROTO_TCP;
1618 tp->ccv->ccvc.tcp = tp;
1619 rw_rlock(&tcp_function_lock);
1620 tp->t_fb = tcp_func_set_ptr;
1621 refcount_acquire(&tp->t_fb->tfb_refcnt);
1622 rw_runlock(&tcp_function_lock);
1623 /*
1624 * Use the current system default CC algorithm.
1625 */
1626 CC_LIST_RLOCK();
1627 KASSERT(!STAILQ_EMPTY(&cc_list), ("cc_list is empty!"));
1628 CC_ALGO(tp) = CC_DEFAULT();
1629 CC_LIST_RUNLOCK();
1630 /*
1631 * The tcpcb will hold a reference on its inpcb until tcp_discardcb()
1632 * is called.
1633 */
1634 in_pcbref(inp); /* Reference for tcpcb */
1635 tp->t_inpcb = inp;
1636
1637 if (CC_ALGO(tp)->cb_init != NULL)
1638 if (CC_ALGO(tp)->cb_init(tp->ccv) > 0) {
1639 if (tp->t_fb->tfb_tcp_fb_fini)
1640 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 1);
1641 refcount_release(&tp->t_fb->tfb_refcnt);
1642 uma_zfree(V_tcpcb_zone, tm);
1643 return (NULL);
1644 }
1645
1646 #ifdef TCP_HHOOK
1647 tp->osd = &tm->osd;
1648 if (khelp_init_osd(HELPER_CLASS_TCP, tp->osd)) {
1649 if (tp->t_fb->tfb_tcp_fb_fini)
1650 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 1);
1651 refcount_release(&tp->t_fb->tfb_refcnt);
1652 uma_zfree(V_tcpcb_zone, tm);
1653 return (NULL);
1654 }
1655 #endif
1656
1657 #ifdef VIMAGE
1658 tp->t_vnet = inp->inp_vnet;
1659 #endif
1660 tp->t_timers = &tm->tt;
1661 TAILQ_INIT(&tp->t_segq);
1662 tp->t_maxseg =
1663 #ifdef INET6
1664 isipv6 ? V_tcp_v6mssdflt :
1665 #endif /* INET6 */
1666 V_tcp_mssdflt;
1667
1668 /* Set up our timeouts. */
1669 callout_init(&tp->t_timers->tt_rexmt, 1);
1670 callout_init(&tp->t_timers->tt_persist, 1);
1671 callout_init(&tp->t_timers->tt_keep, 1);
1672 callout_init(&tp->t_timers->tt_2msl, 1);
1673 callout_init(&tp->t_timers->tt_delack, 1);
1674
1675 if (V_tcp_do_rfc1323)
1676 tp->t_flags = (TF_REQ_SCALE|TF_REQ_TSTMP);
1677 if (V_tcp_do_sack)
1678 tp->t_flags |= TF_SACK_PERMIT;
1679 TAILQ_INIT(&tp->snd_holes);
1680
1681 /*
1682 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
1683 * rtt estimate. Set rttvar so that srtt + 4 * rttvar gives
1684 * reasonable initial retransmit time.
1685 */
1686 tp->t_srtt = TCPTV_SRTTBASE;
1687 tp->t_rttvar = ((tcp_rexmit_initial - TCPTV_SRTTBASE) << TCP_RTTVAR_SHIFT) / 4;
1688 tp->t_rttmin = tcp_rexmit_min;
1689 tp->t_rxtcur = tcp_rexmit_initial;
1690 tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
1691 tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
1692 tp->t_rcvtime = ticks;
1693 /*
1694 * IPv4 TTL initialization is necessary for an IPv6 socket as well,
1695 * because the socket may be bound to an IPv6 wildcard address,
1696 * which may match an IPv4-mapped IPv6 address.
1697 */
1698 inp->inp_ip_ttl = V_ip_defttl;
1699 inp->inp_ppcb = tp;
1700 #ifdef TCPPCAP
1701 /*
1702 * Init the TCP PCAP queues.
1703 */
1704 tcp_pcap_tcpcb_init(tp);
1705 #endif
1706 #ifdef TCP_BLACKBOX
1707 /* Initialize the per-TCPCB log data. */
1708 tcp_log_tcpcbinit(tp);
1709 #endif
1710 if (tp->t_fb->tfb_tcp_fb_init) {
1711 (*tp->t_fb->tfb_tcp_fb_init)(tp);
1712 }
1713 return (tp); /* XXX */
1714 }
1715
1716 /*
1717 * Switch the congestion control algorithm back to NewReno for any active
1718 * control blocks using an algorithm which is about to go away.
1719 * This ensures the CC framework can allow the unload to proceed without leaving
1720 * any dangling pointers which would trigger a panic.
1721 * Returning non-zero would inform the CC framework that something went wrong
1722 * and it would be unsafe to allow the unload to proceed. However, there is no
1723 * way for this to occur with this implementation so we always return zero.
1724 */
1725 int
1726 tcp_ccalgounload(struct cc_algo *unload_algo)
1727 {
1728 struct cc_algo *tmpalgo;
1729 struct inpcb *inp;
1730 struct tcpcb *tp;
1731 VNET_ITERATOR_DECL(vnet_iter);
1732
1733 /*
1734 * Check all active control blocks across all network stacks and change
1735 * any that are using "unload_algo" back to NewReno. If "unload_algo"
1736 * requires cleanup code to be run, call it.
1737 */
1738 VNET_LIST_RLOCK();
1739 VNET_FOREACH(vnet_iter) {
1740 CURVNET_SET(vnet_iter);
1741 INP_INFO_WLOCK(&V_tcbinfo);
1742 /*
1743 * New connections already part way through being initialised
1744 * with the CC algo we're removing will not race with this code
1745 * because the INP_INFO_WLOCK is held during initialisation. We
1746 * therefore don't enter the loop below until the connection
1747 * list has stabilised.
1748 */
1749 CK_LIST_FOREACH(inp, &V_tcb, inp_list) {
1750 INP_WLOCK(inp);
1751 /* Important to skip tcptw structs. */
1752 if (!(inp->inp_flags & INP_TIMEWAIT) &&
1753 (tp = intotcpcb(inp)) != NULL) {
1754 /*
1755 * By holding INP_WLOCK here, we are assured
1756 * that the connection is not currently
1757 * executing inside the CC module's functions
1758 * i.e. it is safe to make the switch back to
1759 * NewReno.
1760 */
1761 if (CC_ALGO(tp) == unload_algo) {
1762 tmpalgo = CC_ALGO(tp);
1763 if (tmpalgo->cb_destroy != NULL)
1764 tmpalgo->cb_destroy(tp->ccv);
1765 CC_DATA(tp) = NULL;
1766 /*
1767 * NewReno may allocate memory on
1768 * demand for certain stateful
1769 * configuration as needed, but is
1770 * coded to never fail on memory
1771 * allocation failure so it is a safe
1772 * fallback.
1773 */
1774 CC_ALGO(tp) = &newreno_cc_algo;
1775 }
1776 }
1777 INP_WUNLOCK(inp);
1778 }
1779 INP_INFO_WUNLOCK(&V_tcbinfo);
1780 CURVNET_RESTORE();
1781 }
1782 VNET_LIST_RUNLOCK();
1783
1784 return (0);
1785 }
1786
1787 /*
1788 * Drop a TCP connection, reporting
1789 * the specified error. If connection is synchronized,
1790 * then send a RST to peer.
1791 */
1792 struct tcpcb *
1793 tcp_drop(struct tcpcb *tp, int errno)
1794 {
1795 struct socket *so = tp->t_inpcb->inp_socket;
1796
1797 INP_INFO_LOCK_ASSERT(&V_tcbinfo);
1798 INP_WLOCK_ASSERT(tp->t_inpcb);
1799
1800 if (TCPS_HAVERCVDSYN(tp->t_state)) {
1801 tcp_state_change(tp, TCPS_CLOSED);
1802 (void) tp->t_fb->tfb_tcp_output(tp);
1803 TCPSTAT_INC(tcps_drops);
1804 } else
1805 TCPSTAT_INC(tcps_conndrops);
1806 if (errno == ETIMEDOUT && tp->t_softerror)
1807 errno = tp->t_softerror;
1808 so->so_error = errno;
1809 return (tcp_close(tp));
1810 }
1811
1812 void
1813 tcp_discardcb(struct tcpcb *tp)
1814 {
1815 struct inpcb *inp = tp->t_inpcb;
1816 struct socket *so = inp->inp_socket;
1817 #ifdef INET6
1818 int isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
1819 #endif /* INET6 */
1820 int released __unused;
1821
1822 INP_WLOCK_ASSERT(inp);
1823
1824 /*
1825 * Make sure that all of our timers are stopped before we delete the
1826 * PCB.
1827 *
1828 * If stopping a timer fails, we schedule a discard function in same
1829 * callout, and the last discard function called will take care of
1830 * deleting the tcpcb.
1831 */
1832 tp->t_timers->tt_draincnt = 0;
1833 tcp_timer_stop(tp, TT_REXMT);
1834 tcp_timer_stop(tp, TT_PERSIST);
1835 tcp_timer_stop(tp, TT_KEEP);
1836 tcp_timer_stop(tp, TT_2MSL);
1837 tcp_timer_stop(tp, TT_DELACK);
1838 if (tp->t_fb->tfb_tcp_timer_stop_all) {
1839 /*
1840 * Call the stop-all function of the methods,
1841 * this function should call the tcp_timer_stop()
1842 * method with each of the function specific timeouts.
1843 * That stop will be called via the tfb_tcp_timer_stop()
1844 * which should use the async drain function of the
1845 * callout system (see tcp_var.h).
1846 */
1847 tp->t_fb->tfb_tcp_timer_stop_all(tp);
1848 }
1849
1850 /*
1851 * If we got enough samples through the srtt filter,
1852 * save the rtt and rttvar in the routing entry.
1853 * 'Enough' is arbitrarily defined as 4 rtt samples.
1854 * 4 samples is enough for the srtt filter to converge
1855 * to within enough % of the correct value; fewer samples
1856 * and we could save a bogus rtt. The danger is not high
1857 * as tcp quickly recovers from everything.
1858 * XXX: Works very well but needs some more statistics!
1859 */
1860 if (tp->t_rttupdated >= 4) {
1861 struct hc_metrics_lite metrics;
1862 uint32_t ssthresh;
1863
1864 bzero(&metrics, sizeof(metrics));
1865 /*
1866 * Update the ssthresh always when the conditions below
1867 * are satisfied. This gives us better new start value
1868 * for the congestion avoidance for new connections.
1869 * ssthresh is only set if packet loss occurred on a session.
1870 *
1871 * XXXRW: 'so' may be NULL here, and/or socket buffer may be
1872 * being torn down. Ideally this code would not use 'so'.
1873 */
1874 ssthresh = tp->snd_ssthresh;
1875 if (ssthresh != 0 && ssthresh < so->so_snd.sb_hiwat / 2) {
1876 /*
1877 * convert the limit from user data bytes to
1878 * packets then to packet data bytes.
1879 */
1880 ssthresh = (ssthresh + tp->t_maxseg / 2) / tp->t_maxseg;
1881 if (ssthresh < 2)
1882 ssthresh = 2;
1883 ssthresh *= (tp->t_maxseg +
1884 #ifdef INET6
1885 (isipv6 ? sizeof (struct ip6_hdr) +
1886 sizeof (struct tcphdr) :
1887 #endif
1888 sizeof (struct tcpiphdr)
1889 #ifdef INET6
1890 )
1891 #endif
1892 );
1893 } else
1894 ssthresh = 0;
1895 metrics.rmx_ssthresh = ssthresh;
1896
1897 metrics.rmx_rtt = tp->t_srtt;
1898 metrics.rmx_rttvar = tp->t_rttvar;
1899 metrics.rmx_cwnd = tp->snd_cwnd;
1900 metrics.rmx_sendpipe = 0;
1901 metrics.rmx_recvpipe = 0;
1902
1903 tcp_hc_update(&inp->inp_inc, &metrics);
1904 }
1905
1906 /* free the reassembly queue, if any */
1907 tcp_reass_flush(tp);
1908
1909 #ifdef TCP_OFFLOAD
1910 /* Disconnect offload device, if any. */
1911 if (tp->t_flags & TF_TOE)
1912 tcp_offload_detach(tp);
1913 #endif
1914
1915 tcp_free_sackholes(tp);
1916
1917 #ifdef TCPPCAP
1918 /* Free the TCP PCAP queues. */
1919 tcp_pcap_drain(&(tp->t_inpkts));
1920 tcp_pcap_drain(&(tp->t_outpkts));
1921 #endif
1922
1923 /* Allow the CC algorithm to clean up after itself. */
1924 if (CC_ALGO(tp)->cb_destroy != NULL)
1925 CC_ALGO(tp)->cb_destroy(tp->ccv);
1926 CC_DATA(tp) = NULL;
1927
1928 #ifdef TCP_HHOOK
1929 khelp_destroy_osd(tp->osd);
1930 #endif
1931
1932 CC_ALGO(tp) = NULL;
1933 inp->inp_ppcb = NULL;
1934 if (tp->t_timers->tt_draincnt == 0) {
1935 /* We own the last reference on tcpcb, let's free it. */
1936 #ifdef TCP_BLACKBOX
1937 tcp_log_tcpcbfini(tp);
1938 #endif
1939 TCPSTATES_DEC(tp->t_state);
1940 if (tp->t_fb->tfb_tcp_fb_fini)
1941 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 1);
1942 refcount_release(&tp->t_fb->tfb_refcnt);
1943 tp->t_inpcb = NULL;
1944 uma_zfree(V_tcpcb_zone, tp);
1945 released = in_pcbrele_wlocked(inp);
1946 KASSERT(!released, ("%s: inp %p should not have been released "
1947 "here", __func__, inp));
1948 }
1949 }
1950
1951 void
1952 tcp_timer_discard(void *ptp)
1953 {
1954 struct inpcb *inp;
1955 struct tcpcb *tp;
1956 struct epoch_tracker et;
1957
1958 tp = (struct tcpcb *)ptp;
1959 CURVNET_SET(tp->t_vnet);
1960 INP_INFO_RLOCK_ET(&V_tcbinfo, et);
1961 inp = tp->t_inpcb;
1962 KASSERT(inp != NULL, ("%s: tp %p tp->t_inpcb == NULL",
1963 __func__, tp));
1964 INP_WLOCK(inp);
1965 KASSERT((tp->t_timers->tt_flags & TT_STOPPED) != 0,
1966 ("%s: tcpcb has to be stopped here", __func__));
1967 tp->t_timers->tt_draincnt--;
1968 if (tp->t_timers->tt_draincnt == 0) {
1969 /* We own the last reference on this tcpcb, let's free it. */
1970 #ifdef TCP_BLACKBOX
1971 tcp_log_tcpcbfini(tp);
1972 #endif
1973 TCPSTATES_DEC(tp->t_state);
1974 if (tp->t_fb->tfb_tcp_fb_fini)
1975 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 1);
1976 refcount_release(&tp->t_fb->tfb_refcnt);
1977 tp->t_inpcb = NULL;
1978 uma_zfree(V_tcpcb_zone, tp);
1979 if (in_pcbrele_wlocked(inp)) {
1980 INP_INFO_RUNLOCK_ET(&V_tcbinfo, et);
1981 CURVNET_RESTORE();
1982 return;
1983 }
1984 }
1985 INP_WUNLOCK(inp);
1986 INP_INFO_RUNLOCK_ET(&V_tcbinfo, et);
1987 CURVNET_RESTORE();
1988 }
1989
1990 /*
1991 * Attempt to close a TCP control block, marking it as dropped, and freeing
1992 * the socket if we hold the only reference.
1993 */
1994 struct tcpcb *
1995 tcp_close(struct tcpcb *tp)
1996 {
1997 struct inpcb *inp = tp->t_inpcb;
1998 struct socket *so;
1999
2000 INP_INFO_LOCK_ASSERT(&V_tcbinfo);
2001 INP_WLOCK_ASSERT(inp);
2002
2003 #ifdef TCP_OFFLOAD
2004 if (tp->t_state == TCPS_LISTEN)
2005 tcp_offload_listen_stop(tp);
2006 #endif
2007 /*
2008 * This releases the TFO pending counter resource for TFO listen
2009 * sockets as well as passively-created TFO sockets that transition
2010 * from SYN_RECEIVED to CLOSED.
2011 */
2012 if (tp->t_tfo_pending) {
2013 tcp_fastopen_decrement_counter(tp->t_tfo_pending);
2014 tp->t_tfo_pending = NULL;
2015 }
2016 in_pcbdrop(inp);
2017 TCPSTAT_INC(tcps_closed);
2018 if (tp->t_state != TCPS_CLOSED)
2019 tcp_state_change(tp, TCPS_CLOSED);
2020 KASSERT(inp->inp_socket != NULL, ("tcp_close: inp_socket NULL"));
2021 so = inp->inp_socket;
2022 soisdisconnected(so);
2023 if (inp->inp_flags & INP_SOCKREF) {
2024 KASSERT(so->so_state & SS_PROTOREF,
2025 ("tcp_close: !SS_PROTOREF"));
2026 inp->inp_flags &= ~INP_SOCKREF;
2027 INP_WUNLOCK(inp);
2028 SOCK_LOCK(so);
2029 so->so_state &= ~SS_PROTOREF;
2030 sofree(so);
2031 return (NULL);
2032 }
2033 return (tp);
2034 }
2035
2036 void
2037 tcp_drain(void)
2038 {
2039 VNET_ITERATOR_DECL(vnet_iter);
2040
2041 if (!do_tcpdrain)
2042 return;
2043
2044 VNET_LIST_RLOCK_NOSLEEP();
2045 VNET_FOREACH(vnet_iter) {
2046 CURVNET_SET(vnet_iter);
2047 struct inpcb *inpb;
2048 struct tcpcb *tcpb;
2049
2050 /*
2051 * Walk the tcpbs, if existing, and flush the reassembly queue,
2052 * if there is one...
2053 * XXX: The "Net/3" implementation doesn't imply that the TCP
2054 * reassembly queue should be flushed, but in a situation
2055 * where we're really low on mbufs, this is potentially
2056 * useful.
2057 */
2058 INP_INFO_WLOCK(&V_tcbinfo);
2059 CK_LIST_FOREACH(inpb, V_tcbinfo.ipi_listhead, inp_list) {
2060 INP_WLOCK(inpb);
2061 if (inpb->inp_flags & INP_TIMEWAIT) {
2062 INP_WUNLOCK(inpb);
2063 continue;
2064 }
2065 if ((tcpb = intotcpcb(inpb)) != NULL) {
2066 tcp_reass_flush(tcpb);
2067 tcp_clean_sackreport(tcpb);
2068 #ifdef TCP_BLACKBOX
2069 tcp_log_drain(tcpb);
2070 #endif
2071 #ifdef TCPPCAP
2072 if (tcp_pcap_aggressive_free) {
2073 /* Free the TCP PCAP queues. */
2074 tcp_pcap_drain(&(tcpb->t_inpkts));
2075 tcp_pcap_drain(&(tcpb->t_outpkts));
2076 }
2077 #endif
2078 }
2079 INP_WUNLOCK(inpb);
2080 }
2081 INP_INFO_WUNLOCK(&V_tcbinfo);
2082 CURVNET_RESTORE();
2083 }
2084 VNET_LIST_RUNLOCK_NOSLEEP();
2085 }
2086
2087 /*
2088 * Notify a tcp user of an asynchronous error;
2089 * store error as soft error, but wake up user
2090 * (for now, won't do anything until can select for soft error).
2091 *
2092 * Do not wake up user since there currently is no mechanism for
2093 * reporting soft errors (yet - a kqueue filter may be added).
2094 */
2095 static struct inpcb *
2096 tcp_notify(struct inpcb *inp, int error)
2097 {
2098 struct tcpcb *tp;
2099
2100 INP_INFO_LOCK_ASSERT(&V_tcbinfo);
2101 INP_WLOCK_ASSERT(inp);
2102
2103 if ((inp->inp_flags & INP_TIMEWAIT) ||
2104 (inp->inp_flags & INP_DROPPED))
2105 return (inp);
2106
2107 tp = intotcpcb(inp);
2108 KASSERT(tp != NULL, ("tcp_notify: tp == NULL"));
2109
2110 /*
2111 * Ignore some errors if we are hooked up.
2112 * If connection hasn't completed, has retransmitted several times,
2113 * and receives a second error, give up now. This is better
2114 * than waiting a long time to establish a connection that
2115 * can never complete.
2116 */
2117 if (tp->t_state == TCPS_ESTABLISHED &&
2118 (error == EHOSTUNREACH || error == ENETUNREACH ||
2119 error == EHOSTDOWN)) {
2120 if (inp->inp_route.ro_rt) {
2121 RTFREE(inp->inp_route.ro_rt);
2122 inp->inp_route.ro_rt = (struct rtentry *)NULL;
2123 }
2124 return (inp);
2125 } else if (tp->t_state < TCPS_ESTABLISHED && tp->t_rxtshift > 3 &&
2126 tp->t_softerror) {
2127 tp = tcp_drop(tp, error);
2128 if (tp != NULL)
2129 return (inp);
2130 else
2131 return (NULL);
2132 } else {
2133 tp->t_softerror = error;
2134 return (inp);
2135 }
2136 #if 0
2137 wakeup( &so->so_timeo);
2138 sorwakeup(so);
2139 sowwakeup(so);
2140 #endif
2141 }
2142
2143 static int
2144 tcp_pcblist(SYSCTL_HANDLER_ARGS)
2145 {
2146 int error, i, m, n, pcb_count;
2147 struct inpcb *inp, **inp_list;
2148 inp_gen_t gencnt;
2149 struct xinpgen xig;
2150 struct epoch_tracker et;
2151
2152 /*
2153 * The process of preparing the TCB list is too time-consuming and
2154 * resource-intensive to repeat twice on every request.
2155 */
2156 if (req->oldptr == NULL) {
2157 n = V_tcbinfo.ipi_count +
2158 counter_u64_fetch(V_tcps_states[TCPS_SYN_RECEIVED]);
2159 n += imax(n / 8, 10);
2160 req->oldidx = 2 * (sizeof xig) + n * sizeof(struct xtcpcb);
2161 return (0);
2162 }
2163
2164 if (req->newptr != NULL)
2165 return (EPERM);
2166
2167 /*
2168 * OK, now we're committed to doing something.
2169 */
2170 INP_LIST_RLOCK(&V_tcbinfo);
2171 gencnt = V_tcbinfo.ipi_gencnt;
2172 n = V_tcbinfo.ipi_count;
2173 INP_LIST_RUNLOCK(&V_tcbinfo);
2174
2175 m = counter_u64_fetch(V_tcps_states[TCPS_SYN_RECEIVED]);
2176
2177 error = sysctl_wire_old_buffer(req, 2 * (sizeof xig)
2178 + (n + m) * sizeof(struct xtcpcb));
2179 if (error != 0)
2180 return (error);
2181
2182 bzero(&xig, sizeof(xig));
2183 xig.xig_len = sizeof xig;
2184 xig.xig_count = n + m;
2185 xig.xig_gen = gencnt;
2186 xig.xig_sogen = so_gencnt;
2187 error = SYSCTL_OUT(req, &xig, sizeof xig);
2188 if (error)
2189 return (error);
2190
2191 error = syncache_pcblist(req, m, &pcb_count);
2192 if (error)
2193 return (error);
2194
2195 inp_list = malloc(n * sizeof *inp_list, M_TEMP, M_WAITOK);
2196
2197 INP_INFO_WLOCK(&V_tcbinfo);
2198 for (inp = CK_LIST_FIRST(V_tcbinfo.ipi_listhead), i = 0;
2199 inp != NULL && i < n; inp = CK_LIST_NEXT(inp, inp_list)) {
2200 INP_WLOCK(inp);
2201 if (inp->inp_gencnt <= gencnt) {
2202 /*
2203 * XXX: This use of cr_cansee(), introduced with
2204 * TCP state changes, is not quite right, but for
2205 * now, better than nothing.
2206 */
2207 if (inp->inp_flags & INP_TIMEWAIT) {
2208 if (intotw(inp) != NULL)
2209 error = cr_cansee(req->td->td_ucred,
2210 intotw(inp)->tw_cred);
2211 else
2212 error = EINVAL; /* Skip this inp. */
2213 } else
2214 error = cr_canseeinpcb(req->td->td_ucred, inp);
2215 if (error == 0) {
2216 in_pcbref(inp);
2217 inp_list[i++] = inp;
2218 }
2219 }
2220 INP_WUNLOCK(inp);
2221 }
2222 INP_INFO_WUNLOCK(&V_tcbinfo);
2223 n = i;
2224
2225 error = 0;
2226 for (i = 0; i < n; i++) {
2227 inp = inp_list[i];
2228 INP_RLOCK(inp);
2229 if (inp->inp_gencnt <= gencnt) {
2230 struct xtcpcb xt;
2231
2232 tcp_inptoxtp(inp, &xt);
2233 INP_RUNLOCK(inp);
2234 error = SYSCTL_OUT(req, &xt, sizeof xt);
2235 } else
2236 INP_RUNLOCK(inp);
2237 }
2238 INP_INFO_RLOCK_ET(&V_tcbinfo, et);
2239 for (i = 0; i < n; i++) {
2240 inp = inp_list[i];
2241 INP_RLOCK(inp);
2242 if (!in_pcbrele_rlocked(inp))
2243 INP_RUNLOCK(inp);
2244 }
2245 INP_INFO_RUNLOCK_ET(&V_tcbinfo, et);
2246
2247 if (!error) {
2248 /*
2249 * Give the user an updated idea of our state.
2250 * If the generation differs from what we told
2251 * her before, she knows that something happened
2252 * while we were processing this request, and it
2253 * might be necessary to retry.
2254 */
2255 INP_LIST_RLOCK(&V_tcbinfo);
2256 xig.xig_gen = V_tcbinfo.ipi_gencnt;
2257 xig.xig_sogen = so_gencnt;
2258 xig.xig_count = V_tcbinfo.ipi_count + pcb_count;
2259 INP_LIST_RUNLOCK(&V_tcbinfo);
2260 error = SYSCTL_OUT(req, &xig, sizeof xig);
2261 }
2262 free(inp_list, M_TEMP);
2263 return (error);
2264 }
2265
2266 SYSCTL_PROC(_net_inet_tcp, TCPCTL_PCBLIST, pcblist,
2267 CTLTYPE_OPAQUE | CTLFLAG_RD, NULL, 0,
2268 tcp_pcblist, "S,xtcpcb", "List of active TCP connections");
2269
2270 #ifdef INET
2271 static int
2272 tcp_getcred(SYSCTL_HANDLER_ARGS)
2273 {
2274 struct xucred xuc;
2275 struct sockaddr_in addrs[2];
2276 struct inpcb *inp;
2277 int error;
2278
2279 error = priv_check(req->td, PRIV_NETINET_GETCRED);
2280 if (error)
2281 return (error);
2282 error = SYSCTL_IN(req, addrs, sizeof(addrs));
2283 if (error)
2284 return (error);
2285 inp = in_pcblookup(&V_tcbinfo, addrs[1].sin_addr, addrs[1].sin_port,
2286 addrs[0].sin_addr, addrs[0].sin_port, INPLOOKUP_RLOCKPCB, NULL);
2287 if (inp != NULL) {
2288 if (inp->inp_socket == NULL)
2289 error = ENOENT;
2290 if (error == 0)
2291 error = cr_canseeinpcb(req->td->td_ucred, inp);
2292 if (error == 0)
2293 cru2x(inp->inp_cred, &xuc);
2294 INP_RUNLOCK(inp);
2295 } else
2296 error = ENOENT;
2297 if (error == 0)
2298 error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
2299 return (error);
2300 }
2301
2302 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, getcred,
2303 CTLTYPE_OPAQUE|CTLFLAG_RW|CTLFLAG_PRISON, 0, 0,
2304 tcp_getcred, "S,xucred", "Get the xucred of a TCP connection");
2305 #endif /* INET */
2306
2307 #ifdef INET6
2308 static int
2309 tcp6_getcred(SYSCTL_HANDLER_ARGS)
2310 {
2311 struct xucred xuc;
2312 struct sockaddr_in6 addrs[2];
2313 struct inpcb *inp;
2314 int error;
2315 #ifdef INET
2316 int mapped = 0;
2317 #endif
2318
2319 error = priv_check(req->td, PRIV_NETINET_GETCRED);
2320 if (error)
2321 return (error);
2322 error = SYSCTL_IN(req, addrs, sizeof(addrs));
2323 if (error)
2324 return (error);
2325 if ((error = sa6_embedscope(&addrs[0], V_ip6_use_defzone)) != 0 ||
2326 (error = sa6_embedscope(&addrs[1], V_ip6_use_defzone)) != 0) {
2327 return (error);
2328 }
2329 if (IN6_IS_ADDR_V4MAPPED(&addrs[0].sin6_addr)) {
2330 #ifdef INET
2331 if (IN6_IS_ADDR_V4MAPPED(&addrs[1].sin6_addr))
2332 mapped = 1;
2333 else
2334 #endif
2335 return (EINVAL);
2336 }
2337
2338 #ifdef INET
2339 if (mapped == 1)
2340 inp = in_pcblookup(&V_tcbinfo,
2341 *(struct in_addr *)&addrs[1].sin6_addr.s6_addr[12],
2342 addrs[1].sin6_port,
2343 *(struct in_addr *)&addrs[0].sin6_addr.s6_addr[12],
2344 addrs[0].sin6_port, INPLOOKUP_RLOCKPCB, NULL);
2345 else
2346 #endif
2347 inp = in6_pcblookup(&V_tcbinfo,
2348 &addrs[1].sin6_addr, addrs[1].sin6_port,
2349 &addrs[0].sin6_addr, addrs[0].sin6_port,
2350 INPLOOKUP_RLOCKPCB, NULL);
2351 if (inp != NULL) {
2352 if (inp->inp_socket == NULL)
2353 error = ENOENT;
2354 if (error == 0)
2355 error = cr_canseeinpcb(req->td->td_ucred, inp);
2356 if (error == 0)
2357 cru2x(inp->inp_cred, &xuc);
2358 INP_RUNLOCK(inp);
2359 } else
2360 error = ENOENT;
2361 if (error == 0)
2362 error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
2363 return (error);
2364 }
2365
2366 SYSCTL_PROC(_net_inet6_tcp6, OID_AUTO, getcred,
2367 CTLTYPE_OPAQUE|CTLFLAG_RW|CTLFLAG_PRISON, 0, 0,
2368 tcp6_getcred, "S,xucred", "Get the xucred of a TCP6 connection");
2369 #endif /* INET6 */
2370
2371
2372 #ifdef INET
2373 void
2374 tcp_ctlinput(int cmd, struct sockaddr *sa, void *vip)
2375 {
2376 struct ip *ip = vip;
2377 struct tcphdr *th;
2378 struct in_addr faddr;
2379 struct inpcb *inp;
2380 struct tcpcb *tp;
2381 struct inpcb *(*notify)(struct inpcb *, int) = tcp_notify;
2382 struct icmp *icp;
2383 struct in_conninfo inc;
2384 struct epoch_tracker et;
2385 tcp_seq icmp_tcp_seq;
2386 int mtu;
2387
2388 faddr = ((struct sockaddr_in *)sa)->sin_addr;
2389 if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY)
2390 return;
2391
2392 if (cmd == PRC_MSGSIZE)
2393 notify = tcp_mtudisc_notify;
2394 else if (V_icmp_may_rst && (cmd == PRC_UNREACH_ADMIN_PROHIB ||
2395 cmd == PRC_UNREACH_PORT || cmd == PRC_UNREACH_PROTOCOL ||
2396 cmd == PRC_TIMXCEED_INTRANS) && ip)
2397 notify = tcp_drop_syn_sent;
2398
2399 /*
2400 * Hostdead is ugly because it goes linearly through all PCBs.
2401 * XXX: We never get this from ICMP, otherwise it makes an
2402 * excellent DoS attack on machines with many connections.
2403 */
2404 else if (cmd == PRC_HOSTDEAD)
2405 ip = NULL;
2406 else if ((unsigned)cmd >= PRC_NCMDS || inetctlerrmap[cmd] == 0)
2407 return;
2408
2409 if (ip == NULL) {
2410 in_pcbnotifyall(&V_tcbinfo, faddr, inetctlerrmap[cmd], notify);
2411 return;
2412 }
2413
2414 icp = (struct icmp *)((caddr_t)ip - offsetof(struct icmp, icmp_ip));
2415 th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
2416 INP_INFO_RLOCK_ET(&V_tcbinfo, et);
2417 inp = in_pcblookup(&V_tcbinfo, faddr, th->th_dport, ip->ip_src,
2418 th->th_sport, INPLOOKUP_WLOCKPCB, NULL);
2419 if (inp != NULL && PRC_IS_REDIRECT(cmd)) {
2420 /* signal EHOSTDOWN, as it flushes the cached route */
2421 inp = (*notify)(inp, EHOSTDOWN);
2422 goto out;
2423 }
2424 icmp_tcp_seq = th->th_seq;
2425 if (inp != NULL) {
2426 if (!(inp->inp_flags & INP_TIMEWAIT) &&
2427 !(inp->inp_flags & INP_DROPPED) &&
2428 !(inp->inp_socket == NULL)) {
2429 tp = intotcpcb(inp);
2430 if (SEQ_GEQ(ntohl(icmp_tcp_seq), tp->snd_una) &&
2431 SEQ_LT(ntohl(icmp_tcp_seq), tp->snd_max)) {
2432 if (cmd == PRC_MSGSIZE) {
2433 /*
2434 * MTU discovery:
2435 * If we got a needfrag set the MTU
2436 * in the route to the suggested new
2437 * value (if given) and then notify.
2438 */
2439 mtu = ntohs(icp->icmp_nextmtu);
2440 /*
2441 * If no alternative MTU was
2442 * proposed, try the next smaller
2443 * one.
2444 */
2445 if (!mtu)
2446 mtu = ip_next_mtu(
2447 ntohs(ip->ip_len), 1);
2448 if (mtu < V_tcp_minmss +
2449 sizeof(struct tcpiphdr))
2450 mtu = V_tcp_minmss +
2451 sizeof(struct tcpiphdr);
2452 /*
2453 * Only process the offered MTU if it
2454 * is smaller than the current one.
2455 */
2456 if (mtu < tp->t_maxseg +
2457 sizeof(struct tcpiphdr)) {
2458 bzero(&inc, sizeof(inc));
2459 inc.inc_faddr = faddr;
2460 inc.inc_fibnum =
2461 inp->inp_inc.inc_fibnum;
2462 tcp_hc_updatemtu(&inc, mtu);
2463 tcp_mtudisc(inp, mtu);
2464 }
2465 } else
2466 inp = (*notify)(inp,
2467 inetctlerrmap[cmd]);
2468 }
2469 }
2470 } else {
2471 bzero(&inc, sizeof(inc));
2472 inc.inc_fport = th->th_dport;
2473 inc.inc_lport = th->th_sport;
2474 inc.inc_faddr = faddr;
2475 inc.inc_laddr = ip->ip_src;
2476 syncache_unreach(&inc, icmp_tcp_seq);
2477 }
2478 out:
2479 if (inp != NULL)
2480 INP_WUNLOCK(inp);
2481 INP_INFO_RUNLOCK_ET(&V_tcbinfo, et);
2482 }
2483 #endif /* INET */
2484
2485 #ifdef INET6
2486 void
2487 tcp6_ctlinput(int cmd, struct sockaddr *sa, void *d)
2488 {
2489 struct in6_addr *dst;
2490 struct inpcb *(*notify)(struct inpcb *, int) = tcp_notify;
2491 struct ip6_hdr *ip6;
2492 struct mbuf *m;
2493 struct inpcb *inp;
2494 struct tcpcb *tp;
2495 struct icmp6_hdr *icmp6;
2496 struct ip6ctlparam *ip6cp = NULL;
2497 const struct sockaddr_in6 *sa6_src = NULL;
2498 struct in_conninfo inc;
2499 struct epoch_tracker et;
2500 struct tcp_ports {
2501 uint16_t th_sport;
2502 uint16_t th_dport;
2503 } t_ports;
2504 tcp_seq icmp_tcp_seq;
2505 unsigned int mtu;
2506 unsigned int off;
2507
2508 if (sa->sa_family != AF_INET6 ||
2509 sa->sa_len != sizeof(struct sockaddr_in6))
2510 return;
2511
2512 /* if the parameter is from icmp6, decode it. */
2513 if (d != NULL) {
2514 ip6cp = (struct ip6ctlparam *)d;
2515 icmp6 = ip6cp->ip6c_icmp6;
2516 m = ip6cp->ip6c_m;
2517 ip6 = ip6cp->ip6c_ip6;
2518 off = ip6cp->ip6c_off;
2519 sa6_src = ip6cp->ip6c_src;
2520 dst = ip6cp->ip6c_finaldst;
2521 } else {
2522 m = NULL;
2523 ip6 = NULL;
2524 off = 0; /* fool gcc */
2525 sa6_src = &sa6_any;
2526 dst = NULL;
2527 }
2528
2529 if (cmd == PRC_MSGSIZE)
2530 notify = tcp_mtudisc_notify;
2531 else if (V_icmp_may_rst && (cmd == PRC_UNREACH_ADMIN_PROHIB ||
2532 cmd == PRC_UNREACH_PORT || cmd == PRC_UNREACH_PROTOCOL ||
2533 cmd == PRC_TIMXCEED_INTRANS) && ip6 != NULL)
2534 notify = tcp_drop_syn_sent;
2535
2536 /*
2537 * Hostdead is ugly because it goes linearly through all PCBs.
2538 * XXX: We never get this from ICMP, otherwise it makes an
2539 * excellent DoS attack on machines with many connections.
2540 */
2541 else if (cmd == PRC_HOSTDEAD)
2542 ip6 = NULL;
2543 else if ((unsigned)cmd >= PRC_NCMDS || inet6ctlerrmap[cmd] == 0)
2544 return;
2545
2546 if (ip6 == NULL) {
2547 in6_pcbnotify(&V_tcbinfo, sa, 0,
2548 (const struct sockaddr *)sa6_src,
2549 0, cmd, NULL, notify);
2550 return;
2551 }
2552
2553 /* Check if we can safely get the ports from the tcp hdr */
2554 if (m == NULL ||
2555 (m->m_pkthdr.len <
2556 (int32_t) (off + sizeof(struct tcp_ports)))) {
2557 return;
2558 }
2559 bzero(&t_ports, sizeof(struct tcp_ports));
2560 m_copydata(m, off, sizeof(struct tcp_ports), (caddr_t)&t_ports);
2561 INP_INFO_RLOCK_ET(&V_tcbinfo, et);
2562 inp = in6_pcblookup(&V_tcbinfo, &ip6->ip6_dst, t_ports.th_dport,
2563 &ip6->ip6_src, t_ports.th_sport, INPLOOKUP_WLOCKPCB, NULL);
2564 if (inp != NULL && PRC_IS_REDIRECT(cmd)) {
2565 /* signal EHOSTDOWN, as it flushes the cached route */
2566 inp = (*notify)(inp, EHOSTDOWN);
2567 goto out;
2568 }
2569 off += sizeof(struct tcp_ports);
2570 if (m->m_pkthdr.len < (int32_t) (off + sizeof(tcp_seq))) {
2571 goto out;
2572 }
2573 m_copydata(m, off, sizeof(tcp_seq), (caddr_t)&icmp_tcp_seq);
2574 if (inp != NULL) {
2575 if (!(inp->inp_flags & INP_TIMEWAIT) &&
2576 !(inp->inp_flags & INP_DROPPED) &&
2577 !(inp->inp_socket == NULL)) {
2578 tp = intotcpcb(inp);
2579 if (SEQ_GEQ(ntohl(icmp_tcp_seq), tp->snd_una) &&
2580 SEQ_LT(ntohl(icmp_tcp_seq), tp->snd_max)) {
2581 if (cmd == PRC_MSGSIZE) {
2582 /*
2583 * MTU discovery:
2584 * If we got a needfrag set the MTU
2585 * in the route to the suggested new
2586 * value (if given) and then notify.
2587 */
2588 mtu = ntohl(icmp6->icmp6_mtu);
2589 /*
2590 * If no alternative MTU was
2591 * proposed, or the proposed
2592 * MTU was too small, set to
2593 * the min.
2594 */
2595 if (mtu < IPV6_MMTU)
2596 mtu = IPV6_MMTU - 8;
2597 bzero(&inc, sizeof(inc));
2598 inc.inc_fibnum = M_GETFIB(m);
2599 inc.inc_flags |= INC_ISIPV6;
2600 inc.inc6_faddr = *dst;
2601 if (in6_setscope(&inc.inc6_faddr,
2602 m->m_pkthdr.rcvif, NULL))
2603 goto out;
2604 /*
2605 * Only process the offered MTU if it
2606 * is smaller than the current one.
2607 */
2608 if (mtu < tp->t_maxseg +
2609 sizeof (struct tcphdr) +
2610 sizeof (struct ip6_hdr)) {
2611 tcp_hc_updatemtu(&inc, mtu);
2612 tcp_mtudisc(inp, mtu);
2613 ICMP6STAT_INC(icp6s_pmtuchg);
2614 }
2615 } else
2616 inp = (*notify)(inp,
2617 inet6ctlerrmap[cmd]);
2618 }
2619 }
2620 } else {
2621 bzero(&inc, sizeof(inc));
2622 inc.inc_fibnum = M_GETFIB(m);
2623 inc.inc_flags |= INC_ISIPV6;
2624 inc.inc_fport = t_ports.th_dport;
2625 inc.inc_lport = t_ports.th_sport;
2626 inc.inc6_faddr = *dst;
2627 inc.inc6_laddr = ip6->ip6_src;
2628 syncache_unreach(&inc, icmp_tcp_seq);
2629 }
2630 out:
2631 if (inp != NULL)
2632 INP_WUNLOCK(inp);
2633 INP_INFO_RUNLOCK_ET(&V_tcbinfo, et);
2634 }
2635 #endif /* INET6 */
2636
2637 static uint32_t
2638 tcp_keyed_hash(struct in_conninfo *inc, u_char *key, u_int len)
2639 {
2640 MD5_CTX ctx;
2641 uint32_t hash[4];
2642
2643 MD5Init(&ctx);
2644 MD5Update(&ctx, &inc->inc_fport, sizeof(uint16_t));
2645 MD5Update(&ctx, &inc->inc_lport, sizeof(uint16_t));
2646 switch (inc->inc_flags & INC_ISIPV6) {
2647 #ifdef INET
2648 case 0:
2649 MD5Update(&ctx, &inc->inc_faddr, sizeof(struct in_addr));
2650 MD5Update(&ctx, &inc->inc_laddr, sizeof(struct in_addr));
2651 break;
2652 #endif
2653 #ifdef INET6
2654 case INC_ISIPV6:
2655 MD5Update(&ctx, &inc->inc6_faddr, sizeof(struct in6_addr));
2656 MD5Update(&ctx, &inc->inc6_laddr, sizeof(struct in6_addr));
2657 break;
2658 #endif
2659 }
2660 MD5Update(&ctx, key, len);
2661 MD5Final((unsigned char *)hash, &ctx);
2662
2663 return (hash[0]);
2664 }
2665
2666 uint32_t
2667 tcp_new_ts_offset(struct in_conninfo *inc)
2668 {
2669 struct in_conninfo inc_store, *local_inc;
2670
2671 if (!V_tcp_ts_offset_per_conn) {
2672 memcpy(&inc_store, inc, sizeof(struct in_conninfo));
2673 inc_store.inc_lport = 0;
2674 inc_store.inc_fport = 0;
2675 local_inc = &inc_store;
2676 } else {
2677 local_inc = inc;
2678 }
2679 return (tcp_keyed_hash(local_inc, V_ts_offset_secret,
2680 sizeof(V_ts_offset_secret)));
2681 }
2682
2683 /*
2684 * Following is where TCP initial sequence number generation occurs.
2685 *
2686 * There are two places where we must use initial sequence numbers:
2687 * 1. In SYN-ACK packets.
2688 * 2. In SYN packets.
2689 *
2690 * All ISNs for SYN-ACK packets are generated by the syncache. See
2691 * tcp_syncache.c for details.
2692 *
2693 * The ISNs in SYN packets must be monotonic; TIME_WAIT recycling
2694 * depends on this property. In addition, these ISNs should be
2695 * unguessable so as to prevent connection hijacking. To satisfy
2696 * the requirements of this situation, the algorithm outlined in
2697 * RFC 1948 is used, with only small modifications.
2698 *
2699 * Implementation details:
2700 *
2701 * Time is based off the system timer, and is corrected so that it
2702 * increases by one megabyte per second. This allows for proper
2703 * recycling on high speed LANs while still leaving over an hour
2704 * before rollover.
2705 *
2706 * As reading the *exact* system time is too expensive to be done
2707 * whenever setting up a TCP connection, we increment the time
2708 * offset in two ways. First, a small random positive increment
2709 * is added to isn_offset for each connection that is set up.
2710 * Second, the function tcp_isn_tick fires once per clock tick
2711 * and increments isn_offset as necessary so that sequence numbers
2712 * are incremented at approximately ISN_BYTES_PER_SECOND. The
2713 * random positive increments serve only to ensure that the same
2714 * exact sequence number is never sent out twice (as could otherwise
2715 * happen when a port is recycled in less than the system tick
2716 * interval.)
2717 *
2718 * net.inet.tcp.isn_reseed_interval controls the number of seconds
2719 * between seeding of isn_secret. This is normally set to zero,
2720 * as reseeding should not be necessary.
2721 *
2722 * Locking of the global variables isn_secret, isn_last_reseed, isn_offset,
2723 * isn_offset_old, and isn_ctx is performed using the ISN lock. In
2724 * general, this means holding an exclusive (write) lock.
2725 */
2726
2727 #define ISN_BYTES_PER_SECOND 1048576
2728 #define ISN_STATIC_INCREMENT 4096
2729 #define ISN_RANDOM_INCREMENT (4096 - 1)
2730 #define ISN_SECRET_LENGTH 32
2731
2732 VNET_DEFINE_STATIC(u_char, isn_secret[ISN_SECRET_LENGTH]);
2733 VNET_DEFINE_STATIC(int, isn_last);
2734 VNET_DEFINE_STATIC(int, isn_last_reseed);
2735 VNET_DEFINE_STATIC(u_int32_t, isn_offset);
2736 VNET_DEFINE_STATIC(u_int32_t, isn_offset_old);
2737
2738 #define V_isn_secret VNET(isn_secret)
2739 #define V_isn_last VNET(isn_last)
2740 #define V_isn_last_reseed VNET(isn_last_reseed)
2741 #define V_isn_offset VNET(isn_offset)
2742 #define V_isn_offset_old VNET(isn_offset_old)
2743
2744 tcp_seq
2745 tcp_new_isn(struct in_conninfo *inc)
2746 {
2747 tcp_seq new_isn;
2748 u_int32_t projected_offset;
2749
2750 ISN_LOCK();
2751 /* Seed if this is the first use, reseed if requested. */
2752 if ((V_isn_last_reseed == 0) || ((V_tcp_isn_reseed_interval > 0) &&
2753 (((u_int)V_isn_last_reseed + (u_int)V_tcp_isn_reseed_interval*hz)
2754 < (u_int)ticks))) {
2755 arc4rand(&V_isn_secret, sizeof(V_isn_secret), 0);
2756 V_isn_last_reseed = ticks;
2757 }
2758
2759 /* Compute the md5 hash and return the ISN. */
2760 new_isn = (tcp_seq)tcp_keyed_hash(inc, V_isn_secret,
2761 sizeof(V_isn_secret));
2762 V_isn_offset += ISN_STATIC_INCREMENT +
2763 (arc4random() & ISN_RANDOM_INCREMENT);
2764 if (ticks != V_isn_last) {
2765 projected_offset = V_isn_offset_old +
2766 ISN_BYTES_PER_SECOND / hz * (ticks - V_isn_last);
2767 if (SEQ_GT(projected_offset, V_isn_offset))
2768 V_isn_offset = projected_offset;
2769 V_isn_offset_old = V_isn_offset;
2770 V_isn_last = ticks;
2771 }
2772 new_isn += V_isn_offset;
2773 ISN_UNLOCK();
2774 return (new_isn);
2775 }
2776
2777 /*
2778 * When a specific ICMP unreachable message is received and the
2779 * connection state is SYN-SENT, drop the connection. This behavior
2780 * is controlled by the icmp_may_rst sysctl.
2781 */
2782 struct inpcb *
2783 tcp_drop_syn_sent(struct inpcb *inp, int errno)
2784 {
2785 struct tcpcb *tp;
2786
2787 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2788 INP_WLOCK_ASSERT(inp);
2789
2790 if ((inp->inp_flags & INP_TIMEWAIT) ||
2791 (inp->inp_flags & INP_DROPPED))
2792 return (inp);
2793
2794 tp = intotcpcb(inp);
2795 if (tp->t_state != TCPS_SYN_SENT)
2796 return (inp);
2797
2798 if (IS_FASTOPEN(tp->t_flags))
2799 tcp_fastopen_disable_path(tp);
2800
2801 tp = tcp_drop(tp, errno);
2802 if (tp != NULL)
2803 return (inp);
2804 else
2805 return (NULL);
2806 }
2807
2808 /*
2809 * When `need fragmentation' ICMP is received, update our idea of the MSS
2810 * based on the new value. Also nudge TCP to send something, since we
2811 * know the packet we just sent was dropped.
2812 * This duplicates some code in the tcp_mss() function in tcp_input.c.
2813 */
2814 static struct inpcb *
2815 tcp_mtudisc_notify(struct inpcb *inp, int error)
2816 {
2817
2818 tcp_mtudisc(inp, -1);
2819 return (inp);
2820 }
2821
2822 static void
2823 tcp_mtudisc(struct inpcb *inp, int mtuoffer)
2824 {
2825 struct tcpcb *tp;
2826 struct socket *so;
2827
2828 INP_WLOCK_ASSERT(inp);
2829 if ((inp->inp_flags & INP_TIMEWAIT) ||
2830 (inp->inp_flags & INP_DROPPED))
2831 return;
2832
2833 tp = intotcpcb(inp);
2834 KASSERT(tp != NULL, ("tcp_mtudisc: tp == NULL"));
2835
2836 tcp_mss_update(tp, -1, mtuoffer, NULL, NULL);
2837
2838 so = inp->inp_socket;
2839 SOCKBUF_LOCK(&so->so_snd);
2840 /* If the mss is larger than the socket buffer, decrease the mss. */
2841 if (so->so_snd.sb_hiwat < tp->t_maxseg)
2842 tp->t_maxseg = so->so_snd.sb_hiwat;
2843 SOCKBUF_UNLOCK(&so->so_snd);
2844
2845 TCPSTAT_INC(tcps_mturesent);
2846 tp->t_rtttime = 0;
2847 tp->snd_nxt = tp->snd_una;
2848 tcp_free_sackholes(tp);
2849 tp->snd_recover = tp->snd_max;
2850 if (tp->t_flags & TF_SACK_PERMIT)
2851 EXIT_FASTRECOVERY(tp->t_flags);
2852 tp->t_fb->tfb_tcp_output(tp);
2853 }
2854
2855 #ifdef INET
2856 /*
2857 * Look-up the routing entry to the peer of this inpcb. If no route
2858 * is found and it cannot be allocated, then return 0. This routine
2859 * is called by TCP routines that access the rmx structure and by
2860 * tcp_mss_update to get the peer/interface MTU.
2861 */
2862 uint32_t
2863 tcp_maxmtu(struct in_conninfo *inc, struct tcp_ifcap *cap)
2864 {
2865 struct nhop4_extended nh4;
2866 struct ifnet *ifp;
2867 uint32_t maxmtu = 0;
2868
2869 KASSERT(inc != NULL, ("tcp_maxmtu with NULL in_conninfo pointer"));
2870
2871 if (inc->inc_faddr.s_addr != INADDR_ANY) {
2872
2873 if (fib4_lookup_nh_ext(inc->inc_fibnum, inc->inc_faddr,
2874 NHR_REF, 0, &nh4) != 0)
2875 return (0);
2876
2877 ifp = nh4.nh_ifp;
2878 maxmtu = nh4.nh_mtu;
2879
2880 /* Report additional interface capabilities. */
2881 if (cap != NULL) {
2882 if (ifp->if_capenable & IFCAP_TSO4 &&
2883 ifp->if_hwassist & CSUM_TSO) {
2884 cap->ifcap |= CSUM_TSO;
2885 cap->tsomax = ifp->if_hw_tsomax;
2886 cap->tsomaxsegcount = ifp->if_hw_tsomaxsegcount;
2887 cap->tsomaxsegsize = ifp->if_hw_tsomaxsegsize;
2888 }
2889 }
2890 fib4_free_nh_ext(inc->inc_fibnum, &nh4);
2891 }
2892 return (maxmtu);
2893 }
2894 #endif /* INET */
2895
2896 #ifdef INET6
2897 uint32_t
2898 tcp_maxmtu6(struct in_conninfo *inc, struct tcp_ifcap *cap)
2899 {
2900 struct nhop6_extended nh6;
2901 struct in6_addr dst6;
2902 uint32_t scopeid;
2903 struct ifnet *ifp;
2904 uint32_t maxmtu = 0;
2905
2906 KASSERT(inc != NULL, ("tcp_maxmtu6 with NULL in_conninfo pointer"));
2907
2908 if (inc->inc_flags & INC_IPV6MINMTU)
2909 return (IPV6_MMTU);
2910
2911 if (!IN6_IS_ADDR_UNSPECIFIED(&inc->inc6_faddr)) {
2912 in6_splitscope(&inc->inc6_faddr, &dst6, &scopeid);
2913 if (fib6_lookup_nh_ext(inc->inc_fibnum, &dst6, scopeid, 0,
2914 0, &nh6) != 0)
2915 return (0);
2916
2917 ifp = nh6.nh_ifp;
2918 maxmtu = nh6.nh_mtu;
2919
2920 /* Report additional interface capabilities. */
2921 if (cap != NULL) {
2922 if (ifp->if_capenable & IFCAP_TSO6 &&
2923 ifp->if_hwassist & CSUM_TSO) {
2924 cap->ifcap |= CSUM_TSO;
2925 cap->tsomax = ifp->if_hw_tsomax;
2926 cap->tsomaxsegcount = ifp->if_hw_tsomaxsegcount;
2927 cap->tsomaxsegsize = ifp->if_hw_tsomaxsegsize;
2928 }
2929 }
2930 fib6_free_nh_ext(inc->inc_fibnum, &nh6);
2931 }
2932
2933 return (maxmtu);
2934 }
2935 #endif /* INET6 */
2936
2937 /*
2938 * Calculate effective SMSS per RFC5681 definition for a given TCP
2939 * connection at its current state, taking into account SACK and etc.
2940 */
2941 u_int
2942 tcp_maxseg(const struct tcpcb *tp)
2943 {
2944 u_int optlen;
2945
2946 if (tp->t_flags & TF_NOOPT)
2947 return (tp->t_maxseg);
2948
2949 /*
2950 * Here we have a simplified code from tcp_addoptions(),
2951 * without a proper loop, and having most of paddings hardcoded.
2952 * We might make mistakes with padding here in some edge cases,
2953 * but this is harmless, since result of tcp_maxseg() is used
2954 * only in cwnd and ssthresh estimations.
2955 */
2956 if (TCPS_HAVEESTABLISHED(tp->t_state)) {
2957 if (tp->t_flags & TF_RCVD_TSTMP)
2958 optlen = TCPOLEN_TSTAMP_APPA;
2959 else
2960 optlen = 0;
2961 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
2962 if (tp->t_flags & TF_SIGNATURE)
2963 optlen += PADTCPOLEN(TCPOLEN_SIGNATURE);
2964 #endif
2965 if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks > 0) {
2966 optlen += TCPOLEN_SACKHDR;
2967 optlen += tp->rcv_numsacks * TCPOLEN_SACK;
2968 optlen = PADTCPOLEN(optlen);
2969 }
2970 } else {
2971 if (tp->t_flags & TF_REQ_TSTMP)
2972 optlen = TCPOLEN_TSTAMP_APPA;
2973 else
2974 optlen = PADTCPOLEN(TCPOLEN_MAXSEG);
2975 if (tp->t_flags & TF_REQ_SCALE)
2976 optlen += PADTCPOLEN(TCPOLEN_WINDOW);
2977 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
2978 if (tp->t_flags & TF_SIGNATURE)
2979 optlen += PADTCPOLEN(TCPOLEN_SIGNATURE);
2980 #endif
2981 if (tp->t_flags & TF_SACK_PERMIT)
2982 optlen += PADTCPOLEN(TCPOLEN_SACK_PERMITTED);
2983 }
2984 #undef PAD
2985 optlen = min(optlen, TCP_MAXOLEN);
2986 return (tp->t_maxseg - optlen);
2987 }
2988
2989 static int
2990 sysctl_drop(SYSCTL_HANDLER_ARGS)
2991 {
2992 /* addrs[0] is a foreign socket, addrs[1] is a local one. */
2993 struct sockaddr_storage addrs[2];
2994 struct inpcb *inp;
2995 struct tcpcb *tp;
2996 struct tcptw *tw;
2997 struct sockaddr_in *fin, *lin;
2998 struct epoch_tracker et;
2999 #ifdef INET6
3000 struct sockaddr_in6 *fin6, *lin6;
3001 #endif
3002 int error;
3003
3004 inp = NULL;
3005 fin = lin = NULL;
3006 #ifdef INET6
3007 fin6 = lin6 = NULL;
3008 #endif
3009 error = 0;
3010
3011 if (req->oldptr != NULL || req->oldlen != 0)
3012 return (EINVAL);
3013 if (req->newptr == NULL)
3014 return (EPERM);
3015 if (req->newlen < sizeof(addrs))
3016 return (ENOMEM);
3017 error = SYSCTL_IN(req, &addrs, sizeof(addrs));
3018 if (error)
3019 return (error);
3020
3021 switch (addrs[0].ss_family) {
3022 #ifdef INET6
3023 case AF_INET6:
3024 fin6 = (struct sockaddr_in6 *)&addrs[0];
3025 lin6 = (struct sockaddr_in6 *)&addrs[1];
3026 if (fin6->sin6_len != sizeof(struct sockaddr_in6) ||
3027 lin6->sin6_len != sizeof(struct sockaddr_in6))
3028 return (EINVAL);
3029 if (IN6_IS_ADDR_V4MAPPED(&fin6->sin6_addr)) {
3030 if (!IN6_IS_ADDR_V4MAPPED(&lin6->sin6_addr))
3031 return (EINVAL);
3032 in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[0]);
3033 in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[1]);
3034 fin = (struct sockaddr_in *)&addrs[0];
3035 lin = (struct sockaddr_in *)&addrs[1];
3036 break;
3037 }
3038 error = sa6_embedscope(fin6, V_ip6_use_defzone);
3039 if (error)
3040 return (error);
3041 error = sa6_embedscope(lin6, V_ip6_use_defzone);
3042 if (error)
3043 return (error);
3044 break;
3045 #endif
3046 #ifdef INET
3047 case AF_INET:
3048 fin = (struct sockaddr_in *)&addrs[0];
3049 lin = (struct sockaddr_in *)&addrs[1];
3050 if (fin->sin_len != sizeof(struct sockaddr_in) ||
3051 lin->sin_len != sizeof(struct sockaddr_in))
3052 return (EINVAL);
3053 break;
3054 #endif
3055 default:
3056 return (EINVAL);
3057 }
3058 INP_INFO_RLOCK_ET(&V_tcbinfo, et);
3059 switch (addrs[0].ss_family) {
3060 #ifdef INET6
3061 case AF_INET6:
3062 inp = in6_pcblookup(&V_tcbinfo, &fin6->sin6_addr,
3063 fin6->sin6_port, &lin6->sin6_addr, lin6->sin6_port,
3064 INPLOOKUP_WLOCKPCB, NULL);
3065 break;
3066 #endif
3067 #ifdef INET
3068 case AF_INET:
3069 inp = in_pcblookup(&V_tcbinfo, fin->sin_addr, fin->sin_port,
3070 lin->sin_addr, lin->sin_port, INPLOOKUP_WLOCKPCB, NULL);
3071 break;
3072 #endif
3073 }
3074 if (inp != NULL) {
3075 if (inp->inp_flags & INP_TIMEWAIT) {
3076 /*
3077 * XXXRW: There currently exists a state where an
3078 * inpcb is present, but its timewait state has been
3079 * discarded. For now, don't allow dropping of this
3080 * type of inpcb.
3081 */
3082 tw = intotw(inp);
3083 if (tw != NULL)
3084 tcp_twclose(tw, 0);
3085 else
3086 INP_WUNLOCK(inp);
3087 } else if (!(inp->inp_flags & INP_DROPPED) &&
3088 !(inp->inp_socket->so_options & SO_ACCEPTCONN)) {
3089 tp = intotcpcb(inp);
3090 tp = tcp_drop(tp, ECONNABORTED);
3091 if (tp != NULL)
3092 INP_WUNLOCK(inp);
3093 } else
3094 INP_WUNLOCK(inp);
3095 } else
3096 error = ESRCH;
3097 INP_INFO_RUNLOCK_ET(&V_tcbinfo, et);
3098 return (error);
3099 }
3100
3101 SYSCTL_PROC(_net_inet_tcp, TCPCTL_DROP, drop,
3102 CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP, NULL,
3103 0, sysctl_drop, "", "Drop TCP connection");
3104
3105 /*
3106 * Generate a standardized TCP log line for use throughout the
3107 * tcp subsystem. Memory allocation is done with M_NOWAIT to
3108 * allow use in the interrupt context.
3109 *
3110 * NB: The caller MUST free(s, M_TCPLOG) the returned string.
3111 * NB: The function may return NULL if memory allocation failed.
3112 *
3113 * Due to header inclusion and ordering limitations the struct ip
3114 * and ip6_hdr pointers have to be passed as void pointers.
3115 */
3116 char *
3117 tcp_log_vain(struct in_conninfo *inc, struct tcphdr *th, void *ip4hdr,
3118 const void *ip6hdr)
3119 {
3120
3121 /* Is logging enabled? */
3122 if (V_tcp_log_in_vain == 0)
3123 return (NULL);
3124
3125 return (tcp_log_addr(inc, th, ip4hdr, ip6hdr));
3126 }
3127
3128 char *
3129 tcp_log_addrs(struct in_conninfo *inc, struct tcphdr *th, void *ip4hdr,
3130 const void *ip6hdr)
3131 {
3132
3133 /* Is logging enabled? */
3134 if (tcp_log_debug == 0)
3135 return (NULL);
3136
3137 return (tcp_log_addr(inc, th, ip4hdr, ip6hdr));
3138 }
3139
3140 static char *
3141 tcp_log_addr(struct in_conninfo *inc, struct tcphdr *th, void *ip4hdr,
3142 const void *ip6hdr)
3143 {
3144 char *s, *sp;
3145 size_t size;
3146 struct ip *ip;
3147 #ifdef INET6
3148 const struct ip6_hdr *ip6;
3149
3150 ip6 = (const struct ip6_hdr *)ip6hdr;
3151 #endif /* INET6 */
3152 ip = (struct ip *)ip4hdr;
3153
3154 /*
3155 * The log line looks like this:
3156 * "TCP: [1.2.3.4]:50332 to [1.2.3.4]:80 tcpflags 0x2<SYN>"
3157 */
3158 size = sizeof("TCP: []:12345 to []:12345 tcpflags 0x2<>") +
3159 sizeof(PRINT_TH_FLAGS) + 1 +
3160 #ifdef INET6
3161 2 * INET6_ADDRSTRLEN;
3162 #else
3163 2 * INET_ADDRSTRLEN;
3164 #endif /* INET6 */
3165
3166 s = malloc(size, M_TCPLOG, M_ZERO|M_NOWAIT);
3167 if (s == NULL)
3168 return (NULL);
3169
3170 strcat(s, "TCP: [");
3171 sp = s + strlen(s);
3172
3173 if (inc && ((inc->inc_flags & INC_ISIPV6) == 0)) {
3174 inet_ntoa_r(inc->inc_faddr, sp);
3175 sp = s + strlen(s);
3176 sprintf(sp, "]:%i to [", ntohs(inc->inc_fport));
3177 sp = s + strlen(s);
3178 inet_ntoa_r(inc->inc_laddr, sp);
3179 sp = s + strlen(s);
3180 sprintf(sp, "]:%i", ntohs(inc->inc_lport));
3181 #ifdef INET6
3182 } else if (inc) {
3183 ip6_sprintf(sp, &inc->inc6_faddr);
3184 sp = s + strlen(s);
3185 sprintf(sp, "]:%i to [", ntohs(inc->inc_fport));
3186 sp = s + strlen(s);
3187 ip6_sprintf(sp, &inc->inc6_laddr);
3188 sp = s + strlen(s);
3189 sprintf(sp, "]:%i", ntohs(inc->inc_lport));
3190 } else if (ip6 && th) {
3191 ip6_sprintf(sp, &ip6->ip6_src);
3192 sp = s + strlen(s);
3193 sprintf(sp, "]:%i to [", ntohs(th->th_sport));
3194 sp = s + strlen(s);
3195 ip6_sprintf(sp, &ip6->ip6_dst);
3196 sp = s + strlen(s);
3197 sprintf(sp, "]:%i", ntohs(th->th_dport));
3198 #endif /* INET6 */
3199 #ifdef INET
3200 } else if (ip && th) {
3201 inet_ntoa_r(ip->ip_src, sp);
3202 sp = s + strlen(s);
3203 sprintf(sp, "]:%i to [", ntohs(th->th_sport));
3204 sp = s + strlen(s);
3205 inet_ntoa_r(ip->ip_dst, sp);
3206 sp = s + strlen(s);
3207 sprintf(sp, "]:%i", ntohs(th->th_dport));
3208 #endif /* INET */
3209 } else {
3210 free(s, M_TCPLOG);
3211 return (NULL);
3212 }
3213 sp = s + strlen(s);
3214 if (th)
3215 sprintf(sp, " tcpflags 0x%b", th->th_flags, PRINT_TH_FLAGS);
3216 if (*(s + size - 1) != '\0')
3217 panic("%s: string too long", __func__);
3218 return (s);
3219 }
3220
3221 /*
3222 * A subroutine which makes it easy to track TCP state changes with DTrace.
3223 * This function shouldn't be called for t_state initializations that don't
3224 * correspond to actual TCP state transitions.
3225 */
3226 void
3227 tcp_state_change(struct tcpcb *tp, int newstate)
3228 {
3229 #if defined(KDTRACE_HOOKS)
3230 int pstate = tp->t_state;
3231 #endif
3232
3233 TCPSTATES_DEC(tp->t_state);
3234 TCPSTATES_INC(newstate);
3235 tp->t_state = newstate;
3236 TCP_PROBE6(state__change, NULL, tp, NULL, tp, NULL, pstate);
3237 }
3238
3239 /*
3240 * Create an external-format (``xtcpcb'') structure using the information in
3241 * the kernel-format tcpcb structure pointed to by tp. This is done to
3242 * reduce the spew of irrelevant information over this interface, to isolate
3243 * user code from changes in the kernel structure, and potentially to provide
3244 * information-hiding if we decide that some of this information should be
3245 * hidden from users.
3246 */
3247 void
3248 tcp_inptoxtp(const struct inpcb *inp, struct xtcpcb *xt)
3249 {
3250 struct tcpcb *tp = intotcpcb(inp);
3251 sbintime_t now;
3252
3253 bzero(xt, sizeof(*xt));
3254 if (inp->inp_flags & INP_TIMEWAIT) {
3255 xt->t_state = TCPS_TIME_WAIT;
3256 } else {
3257 xt->t_state = tp->t_state;
3258 xt->t_logstate = tp->t_logstate;
3259 xt->t_flags = tp->t_flags;
3260 xt->t_sndzerowin = tp->t_sndzerowin;
3261 xt->t_sndrexmitpack = tp->t_sndrexmitpack;
3262 xt->t_rcvoopack = tp->t_rcvoopack;
3263 xt->t_rcv_wnd = tp->rcv_wnd;
3264 xt->t_snd_wnd = tp->snd_wnd;
3265 xt->t_snd_cwnd = tp->snd_cwnd;
3266 xt->t_snd_ssthresh = tp->snd_ssthresh;
3267 xt->t_maxseg = tp->t_maxseg;
3268 xt->xt_ecn = (tp->t_flags & TF_ECN_PERMIT) ? 1 : 0;
3269
3270 now = getsbinuptime();
3271 #define COPYTIMER(ttt) do { \
3272 if (callout_active(&tp->t_timers->ttt)) \
3273 xt->ttt = (tp->t_timers->ttt.c_time - now) / \
3274 SBT_1MS; \
3275 else \
3276 xt->ttt = 0; \
3277 } while (0)
3278 COPYTIMER(tt_delack);
3279 COPYTIMER(tt_rexmt);
3280 COPYTIMER(tt_persist);
3281 COPYTIMER(tt_keep);
3282 COPYTIMER(tt_2msl);
3283 #undef COPYTIMER
3284 xt->t_rcvtime = 1000 * (ticks - tp->t_rcvtime) / hz;
3285
3286 bcopy(tp->t_fb->tfb_tcp_block_name, xt->xt_stack,
3287 TCP_FUNCTION_NAME_LEN_MAX);
3288 bcopy(CC_ALGO(tp)->name, xt->xt_cc,
3289 TCP_CA_NAME_MAX);
3290 #ifdef TCP_BLACKBOX
3291 (void)tcp_log_get_id(tp, xt->xt_logid);
3292 #endif
3293 }
3294
3295 xt->xt_len = sizeof(struct xtcpcb);
3296 in_pcbtoxinpcb(inp, &xt->xt_inp);
3297 if (inp->inp_socket == NULL)
3298 xt->xt_inp.xi_socket.xso_protocol = IPPROTO_TCP;
3299 }
Cache object: 3c8e83699a396b04a3a5d46e5b8e9d8b
|