1 /*-
2 * SPDX-License-Identifier: BSD-3-Clause
3 *
4 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
5 * The Regents of the University of California. All rights reserved.
6 * Copyright (c) 2007-2008,2010
7 * Swinburne University of Technology, Melbourne, Australia.
8 * Copyright (c) 2009-2010 Lawrence Stewart <lstewart@freebsd.org>
9 * Copyright (c) 2010 The FreeBSD Foundation
10 * Copyright (c) 2010-2011 Juniper Networks, Inc.
11 * All rights reserved.
12 *
13 * Portions of this software were developed at the Centre for Advanced Internet
14 * Architectures, Swinburne University of Technology, by Lawrence Stewart,
15 * James Healy and David Hayes, made possible in part by a grant from the Cisco
16 * University Research Program Fund at Community Foundation Silicon Valley.
17 *
18 * Portions of this software were developed at the Centre for Advanced
19 * Internet Architectures, Swinburne University of Technology, Melbourne,
20 * Australia by David Hayes under sponsorship from the FreeBSD Foundation.
21 *
22 * Portions of this software were developed by Robert N. M. Watson under
23 * contract to Juniper Networks, Inc.
24 *
25 * Redistribution and use in source and binary forms, with or without
26 * modification, are permitted provided that the following conditions
27 * are met:
28 * 1. Redistributions of source code must retain the above copyright
29 * notice, this list of conditions and the following disclaimer.
30 * 2. Redistributions in binary form must reproduce the above copyright
31 * notice, this list of conditions and the following disclaimer in the
32 * documentation and/or other materials provided with the distribution.
33 * 3. Neither the name of the University nor the names of its contributors
34 * may be used to endorse or promote products derived from this software
35 * without specific prior written permission.
36 *
37 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
38 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
39 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
40 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
41 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
42 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
43 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
44 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
45 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
46 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47 * SUCH DAMAGE.
48 *
49 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
50 */
51
52 #include <sys/cdefs.h>
53 __FBSDID("$FreeBSD: stable/12/sys/netinet/tcp_input.c 373171 2023-08-14 09:40:09Z rscheff $");
54
55 #include "opt_inet.h"
56 #include "opt_inet6.h"
57 #include "opt_ipsec.h"
58 #include "opt_tcpdebug.h"
59
60 #include <sys/param.h>
61 #include <sys/kernel.h>
62 #ifdef TCP_HHOOK
63 #include <sys/hhook.h>
64 #endif
65 #include <sys/malloc.h>
66 #include <sys/mbuf.h>
67 #include <sys/proc.h> /* for proc0 declaration */
68 #include <sys/protosw.h>
69 #include <sys/sdt.h>
70 #include <sys/signalvar.h>
71 #include <sys/socket.h>
72 #include <sys/socketvar.h>
73 #include <sys/sysctl.h>
74 #include <sys/syslog.h>
75 #include <sys/systm.h>
76
77 #include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
78
79 #include <vm/uma.h>
80
81 #include <net/if.h>
82 #include <net/if_var.h>
83 #include <net/route.h>
84 #include <net/vnet.h>
85
86 #define TCPSTATES /* for logging */
87
88 #include <netinet/in.h>
89 #include <netinet/in_kdtrace.h>
90 #include <netinet/in_pcb.h>
91 #include <netinet/in_systm.h>
92 #include <netinet/ip.h>
93 #include <netinet/ip_icmp.h> /* required for icmp_var.h */
94 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
95 #include <netinet/ip_var.h>
96 #include <netinet/ip_options.h>
97 #include <netinet/ip6.h>
98 #include <netinet/icmp6.h>
99 #include <netinet6/in6_pcb.h>
100 #include <netinet6/in6_var.h>
101 #include <netinet6/ip6_var.h>
102 #include <netinet6/nd6.h>
103 #include <netinet/tcp.h>
104 #include <netinet/tcp_fsm.h>
105 #include <netinet/tcp_log_buf.h>
106 #include <netinet/tcp_seq.h>
107 #include <netinet/tcp_timer.h>
108 #include <netinet/tcp_var.h>
109 #include <netinet6/tcp6_var.h>
110 #include <netinet/tcpip.h>
111 #include <netinet/cc/cc.h>
112 #include <netinet/tcp_fastopen.h>
113 #ifdef TCPPCAP
114 #include <netinet/tcp_pcap.h>
115 #endif
116 #include <netinet/tcp_syncache.h>
117 #ifdef TCPDEBUG
118 #include <netinet/tcp_debug.h>
119 #endif /* TCPDEBUG */
120 #ifdef TCP_OFFLOAD
121 #include <netinet/tcp_offload.h>
122 #endif
123
124 #include <netipsec/ipsec_support.h>
125
126 #include <machine/in_cksum.h>
127
128 #include <security/mac/mac_framework.h>
129
130 const int tcprexmtthresh = 3;
131
132 VNET_DEFINE(int, tcp_log_in_vain) = 0;
133 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_VNET | CTLFLAG_RW,
134 &VNET_NAME(tcp_log_in_vain), 0,
135 "Log all incoming TCP segments to closed ports");
136
137 VNET_DEFINE(int, blackhole) = 0;
138 #define V_blackhole VNET(blackhole)
139 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_VNET | CTLFLAG_RW,
140 &VNET_NAME(blackhole), 0,
141 "Do not send RST on segments to closed ports");
142
143 VNET_DEFINE(int, tcp_delack_enabled) = 1;
144 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_VNET | CTLFLAG_RW,
145 &VNET_NAME(tcp_delack_enabled), 0,
146 "Delay ACK to try and piggyback it onto a data packet");
147
148 VNET_DEFINE(int, drop_synfin) = 0;
149 SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_VNET | CTLFLAG_RW,
150 &VNET_NAME(drop_synfin), 0,
151 "Drop TCP packets with SYN+FIN set");
152
153 VNET_DEFINE(int, tcp_do_rfc6675_pipe) = 0;
154 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc6675_pipe, CTLFLAG_VNET | CTLFLAG_RW,
155 &VNET_NAME(tcp_do_rfc6675_pipe), 0,
156 "Use calculated pipe/in-flight bytes per RFC 6675");
157
158 VNET_DEFINE(int, tcp_do_rfc3042) = 1;
159 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3042, CTLFLAG_VNET | CTLFLAG_RW,
160 &VNET_NAME(tcp_do_rfc3042), 0,
161 "Enable RFC 3042 (Limited Transmit)");
162
163 VNET_DEFINE(int, tcp_do_rfc3390) = 1;
164 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_VNET | CTLFLAG_RW,
165 &VNET_NAME(tcp_do_rfc3390), 0,
166 "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
167
168 VNET_DEFINE(int, tcp_initcwnd_segments) = 10;
169 SYSCTL_INT(_net_inet_tcp, OID_AUTO, initcwnd_segments,
170 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(tcp_initcwnd_segments), 0,
171 "Slow-start flight size (initial congestion window) in number of segments");
172
173 VNET_DEFINE(int, tcp_do_rfc3465) = 1;
174 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3465, CTLFLAG_VNET | CTLFLAG_RW,
175 &VNET_NAME(tcp_do_rfc3465), 0,
176 "Enable RFC 3465 (Appropriate Byte Counting)");
177
178 VNET_DEFINE(int, tcp_abc_l_var) = 2;
179 SYSCTL_INT(_net_inet_tcp, OID_AUTO, abc_l_var, CTLFLAG_VNET | CTLFLAG_RW,
180 &VNET_NAME(tcp_abc_l_var), 2,
181 "Cap the max cwnd increment during slow-start to this number of segments");
182
183 static SYSCTL_NODE(_net_inet_tcp, OID_AUTO, ecn, CTLFLAG_RW, 0, "TCP ECN");
184
185 VNET_DEFINE(int, tcp_do_ecn) = 2;
186 SYSCTL_INT(_net_inet_tcp_ecn, OID_AUTO, enable, CTLFLAG_VNET | CTLFLAG_RW,
187 &VNET_NAME(tcp_do_ecn), 0,
188 "TCP ECN support");
189
190 VNET_DEFINE(int, tcp_ecn_maxretries) = 1;
191 SYSCTL_INT(_net_inet_tcp_ecn, OID_AUTO, maxretries, CTLFLAG_VNET | CTLFLAG_RW,
192 &VNET_NAME(tcp_ecn_maxretries), 0,
193 "Max retries before giving up on ECN");
194
195 VNET_DEFINE(int, tcp_insecure_syn) = 0;
196 SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_syn, CTLFLAG_VNET | CTLFLAG_RW,
197 &VNET_NAME(tcp_insecure_syn), 0,
198 "Follow RFC793 instead of RFC5961 criteria for accepting SYN packets");
199
200 VNET_DEFINE(int, tcp_insecure_rst) = 0;
201 SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_rst, CTLFLAG_VNET | CTLFLAG_RW,
202 &VNET_NAME(tcp_insecure_rst), 0,
203 "Follow RFC793 instead of RFC5961 criteria for accepting RST packets");
204
205 VNET_DEFINE(int, tcp_recvspace) = 1024*64;
206 #define V_tcp_recvspace VNET(tcp_recvspace)
207 SYSCTL_INT(_net_inet_tcp, TCPCTL_RECVSPACE, recvspace, CTLFLAG_VNET | CTLFLAG_RW,
208 &VNET_NAME(tcp_recvspace), 0, "Initial receive socket buffer size");
209
210 VNET_DEFINE(int, tcp_do_autorcvbuf) = 1;
211 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_VNET | CTLFLAG_RW,
212 &VNET_NAME(tcp_do_autorcvbuf), 0,
213 "Enable automatic receive buffer sizing");
214
215 VNET_DEFINE(int, tcp_autorcvbuf_inc) = 16*1024;
216 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_inc, CTLFLAG_VNET | CTLFLAG_RW,
217 &VNET_NAME(tcp_autorcvbuf_inc), 0,
218 "Incrementor step size of automatic receive buffer");
219
220 VNET_DEFINE(int, tcp_autorcvbuf_max) = 2*1024*1024;
221 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_VNET | CTLFLAG_RW,
222 &VNET_NAME(tcp_autorcvbuf_max), 0,
223 "Max size of automatic receive buffer");
224
225 VNET_DEFINE(struct inpcbhead, tcb);
226 #define tcb6 tcb /* for KAME src sync over BSD*'s */
227 VNET_DEFINE(struct inpcbinfo, tcbinfo);
228
229 /*
230 * TCP statistics are stored in an array of counter(9)s, which size matches
231 * size of struct tcpstat. TCP running connection count is a regular array.
232 */
233 VNET_PCPUSTAT_DEFINE(struct tcpstat, tcpstat);
234 SYSCTL_VNET_PCPUSTAT(_net_inet_tcp, TCPCTL_STATS, stats, struct tcpstat,
235 tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
236 VNET_DEFINE(counter_u64_t, tcps_states[TCP_NSTATES]);
237 SYSCTL_COUNTER_U64_ARRAY(_net_inet_tcp, TCPCTL_STATES, states, CTLFLAG_RD |
238 CTLFLAG_VNET, &VNET_NAME(tcps_states)[0], TCP_NSTATES,
239 "TCP connection counts by TCP state");
240
241 static void
tcp_vnet_init(const void * unused)242 tcp_vnet_init(const void *unused)
243 {
244
245 COUNTER_ARRAY_ALLOC(V_tcps_states, TCP_NSTATES, M_WAITOK);
246 VNET_PCPUSTAT_ALLOC(tcpstat, M_WAITOK);
247 }
248 VNET_SYSINIT(tcp_vnet_init, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY,
249 tcp_vnet_init, NULL);
250
251 #ifdef VIMAGE
252 static void
tcp_vnet_uninit(const void * unused)253 tcp_vnet_uninit(const void *unused)
254 {
255
256 COUNTER_ARRAY_FREE(V_tcps_states, TCP_NSTATES);
257 VNET_PCPUSTAT_FREE(tcpstat);
258 }
259 VNET_SYSUNINIT(tcp_vnet_uninit, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY,
260 tcp_vnet_uninit, NULL);
261 #endif /* VIMAGE */
262
263 /*
264 * Kernel module interface for updating tcpstat. The argument is an index
265 * into tcpstat treated as an array.
266 */
267 void
kmod_tcpstat_inc(int statnum)268 kmod_tcpstat_inc(int statnum)
269 {
270
271 counter_u64_add(VNET(tcpstat)[statnum], 1);
272 }
273
274 #ifdef TCP_HHOOK
275 /*
276 * Wrapper for the TCP established input helper hook.
277 */
278 void
hhook_run_tcp_est_in(struct tcpcb * tp,struct tcphdr * th,struct tcpopt * to)279 hhook_run_tcp_est_in(struct tcpcb *tp, struct tcphdr *th, struct tcpopt *to)
280 {
281 struct tcp_hhook_data hhook_data;
282
283 if (V_tcp_hhh[HHOOK_TCP_EST_IN]->hhh_nhooks > 0) {
284 hhook_data.tp = tp;
285 hhook_data.th = th;
286 hhook_data.to = to;
287
288 hhook_run_hooks(V_tcp_hhh[HHOOK_TCP_EST_IN], &hhook_data,
289 tp->osd);
290 }
291 }
292 #endif
293
294 /*
295 * CC wrapper hook functions
296 */
297 void
cc_ack_received(struct tcpcb * tp,struct tcphdr * th,uint16_t nsegs,uint16_t type)298 cc_ack_received(struct tcpcb *tp, struct tcphdr *th, uint16_t nsegs,
299 uint16_t type)
300 {
301 INP_WLOCK_ASSERT(tp->t_inpcb);
302
303 tp->ccv->nsegs = nsegs;
304 tp->ccv->bytes_this_ack = BYTES_THIS_ACK(tp, th);
305 if (tp->snd_cwnd <= tp->snd_wnd)
306 tp->ccv->flags |= CCF_CWND_LIMITED;
307 else
308 tp->ccv->flags &= ~CCF_CWND_LIMITED;
309
310 if (type == CC_ACK) {
311 if (tp->snd_cwnd > tp->snd_ssthresh) {
312 tp->t_bytes_acked += tp->ccv->bytes_this_ack;
313 if (tp->t_bytes_acked >= tp->snd_cwnd) {
314 tp->t_bytes_acked -= tp->snd_cwnd;
315 tp->ccv->flags |= CCF_ABC_SENTAWND;
316 }
317 } else {
318 tp->ccv->flags &= ~CCF_ABC_SENTAWND;
319 tp->t_bytes_acked = 0;
320 }
321 }
322
323 if (CC_ALGO(tp)->ack_received != NULL) {
324 /* XXXLAS: Find a way to live without this */
325 tp->ccv->curack = th->th_ack;
326 CC_ALGO(tp)->ack_received(tp->ccv, type);
327 }
328 }
329
330 void
cc_conn_init(struct tcpcb * tp)331 cc_conn_init(struct tcpcb *tp)
332 {
333 struct hc_metrics_lite metrics;
334 struct inpcb *inp = tp->t_inpcb;
335 u_int maxseg;
336 int rtt;
337
338 INP_WLOCK_ASSERT(tp->t_inpcb);
339
340 tcp_hc_get(&inp->inp_inc, &metrics);
341 maxseg = tcp_maxseg(tp);
342
343 if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
344 tp->t_srtt = rtt;
345 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
346 TCPSTAT_INC(tcps_usedrtt);
347 if (metrics.rmx_rttvar) {
348 tp->t_rttvar = metrics.rmx_rttvar;
349 TCPSTAT_INC(tcps_usedrttvar);
350 } else {
351 /* default variation is +- 1 rtt */
352 tp->t_rttvar =
353 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
354 }
355 TCPT_RANGESET(tp->t_rxtcur,
356 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
357 tp->t_rttmin, TCPTV_REXMTMAX);
358 }
359 if (metrics.rmx_ssthresh) {
360 /*
361 * There's some sort of gateway or interface
362 * buffer limit on the path. Use this to set
363 * the slow start threshold, but set the
364 * threshold to no less than 2*mss.
365 */
366 tp->snd_ssthresh = max(2 * maxseg, metrics.rmx_ssthresh);
367 TCPSTAT_INC(tcps_usedssthresh);
368 }
369
370 /*
371 * Set the initial slow-start flight size.
372 *
373 * RFC5681 Section 3.1 specifies the default conservative values.
374 * RFC3390 specifies slightly more aggressive values.
375 * RFC6928 increases it to ten segments.
376 * Support for user specified value for initial flight size.
377 *
378 * If a SYN or SYN/ACK was lost and retransmitted, we have to
379 * reduce the initial CWND to one segment as congestion is likely
380 * requiring us to be cautious.
381 */
382 if (tp->snd_cwnd == 1)
383 tp->snd_cwnd = maxseg; /* SYN(-ACK) lost */
384 else if (V_tcp_initcwnd_segments)
385 tp->snd_cwnd = min(V_tcp_initcwnd_segments * maxseg,
386 max(2 * maxseg, V_tcp_initcwnd_segments * 1460));
387 else if (V_tcp_do_rfc3390)
388 tp->snd_cwnd = min(4 * maxseg, max(2 * maxseg, 4380));
389 else {
390 /* Per RFC5681 Section 3.1 */
391 if (maxseg > 2190)
392 tp->snd_cwnd = 2 * maxseg;
393 else if (maxseg > 1095)
394 tp->snd_cwnd = 3 * maxseg;
395 else
396 tp->snd_cwnd = 4 * maxseg;
397 }
398
399 if (CC_ALGO(tp)->conn_init != NULL)
400 CC_ALGO(tp)->conn_init(tp->ccv);
401 }
402
403 void inline
cc_cong_signal(struct tcpcb * tp,struct tcphdr * th,uint32_t type)404 cc_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type)
405 {
406 INP_WLOCK_ASSERT(tp->t_inpcb);
407
408 switch(type) {
409 case CC_NDUPACK:
410 if (!IN_FASTRECOVERY(tp->t_flags)) {
411 tp->snd_recover = tp->snd_max;
412 if (tp->t_flags & TF_ECN_PERMIT)
413 tp->t_flags |= TF_ECN_SND_CWR;
414 }
415 break;
416 case CC_ECN:
417 if (!IN_CONGRECOVERY(tp->t_flags) ||
418 /*
419 * Allow ECN reaction on ACK to CWR, if
420 * that data segment was also CE marked.
421 */
422 SEQ_GEQ(th->th_ack, tp->snd_recover)) {
423 EXIT_CONGRECOVERY(tp->t_flags);
424 TCPSTAT_INC(tcps_ecn_rcwnd);
425 tp->snd_recover = tp->snd_max + 1;
426 if (tp->t_flags & TF_ECN_PERMIT)
427 tp->t_flags |= TF_ECN_SND_CWR;
428 }
429 break;
430 case CC_RTO:
431 tp->t_dupacks = 0;
432 tp->t_bytes_acked = 0;
433 EXIT_RECOVERY(tp->t_flags);
434 if (tp->t_flags & TF_ECN_PERMIT)
435 tp->t_flags |= TF_ECN_SND_CWR;
436 break;
437 case CC_RTO_ERR:
438 TCPSTAT_INC(tcps_sndrexmitbad);
439 /* RTO was unnecessary, so reset everything. */
440 tp->snd_cwnd = tp->snd_cwnd_prev;
441 tp->snd_ssthresh = tp->snd_ssthresh_prev;
442 tp->snd_recover = tp->snd_recover_prev;
443 if (tp->t_flags & TF_WASFRECOVERY)
444 ENTER_FASTRECOVERY(tp->t_flags);
445 if (tp->t_flags & TF_WASCRECOVERY)
446 ENTER_CONGRECOVERY(tp->t_flags);
447 tp->snd_nxt = tp->snd_max;
448 tp->t_flags &= ~TF_PREVVALID;
449 tp->t_badrxtwin = 0;
450 break;
451 }
452
453 if (CC_ALGO(tp)->cong_signal != NULL) {
454 if (th != NULL)
455 tp->ccv->curack = th->th_ack;
456 CC_ALGO(tp)->cong_signal(tp->ccv, type);
457 }
458 }
459
460 void inline
cc_post_recovery(struct tcpcb * tp,struct tcphdr * th)461 cc_post_recovery(struct tcpcb *tp, struct tcphdr *th)
462 {
463 INP_WLOCK_ASSERT(tp->t_inpcb);
464
465 /* XXXLAS: KASSERT that we're in recovery? */
466
467 if (CC_ALGO(tp)->post_recovery != NULL) {
468 tp->ccv->curack = th->th_ack;
469 CC_ALGO(tp)->post_recovery(tp->ccv);
470 }
471 /* XXXLAS: EXIT_RECOVERY ? */
472 tp->t_bytes_acked = 0;
473 }
474
475 /*
476 * Indicate whether this ack should be delayed. We can delay the ack if
477 * following conditions are met:
478 * - There is no delayed ack timer in progress.
479 * - Our last ack wasn't a 0-sized window. We never want to delay
480 * the ack that opens up a 0-sized window.
481 * - LRO wasn't used for this segment. We make sure by checking that the
482 * segment size is not larger than the MSS.
483 */
484 #define DELAY_ACK(tp, tlen) \
485 ((!tcp_timer_active(tp, TT_DELACK) && \
486 (tp->t_flags & TF_RXWIN0SENT) == 0) && \
487 (tlen <= tp->t_maxseg) && \
488 (V_tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
489
490 void inline
cc_ecnpkt_handler(struct tcpcb * tp,struct tcphdr * th,uint8_t iptos)491 cc_ecnpkt_handler(struct tcpcb *tp, struct tcphdr *th, uint8_t iptos)
492 {
493 INP_WLOCK_ASSERT(tp->t_inpcb);
494
495 if (CC_ALGO(tp)->ecnpkt_handler != NULL) {
496 switch (iptos & IPTOS_ECN_MASK) {
497 case IPTOS_ECN_CE:
498 tp->ccv->flags |= CCF_IPHDR_CE;
499 break;
500 case IPTOS_ECN_ECT0:
501 /* FALLTHROUGH */
502 case IPTOS_ECN_ECT1:
503 /* FALLTHROUGH */
504 case IPTOS_ECN_NOTECT:
505 tp->ccv->flags &= ~CCF_IPHDR_CE;
506 break;
507 }
508
509 if (th->th_flags & TH_CWR)
510 tp->ccv->flags |= CCF_TCPHDR_CWR;
511 else
512 tp->ccv->flags &= ~CCF_TCPHDR_CWR;
513
514 CC_ALGO(tp)->ecnpkt_handler(tp->ccv);
515
516 if (tp->ccv->flags & CCF_ACKNOW) {
517 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
518 tp->t_flags |= TF_ACKNOW;
519 }
520 }
521 }
522
523 /*
524 * TCP input handling is split into multiple parts:
525 * tcp6_input is a thin wrapper around tcp_input for the extended
526 * ip6_protox[] call format in ip6_input
527 * tcp_input handles primary segment validation, inpcb lookup and
528 * SYN processing on listen sockets
529 * tcp_do_segment processes the ACK and text of the segment for
530 * establishing, established and closing connections
531 */
532 #ifdef INET6
533 int
tcp6_input(struct mbuf ** mp,int * offp,int proto)534 tcp6_input(struct mbuf **mp, int *offp, int proto)
535 {
536 struct mbuf *m;
537 struct in6_ifaddr *ia6;
538 struct ip6_hdr *ip6;
539
540 m = *mp;
541 if (m->m_len < *offp + sizeof(struct tcphdr)) {
542 m = m_pullup(m, *offp + sizeof(struct tcphdr));
543 if (m == NULL) {
544 *mp = m;
545 TCPSTAT_INC(tcps_rcvshort);
546 return (IPPROTO_DONE);
547 }
548 }
549
550 /*
551 * draft-itojun-ipv6-tcp-to-anycast
552 * better place to put this in?
553 */
554 ip6 = mtod(m, struct ip6_hdr *);
555 ia6 = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */);
556 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
557
558 ifa_free(&ia6->ia_ifa);
559 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
560 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
561 *mp = NULL;
562 return (IPPROTO_DONE);
563 }
564 if (ia6)
565 ifa_free(&ia6->ia_ifa);
566
567 *mp = m;
568 return (tcp_input(mp, offp, proto));
569 }
570 #endif /* INET6 */
571
572 int
tcp_input(struct mbuf ** mp,int * offp,int proto)573 tcp_input(struct mbuf **mp, int *offp, int proto)
574 {
575 struct mbuf *m = *mp;
576 struct tcphdr *th = NULL;
577 struct ip *ip = NULL;
578 struct inpcb *inp = NULL;
579 struct tcpcb *tp = NULL;
580 struct socket *so = NULL;
581 u_char *optp = NULL;
582 int off0;
583 int optlen = 0;
584 #ifdef INET
585 int len;
586 uint8_t ipttl;
587 #endif
588 int tlen = 0, off;
589 int drop_hdrlen;
590 int thflags;
591 int rstreason = 0; /* For badport_bandlim accounting purposes */
592 uint8_t iptos;
593 struct m_tag *fwd_tag = NULL;
594 struct epoch_tracker et;
595 #ifdef INET6
596 struct ip6_hdr *ip6 = NULL;
597 int isipv6;
598 #else
599 const void *ip6 = NULL;
600 #endif /* INET6 */
601 struct tcpopt to; /* options in this segment */
602 char *s = NULL; /* address and port logging */
603 int ti_locked;
604 #ifdef TCPDEBUG
605 /*
606 * The size of tcp_saveipgen must be the size of the max ip header,
607 * now IPv6.
608 */
609 u_char tcp_saveipgen[IP6_HDR_LEN];
610 struct tcphdr tcp_savetcp;
611 short ostate = 0;
612 #endif
613
614 #ifdef INET6
615 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
616 #endif
617
618 off0 = *offp;
619 m = *mp;
620 *mp = NULL;
621 to.to_flags = 0;
622 TCPSTAT_INC(tcps_rcvtotal);
623
624 #ifdef INET6
625 if (isipv6) {
626
627 ip6 = mtod(m, struct ip6_hdr *);
628 th = (struct tcphdr *)((caddr_t)ip6 + off0);
629 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
630 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID_IPV6) {
631 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
632 th->th_sum = m->m_pkthdr.csum_data;
633 else
634 th->th_sum = in6_cksum_pseudo(ip6, tlen,
635 IPPROTO_TCP, m->m_pkthdr.csum_data);
636 th->th_sum ^= 0xffff;
637 } else
638 th->th_sum = in6_cksum(m, IPPROTO_TCP, off0, tlen);
639 if (th->th_sum) {
640 TCPSTAT_INC(tcps_rcvbadsum);
641 goto drop;
642 }
643
644 /*
645 * Be proactive about unspecified IPv6 address in source.
646 * As we use all-zero to indicate unbounded/unconnected pcb,
647 * unspecified IPv6 address can be used to confuse us.
648 *
649 * Note that packets with unspecified IPv6 destination is
650 * already dropped in ip6_input.
651 */
652 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
653 /* XXX stat */
654 goto drop;
655 }
656 iptos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
657 }
658 #endif
659 #if defined(INET) && defined(INET6)
660 else
661 #endif
662 #ifdef INET
663 {
664 /*
665 * Get IP and TCP header together in first mbuf.
666 * Note: IP leaves IP header in first mbuf.
667 */
668 if (off0 > sizeof (struct ip)) {
669 ip_stripoptions(m);
670 off0 = sizeof(struct ip);
671 }
672 if (m->m_len < sizeof (struct tcpiphdr)) {
673 if ((m = m_pullup(m, sizeof (struct tcpiphdr)))
674 == NULL) {
675 TCPSTAT_INC(tcps_rcvshort);
676 return (IPPROTO_DONE);
677 }
678 }
679 ip = mtod(m, struct ip *);
680 th = (struct tcphdr *)((caddr_t)ip + off0);
681 tlen = ntohs(ip->ip_len) - off0;
682
683 iptos = ip->ip_tos;
684 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
685 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
686 th->th_sum = m->m_pkthdr.csum_data;
687 else
688 th->th_sum = in_pseudo(ip->ip_src.s_addr,
689 ip->ip_dst.s_addr,
690 htonl(m->m_pkthdr.csum_data + tlen +
691 IPPROTO_TCP));
692 th->th_sum ^= 0xffff;
693 } else {
694 struct ipovly *ipov = (struct ipovly *)ip;
695
696 /*
697 * Checksum extended TCP header and data.
698 */
699 len = off0 + tlen;
700 ipttl = ip->ip_ttl;
701 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
702 ipov->ih_len = htons(tlen);
703 th->th_sum = in_cksum(m, len);
704 /* Reset length for SDT probes. */
705 ip->ip_len = htons(len);
706 /* Reset TOS bits */
707 ip->ip_tos = iptos;
708 /* Re-initialization for later version check */
709 ip->ip_ttl = ipttl;
710 ip->ip_v = IPVERSION;
711 ip->ip_hl = off0 >> 2;
712 }
713
714 if (th->th_sum) {
715 TCPSTAT_INC(tcps_rcvbadsum);
716 goto drop;
717 }
718 }
719 #endif /* INET */
720
721 /*
722 * Check that TCP offset makes sense,
723 * pull out TCP options and adjust length. XXX
724 */
725 off = th->th_off << 2;
726 if (off < sizeof (struct tcphdr) || off > tlen) {
727 TCPSTAT_INC(tcps_rcvbadoff);
728 goto drop;
729 }
730 tlen -= off; /* tlen is used instead of ti->ti_len */
731 if (off > sizeof (struct tcphdr)) {
732 #ifdef INET6
733 if (isipv6) {
734 if (m->m_len < off0 + off) {
735 m = m_pullup(m, off0 + off);
736 if (m == NULL) {
737 TCPSTAT_INC(tcps_rcvshort);
738 return (IPPROTO_DONE);
739 }
740 }
741 ip6 = mtod(m, struct ip6_hdr *);
742 th = (struct tcphdr *)((caddr_t)ip6 + off0);
743 }
744 #endif
745 #if defined(INET) && defined(INET6)
746 else
747 #endif
748 #ifdef INET
749 {
750 if (m->m_len < sizeof(struct ip) + off) {
751 if ((m = m_pullup(m, sizeof (struct ip) + off))
752 == NULL) {
753 TCPSTAT_INC(tcps_rcvshort);
754 return (IPPROTO_DONE);
755 }
756 ip = mtod(m, struct ip *);
757 th = (struct tcphdr *)((caddr_t)ip + off0);
758 }
759 }
760 #endif
761 optlen = off - sizeof (struct tcphdr);
762 optp = (u_char *)(th + 1);
763 }
764 thflags = th->th_flags;
765
766 /*
767 * Convert TCP protocol specific fields to host format.
768 */
769 tcp_fields_to_host(th);
770
771 /*
772 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options.
773 */
774 drop_hdrlen = off0 + off;
775
776 /*
777 * Locate pcb for segment; if we're likely to add or remove a
778 * connection then first acquire pcbinfo lock. There are three cases
779 * where we might discover later we need a write lock despite the
780 * flags: ACKs moving a connection out of the syncache, ACKs for a
781 * connection in TIMEWAIT and SYNs not targeting a listening socket.
782 */
783 if ((thflags & (TH_FIN | TH_RST)) != 0) {
784 INP_INFO_RLOCK_ET(&V_tcbinfo, et);
785 ti_locked = TI_RLOCKED;
786 } else
787 ti_locked = TI_UNLOCKED;
788
789 /*
790 * Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain.
791 */
792 if (
793 #ifdef INET6
794 (isipv6 && (m->m_flags & M_IP6_NEXTHOP))
795 #ifdef INET
796 || (!isipv6 && (m->m_flags & M_IP_NEXTHOP))
797 #endif
798 #endif
799 #if defined(INET) && !defined(INET6)
800 (m->m_flags & M_IP_NEXTHOP)
801 #endif
802 )
803 fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
804
805 findpcb:
806 #ifdef INVARIANTS
807 if (ti_locked == TI_RLOCKED) {
808 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
809 } else {
810 INP_INFO_WUNLOCK_ASSERT(&V_tcbinfo);
811 }
812 #endif
813 #ifdef INET6
814 if (isipv6 && fwd_tag != NULL) {
815 struct sockaddr_in6 *next_hop6;
816
817 next_hop6 = (struct sockaddr_in6 *)(fwd_tag + 1);
818 /*
819 * Transparently forwarded. Pretend to be the destination.
820 * Already got one like this?
821 */
822 inp = in6_pcblookup_mbuf(&V_tcbinfo,
823 &ip6->ip6_src, th->th_sport, &ip6->ip6_dst, th->th_dport,
824 INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif, m);
825 if (!inp) {
826 /*
827 * It's new. Try to find the ambushing socket.
828 * Because we've rewritten the destination address,
829 * any hardware-generated hash is ignored.
830 */
831 inp = in6_pcblookup(&V_tcbinfo, &ip6->ip6_src,
832 th->th_sport, &next_hop6->sin6_addr,
833 next_hop6->sin6_port ? ntohs(next_hop6->sin6_port) :
834 th->th_dport, INPLOOKUP_WILDCARD |
835 INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif);
836 }
837 } else if (isipv6) {
838 inp = in6_pcblookup_mbuf(&V_tcbinfo, &ip6->ip6_src,
839 th->th_sport, &ip6->ip6_dst, th->th_dport,
840 INPLOOKUP_WILDCARD | INPLOOKUP_WLOCKPCB,
841 m->m_pkthdr.rcvif, m);
842 }
843 #endif /* INET6 */
844 #if defined(INET6) && defined(INET)
845 else
846 #endif
847 #ifdef INET
848 if (fwd_tag != NULL) {
849 struct sockaddr_in *next_hop;
850
851 next_hop = (struct sockaddr_in *)(fwd_tag+1);
852 /*
853 * Transparently forwarded. Pretend to be the destination.
854 * already got one like this?
855 */
856 inp = in_pcblookup_mbuf(&V_tcbinfo, ip->ip_src, th->th_sport,
857 ip->ip_dst, th->th_dport, INPLOOKUP_WLOCKPCB,
858 m->m_pkthdr.rcvif, m);
859 if (!inp) {
860 /*
861 * It's new. Try to find the ambushing socket.
862 * Because we've rewritten the destination address,
863 * any hardware-generated hash is ignored.
864 */
865 inp = in_pcblookup(&V_tcbinfo, ip->ip_src,
866 th->th_sport, next_hop->sin_addr,
867 next_hop->sin_port ? ntohs(next_hop->sin_port) :
868 th->th_dport, INPLOOKUP_WILDCARD |
869 INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif);
870 }
871 } else
872 inp = in_pcblookup_mbuf(&V_tcbinfo, ip->ip_src,
873 th->th_sport, ip->ip_dst, th->th_dport,
874 INPLOOKUP_WILDCARD | INPLOOKUP_WLOCKPCB,
875 m->m_pkthdr.rcvif, m);
876 #endif /* INET */
877
878 /*
879 * If the INPCB does not exist then all data in the incoming
880 * segment is discarded and an appropriate RST is sent back.
881 * XXX MRT Send RST using which routing table?
882 */
883 if (inp == NULL) {
884 /*
885 * Log communication attempts to ports that are not
886 * in use.
887 */
888 if ((V_tcp_log_in_vain == 1 && (thflags & TH_SYN)) ||
889 V_tcp_log_in_vain == 2) {
890 if ((s = tcp_log_vain(NULL, th, (void *)ip, ip6)))
891 log(LOG_INFO, "%s; %s: Connection attempt "
892 "to closed port\n", s, __func__);
893 }
894 /*
895 * When blackholing do not respond with a RST but
896 * completely ignore the segment and drop it.
897 */
898 if ((V_blackhole == 1 && (thflags & TH_SYN)) ||
899 V_blackhole == 2)
900 goto dropunlock;
901
902 rstreason = BANDLIM_RST_CLOSEDPORT;
903 goto dropwithreset;
904 }
905 INP_WLOCK_ASSERT(inp);
906 /*
907 * While waiting for inp lock during the lookup, another thread
908 * can have dropped the inpcb, in which case we need to loop back
909 * and try to find a new inpcb to deliver to.
910 */
911 if (inp->inp_flags & INP_DROPPED) {
912 INP_WUNLOCK(inp);
913 inp = NULL;
914 goto findpcb;
915 }
916 if ((inp->inp_flowtype == M_HASHTYPE_NONE) &&
917 (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE) &&
918 ((inp->inp_socket == NULL) ||
919 (inp->inp_socket->so_options & SO_ACCEPTCONN) == 0)) {
920 inp->inp_flowid = m->m_pkthdr.flowid;
921 inp->inp_flowtype = M_HASHTYPE_GET(m);
922 }
923 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
924 #ifdef INET6
925 if (isipv6 && IPSEC_ENABLED(ipv6) &&
926 IPSEC_CHECK_POLICY(ipv6, m, inp) != 0) {
927 goto dropunlock;
928 }
929 #ifdef INET
930 else
931 #endif
932 #endif /* INET6 */
933 #ifdef INET
934 if (IPSEC_ENABLED(ipv4) &&
935 IPSEC_CHECK_POLICY(ipv4, m, inp) != 0) {
936 goto dropunlock;
937 }
938 #endif /* INET */
939 #endif /* IPSEC */
940
941 /*
942 * Check the minimum TTL for socket.
943 */
944 if (inp->inp_ip_minttl != 0) {
945 #ifdef INET6
946 if (isipv6) {
947 if (inp->inp_ip_minttl > ip6->ip6_hlim)
948 goto dropunlock;
949 } else
950 #endif
951 if (inp->inp_ip_minttl > ip->ip_ttl)
952 goto dropunlock;
953 }
954
955 /*
956 * A previous connection in TIMEWAIT state is supposed to catch stray
957 * or duplicate segments arriving late. If this segment was a
958 * legitimate new connection attempt, the old INPCB gets removed and
959 * we can try again to find a listening socket.
960 *
961 * At this point, due to earlier optimism, we may hold only an inpcb
962 * lock, and not the inpcbinfo write lock. If so, we need to try to
963 * acquire it, or if that fails, acquire a reference on the inpcb,
964 * drop all locks, acquire a global write lock, and then re-acquire
965 * the inpcb lock. We may at that point discover that another thread
966 * has tried to free the inpcb, in which case we need to loop back
967 * and try to find a new inpcb to deliver to.
968 *
969 * XXXRW: It may be time to rethink timewait locking.
970 */
971 if (inp->inp_flags & INP_TIMEWAIT) {
972 if (ti_locked == TI_UNLOCKED) {
973 INP_INFO_RLOCK_ET(&V_tcbinfo, et);
974 ti_locked = TI_RLOCKED;
975 }
976 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
977
978 tcp_dooptions(&to, optp, optlen,
979 (thflags & TH_SYN) ? TO_SYN : 0);
980 /*
981 * NB: tcp_twcheck unlocks the INP and frees the mbuf.
982 */
983 if (tcp_twcheck(inp, &to, th, m, tlen))
984 goto findpcb;
985 INP_INFO_RUNLOCK_ET(&V_tcbinfo, et);
986 return (IPPROTO_DONE);
987 }
988 /*
989 * The TCPCB may no longer exist if the connection is winding
990 * down or it is in the CLOSED state. Either way we drop the
991 * segment and send an appropriate response.
992 */
993 tp = intotcpcb(inp);
994 if (tp == NULL || tp->t_state == TCPS_CLOSED) {
995 rstreason = BANDLIM_RST_CLOSEDPORT;
996 goto dropwithreset;
997 }
998
999 #ifdef TCP_OFFLOAD
1000 if (tp->t_flags & TF_TOE) {
1001 tcp_offload_input(tp, m);
1002 m = NULL; /* consumed by the TOE driver */
1003 goto dropunlock;
1004 }
1005 #endif
1006
1007 /*
1008 * We've identified a valid inpcb, but it could be that we need an
1009 * inpcbinfo write lock but don't hold it. In this case, attempt to
1010 * acquire using the same strategy as the TIMEWAIT case above. If we
1011 * relock, we have to jump back to 'relocked' as the connection might
1012 * now be in TIMEWAIT.
1013 */
1014 #ifdef INVARIANTS
1015 if ((thflags & (TH_FIN | TH_RST)) != 0)
1016 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1017 #endif
1018 if (!((tp->t_state == TCPS_ESTABLISHED && (thflags & TH_SYN) == 0) ||
1019 (tp->t_state == TCPS_LISTEN && (thflags & TH_SYN) &&
1020 !IS_FASTOPEN(tp->t_flags)))) {
1021 if (ti_locked == TI_UNLOCKED) {
1022 INP_INFO_RLOCK_ET(&V_tcbinfo, et);
1023 ti_locked = TI_RLOCKED;
1024 }
1025 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1026 }
1027
1028 #ifdef MAC
1029 INP_WLOCK_ASSERT(inp);
1030 if (mac_inpcb_check_deliver(inp, m))
1031 goto dropunlock;
1032 #endif
1033 so = inp->inp_socket;
1034 KASSERT(so != NULL, ("%s: so == NULL", __func__));
1035 #ifdef TCPDEBUG
1036 if (so->so_options & SO_DEBUG) {
1037 ostate = tp->t_state;
1038 #ifdef INET6
1039 if (isipv6) {
1040 bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
1041 } else
1042 #endif
1043 bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
1044 tcp_savetcp = *th;
1045 }
1046 #endif /* TCPDEBUG */
1047 /*
1048 * When the socket is accepting connections (the INPCB is in LISTEN
1049 * state) we look into the SYN cache if this is a new connection
1050 * attempt or the completion of a previous one.
1051 */
1052 KASSERT(tp->t_state == TCPS_LISTEN || !(so->so_options & SO_ACCEPTCONN),
1053 ("%s: so accepting but tp %p not listening", __func__, tp));
1054 if (tp->t_state == TCPS_LISTEN && (so->so_options & SO_ACCEPTCONN)) {
1055 struct in_conninfo inc;
1056
1057 bzero(&inc, sizeof(inc));
1058 #ifdef INET6
1059 if (isipv6) {
1060 inc.inc_flags |= INC_ISIPV6;
1061 if (inp->inp_inc.inc_flags & INC_IPV6MINMTU)
1062 inc.inc_flags |= INC_IPV6MINMTU;
1063 inc.inc6_faddr = ip6->ip6_src;
1064 inc.inc6_laddr = ip6->ip6_dst;
1065 } else
1066 #endif
1067 {
1068 inc.inc_faddr = ip->ip_src;
1069 inc.inc_laddr = ip->ip_dst;
1070 }
1071 inc.inc_fport = th->th_sport;
1072 inc.inc_lport = th->th_dport;
1073 inc.inc_fibnum = so->so_fibnum;
1074
1075 /*
1076 * Check for an existing connection attempt in syncache if
1077 * the flag is only ACK. A successful lookup creates a new
1078 * socket appended to the listen queue in SYN_RECEIVED state.
1079 */
1080 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
1081
1082 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1083 /*
1084 * Parse the TCP options here because
1085 * syncookies need access to the reflected
1086 * timestamp.
1087 */
1088 tcp_dooptions(&to, optp, optlen, 0);
1089 /*
1090 * NB: syncache_expand() doesn't unlock
1091 * inp and tcpinfo locks.
1092 */
1093 rstreason = syncache_expand(&inc, &to, th, &so, m);
1094 if (rstreason < 0) {
1095 /*
1096 * A failing TCP MD5 signature comparison
1097 * must result in the segment being dropped
1098 * and must not produce any response back
1099 * to the sender.
1100 */
1101 goto dropunlock;
1102 } else if (rstreason == 0) {
1103 /*
1104 * No syncache entry or ACK was not
1105 * for our SYN/ACK. Send a RST.
1106 * NB: syncache did its own logging
1107 * of the failure cause.
1108 */
1109 rstreason = BANDLIM_RST_OPENPORT;
1110 goto dropwithreset;
1111 }
1112 tfo_socket_result:
1113 if (so == NULL) {
1114 /*
1115 * We completed the 3-way handshake
1116 * but could not allocate a socket
1117 * either due to memory shortage,
1118 * listen queue length limits or
1119 * global socket limits. Send RST
1120 * or wait and have the remote end
1121 * retransmit the ACK for another
1122 * try.
1123 */
1124 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1125 log(LOG_DEBUG, "%s; %s: Listen socket: "
1126 "Socket allocation failed due to "
1127 "limits or memory shortage, %s\n",
1128 s, __func__,
1129 V_tcp_sc_rst_sock_fail ?
1130 "sending RST" : "try again");
1131 if (V_tcp_sc_rst_sock_fail) {
1132 rstreason = BANDLIM_UNLIMITED;
1133 goto dropwithreset;
1134 } else
1135 goto dropunlock;
1136 }
1137 /*
1138 * Socket is created in state SYN_RECEIVED.
1139 * Unlock the listen socket, lock the newly
1140 * created socket and update the tp variable.
1141 */
1142 INP_WUNLOCK(inp); /* listen socket */
1143 inp = sotoinpcb(so);
1144 /*
1145 * New connection inpcb is already locked by
1146 * syncache_expand().
1147 */
1148 INP_WLOCK_ASSERT(inp);
1149 tp = intotcpcb(inp);
1150 KASSERT(tp->t_state == TCPS_SYN_RECEIVED,
1151 ("%s: ", __func__));
1152 /*
1153 * Process the segment and the data it
1154 * contains. tcp_do_segment() consumes
1155 * the mbuf chain and unlocks the inpcb.
1156 */
1157 TCP_PROBE5(receive, NULL, tp, m, tp, th);
1158 tp->t_fb->tfb_tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen,
1159 iptos);
1160 if (ti_locked == TI_RLOCKED)
1161 INP_INFO_RUNLOCK_ET(&V_tcbinfo, et);
1162 return (IPPROTO_DONE);
1163 }
1164 /*
1165 * Segment flag validation for new connection attempts:
1166 *
1167 * Our (SYN|ACK) response was rejected.
1168 * Check with syncache and remove entry to prevent
1169 * retransmits.
1170 *
1171 * NB: syncache_chkrst does its own logging of failure
1172 * causes.
1173 */
1174 if (thflags & TH_RST) {
1175 syncache_chkrst(&inc, th, m);
1176 goto dropunlock;
1177 }
1178 /*
1179 * We can't do anything without SYN.
1180 */
1181 if ((thflags & TH_SYN) == 0) {
1182 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1183 log(LOG_DEBUG, "%s; %s: Listen socket: "
1184 "SYN is missing, segment ignored\n",
1185 s, __func__);
1186 TCPSTAT_INC(tcps_badsyn);
1187 goto dropunlock;
1188 }
1189 /*
1190 * (SYN|ACK) is bogus on a listen socket.
1191 */
1192 if (thflags & TH_ACK) {
1193 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1194 log(LOG_DEBUG, "%s; %s: Listen socket: "
1195 "SYN|ACK invalid, segment rejected\n",
1196 s, __func__);
1197 syncache_badack(&inc); /* XXX: Not needed! */
1198 TCPSTAT_INC(tcps_badsyn);
1199 rstreason = BANDLIM_RST_OPENPORT;
1200 goto dropwithreset;
1201 }
1202 /*
1203 * If the drop_synfin option is enabled, drop all
1204 * segments with both the SYN and FIN bits set.
1205 * This prevents e.g. nmap from identifying the
1206 * TCP/IP stack.
1207 * XXX: Poor reasoning. nmap has other methods
1208 * and is constantly refining its stack detection
1209 * strategies.
1210 * XXX: This is a violation of the TCP specification
1211 * and was used by RFC1644.
1212 */
1213 if ((thflags & TH_FIN) && V_drop_synfin) {
1214 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1215 log(LOG_DEBUG, "%s; %s: Listen socket: "
1216 "SYN|FIN segment ignored (based on "
1217 "sysctl setting)\n", s, __func__);
1218 TCPSTAT_INC(tcps_badsyn);
1219 goto dropunlock;
1220 }
1221 /*
1222 * Segment's flags are (SYN) or (SYN|FIN).
1223 *
1224 * TH_PUSH, TH_URG, TH_ECE, TH_CWR are ignored
1225 * as they do not affect the state of the TCP FSM.
1226 * The data pointed to by TH_URG and th_urp is ignored.
1227 */
1228 KASSERT((thflags & (TH_RST|TH_ACK)) == 0,
1229 ("%s: Listen socket: TH_RST or TH_ACK set", __func__));
1230 KASSERT(thflags & (TH_SYN),
1231 ("%s: Listen socket: TH_SYN not set", __func__));
1232 #ifdef INET6
1233 /*
1234 * If deprecated address is forbidden,
1235 * we do not accept SYN to deprecated interface
1236 * address to prevent any new inbound connection from
1237 * getting established.
1238 * When we do not accept SYN, we send a TCP RST,
1239 * with deprecated source address (instead of dropping
1240 * it). We compromise it as it is much better for peer
1241 * to send a RST, and RST will be the final packet
1242 * for the exchange.
1243 *
1244 * If we do not forbid deprecated addresses, we accept
1245 * the SYN packet. RFC2462 does not suggest dropping
1246 * SYN in this case.
1247 * If we decipher RFC2462 5.5.4, it says like this:
1248 * 1. use of deprecated addr with existing
1249 * communication is okay - "SHOULD continue to be
1250 * used"
1251 * 2. use of it with new communication:
1252 * (2a) "SHOULD NOT be used if alternate address
1253 * with sufficient scope is available"
1254 * (2b) nothing mentioned otherwise.
1255 * Here we fall into (2b) case as we have no choice in
1256 * our source address selection - we must obey the peer.
1257 *
1258 * The wording in RFC2462 is confusing, and there are
1259 * multiple description text for deprecated address
1260 * handling - worse, they are not exactly the same.
1261 * I believe 5.5.4 is the best one, so we follow 5.5.4.
1262 */
1263 if (isipv6 && !V_ip6_use_deprecated) {
1264 struct in6_ifaddr *ia6;
1265
1266 ia6 = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */);
1267 if (ia6 != NULL &&
1268 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
1269 ifa_free(&ia6->ia_ifa);
1270 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1271 log(LOG_DEBUG, "%s; %s: Listen socket: "
1272 "Connection attempt to deprecated "
1273 "IPv6 address rejected\n",
1274 s, __func__);
1275 rstreason = BANDLIM_RST_OPENPORT;
1276 goto dropwithreset;
1277 }
1278 if (ia6)
1279 ifa_free(&ia6->ia_ifa);
1280 }
1281 #endif /* INET6 */
1282 /*
1283 * Basic sanity checks on incoming SYN requests:
1284 * Don't respond if the destination is a link layer
1285 * broadcast according to RFC1122 4.2.3.10, p. 104.
1286 * If it is from this socket it must be forged.
1287 * Don't respond if the source or destination is a
1288 * global or subnet broad- or multicast address.
1289 * Note that it is quite possible to receive unicast
1290 * link-layer packets with a broadcast IP address. Use
1291 * in_broadcast() to find them.
1292 */
1293 if (m->m_flags & (M_BCAST|M_MCAST)) {
1294 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1295 log(LOG_DEBUG, "%s; %s: Listen socket: "
1296 "Connection attempt from broad- or multicast "
1297 "link layer address ignored\n", s, __func__);
1298 goto dropunlock;
1299 }
1300 #ifdef INET6
1301 if (isipv6) {
1302 if (th->th_dport == th->th_sport &&
1303 IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &ip6->ip6_src)) {
1304 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1305 log(LOG_DEBUG, "%s; %s: Listen socket: "
1306 "Connection attempt to/from self "
1307 "ignored\n", s, __func__);
1308 goto dropunlock;
1309 }
1310 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
1311 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
1312 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1313 log(LOG_DEBUG, "%s; %s: Listen socket: "
1314 "Connection attempt from/to multicast "
1315 "address ignored\n", s, __func__);
1316 goto dropunlock;
1317 }
1318 }
1319 #endif
1320 #if defined(INET) && defined(INET6)
1321 else
1322 #endif
1323 #ifdef INET
1324 {
1325 if (th->th_dport == th->th_sport &&
1326 ip->ip_dst.s_addr == ip->ip_src.s_addr) {
1327 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1328 log(LOG_DEBUG, "%s; %s: Listen socket: "
1329 "Connection attempt from/to self "
1330 "ignored\n", s, __func__);
1331 goto dropunlock;
1332 }
1333 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
1334 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
1335 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
1336 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
1337 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1338 log(LOG_DEBUG, "%s; %s: Listen socket: "
1339 "Connection attempt from/to broad- "
1340 "or multicast address ignored\n",
1341 s, __func__);
1342 goto dropunlock;
1343 }
1344 }
1345 #endif
1346 /*
1347 * SYN appears to be valid. Create compressed TCP state
1348 * for syncache.
1349 */
1350 #ifdef TCPDEBUG
1351 if (so->so_options & SO_DEBUG)
1352 tcp_trace(TA_INPUT, ostate, tp,
1353 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1354 #endif
1355 TCP_PROBE3(debug__input, tp, th, m);
1356 tcp_dooptions(&to, optp, optlen, TO_SYN);
1357 if (syncache_add(&inc, &to, th, inp, &so, m, NULL, NULL, iptos))
1358 goto tfo_socket_result;
1359
1360 /*
1361 * Entry added to syncache and mbuf consumed.
1362 * Only the listen socket is unlocked by syncache_add().
1363 */
1364 if (ti_locked == TI_RLOCKED) {
1365 INP_INFO_RUNLOCK_ET(&V_tcbinfo, et);
1366 ti_locked = TI_UNLOCKED;
1367 }
1368 INP_INFO_WUNLOCK_ASSERT(&V_tcbinfo);
1369 return (IPPROTO_DONE);
1370 } else if (tp->t_state == TCPS_LISTEN) {
1371 /*
1372 * When a listen socket is torn down the SO_ACCEPTCONN
1373 * flag is removed first while connections are drained
1374 * from the accept queue in a unlock/lock cycle of the
1375 * ACCEPT_LOCK, opening a race condition allowing a SYN
1376 * attempt go through unhandled.
1377 */
1378 goto dropunlock;
1379 }
1380 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1381 if (tp->t_flags & TF_SIGNATURE) {
1382 tcp_dooptions(&to, optp, optlen, thflags);
1383 if ((to.to_flags & TOF_SIGNATURE) == 0) {
1384 TCPSTAT_INC(tcps_sig_err_nosigopt);
1385 goto dropunlock;
1386 }
1387 if (!TCPMD5_ENABLED() ||
1388 TCPMD5_INPUT(m, th, to.to_signature) != 0)
1389 goto dropunlock;
1390 }
1391 #endif
1392 TCP_PROBE5(receive, NULL, tp, m, tp, th);
1393
1394 /*
1395 * Segment belongs to a connection in SYN_SENT, ESTABLISHED or later
1396 * state. tcp_do_segment() always consumes the mbuf chain, unlocks
1397 * the inpcb, and unlocks pcbinfo.
1398 */
1399 tp->t_fb->tfb_tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen, iptos);
1400 if (ti_locked == TI_RLOCKED)
1401 INP_INFO_RUNLOCK_ET(&V_tcbinfo, et);
1402 return (IPPROTO_DONE);
1403
1404 dropwithreset:
1405 TCP_PROBE5(receive, NULL, tp, m, tp, th);
1406
1407 if (ti_locked == TI_RLOCKED) {
1408 INP_INFO_RUNLOCK_ET(&V_tcbinfo, et);
1409 ti_locked = TI_UNLOCKED;
1410 }
1411 #ifdef INVARIANTS
1412 else {
1413 KASSERT(ti_locked == TI_UNLOCKED, ("%s: dropwithreset "
1414 "ti_locked: %d", __func__, ti_locked));
1415 INP_INFO_WUNLOCK_ASSERT(&V_tcbinfo);
1416 }
1417 #endif
1418
1419 if (inp != NULL) {
1420 tcp_dropwithreset(m, th, tp, tlen, rstreason);
1421 INP_WUNLOCK(inp);
1422 } else
1423 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
1424 m = NULL; /* mbuf chain got consumed. */
1425 goto drop;
1426
1427 dropunlock:
1428 if (m != NULL)
1429 TCP_PROBE5(receive, NULL, tp, m, tp, th);
1430
1431 if (ti_locked == TI_RLOCKED) {
1432 INP_INFO_RUNLOCK_ET(&V_tcbinfo, et);
1433 ti_locked = TI_UNLOCKED;
1434 }
1435 #ifdef INVARIANTS
1436 else {
1437 KASSERT(ti_locked == TI_UNLOCKED, ("%s: dropunlock "
1438 "ti_locked: %d", __func__, ti_locked));
1439 INP_INFO_WUNLOCK_ASSERT(&V_tcbinfo);
1440 }
1441 #endif
1442
1443 if (inp != NULL)
1444 INP_WUNLOCK(inp);
1445
1446 drop:
1447 INP_INFO_WUNLOCK_ASSERT(&V_tcbinfo);
1448 if (s != NULL)
1449 free(s, M_TCPLOG);
1450 if (m != NULL)
1451 m_freem(m);
1452 return (IPPROTO_DONE);
1453 }
1454
1455 /*
1456 * Automatic sizing of receive socket buffer. Often the send
1457 * buffer size is not optimally adjusted to the actual network
1458 * conditions at hand (delay bandwidth product). Setting the
1459 * buffer size too small limits throughput on links with high
1460 * bandwidth and high delay (eg. trans-continental/oceanic links).
1461 *
1462 * On the receive side the socket buffer memory is only rarely
1463 * used to any significant extent. This allows us to be much
1464 * more aggressive in scaling the receive socket buffer. For
1465 * the case that the buffer space is actually used to a large
1466 * extent and we run out of kernel memory we can simply drop
1467 * the new segments; TCP on the sender will just retransmit it
1468 * later. Setting the buffer size too big may only consume too
1469 * much kernel memory if the application doesn't read() from
1470 * the socket or packet loss or reordering makes use of the
1471 * reassembly queue.
1472 *
1473 * The criteria to step up the receive buffer one notch are:
1474 * 1. Application has not set receive buffer size with
1475 * SO_RCVBUF. Setting SO_RCVBUF clears SB_AUTOSIZE.
1476 * 2. the number of bytes received during the time it takes
1477 * one timestamp to be reflected back to us (the RTT);
1478 * 3. received bytes per RTT is within seven eighth of the
1479 * current socket buffer size;
1480 * 4. receive buffer size has not hit maximal automatic size;
1481 *
1482 * This algorithm does one step per RTT at most and only if
1483 * we receive a bulk stream w/o packet losses or reorderings.
1484 * Shrinking the buffer during idle times is not necessary as
1485 * it doesn't consume any memory when idle.
1486 *
1487 * TODO: Only step up if the application is actually serving
1488 * the buffer to better manage the socket buffer resources.
1489 */
1490 int
tcp_autorcvbuf(struct mbuf * m,struct tcphdr * th,struct socket * so,struct tcpcb * tp,int tlen)1491 tcp_autorcvbuf(struct mbuf *m, struct tcphdr *th, struct socket *so,
1492 struct tcpcb *tp, int tlen)
1493 {
1494 int newsize = 0;
1495
1496 if (V_tcp_do_autorcvbuf && (so->so_rcv.sb_flags & SB_AUTOSIZE) &&
1497 tp->t_srtt != 0 && tp->rfbuf_ts != 0 &&
1498 TCP_TS_TO_TICKS(tcp_ts_getticks() - tp->rfbuf_ts) >
1499 (tp->t_srtt >> TCP_RTT_SHIFT)) {
1500 if (tp->rfbuf_cnt > (so->so_rcv.sb_hiwat / 8 * 7) &&
1501 so->so_rcv.sb_hiwat < V_tcp_autorcvbuf_max) {
1502 newsize = min(so->so_rcv.sb_hiwat +
1503 V_tcp_autorcvbuf_inc, V_tcp_autorcvbuf_max);
1504 }
1505 TCP_PROBE6(receive__autoresize, NULL, tp, m, tp, th, newsize);
1506
1507 /* Start over with next RTT. */
1508 tp->rfbuf_ts = 0;
1509 tp->rfbuf_cnt = 0;
1510 } else {
1511 tp->rfbuf_cnt += tlen; /* add up */
1512 }
1513 return (newsize);
1514 }
1515
1516 void
tcp_do_segment(struct mbuf * m,struct tcphdr * th,struct socket * so,struct tcpcb * tp,int drop_hdrlen,int tlen,uint8_t iptos)1517 tcp_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
1518 struct tcpcb *tp, int drop_hdrlen, int tlen, uint8_t iptos)
1519 {
1520 int thflags, acked, ourfinisacked, needoutput = 0, sack_changed;
1521 int rstreason, todrop, win, incforsyn = 0;
1522 uint32_t tiwin;
1523 uint16_t nsegs;
1524 char *s;
1525 struct in_conninfo *inc;
1526 struct mbuf *mfree;
1527 struct tcpopt to;
1528 int tfo_syn;
1529
1530 #ifdef TCPDEBUG
1531 /*
1532 * The size of tcp_saveipgen must be the size of the max ip header,
1533 * now IPv6.
1534 */
1535 u_char tcp_saveipgen[IP6_HDR_LEN];
1536 struct tcphdr tcp_savetcp;
1537 short ostate = 0;
1538 #endif
1539 thflags = th->th_flags;
1540 inc = &tp->t_inpcb->inp_inc;
1541 tp->sackhint.last_sack_ack = 0;
1542 sack_changed = 0;
1543 nsegs = max(1, m->m_pkthdr.lro_nsegs);
1544 /*
1545 * If this is either a state-changing packet or current state isn't
1546 * established, we require a write lock on tcbinfo. Otherwise, we
1547 * allow the tcbinfo to be in either alocked or unlocked, as the
1548 * caller may have unnecessarily acquired a write lock due to a race.
1549 */
1550 if ((thflags & (TH_SYN | TH_FIN | TH_RST)) != 0 ||
1551 tp->t_state != TCPS_ESTABLISHED) {
1552 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1553 }
1554 INP_WLOCK_ASSERT(tp->t_inpcb);
1555 KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
1556 __func__));
1557 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
1558 __func__));
1559
1560 #ifdef TCPPCAP
1561 /* Save segment, if requested. */
1562 tcp_pcap_add(th, m, &(tp->t_inpkts));
1563 #endif
1564 TCP_LOG_EVENT(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_IN, 0,
1565 tlen, NULL, true);
1566
1567 if ((thflags & TH_SYN) && (thflags & TH_FIN) && V_drop_synfin) {
1568 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1569 log(LOG_DEBUG, "%s; %s: "
1570 "SYN|FIN segment ignored (based on "
1571 "sysctl setting)\n", s, __func__);
1572 free(s, M_TCPLOG);
1573 }
1574 goto drop;
1575 }
1576
1577 /*
1578 * If a segment with the ACK-bit set arrives in the SYN-SENT state
1579 * check SEQ.ACK first.
1580 */
1581 if ((tp->t_state == TCPS_SYN_SENT) && (thflags & TH_ACK) &&
1582 (SEQ_LEQ(th->th_ack, tp->iss) || SEQ_GT(th->th_ack, tp->snd_max))) {
1583 rstreason = BANDLIM_UNLIMITED;
1584 goto dropwithreset;
1585 }
1586
1587 /*
1588 * Segment received on connection.
1589 * Reset idle time and keep-alive timer.
1590 * XXX: This should be done after segment
1591 * validation to ignore broken/spoofed segs.
1592 */
1593 tp->t_rcvtime = ticks;
1594
1595 /*
1596 * Scale up the window into a 32-bit value.
1597 * For the SYN_SENT state the scale is zero.
1598 */
1599 tiwin = th->th_win << tp->snd_scale;
1600
1601 /*
1602 * TCP ECN processing.
1603 */
1604 if (tp->t_flags & TF_ECN_PERMIT) {
1605 if (thflags & TH_CWR) {
1606 tp->t_flags &= ~TF_ECN_SND_ECE;
1607 tp->t_flags |= TF_ACKNOW;
1608 }
1609 switch (iptos & IPTOS_ECN_MASK) {
1610 case IPTOS_ECN_CE:
1611 tp->t_flags |= TF_ECN_SND_ECE;
1612 TCPSTAT_INC(tcps_ecn_ce);
1613 break;
1614 case IPTOS_ECN_ECT0:
1615 TCPSTAT_INC(tcps_ecn_ect0);
1616 break;
1617 case IPTOS_ECN_ECT1:
1618 TCPSTAT_INC(tcps_ecn_ect1);
1619 break;
1620 }
1621
1622 /* Process a packet differently from RFC3168. */
1623 cc_ecnpkt_handler(tp, th, iptos);
1624
1625 /* Congestion experienced. */
1626 if (thflags & TH_ECE) {
1627 cc_cong_signal(tp, th, CC_ECN);
1628 }
1629 }
1630
1631 /*
1632 * Parse options on any incoming segment.
1633 */
1634 tcp_dooptions(&to, (u_char *)(th + 1),
1635 (th->th_off << 2) - sizeof(struct tcphdr),
1636 (thflags & TH_SYN) ? TO_SYN : 0);
1637
1638 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1639 if ((tp->t_flags & TF_SIGNATURE) != 0 &&
1640 (to.to_flags & TOF_SIGNATURE) == 0) {
1641 TCPSTAT_INC(tcps_sig_err_sigopt);
1642 /* XXX: should drop? */
1643 }
1644 #endif
1645 /*
1646 * If echoed timestamp is later than the current time,
1647 * fall back to non RFC1323 RTT calculation. Normalize
1648 * timestamp if syncookies were used when this connection
1649 * was established.
1650 */
1651 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
1652 to.to_tsecr -= tp->ts_offset;
1653 if (TSTMP_GT(to.to_tsecr, tcp_ts_getticks()))
1654 to.to_tsecr = 0;
1655 else if (tp->t_flags & TF_PREVVALID &&
1656 tp->t_badrxtwin != 0 && SEQ_LT(to.to_tsecr, tp->t_badrxtwin))
1657 cc_cong_signal(tp, th, CC_RTO_ERR);
1658 }
1659 /*
1660 * Process options only when we get SYN/ACK back. The SYN case
1661 * for incoming connections is handled in tcp_syncache.
1662 * According to RFC1323 the window field in a SYN (i.e., a <SYN>
1663 * or <SYN,ACK>) segment itself is never scaled.
1664 * XXX this is traditional behavior, may need to be cleaned up.
1665 */
1666 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1667 if ((to.to_flags & TOF_SCALE) &&
1668 (tp->t_flags & TF_REQ_SCALE)) {
1669 tp->t_flags |= TF_RCVD_SCALE;
1670 tp->snd_scale = to.to_wscale;
1671 } else
1672 tp->t_flags &= ~TF_REQ_SCALE;
1673 /*
1674 * Initial send window. It will be updated with
1675 * the next incoming segment to the scaled value.
1676 */
1677 tp->snd_wnd = th->th_win;
1678 if ((to.to_flags & TOF_TS) &&
1679 (tp->t_flags & TF_REQ_TSTMP)) {
1680 tp->t_flags |= TF_RCVD_TSTMP;
1681 tp->ts_recent = to.to_tsval;
1682 tp->ts_recent_age = tcp_ts_getticks();
1683 } else
1684 tp->t_flags &= ~TF_REQ_TSTMP;
1685 if (to.to_flags & TOF_MSS)
1686 tcp_mss(tp, to.to_mss);
1687 if ((tp->t_flags & TF_SACK_PERMIT) &&
1688 (to.to_flags & TOF_SACKPERM) == 0)
1689 tp->t_flags &= ~TF_SACK_PERMIT;
1690 if (IS_FASTOPEN(tp->t_flags)) {
1691 if (to.to_flags & TOF_FASTOPEN) {
1692 uint16_t mss;
1693
1694 if (to.to_flags & TOF_MSS)
1695 mss = to.to_mss;
1696 else
1697 if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0)
1698 mss = TCP6_MSS;
1699 else
1700 mss = TCP_MSS;
1701 tcp_fastopen_update_cache(tp, mss,
1702 to.to_tfo_len, to.to_tfo_cookie);
1703 } else
1704 tcp_fastopen_disable_path(tp);
1705 }
1706 }
1707
1708 /*
1709 * If timestamps were negotiated during SYN/ACK and a
1710 * segment without a timestamp is received, silently drop
1711 * the segment, unless it is a RST segment or missing timestamps are
1712 * tolerated.
1713 * See section 3.2 of RFC 7323.
1714 */
1715 if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS)) {
1716 if (((thflags & TH_RST) != 0) || V_tcp_tolerate_missing_ts) {
1717 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1718 log(LOG_DEBUG, "%s; %s: Timestamp missing, "
1719 "segment processed normally\n",
1720 s, __func__);
1721 free(s, M_TCPLOG);
1722 }
1723 } else {
1724 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1725 log(LOG_DEBUG, "%s; %s: Timestamp missing, "
1726 "segment silently dropped\n", s, __func__);
1727 free(s, M_TCPLOG);
1728 }
1729 goto drop;
1730 }
1731 }
1732 /*
1733 * If timestamps were not negotiated during SYN/ACK and a
1734 * segment with a timestamp is received, ignore the
1735 * timestamp and process the packet normally.
1736 * See section 3.2 of RFC 7323.
1737 */
1738 if (!(tp->t_flags & TF_RCVD_TSTMP) && (to.to_flags & TOF_TS)) {
1739 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1740 log(LOG_DEBUG, "%s; %s: Timestamp not expected, "
1741 "segment processed normally\n", s, __func__);
1742 free(s, M_TCPLOG);
1743 }
1744 }
1745
1746 /*
1747 * Header prediction: check for the two common cases
1748 * of a uni-directional data xfer. If the packet has
1749 * no control flags, is in-sequence, the window didn't
1750 * change and we're not retransmitting, it's a
1751 * candidate. If the length is zero and the ack moved
1752 * forward, we're the sender side of the xfer. Just
1753 * free the data acked & wake any higher level process
1754 * that was blocked waiting for space. If the length
1755 * is non-zero and the ack didn't move, we're the
1756 * receiver side. If we're getting packets in-order
1757 * (the reassembly queue is empty), add the data to
1758 * the socket buffer and note that we need a delayed ack.
1759 * Make sure that the hidden state-flags are also off.
1760 * Since we check for TCPS_ESTABLISHED first, it can only
1761 * be TH_NEEDSYN.
1762 */
1763 if (tp->t_state == TCPS_ESTABLISHED &&
1764 th->th_seq == tp->rcv_nxt &&
1765 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1766 tp->snd_nxt == tp->snd_max &&
1767 tiwin && tiwin == tp->snd_wnd &&
1768 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1769 SEGQ_EMPTY(tp) &&
1770 ((to.to_flags & TOF_TS) == 0 ||
1771 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) ) {
1772
1773 /*
1774 * If last ACK falls within this segment's sequence numbers,
1775 * record the timestamp.
1776 * NOTE that the test is modified according to the latest
1777 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1778 */
1779 if ((to.to_flags & TOF_TS) != 0 &&
1780 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1781 tp->ts_recent_age = tcp_ts_getticks();
1782 tp->ts_recent = to.to_tsval;
1783 }
1784
1785 if (tlen == 0) {
1786 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1787 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1788 !IN_RECOVERY(tp->t_flags) &&
1789 (to.to_flags & TOF_SACK) == 0 &&
1790 TAILQ_EMPTY(&tp->snd_holes)) {
1791 /*
1792 * This is a pure ack for outstanding data.
1793 */
1794 TCPSTAT_INC(tcps_predack);
1795
1796 /*
1797 * "bad retransmit" recovery without timestamps.
1798 */
1799 if ((to.to_flags & TOF_TS) == 0 &&
1800 tp->t_rxtshift == 1 &&
1801 tp->t_flags & TF_PREVVALID &&
1802 (int)(ticks - tp->t_badrxtwin) < 0) {
1803 cc_cong_signal(tp, th, CC_RTO_ERR);
1804 }
1805
1806 /*
1807 * Recalculate the transmit timer / rtt.
1808 *
1809 * Some boxes send broken timestamp replies
1810 * during the SYN+ACK phase, ignore
1811 * timestamps of 0 or we could calculate a
1812 * huge RTT and blow up the retransmit timer.
1813 */
1814 if ((to.to_flags & TOF_TS) != 0 &&
1815 to.to_tsecr) {
1816 uint32_t t;
1817
1818 t = tcp_ts_getticks() - to.to_tsecr;
1819 if (!tp->t_rttlow || tp->t_rttlow > t)
1820 tp->t_rttlow = t;
1821 tcp_xmit_timer(tp,
1822 TCP_TS_TO_TICKS(t) + 1);
1823 } else if (tp->t_rtttime &&
1824 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1825 if (!tp->t_rttlow ||
1826 tp->t_rttlow > ticks - tp->t_rtttime)
1827 tp->t_rttlow = ticks - tp->t_rtttime;
1828 tcp_xmit_timer(tp,
1829 ticks - tp->t_rtttime);
1830 }
1831 acked = BYTES_THIS_ACK(tp, th);
1832
1833 #ifdef TCP_HHOOK
1834 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
1835 hhook_run_tcp_est_in(tp, th, &to);
1836 #endif
1837
1838 TCPSTAT_ADD(tcps_rcvackpack, nsegs);
1839 TCPSTAT_ADD(tcps_rcvackbyte, acked);
1840 sbdrop(&so->so_snd, acked);
1841 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1842 SEQ_LEQ(th->th_ack, tp->snd_recover))
1843 tp->snd_recover = th->th_ack - 1;
1844
1845 /*
1846 * Let the congestion control algorithm update
1847 * congestion control related information. This
1848 * typically means increasing the congestion
1849 * window.
1850 */
1851 cc_ack_received(tp, th, nsegs, CC_ACK);
1852
1853 tp->snd_una = th->th_ack;
1854 /*
1855 * Pull snd_wl2 up to prevent seq wrap relative
1856 * to th_ack.
1857 */
1858 tp->snd_wl2 = th->th_ack;
1859 tp->t_dupacks = 0;
1860 m_freem(m);
1861
1862 /*
1863 * If all outstanding data are acked, stop
1864 * retransmit timer, otherwise restart timer
1865 * using current (possibly backed-off) value.
1866 * If process is waiting for space,
1867 * wakeup/selwakeup/signal. If data
1868 * are ready to send, let tcp_output
1869 * decide between more output or persist.
1870 */
1871 #ifdef TCPDEBUG
1872 if (so->so_options & SO_DEBUG)
1873 tcp_trace(TA_INPUT, ostate, tp,
1874 (void *)tcp_saveipgen,
1875 &tcp_savetcp, 0);
1876 #endif
1877 TCP_PROBE3(debug__input, tp, th, m);
1878 if (tp->snd_una == tp->snd_max)
1879 tcp_timer_activate(tp, TT_REXMT, 0);
1880 else if (!tcp_timer_active(tp, TT_PERSIST))
1881 tcp_timer_activate(tp, TT_REXMT,
1882 tp->t_rxtcur);
1883 sowwakeup(so);
1884 if (sbavail(&so->so_snd))
1885 (void) tp->t_fb->tfb_tcp_output(tp);
1886 goto check_delack;
1887 }
1888 } else if (th->th_ack == tp->snd_una &&
1889 tlen <= sbspace(&so->so_rcv)) {
1890 int newsize = 0; /* automatic sockbuf scaling */
1891
1892 /*
1893 * This is a pure, in-sequence data packet with
1894 * nothing on the reassembly queue and we have enough
1895 * buffer space to take it.
1896 */
1897 /* Clean receiver SACK report if present */
1898 if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks)
1899 tcp_clean_sackreport(tp);
1900 TCPSTAT_INC(tcps_preddat);
1901 tp->rcv_nxt += tlen;
1902 /*
1903 * Pull snd_wl1 up to prevent seq wrap relative to
1904 * th_seq.
1905 */
1906 tp->snd_wl1 = th->th_seq;
1907 /*
1908 * Pull rcv_up up to prevent seq wrap relative to
1909 * rcv_nxt.
1910 */
1911 tp->rcv_up = tp->rcv_nxt;
1912 TCPSTAT_ADD(tcps_rcvpack, nsegs);
1913 TCPSTAT_ADD(tcps_rcvbyte, tlen);
1914 #ifdef TCPDEBUG
1915 if (so->so_options & SO_DEBUG)
1916 tcp_trace(TA_INPUT, ostate, tp,
1917 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1918 #endif
1919 TCP_PROBE3(debug__input, tp, th, m);
1920
1921 newsize = tcp_autorcvbuf(m, th, so, tp, tlen);
1922
1923 /* Add data to socket buffer. */
1924 SOCKBUF_LOCK(&so->so_rcv);
1925 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1926 m_freem(m);
1927 } else {
1928 /*
1929 * Set new socket buffer size.
1930 * Give up when limit is reached.
1931 */
1932 if (newsize)
1933 if (!sbreserve_locked(&so->so_rcv,
1934 newsize, so, NULL))
1935 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1936 m_adj(m, drop_hdrlen); /* delayed header drop */
1937 sbappendstream_locked(&so->so_rcv, m, 0);
1938 }
1939 /* NB: sorwakeup_locked() does an implicit unlock. */
1940 sorwakeup_locked(so);
1941 if (DELAY_ACK(tp, tlen)) {
1942 tp->t_flags |= TF_DELACK;
1943 } else {
1944 tp->t_flags |= TF_ACKNOW;
1945 tp->t_fb->tfb_tcp_output(tp);
1946 }
1947 goto check_delack;
1948 }
1949 }
1950
1951 /*
1952 * Calculate amount of space in receive window,
1953 * and then do TCP input processing.
1954 * Receive window is amount of space in rcv queue,
1955 * but not less than advertised window.
1956 */
1957 win = sbspace(&so->so_rcv);
1958 if (win < 0)
1959 win = 0;
1960 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1961
1962 switch (tp->t_state) {
1963
1964 /*
1965 * If the state is SYN_RECEIVED:
1966 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1967 */
1968 case TCPS_SYN_RECEIVED:
1969 if (thflags & TH_RST) {
1970 /* Handle RST segments later. */
1971 break;
1972 }
1973 if ((thflags & TH_ACK) &&
1974 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1975 SEQ_GT(th->th_ack, tp->snd_max))) {
1976 rstreason = BANDLIM_RST_OPENPORT;
1977 goto dropwithreset;
1978 }
1979 if (IS_FASTOPEN(tp->t_flags)) {
1980 /*
1981 * When a TFO connection is in SYN_RECEIVED, the
1982 * only valid packets are the initial SYN, a
1983 * retransmit/copy of the initial SYN (possibly with
1984 * a subset of the original data), a valid ACK, a
1985 * FIN, or a RST.
1986 */
1987 if ((thflags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
1988 rstreason = BANDLIM_RST_OPENPORT;
1989 goto dropwithreset;
1990 } else if (thflags & TH_SYN) {
1991 /* non-initial SYN is ignored */
1992 if ((tcp_timer_active(tp, TT_DELACK) ||
1993 tcp_timer_active(tp, TT_REXMT)))
1994 goto drop;
1995 } else if (!(thflags & (TH_ACK|TH_FIN|TH_RST))) {
1996 goto drop;
1997 }
1998 }
1999 break;
2000
2001 /*
2002 * If the state is SYN_SENT:
2003 * if seg contains a RST with valid ACK (SEQ.ACK has already
2004 * been verified), then drop the connection.
2005 * if seg contains a RST without an ACK, drop the seg.
2006 * if seg does not contain SYN, then drop the seg.
2007 * Otherwise this is an acceptable SYN segment
2008 * initialize tp->rcv_nxt and tp->irs
2009 * if seg contains ack then advance tp->snd_una
2010 * if seg contains an ECE and ECN support is enabled, the stream
2011 * is ECN capable.
2012 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
2013 * arrange for segment to be acked (eventually)
2014 * continue processing rest of data/controls, beginning with URG
2015 */
2016 case TCPS_SYN_SENT:
2017 if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) {
2018 TCP_PROBE5(connect__refused, NULL, tp,
2019 m, tp, th);
2020 tp = tcp_drop(tp, ECONNREFUSED);
2021 }
2022 if (thflags & TH_RST)
2023 goto drop;
2024 if (!(thflags & TH_SYN))
2025 goto drop;
2026
2027 tp->irs = th->th_seq;
2028 tcp_rcvseqinit(tp);
2029 if (thflags & TH_ACK) {
2030 int tfo_partial_ack = 0;
2031
2032 TCPSTAT_INC(tcps_connects);
2033 soisconnected(so);
2034 #ifdef MAC
2035 mac_socketpeer_set_from_mbuf(m, so);
2036 #endif
2037 /* Do window scaling on this connection? */
2038 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2039 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2040 tp->rcv_scale = tp->request_r_scale;
2041 }
2042 tp->rcv_adv += min(tp->rcv_wnd,
2043 TCP_MAXWIN << tp->rcv_scale);
2044 tp->snd_una++; /* SYN is acked */
2045 /*
2046 * If not all the data that was sent in the TFO SYN
2047 * has been acked, resend the remainder right away.
2048 */
2049 if (IS_FASTOPEN(tp->t_flags) &&
2050 (tp->snd_una != tp->snd_max)) {
2051 tp->snd_nxt = th->th_ack;
2052 tfo_partial_ack = 1;
2053 }
2054 /*
2055 * If there's data, delay ACK; if there's also a FIN
2056 * ACKNOW will be turned on later.
2057 */
2058 if (DELAY_ACK(tp, tlen) && tlen != 0 && !tfo_partial_ack)
2059 tcp_timer_activate(tp, TT_DELACK,
2060 tcp_delacktime);
2061 else
2062 tp->t_flags |= TF_ACKNOW;
2063
2064 if (((thflags & (TH_CWR | TH_ECE)) == TH_ECE) &&
2065 (V_tcp_do_ecn == 1)) {
2066 tp->t_flags |= TF_ECN_PERMIT;
2067 TCPSTAT_INC(tcps_ecn_shs);
2068 }
2069
2070 /*
2071 * Received <SYN,ACK> in SYN_SENT[*] state.
2072 * Transitions:
2073 * SYN_SENT --> ESTABLISHED
2074 * SYN_SENT* --> FIN_WAIT_1
2075 */
2076 tp->t_starttime = ticks;
2077 if (tp->t_flags & TF_NEEDFIN) {
2078 tcp_state_change(tp, TCPS_FIN_WAIT_1);
2079 tp->t_flags &= ~TF_NEEDFIN;
2080 thflags &= ~TH_SYN;
2081 } else {
2082 tcp_state_change(tp, TCPS_ESTABLISHED);
2083 TCP_PROBE5(connect__established, NULL, tp,
2084 m, tp, th);
2085 cc_conn_init(tp);
2086 tcp_timer_activate(tp, TT_KEEP,
2087 TP_KEEPIDLE(tp));
2088 }
2089 } else {
2090 /*
2091 * Received initial SYN in SYN-SENT[*] state =>
2092 * simultaneous open.
2093 * If it succeeds, connection is * half-synchronized.
2094 * Otherwise, do 3-way handshake:
2095 * SYN-SENT -> SYN-RECEIVED
2096 * SYN-SENT* -> SYN-RECEIVED*
2097 */
2098 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
2099 tcp_timer_activate(tp, TT_REXMT, 0);
2100 tcp_state_change(tp, TCPS_SYN_RECEIVED);
2101 }
2102
2103 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2104 INP_WLOCK_ASSERT(tp->t_inpcb);
2105
2106 /*
2107 * Advance th->th_seq to correspond to first data byte.
2108 * If data, trim to stay within window,
2109 * dropping FIN if necessary.
2110 */
2111 th->th_seq++;
2112 if (tlen > tp->rcv_wnd) {
2113 todrop = tlen - tp->rcv_wnd;
2114 m_adj(m, -todrop);
2115 tlen = tp->rcv_wnd;
2116 thflags &= ~TH_FIN;
2117 TCPSTAT_INC(tcps_rcvpackafterwin);
2118 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
2119 }
2120 tp->snd_wl1 = th->th_seq - 1;
2121 tp->rcv_up = th->th_seq;
2122 /*
2123 * Client side of transaction: already sent SYN and data.
2124 * If the remote host used T/TCP to validate the SYN,
2125 * our data will be ACK'd; if so, enter normal data segment
2126 * processing in the middle of step 5, ack processing.
2127 * Otherwise, goto step 6.
2128 */
2129 if (thflags & TH_ACK)
2130 goto process_ACK;
2131
2132 goto step6;
2133
2134 /*
2135 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
2136 * do normal processing.
2137 *
2138 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
2139 */
2140 case TCPS_LAST_ACK:
2141 case TCPS_CLOSING:
2142 break; /* continue normal processing */
2143 }
2144
2145 /*
2146 * States other than LISTEN or SYN_SENT.
2147 * First check the RST flag and sequence number since reset segments
2148 * are exempt from the timestamp and connection count tests. This
2149 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
2150 * below which allowed reset segments in half the sequence space
2151 * to fall though and be processed (which gives forged reset
2152 * segments with a random sequence number a 50 percent chance of
2153 * killing a connection).
2154 * Then check timestamp, if present.
2155 * Then check the connection count, if present.
2156 * Then check that at least some bytes of segment are within
2157 * receive window. If segment begins before rcv_nxt,
2158 * drop leading data (and SYN); if nothing left, just ack.
2159 */
2160 if (thflags & TH_RST) {
2161 /*
2162 * RFC5961 Section 3.2
2163 *
2164 * - RST drops connection only if SEG.SEQ == RCV.NXT.
2165 * - If RST is in window, we send challenge ACK.
2166 *
2167 * Note: to take into account delayed ACKs, we should
2168 * test against last_ack_sent instead of rcv_nxt.
2169 * Note 2: we handle special case of closed window, not
2170 * covered by the RFC.
2171 */
2172 if ((SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
2173 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) ||
2174 (tp->rcv_wnd == 0 && tp->last_ack_sent == th->th_seq)) {
2175
2176 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2177 KASSERT(tp->t_state != TCPS_SYN_SENT,
2178 ("%s: TH_RST for TCPS_SYN_SENT th %p tp %p",
2179 __func__, th, tp));
2180
2181 if (V_tcp_insecure_rst ||
2182 tp->last_ack_sent == th->th_seq) {
2183 TCPSTAT_INC(tcps_drops);
2184 /* Drop the connection. */
2185 switch (tp->t_state) {
2186 case TCPS_SYN_RECEIVED:
2187 so->so_error = ECONNREFUSED;
2188 goto close;
2189 case TCPS_ESTABLISHED:
2190 case TCPS_FIN_WAIT_1:
2191 case TCPS_FIN_WAIT_2:
2192 case TCPS_CLOSE_WAIT:
2193 case TCPS_CLOSING:
2194 case TCPS_LAST_ACK:
2195 so->so_error = ECONNRESET;
2196 close:
2197 /* FALLTHROUGH */
2198 default:
2199 tp = tcp_close(tp);
2200 }
2201 } else {
2202 TCPSTAT_INC(tcps_badrst);
2203 /* Send challenge ACK. */
2204 tcp_respond(tp, mtod(m, void *), th, m,
2205 tp->rcv_nxt, tp->snd_nxt, TH_ACK);
2206 tp->last_ack_sent = tp->rcv_nxt;
2207 m = NULL;
2208 }
2209 }
2210 goto drop;
2211 }
2212
2213 /*
2214 * RFC5961 Section 4.2
2215 * Send challenge ACK for any SYN in synchronized state.
2216 */
2217 if ((thflags & TH_SYN) && tp->t_state != TCPS_SYN_SENT &&
2218 tp->t_state != TCPS_SYN_RECEIVED) {
2219 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2220
2221 TCPSTAT_INC(tcps_badsyn);
2222 if (V_tcp_insecure_syn &&
2223 SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
2224 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
2225 tp = tcp_drop(tp, ECONNRESET);
2226 rstreason = BANDLIM_UNLIMITED;
2227 } else {
2228 /* Send challenge ACK. */
2229 tcp_respond(tp, mtod(m, void *), th, m, tp->rcv_nxt,
2230 tp->snd_nxt, TH_ACK);
2231 tp->last_ack_sent = tp->rcv_nxt;
2232 m = NULL;
2233 }
2234 goto drop;
2235 }
2236
2237 /*
2238 * RFC 1323 PAWS: If we have a timestamp reply on this segment
2239 * and it's less than ts_recent, drop it.
2240 */
2241 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
2242 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
2243
2244 /* Check to see if ts_recent is over 24 days old. */
2245 if (tcp_ts_getticks() - tp->ts_recent_age > TCP_PAWS_IDLE) {
2246 /*
2247 * Invalidate ts_recent. If this segment updates
2248 * ts_recent, the age will be reset later and ts_recent
2249 * will get a valid value. If it does not, setting
2250 * ts_recent to zero will at least satisfy the
2251 * requirement that zero be placed in the timestamp
2252 * echo reply when ts_recent isn't valid. The
2253 * age isn't reset until we get a valid ts_recent
2254 * because we don't want out-of-order segments to be
2255 * dropped when ts_recent is old.
2256 */
2257 tp->ts_recent = 0;
2258 } else {
2259 TCPSTAT_INC(tcps_rcvduppack);
2260 TCPSTAT_ADD(tcps_rcvdupbyte, tlen);
2261 TCPSTAT_INC(tcps_pawsdrop);
2262 if (tlen)
2263 goto dropafterack;
2264 goto drop;
2265 }
2266 }
2267
2268 /*
2269 * In the SYN-RECEIVED state, validate that the packet belongs to
2270 * this connection before trimming the data to fit the receive
2271 * window. Check the sequence number versus IRS since we know
2272 * the sequence numbers haven't wrapped. This is a partial fix
2273 * for the "LAND" DoS attack.
2274 */
2275 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
2276 rstreason = BANDLIM_RST_OPENPORT;
2277 goto dropwithreset;
2278 }
2279
2280 todrop = tp->rcv_nxt - th->th_seq;
2281 if (todrop > 0) {
2282 if (thflags & TH_SYN) {
2283 thflags &= ~TH_SYN;
2284 th->th_seq++;
2285 if (th->th_urp > 1)
2286 th->th_urp--;
2287 else
2288 thflags &= ~TH_URG;
2289 todrop--;
2290 }
2291 /*
2292 * Following if statement from Stevens, vol. 2, p. 960.
2293 */
2294 if (todrop > tlen
2295 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
2296 /*
2297 * Any valid FIN must be to the left of the window.
2298 * At this point the FIN must be a duplicate or out
2299 * of sequence; drop it.
2300 */
2301 thflags &= ~TH_FIN;
2302
2303 /*
2304 * Send an ACK to resynchronize and drop any data.
2305 * But keep on processing for RST or ACK.
2306 */
2307 tp->t_flags |= TF_ACKNOW;
2308 todrop = tlen;
2309 TCPSTAT_INC(tcps_rcvduppack);
2310 TCPSTAT_ADD(tcps_rcvdupbyte, todrop);
2311 } else {
2312 TCPSTAT_INC(tcps_rcvpartduppack);
2313 TCPSTAT_ADD(tcps_rcvpartdupbyte, todrop);
2314 }
2315 /*
2316 * DSACK - add SACK block for dropped range
2317 */
2318 if ((todrop > 0) && (tp->t_flags & TF_SACK_PERMIT)) {
2319 tcp_update_sack_list(tp, th->th_seq,
2320 th->th_seq + todrop);
2321 /*
2322 * ACK now, as the next in-sequence segment
2323 * will clear the DSACK block again
2324 */
2325 tp->t_flags |= TF_ACKNOW;
2326 }
2327 drop_hdrlen += todrop; /* drop from the top afterwards */
2328 th->th_seq += todrop;
2329 tlen -= todrop;
2330 if (th->th_urp > todrop)
2331 th->th_urp -= todrop;
2332 else {
2333 thflags &= ~TH_URG;
2334 th->th_urp = 0;
2335 }
2336 }
2337
2338 /*
2339 * If new data are received on a connection after the
2340 * user processes are gone, then RST the other end.
2341 */
2342 if ((so->so_state & SS_NOFDREF) &&
2343 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
2344 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2345
2346 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
2347 log(LOG_DEBUG, "%s; %s: %s: Received %d bytes of data "
2348 "after socket was closed, "
2349 "sending RST and removing tcpcb\n",
2350 s, __func__, tcpstates[tp->t_state], tlen);
2351 free(s, M_TCPLOG);
2352 }
2353 tp = tcp_close(tp);
2354 TCPSTAT_INC(tcps_rcvafterclose);
2355 rstreason = BANDLIM_UNLIMITED;
2356 goto dropwithreset;
2357 }
2358
2359 /*
2360 * If segment ends after window, drop trailing data
2361 * (and PUSH and FIN); if nothing left, just ACK.
2362 */
2363 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
2364 if (todrop > 0) {
2365 TCPSTAT_INC(tcps_rcvpackafterwin);
2366 if (todrop >= tlen) {
2367 TCPSTAT_ADD(tcps_rcvbyteafterwin, tlen);
2368 /*
2369 * If window is closed can only take segments at
2370 * window edge, and have to drop data and PUSH from
2371 * incoming segments. Continue processing, but
2372 * remember to ack. Otherwise, drop segment
2373 * and ack.
2374 */
2375 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
2376 tp->t_flags |= TF_ACKNOW;
2377 TCPSTAT_INC(tcps_rcvwinprobe);
2378 } else
2379 goto dropafterack;
2380 } else
2381 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
2382 m_adj(m, -todrop);
2383 tlen -= todrop;
2384 thflags &= ~(TH_PUSH|TH_FIN);
2385 }
2386
2387 /*
2388 * If last ACK falls within this segment's sequence numbers,
2389 * record its timestamp.
2390 * NOTE:
2391 * 1) That the test incorporates suggestions from the latest
2392 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
2393 * 2) That updating only on newer timestamps interferes with
2394 * our earlier PAWS tests, so this check should be solely
2395 * predicated on the sequence space of this segment.
2396 * 3) That we modify the segment boundary check to be
2397 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
2398 * instead of RFC1323's
2399 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
2400 * This modified check allows us to overcome RFC1323's
2401 * limitations as described in Stevens TCP/IP Illustrated
2402 * Vol. 2 p.869. In such cases, we can still calculate the
2403 * RTT correctly when RCV.NXT == Last.ACK.Sent.
2404 */
2405 if ((to.to_flags & TOF_TS) != 0 &&
2406 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
2407 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
2408 ((thflags & (TH_SYN|TH_FIN)) != 0))) {
2409 tp->ts_recent_age = tcp_ts_getticks();
2410 tp->ts_recent = to.to_tsval;
2411 }
2412
2413 /*
2414 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
2415 * flag is on (half-synchronized state), then queue data for
2416 * later processing; else drop segment and return.
2417 */
2418 if ((thflags & TH_ACK) == 0) {
2419 if (tp->t_state == TCPS_SYN_RECEIVED ||
2420 (tp->t_flags & TF_NEEDSYN)) {
2421 if (tp->t_state == TCPS_SYN_RECEIVED &&
2422 IS_FASTOPEN(tp->t_flags)) {
2423 tp->snd_wnd = tiwin;
2424 cc_conn_init(tp);
2425 }
2426 goto step6;
2427 } else if (tp->t_flags & TF_ACKNOW)
2428 goto dropafterack;
2429 else
2430 goto drop;
2431 }
2432
2433 /*
2434 * Ack processing.
2435 */
2436 switch (tp->t_state) {
2437
2438 /*
2439 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
2440 * ESTABLISHED state and continue processing.
2441 * The ACK was checked above.
2442 */
2443 case TCPS_SYN_RECEIVED:
2444
2445 TCPSTAT_INC(tcps_connects);
2446 soisconnected(so);
2447 /* Do window scaling? */
2448 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2449 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2450 tp->rcv_scale = tp->request_r_scale;
2451 }
2452 tp->snd_wnd = tiwin;
2453 /*
2454 * Make transitions:
2455 * SYN-RECEIVED -> ESTABLISHED
2456 * SYN-RECEIVED* -> FIN-WAIT-1
2457 */
2458 tp->t_starttime = ticks;
2459 if (IS_FASTOPEN(tp->t_flags) && tp->t_tfo_pending) {
2460 tcp_fastopen_decrement_counter(tp->t_tfo_pending);
2461 tp->t_tfo_pending = NULL;
2462 }
2463 if (tp->t_flags & TF_NEEDFIN) {
2464 tcp_state_change(tp, TCPS_FIN_WAIT_1);
2465 tp->t_flags &= ~TF_NEEDFIN;
2466 } else {
2467 tcp_state_change(tp, TCPS_ESTABLISHED);
2468 TCP_PROBE5(accept__established, NULL, tp,
2469 m, tp, th);
2470 /*
2471 * TFO connections call cc_conn_init() during SYN
2472 * processing. Calling it again here for such
2473 * connections is not harmless as it would undo the
2474 * snd_cwnd reduction that occurs when a TFO SYN|ACK
2475 * is retransmitted.
2476 */
2477 if (!IS_FASTOPEN(tp->t_flags))
2478 cc_conn_init(tp);
2479 tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp));
2480 }
2481 /*
2482 * Account for the ACK of our SYN prior to
2483 * regular ACK processing below, except for
2484 * simultaneous SYN, which is handled later.
2485 */
2486 if (SEQ_GT(th->th_ack, tp->snd_una) && !(tp->t_flags & TF_NEEDSYN))
2487 incforsyn = 1;
2488 /*
2489 * If segment contains data or ACK, will call tcp_reass()
2490 * later; if not, do so now to pass queued data to user.
2491 */
2492 if (tlen == 0 && (thflags & TH_FIN) == 0)
2493 (void) tcp_reass(tp, (struct tcphdr *)0, NULL, 0,
2494 (struct mbuf *)0);
2495 tp->snd_wl1 = th->th_seq - 1;
2496 /* FALLTHROUGH */
2497
2498 /*
2499 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2500 * ACKs. If the ack is in the range
2501 * tp->snd_una < th->th_ack <= tp->snd_max
2502 * then advance tp->snd_una to th->th_ack and drop
2503 * data from the retransmission queue. If this ACK reflects
2504 * more up to date window information we update our window information.
2505 */
2506 case TCPS_ESTABLISHED:
2507 case TCPS_FIN_WAIT_1:
2508 case TCPS_FIN_WAIT_2:
2509 case TCPS_CLOSE_WAIT:
2510 case TCPS_CLOSING:
2511 case TCPS_LAST_ACK:
2512 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2513 TCPSTAT_INC(tcps_rcvacktoomuch);
2514 goto dropafterack;
2515 }
2516 if ((tp->t_flags & TF_SACK_PERMIT) &&
2517 ((to.to_flags & TOF_SACK) ||
2518 !TAILQ_EMPTY(&tp->snd_holes)))
2519 sack_changed = tcp_sack_doack(tp, &to, th->th_ack);
2520 else
2521 /*
2522 * Reset the value so that previous (valid) value
2523 * from the last ack with SACK doesn't get used.
2524 */
2525 tp->sackhint.sacked_bytes = 0;
2526
2527 #ifdef TCP_HHOOK
2528 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
2529 hhook_run_tcp_est_in(tp, th, &to);
2530 #endif
2531
2532 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
2533 u_int maxseg;
2534
2535 maxseg = tcp_maxseg(tp);
2536 if (tlen == 0 &&
2537 (tiwin == tp->snd_wnd ||
2538 (tp->t_flags & TF_SACK_PERMIT))) {
2539 /*
2540 * If this is the first time we've seen a
2541 * FIN from the remote, this is not a
2542 * duplicate and it needs to be processed
2543 * normally. This happens during a
2544 * simultaneous close.
2545 */
2546 if ((thflags & TH_FIN) &&
2547 (TCPS_HAVERCVDFIN(tp->t_state) == 0)) {
2548 tp->t_dupacks = 0;
2549 break;
2550 }
2551 TCPSTAT_INC(tcps_rcvdupack);
2552 /*
2553 * If we have outstanding data (other than
2554 * a window probe), this is a completely
2555 * duplicate ack (ie, window info didn't
2556 * change and FIN isn't set),
2557 * the ack is the biggest we've
2558 * seen and we've seen exactly our rexmt
2559 * threshold of them, assume a packet
2560 * has been dropped and retransmit it.
2561 * Kludge snd_nxt & the congestion
2562 * window so we send only this one
2563 * packet.
2564 *
2565 * We know we're losing at the current
2566 * window size so do congestion avoidance
2567 * (set ssthresh to half the current window
2568 * and pull our congestion window back to
2569 * the new ssthresh).
2570 *
2571 * Dup acks mean that packets have left the
2572 * network (they're now cached at the receiver)
2573 * so bump cwnd by the amount in the receiver
2574 * to keep a constant cwnd packets in the
2575 * network.
2576 *
2577 * When using TCP ECN, notify the peer that
2578 * we reduced the cwnd.
2579 */
2580 /*
2581 * Following 2 kinds of acks should not affect
2582 * dupack counting:
2583 * 1) Old acks
2584 * 2) Acks with SACK but without any new SACK
2585 * information in them. These could result from
2586 * any anomaly in the network like a switch
2587 * duplicating packets or a possible DoS attack.
2588 */
2589 if (th->th_ack != tp->snd_una ||
2590 ((tp->t_flags & TF_SACK_PERMIT) &&
2591 !sack_changed))
2592 break;
2593 else if (!tcp_timer_active(tp, TT_REXMT))
2594 tp->t_dupacks = 0;
2595 else if (++tp->t_dupacks > tcprexmtthresh ||
2596 IN_FASTRECOVERY(tp->t_flags)) {
2597 cc_ack_received(tp, th, nsegs,
2598 CC_DUPACK);
2599 if ((tp->t_flags & TF_SACK_PERMIT) &&
2600 IN_FASTRECOVERY(tp->t_flags)) {
2601 int awnd;
2602
2603 /*
2604 * Compute the amount of data in flight first.
2605 * We can inject new data into the pipe iff
2606 * we have less than 1/2 the original window's
2607 * worth of data in flight.
2608 */
2609 if (V_tcp_do_rfc6675_pipe)
2610 awnd = tcp_compute_pipe(tp);
2611 else
2612 awnd = (tp->snd_nxt - tp->snd_fack) +
2613 tp->sackhint.sack_bytes_rexmit;
2614
2615 if (awnd < tp->snd_ssthresh) {
2616 tp->snd_cwnd += maxseg;
2617 if (tp->snd_cwnd > tp->snd_ssthresh)
2618 tp->snd_cwnd = tp->snd_ssthresh;
2619 }
2620 } else
2621 tp->snd_cwnd += maxseg;
2622 (void) tp->t_fb->tfb_tcp_output(tp);
2623 goto drop;
2624 } else if (tp->t_dupacks == tcprexmtthresh) {
2625 tcp_seq onxt = tp->snd_nxt;
2626
2627 /*
2628 * If we're doing sack, check to
2629 * see if we're already in sack
2630 * recovery. If we're not doing sack,
2631 * check to see if we're in newreno
2632 * recovery.
2633 */
2634 if (tp->t_flags & TF_SACK_PERMIT) {
2635 if (IN_FASTRECOVERY(tp->t_flags)) {
2636 tp->t_dupacks = 0;
2637 break;
2638 }
2639 } else {
2640 if (SEQ_LEQ(th->th_ack,
2641 tp->snd_recover)) {
2642 tp->t_dupacks = 0;
2643 break;
2644 }
2645 }
2646 /* Congestion signal before ack. */
2647 cc_cong_signal(tp, th, CC_NDUPACK);
2648 cc_ack_received(tp, th, nsegs,
2649 CC_DUPACK);
2650 tcp_timer_activate(tp, TT_REXMT, 0);
2651 tp->t_rtttime = 0;
2652 if (tp->t_flags & TF_SACK_PERMIT) {
2653 TCPSTAT_INC(
2654 tcps_sack_recovery_episode);
2655 tp->sack_newdata = tp->snd_nxt;
2656 tp->snd_cwnd = maxseg;
2657 (void) tp->t_fb->tfb_tcp_output(tp);
2658 goto drop;
2659 }
2660 tp->snd_nxt = th->th_ack;
2661 tp->snd_cwnd = maxseg;
2662 (void) tp->t_fb->tfb_tcp_output(tp);
2663 KASSERT(tp->snd_limited <= 2,
2664 ("%s: tp->snd_limited too big",
2665 __func__));
2666 tp->snd_cwnd = tp->snd_ssthresh +
2667 maxseg *
2668 (tp->t_dupacks - tp->snd_limited);
2669 if (SEQ_GT(onxt, tp->snd_nxt))
2670 tp->snd_nxt = onxt;
2671 goto drop;
2672 } else if (V_tcp_do_rfc3042) {
2673 /*
2674 * Process first and second duplicate
2675 * ACKs. Each indicates a segment
2676 * leaving the network, creating room
2677 * for more. Make sure we can send a
2678 * packet on reception of each duplicate
2679 * ACK by increasing snd_cwnd by one
2680 * segment. Restore the original
2681 * snd_cwnd after packet transmission.
2682 */
2683 cc_ack_received(tp, th, nsegs,
2684 CC_DUPACK);
2685 uint32_t oldcwnd = tp->snd_cwnd;
2686 tcp_seq oldsndmax = tp->snd_max;
2687 u_int sent;
2688 int avail;
2689
2690 KASSERT(tp->t_dupacks == 1 ||
2691 tp->t_dupacks == 2,
2692 ("%s: dupacks not 1 or 2",
2693 __func__));
2694 if (tp->t_dupacks == 1)
2695 tp->snd_limited = 0;
2696 tp->snd_cwnd =
2697 (tp->snd_nxt - tp->snd_una) +
2698 (tp->t_dupacks - tp->snd_limited) *
2699 maxseg;
2700 /*
2701 * Only call tcp_output when there
2702 * is new data available to be sent
2703 * or we need to send an ACK.
2704 */
2705 SOCKBUF_LOCK(&so->so_snd);
2706 avail = sbavail(&so->so_snd) -
2707 (tp->snd_nxt - tp->snd_una);
2708 SOCKBUF_UNLOCK(&so->so_snd);
2709 if (avail > 0 || tp->t_flags & TF_ACKNOW)
2710 (void) tp->t_fb->tfb_tcp_output(tp);
2711 sent = tp->snd_max - oldsndmax;
2712 if (sent > maxseg) {
2713 KASSERT((tp->t_dupacks == 2 &&
2714 tp->snd_limited == 0) ||
2715 (sent == maxseg + 1 &&
2716 tp->t_flags & TF_SENTFIN),
2717 ("%s: sent too much",
2718 __func__));
2719 tp->snd_limited = 2;
2720 } else if (sent > 0)
2721 ++tp->snd_limited;
2722 tp->snd_cwnd = oldcwnd;
2723 goto drop;
2724 }
2725 }
2726 break;
2727 } else {
2728 /*
2729 * This ack is advancing the left edge, reset the
2730 * counter.
2731 */
2732 tp->t_dupacks = 0;
2733 /*
2734 * If this ack also has new SACK info, increment the
2735 * counter as per rfc6675. The variable
2736 * sack_changed tracks all changes to the SACK
2737 * scoreboard, including when partial ACKs without
2738 * SACK options are received, and clear the scoreboard
2739 * from the left side. Such partial ACKs should not be
2740 * counted as dupacks here.
2741 */
2742 if ((tp->t_flags & TF_SACK_PERMIT) &&
2743 (to.to_flags & TOF_SACK) &&
2744 sack_changed)
2745 tp->t_dupacks++;
2746 }
2747
2748 KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
2749 ("%s: th_ack <= snd_una", __func__));
2750
2751 /*
2752 * If the congestion window was inflated to account
2753 * for the other side's cached packets, retract it.
2754 */
2755 if (IN_FASTRECOVERY(tp->t_flags)) {
2756 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2757 if (tp->t_flags & TF_SACK_PERMIT)
2758 tcp_sack_partialack(tp, th);
2759 else
2760 tcp_newreno_partial_ack(tp, th);
2761 } else
2762 cc_post_recovery(tp, th);
2763 }
2764 /*
2765 * If we reach this point, ACK is not a duplicate,
2766 * i.e., it ACKs something we sent.
2767 */
2768 if (tp->t_flags & TF_NEEDSYN) {
2769 /*
2770 * T/TCP: Connection was half-synchronized, and our
2771 * SYN has been ACK'd (so connection is now fully
2772 * synchronized). Go to non-starred state,
2773 * increment snd_una for ACK of SYN, and check if
2774 * we can do window scaling.
2775 */
2776 tp->t_flags &= ~TF_NEEDSYN;
2777 tp->snd_una++;
2778 /* Do window scaling? */
2779 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2780 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2781 tp->rcv_scale = tp->request_r_scale;
2782 /* Send window already scaled. */
2783 }
2784 }
2785
2786 process_ACK:
2787 INP_WLOCK_ASSERT(tp->t_inpcb);
2788
2789 /*
2790 * Adjust for the SYN bit in sequence space,
2791 * but don't account for it in cwnd calculations.
2792 * This is for the SYN_RECEIVED, non-simultaneous
2793 * SYN case. SYN_SENT and simultaneous SYN are
2794 * treated elsewhere.
2795 */
2796 if (incforsyn)
2797 tp->snd_una++;
2798 acked = BYTES_THIS_ACK(tp, th);
2799 KASSERT(acked >= 0, ("%s: acked unexepectedly negative "
2800 "(tp->snd_una=%u, th->th_ack=%u, tp=%p, m=%p)", __func__,
2801 tp->snd_una, th->th_ack, tp, m));
2802 TCPSTAT_ADD(tcps_rcvackpack, nsegs);
2803 TCPSTAT_ADD(tcps_rcvackbyte, acked);
2804
2805 /*
2806 * If we just performed our first retransmit, and the ACK
2807 * arrives within our recovery window, then it was a mistake
2808 * to do the retransmit in the first place. Recover our
2809 * original cwnd and ssthresh, and proceed to transmit where
2810 * we left off.
2811 */
2812 if (tp->t_rxtshift == 1 &&
2813 tp->t_flags & TF_PREVVALID &&
2814 tp->t_badrxtwin &&
2815 SEQ_LT(to.to_tsecr, tp->t_badrxtwin))
2816 cc_cong_signal(tp, th, CC_RTO_ERR);
2817
2818 /*
2819 * If we have a timestamp reply, update smoothed
2820 * round trip time. If no timestamp is present but
2821 * transmit timer is running and timed sequence
2822 * number was acked, update smoothed round trip time.
2823 * Since we now have an rtt measurement, cancel the
2824 * timer backoff (cf., Phil Karn's retransmit alg.).
2825 * Recompute the initial retransmit timer.
2826 *
2827 * Some boxes send broken timestamp replies
2828 * during the SYN+ACK phase, ignore
2829 * timestamps of 0 or we could calculate a
2830 * huge RTT and blow up the retransmit timer.
2831 */
2832 if ((to.to_flags & TOF_TS) != 0 && to.to_tsecr) {
2833 uint32_t t;
2834
2835 t = tcp_ts_getticks() - to.to_tsecr;
2836 if (!tp->t_rttlow || tp->t_rttlow > t)
2837 tp->t_rttlow = t;
2838 tcp_xmit_timer(tp, TCP_TS_TO_TICKS(t) + 1);
2839 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
2840 if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
2841 tp->t_rttlow = ticks - tp->t_rtttime;
2842 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2843 }
2844
2845 /*
2846 * If all outstanding data is acked, stop retransmit
2847 * timer and remember to restart (more output or persist).
2848 * If there is more data to be acked, restart retransmit
2849 * timer, using current (possibly backed-off) value.
2850 */
2851 if (th->th_ack == tp->snd_max) {
2852 tcp_timer_activate(tp, TT_REXMT, 0);
2853 needoutput = 1;
2854 } else if (!tcp_timer_active(tp, TT_PERSIST))
2855 tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
2856
2857 /*
2858 * If no data (only SYN) was ACK'd,
2859 * skip rest of ACK processing.
2860 */
2861 if (acked == 0)
2862 goto step6;
2863
2864 /*
2865 * Let the congestion control algorithm update congestion
2866 * control related information. This typically means increasing
2867 * the congestion window.
2868 */
2869 cc_ack_received(tp, th, nsegs, CC_ACK);
2870
2871 SOCKBUF_LOCK(&so->so_snd);
2872 if (acked > sbavail(&so->so_snd)) {
2873 if (tp->snd_wnd >= sbavail(&so->so_snd))
2874 tp->snd_wnd -= sbavail(&so->so_snd);
2875 else
2876 tp->snd_wnd = 0;
2877 mfree = sbcut_locked(&so->so_snd,
2878 (int)sbavail(&so->so_snd));
2879 ourfinisacked = 1;
2880 } else {
2881 mfree = sbcut_locked(&so->so_snd, acked);
2882 if (tp->snd_wnd >= (uint32_t) acked)
2883 tp->snd_wnd -= acked;
2884 else
2885 tp->snd_wnd = 0;
2886 ourfinisacked = 0;
2887 }
2888 /* NB: sowwakeup_locked() does an implicit unlock. */
2889 sowwakeup_locked(so);
2890 m_freem(mfree);
2891 /* Detect una wraparound. */
2892 if (!IN_RECOVERY(tp->t_flags) &&
2893 SEQ_GT(tp->snd_una, tp->snd_recover) &&
2894 SEQ_LEQ(th->th_ack, tp->snd_recover))
2895 tp->snd_recover = th->th_ack - 1;
2896 /* XXXLAS: Can this be moved up into cc_post_recovery? */
2897 if (IN_RECOVERY(tp->t_flags) &&
2898 SEQ_GEQ(th->th_ack, tp->snd_recover)) {
2899 EXIT_RECOVERY(tp->t_flags);
2900 }
2901 tp->snd_una = th->th_ack;
2902 if (tp->t_flags & TF_SACK_PERMIT) {
2903 if (SEQ_GT(tp->snd_una, tp->snd_recover))
2904 tp->snd_recover = tp->snd_una;
2905 }
2906 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2907 tp->snd_nxt = tp->snd_una;
2908
2909 switch (tp->t_state) {
2910
2911 /*
2912 * In FIN_WAIT_1 STATE in addition to the processing
2913 * for the ESTABLISHED state if our FIN is now acknowledged
2914 * then enter FIN_WAIT_2.
2915 */
2916 case TCPS_FIN_WAIT_1:
2917 if (ourfinisacked) {
2918 /*
2919 * If we can't receive any more
2920 * data, then closing user can proceed.
2921 * Starting the timer is contrary to the
2922 * specification, but if we don't get a FIN
2923 * we'll hang forever.
2924 *
2925 * XXXjl:
2926 * we should release the tp also, and use a
2927 * compressed state.
2928 */
2929 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2930 soisdisconnected(so);
2931 tcp_timer_activate(tp, TT_2MSL,
2932 (tcp_fast_finwait2_recycle ?
2933 tcp_finwait2_timeout :
2934 TP_MAXIDLE(tp)));
2935 }
2936 tcp_state_change(tp, TCPS_FIN_WAIT_2);
2937 }
2938 break;
2939
2940 /*
2941 * In CLOSING STATE in addition to the processing for
2942 * the ESTABLISHED state if the ACK acknowledges our FIN
2943 * then enter the TIME-WAIT state, otherwise ignore
2944 * the segment.
2945 */
2946 case TCPS_CLOSING:
2947 if (ourfinisacked) {
2948 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2949 tcp_twstart(tp);
2950 m_freem(m);
2951 return;
2952 }
2953 break;
2954
2955 /*
2956 * In LAST_ACK, we may still be waiting for data to drain
2957 * and/or to be acked, as well as for the ack of our FIN.
2958 * If our FIN is now acknowledged, delete the TCB,
2959 * enter the closed state and return.
2960 */
2961 case TCPS_LAST_ACK:
2962 if (ourfinisacked) {
2963 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2964 tp = tcp_close(tp);
2965 goto drop;
2966 }
2967 break;
2968 }
2969 }
2970
2971 step6:
2972 INP_WLOCK_ASSERT(tp->t_inpcb);
2973
2974 /*
2975 * Update window information.
2976 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2977 */
2978 if ((thflags & TH_ACK) &&
2979 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2980 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2981 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2982 /* keep track of pure window updates */
2983 if (tlen == 0 &&
2984 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2985 TCPSTAT_INC(tcps_rcvwinupd);
2986 tp->snd_wnd = tiwin;
2987 tp->snd_wl1 = th->th_seq;
2988 tp->snd_wl2 = th->th_ack;
2989 if (tp->snd_wnd > tp->max_sndwnd)
2990 tp->max_sndwnd = tp->snd_wnd;
2991 needoutput = 1;
2992 }
2993
2994 /*
2995 * Process segments with URG.
2996 */
2997 if ((thflags & TH_URG) && th->th_urp &&
2998 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2999 /*
3000 * This is a kludge, but if we receive and accept
3001 * random urgent pointers, we'll crash in
3002 * soreceive. It's hard to imagine someone
3003 * actually wanting to send this much urgent data.
3004 */
3005 SOCKBUF_LOCK(&so->so_rcv);
3006 if (th->th_urp + sbavail(&so->so_rcv) > sb_max) {
3007 th->th_urp = 0; /* XXX */
3008 thflags &= ~TH_URG; /* XXX */
3009 SOCKBUF_UNLOCK(&so->so_rcv); /* XXX */
3010 goto dodata; /* XXX */
3011 }
3012 /*
3013 * If this segment advances the known urgent pointer,
3014 * then mark the data stream. This should not happen
3015 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
3016 * a FIN has been received from the remote side.
3017 * In these states we ignore the URG.
3018 *
3019 * According to RFC961 (Assigned Protocols),
3020 * the urgent pointer points to the last octet
3021 * of urgent data. We continue, however,
3022 * to consider it to indicate the first octet
3023 * of data past the urgent section as the original
3024 * spec states (in one of two places).
3025 */
3026 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
3027 tp->rcv_up = th->th_seq + th->th_urp;
3028 so->so_oobmark = sbavail(&so->so_rcv) +
3029 (tp->rcv_up - tp->rcv_nxt) - 1;
3030 if (so->so_oobmark == 0)
3031 so->so_rcv.sb_state |= SBS_RCVATMARK;
3032 sohasoutofband(so);
3033 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
3034 }
3035 SOCKBUF_UNLOCK(&so->so_rcv);
3036 /*
3037 * Remove out of band data so doesn't get presented to user.
3038 * This can happen independent of advancing the URG pointer,
3039 * but if two URG's are pending at once, some out-of-band
3040 * data may creep in... ick.
3041 */
3042 if (th->th_urp <= (uint32_t)tlen &&
3043 !(so->so_options & SO_OOBINLINE)) {
3044 /* hdr drop is delayed */
3045 tcp_pulloutofband(so, th, m, drop_hdrlen);
3046 }
3047 } else {
3048 /*
3049 * If no out of band data is expected,
3050 * pull receive urgent pointer along
3051 * with the receive window.
3052 */
3053 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
3054 tp->rcv_up = tp->rcv_nxt;
3055 }
3056 dodata: /* XXX */
3057 INP_WLOCK_ASSERT(tp->t_inpcb);
3058
3059 /*
3060 * Process the segment text, merging it into the TCP sequencing queue,
3061 * and arranging for acknowledgment of receipt if necessary.
3062 * This process logically involves adjusting tp->rcv_wnd as data
3063 * is presented to the user (this happens in tcp_usrreq.c,
3064 * case PRU_RCVD). If a FIN has already been received on this
3065 * connection then we just ignore the text.
3066 */
3067 tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
3068 IS_FASTOPEN(tp->t_flags));
3069 if ((tlen || (thflags & TH_FIN) || tfo_syn) &&
3070 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
3071 tcp_seq save_start = th->th_seq;
3072 tcp_seq save_rnxt = tp->rcv_nxt;
3073 int save_tlen = tlen;
3074 m_adj(m, drop_hdrlen); /* delayed header drop */
3075 /*
3076 * Insert segment which includes th into TCP reassembly queue
3077 * with control block tp. Set thflags to whether reassembly now
3078 * includes a segment with FIN. This handles the common case
3079 * inline (segment is the next to be received on an established
3080 * connection, and the queue is empty), avoiding linkage into
3081 * and removal from the queue and repetition of various
3082 * conversions.
3083 * Set DELACK for segments received in order, but ack
3084 * immediately when segments are out of order (so
3085 * fast retransmit can work).
3086 */
3087 if (th->th_seq == tp->rcv_nxt &&
3088 SEGQ_EMPTY(tp) &&
3089 (TCPS_HAVEESTABLISHED(tp->t_state) ||
3090 tfo_syn)) {
3091 if (DELAY_ACK(tp, tlen) || tfo_syn)
3092 tp->t_flags |= TF_DELACK;
3093 else
3094 tp->t_flags |= TF_ACKNOW;
3095 tp->rcv_nxt += tlen;
3096 thflags = th->th_flags & TH_FIN;
3097 TCPSTAT_INC(tcps_rcvpack);
3098 TCPSTAT_ADD(tcps_rcvbyte, tlen);
3099 SOCKBUF_LOCK(&so->so_rcv);
3100 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
3101 m_freem(m);
3102 else
3103 sbappendstream_locked(&so->so_rcv, m, 0);
3104 /* NB: sorwakeup_locked() does an implicit unlock. */
3105 sorwakeup_locked(so);
3106 } else {
3107 /*
3108 * XXX: Due to the header drop above "th" is
3109 * theoretically invalid by now. Fortunately
3110 * m_adj() doesn't actually frees any mbufs
3111 * when trimming from the head.
3112 */
3113 tcp_seq temp = save_start;
3114 thflags = tcp_reass(tp, th, &temp, &tlen, m);
3115 tp->t_flags |= TF_ACKNOW;
3116 }
3117 if ((tp->t_flags & TF_SACK_PERMIT) && (save_tlen > 0)) {
3118 if ((tlen == 0) && (SEQ_LT(save_start, save_rnxt))) {
3119 /*
3120 * DSACK actually handled in the fastpath
3121 * above.
3122 */
3123 tcp_update_sack_list(tp, save_start,
3124 save_start + save_tlen);
3125 } else if ((tlen > 0) && SEQ_GT(tp->rcv_nxt, save_rnxt)) {
3126 if ((tp->rcv_numsacks >= 1) &&
3127 (tp->sackblks[0].end == save_start)) {
3128 /*
3129 * Partial overlap, recorded at todrop
3130 * above.
3131 */
3132 tcp_update_sack_list(tp,
3133 tp->sackblks[0].start,
3134 tp->sackblks[0].end);
3135 } else {
3136 tcp_update_dsack_list(tp, save_start,
3137 save_start + save_tlen);
3138 }
3139 } else if (tlen >= save_tlen) {
3140 /* Update of sackblks. */
3141 tcp_update_dsack_list(tp, save_start,
3142 save_start + save_tlen);
3143 } else if (tlen > 0) {
3144 tcp_update_dsack_list(tp, save_start,
3145 save_start + tlen);
3146 }
3147 }
3148 #if 0
3149 /*
3150 * Note the amount of data that peer has sent into
3151 * our window, in order to estimate the sender's
3152 * buffer size.
3153 * XXX: Unused.
3154 */
3155 if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt))
3156 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
3157 else
3158 len = so->so_rcv.sb_hiwat;
3159 #endif
3160 } else {
3161 m_freem(m);
3162 thflags &= ~TH_FIN;
3163 }
3164
3165 /*
3166 * If FIN is received ACK the FIN and let the user know
3167 * that the connection is closing.
3168 */
3169 if (thflags & TH_FIN) {
3170 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
3171 socantrcvmore(so);
3172 /*
3173 * If connection is half-synchronized
3174 * (ie NEEDSYN flag on) then delay ACK,
3175 * so it may be piggybacked when SYN is sent.
3176 * Otherwise, since we received a FIN then no
3177 * more input can be expected, send ACK now.
3178 */
3179 if (tp->t_flags & TF_NEEDSYN)
3180 tp->t_flags |= TF_DELACK;
3181 else
3182 tp->t_flags |= TF_ACKNOW;
3183 tp->rcv_nxt++;
3184 }
3185 switch (tp->t_state) {
3186
3187 /*
3188 * In SYN_RECEIVED and ESTABLISHED STATES
3189 * enter the CLOSE_WAIT state.
3190 */
3191 case TCPS_SYN_RECEIVED:
3192 tp->t_starttime = ticks;
3193 /* FALLTHROUGH */
3194 case TCPS_ESTABLISHED:
3195 tcp_state_change(tp, TCPS_CLOSE_WAIT);
3196 break;
3197
3198 /*
3199 * If still in FIN_WAIT_1 STATE FIN has not been acked so
3200 * enter the CLOSING state.
3201 */
3202 case TCPS_FIN_WAIT_1:
3203 tcp_state_change(tp, TCPS_CLOSING);
3204 break;
3205
3206 /*
3207 * In FIN_WAIT_2 state enter the TIME_WAIT state,
3208 * starting the time-wait timer, turning off the other
3209 * standard timers.
3210 */
3211 case TCPS_FIN_WAIT_2:
3212 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
3213
3214 tcp_twstart(tp);
3215 return;
3216 }
3217 }
3218 #ifdef TCPDEBUG
3219 if (so->so_options & SO_DEBUG)
3220 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
3221 &tcp_savetcp, 0);
3222 #endif
3223 TCP_PROBE3(debug__input, tp, th, m);
3224
3225 /*
3226 * Return any desired output.
3227 */
3228 if (needoutput || (tp->t_flags & TF_ACKNOW))
3229 (void) tp->t_fb->tfb_tcp_output(tp);
3230
3231 check_delack:
3232 INP_WLOCK_ASSERT(tp->t_inpcb);
3233
3234 if (tp->t_flags & TF_DELACK) {
3235 tp->t_flags &= ~TF_DELACK;
3236 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
3237 }
3238 INP_WUNLOCK(tp->t_inpcb);
3239 return;
3240
3241 dropafterack:
3242 /*
3243 * Generate an ACK dropping incoming segment if it occupies
3244 * sequence space, where the ACK reflects our state.
3245 *
3246 * We can now skip the test for the RST flag since all
3247 * paths to this code happen after packets containing
3248 * RST have been dropped.
3249 *
3250 * In the SYN-RECEIVED state, don't send an ACK unless the
3251 * segment we received passes the SYN-RECEIVED ACK test.
3252 * If it fails send a RST. This breaks the loop in the
3253 * "LAND" DoS attack, and also prevents an ACK storm
3254 * between two listening ports that have been sent forged
3255 * SYN segments, each with the source address of the other.
3256 */
3257 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
3258 (SEQ_GT(tp->snd_una, th->th_ack) ||
3259 SEQ_GT(th->th_ack, tp->snd_max)) ) {
3260 rstreason = BANDLIM_RST_OPENPORT;
3261 goto dropwithreset;
3262 }
3263 #ifdef TCPDEBUG
3264 if (so->so_options & SO_DEBUG)
3265 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
3266 &tcp_savetcp, 0);
3267 #endif
3268 TCP_PROBE3(debug__input, tp, th, m);
3269 tp->t_flags |= TF_ACKNOW;
3270 (void) tp->t_fb->tfb_tcp_output(tp);
3271 INP_WUNLOCK(tp->t_inpcb);
3272 m_freem(m);
3273 return;
3274
3275 dropwithreset:
3276 if (tp != NULL) {
3277 tcp_dropwithreset(m, th, tp, tlen, rstreason);
3278 INP_WUNLOCK(tp->t_inpcb);
3279 } else
3280 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
3281 return;
3282
3283 drop:
3284 /*
3285 * Drop space held by incoming segment and return.
3286 */
3287 #ifdef TCPDEBUG
3288 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
3289 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
3290 &tcp_savetcp, 0);
3291 #endif
3292 TCP_PROBE3(debug__input, tp, th, m);
3293 if (tp != NULL)
3294 INP_WUNLOCK(tp->t_inpcb);
3295 m_freem(m);
3296 }
3297
3298 /*
3299 * Issue RST and make ACK acceptable to originator of segment.
3300 * The mbuf must still include the original packet header.
3301 * tp may be NULL.
3302 */
3303 void
tcp_dropwithreset(struct mbuf * m,struct tcphdr * th,struct tcpcb * tp,int tlen,int rstreason)3304 tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
3305 int tlen, int rstreason)
3306 {
3307 #ifdef INET
3308 struct ip *ip;
3309 #endif
3310 #ifdef INET6
3311 struct ip6_hdr *ip6;
3312 #endif
3313
3314 if (tp != NULL) {
3315 INP_WLOCK_ASSERT(tp->t_inpcb);
3316 }
3317
3318 /* Don't bother if destination was broadcast/multicast. */
3319 if ((th->th_flags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
3320 goto drop;
3321 #ifdef INET6
3322 if (mtod(m, struct ip *)->ip_v == 6) {
3323 ip6 = mtod(m, struct ip6_hdr *);
3324 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
3325 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
3326 goto drop;
3327 /* IPv6 anycast check is done at tcp6_input() */
3328 }
3329 #endif
3330 #if defined(INET) && defined(INET6)
3331 else
3332 #endif
3333 #ifdef INET
3334 {
3335 ip = mtod(m, struct ip *);
3336 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
3337 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
3338 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
3339 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
3340 goto drop;
3341 }
3342 #endif
3343
3344 /* Perform bandwidth limiting. */
3345 if (badport_bandlim(rstreason) < 0)
3346 goto drop;
3347
3348 /* tcp_respond consumes the mbuf chain. */
3349 if (th->th_flags & TH_ACK) {
3350 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0,
3351 th->th_ack, TH_RST);
3352 } else {
3353 if (th->th_flags & TH_SYN)
3354 tlen++;
3355 if (th->th_flags & TH_FIN)
3356 tlen++;
3357 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
3358 (tcp_seq)0, TH_RST|TH_ACK);
3359 }
3360 return;
3361 drop:
3362 m_freem(m);
3363 }
3364
3365 /*
3366 * Parse TCP options and place in tcpopt.
3367 */
3368 void
tcp_dooptions(struct tcpopt * to,u_char * cp,int cnt,int flags)3369 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags)
3370 {
3371 int opt, optlen;
3372
3373 to->to_flags = 0;
3374 for (; cnt > 0; cnt -= optlen, cp += optlen) {
3375 opt = cp[0];
3376 if (opt == TCPOPT_EOL)
3377 break;
3378 if (opt == TCPOPT_NOP)
3379 optlen = 1;
3380 else {
3381 if (cnt < 2)
3382 break;
3383 optlen = cp[1];
3384 if (optlen < 2 || optlen > cnt)
3385 break;
3386 }
3387 switch (opt) {
3388 case TCPOPT_MAXSEG:
3389 if (optlen != TCPOLEN_MAXSEG)
3390 continue;
3391 if (!(flags & TO_SYN))
3392 continue;
3393 to->to_flags |= TOF_MSS;
3394 bcopy((char *)cp + 2,
3395 (char *)&to->to_mss, sizeof(to->to_mss));
3396 to->to_mss = ntohs(to->to_mss);
3397 break;
3398 case TCPOPT_WINDOW:
3399 if (optlen != TCPOLEN_WINDOW)
3400 continue;
3401 if (!(flags & TO_SYN))
3402 continue;
3403 to->to_flags |= TOF_SCALE;
3404 to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT);
3405 break;
3406 case TCPOPT_TIMESTAMP:
3407 if (optlen != TCPOLEN_TIMESTAMP)
3408 continue;
3409 to->to_flags |= TOF_TS;
3410 bcopy((char *)cp + 2,
3411 (char *)&to->to_tsval, sizeof(to->to_tsval));
3412 to->to_tsval = ntohl(to->to_tsval);
3413 bcopy((char *)cp + 6,
3414 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
3415 to->to_tsecr = ntohl(to->to_tsecr);
3416 break;
3417 case TCPOPT_SIGNATURE:
3418 /*
3419 * In order to reply to a host which has set the
3420 * TCP_SIGNATURE option in its initial SYN, we have
3421 * to record the fact that the option was observed
3422 * here for the syncache code to perform the correct
3423 * response.
3424 */
3425 if (optlen != TCPOLEN_SIGNATURE)
3426 continue;
3427 to->to_flags |= TOF_SIGNATURE;
3428 to->to_signature = cp + 2;
3429 break;
3430 case TCPOPT_SACK_PERMITTED:
3431 if (optlen != TCPOLEN_SACK_PERMITTED)
3432 continue;
3433 if (!(flags & TO_SYN))
3434 continue;
3435 if (!V_tcp_do_sack)
3436 continue;
3437 to->to_flags |= TOF_SACKPERM;
3438 break;
3439 case TCPOPT_SACK:
3440 if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
3441 continue;
3442 if (flags & TO_SYN)
3443 continue;
3444 to->to_flags |= TOF_SACK;
3445 to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
3446 to->to_sacks = cp + 2;
3447 TCPSTAT_INC(tcps_sack_rcv_blocks);
3448 break;
3449 case TCPOPT_FAST_OPEN:
3450 /*
3451 * Cookie length validation is performed by the
3452 * server side cookie checking code or the client
3453 * side cookie cache update code.
3454 */
3455 if (!(flags & TO_SYN))
3456 continue;
3457 if (!V_tcp_fastopen_client_enable &&
3458 !V_tcp_fastopen_server_enable)
3459 continue;
3460 to->to_flags |= TOF_FASTOPEN;
3461 to->to_tfo_len = optlen - 2;
3462 to->to_tfo_cookie = to->to_tfo_len ? cp + 2 : NULL;
3463 break;
3464 default:
3465 continue;
3466 }
3467 }
3468 }
3469
3470 /*
3471 * Pull out of band byte out of a segment so
3472 * it doesn't appear in the user's data queue.
3473 * It is still reflected in the segment length for
3474 * sequencing purposes.
3475 */
3476 void
tcp_pulloutofband(struct socket * so,struct tcphdr * th,struct mbuf * m,int off)3477 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m,
3478 int off)
3479 {
3480 int cnt = off + th->th_urp - 1;
3481
3482 while (cnt >= 0) {
3483 if (m->m_len > cnt) {
3484 char *cp = mtod(m, caddr_t) + cnt;
3485 struct tcpcb *tp = sototcpcb(so);
3486
3487 INP_WLOCK_ASSERT(tp->t_inpcb);
3488
3489 tp->t_iobc = *cp;
3490 tp->t_oobflags |= TCPOOB_HAVEDATA;
3491 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
3492 m->m_len--;
3493 if (m->m_flags & M_PKTHDR)
3494 m->m_pkthdr.len--;
3495 return;
3496 }
3497 cnt -= m->m_len;
3498 m = m->m_next;
3499 if (m == NULL)
3500 break;
3501 }
3502 panic("tcp_pulloutofband");
3503 }
3504
3505 /*
3506 * Collect new round-trip time estimate
3507 * and update averages and current timeout.
3508 */
3509 void
tcp_xmit_timer(struct tcpcb * tp,int rtt)3510 tcp_xmit_timer(struct tcpcb *tp, int rtt)
3511 {
3512 int delta;
3513
3514 INP_WLOCK_ASSERT(tp->t_inpcb);
3515
3516 TCPSTAT_INC(tcps_rttupdated);
3517 tp->t_rttupdated++;
3518 if ((tp->t_srtt != 0) && (tp->t_rxtshift <= TCP_RTT_INVALIDATE)) {
3519 /*
3520 * srtt is stored as fixed point with 5 bits after the
3521 * binary point (i.e., scaled by 8). The following magic
3522 * is equivalent to the smoothing algorithm in rfc793 with
3523 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
3524 * point). Adjust rtt to origin 0.
3525 */
3526 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
3527 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
3528
3529 if ((tp->t_srtt += delta) <= 0)
3530 tp->t_srtt = 1;
3531
3532 /*
3533 * We accumulate a smoothed rtt variance (actually, a
3534 * smoothed mean difference), then set the retransmit
3535 * timer to smoothed rtt + 4 times the smoothed variance.
3536 * rttvar is stored as fixed point with 4 bits after the
3537 * binary point (scaled by 16). The following is
3538 * equivalent to rfc793 smoothing with an alpha of .75
3539 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
3540 * rfc793's wired-in beta.
3541 */
3542 if (delta < 0)
3543 delta = -delta;
3544 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
3545 if ((tp->t_rttvar += delta) <= 0)
3546 tp->t_rttvar = 1;
3547 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
3548 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3549 } else {
3550 /*
3551 * No rtt measurement yet - use the unsmoothed rtt.
3552 * Set the variance to half the rtt (so our first
3553 * retransmit happens at 3*rtt).
3554 */
3555 tp->t_srtt = rtt << TCP_RTT_SHIFT;
3556 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
3557 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3558 }
3559 tp->t_rtttime = 0;
3560 tp->t_rxtshift = 0;
3561
3562 /*
3563 * the retransmit should happen at rtt + 4 * rttvar.
3564 * Because of the way we do the smoothing, srtt and rttvar
3565 * will each average +1/2 tick of bias. When we compute
3566 * the retransmit timer, we want 1/2 tick of rounding and
3567 * 1 extra tick because of +-1/2 tick uncertainty in the
3568 * firing of the timer. The bias will give us exactly the
3569 * 1.5 tick we need. But, because the bias is
3570 * statistical, we have to test that we don't drop below
3571 * the minimum feasible timer (which is 2 ticks).
3572 */
3573 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
3574 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
3575
3576 /*
3577 * We received an ack for a packet that wasn't retransmitted;
3578 * it is probably safe to discard any error indications we've
3579 * received recently. This isn't quite right, but close enough
3580 * for now (a route might have failed after we sent a segment,
3581 * and the return path might not be symmetrical).
3582 */
3583 tp->t_softerror = 0;
3584 }
3585
3586 /*
3587 * Determine a reasonable value for maxseg size.
3588 * If the route is known, check route for mtu.
3589 * If none, use an mss that can be handled on the outgoing interface
3590 * without forcing IP to fragment. If no route is found, route has no mtu,
3591 * or the destination isn't local, use a default, hopefully conservative
3592 * size (usually 512 or the default IP max size, but no more than the mtu
3593 * of the interface), as we can't discover anything about intervening
3594 * gateways or networks. We also initialize the congestion/slow start
3595 * window to be a single segment if the destination isn't local.
3596 * While looking at the routing entry, we also initialize other path-dependent
3597 * parameters from pre-set or cached values in the routing entry.
3598 *
3599 * NOTE that resulting t_maxseg doesn't include space for TCP options or
3600 * IP options, e.g. IPSEC data, since length of this data may vary, and
3601 * thus it is calculated for every segment separately in tcp_output().
3602 *
3603 * NOTE that this routine is only called when we process an incoming
3604 * segment, or an ICMP need fragmentation datagram. Outgoing SYN/ACK MSS
3605 * settings are handled in tcp_mssopt().
3606 */
3607 void
tcp_mss_update(struct tcpcb * tp,int offer,int mtuoffer,struct hc_metrics_lite * metricptr,struct tcp_ifcap * cap)3608 tcp_mss_update(struct tcpcb *tp, int offer, int mtuoffer,
3609 struct hc_metrics_lite *metricptr, struct tcp_ifcap *cap)
3610 {
3611 int mss = 0;
3612 uint32_t maxmtu = 0;
3613 struct inpcb *inp = tp->t_inpcb;
3614 struct hc_metrics_lite metrics;
3615 #ifdef INET6
3616 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
3617 size_t min_protoh = isipv6 ?
3618 sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
3619 sizeof (struct tcpiphdr);
3620 #else
3621 const size_t min_protoh = sizeof(struct tcpiphdr);
3622 #endif
3623
3624 INP_WLOCK_ASSERT(tp->t_inpcb);
3625
3626 if (mtuoffer != -1) {
3627 KASSERT(offer == -1, ("%s: conflict", __func__));
3628 offer = mtuoffer - min_protoh;
3629 }
3630
3631 /* Initialize. */
3632 #ifdef INET6
3633 if (isipv6) {
3634 maxmtu = tcp_maxmtu6(&inp->inp_inc, cap);
3635 tp->t_maxseg = V_tcp_v6mssdflt;
3636 }
3637 #endif
3638 #if defined(INET) && defined(INET6)
3639 else
3640 #endif
3641 #ifdef INET
3642 {
3643 maxmtu = tcp_maxmtu(&inp->inp_inc, cap);
3644 tp->t_maxseg = V_tcp_mssdflt;
3645 }
3646 #endif
3647
3648 /*
3649 * No route to sender, stay with default mss and return.
3650 */
3651 if (maxmtu == 0) {
3652 /*
3653 * In case we return early we need to initialize metrics
3654 * to a defined state as tcp_hc_get() would do for us
3655 * if there was no cache hit.
3656 */
3657 if (metricptr != NULL)
3658 bzero(metricptr, sizeof(struct hc_metrics_lite));
3659 return;
3660 }
3661
3662 /* What have we got? */
3663 switch (offer) {
3664 case 0:
3665 /*
3666 * Offer == 0 means that there was no MSS on the SYN
3667 * segment, in this case we use tcp_mssdflt as
3668 * already assigned to t_maxseg above.
3669 */
3670 offer = tp->t_maxseg;
3671 break;
3672
3673 case -1:
3674 /*
3675 * Offer == -1 means that we didn't receive SYN yet.
3676 */
3677 /* FALLTHROUGH */
3678
3679 default:
3680 /*
3681 * Prevent DoS attack with too small MSS. Round up
3682 * to at least minmss.
3683 */
3684 offer = max(offer, V_tcp_minmss);
3685 }
3686
3687 /*
3688 * rmx information is now retrieved from tcp_hostcache.
3689 */
3690 tcp_hc_get(&inp->inp_inc, &metrics);
3691 if (metricptr != NULL)
3692 bcopy(&metrics, metricptr, sizeof(struct hc_metrics_lite));
3693
3694 /*
3695 * If there's a discovered mtu in tcp hostcache, use it.
3696 * Else, use the link mtu.
3697 */
3698 if (metrics.rmx_mtu)
3699 mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
3700 else {
3701 #ifdef INET6
3702 if (isipv6) {
3703 mss = maxmtu - min_protoh;
3704 if (!V_path_mtu_discovery &&
3705 !in6_localaddr(&inp->in6p_faddr))
3706 mss = min(mss, V_tcp_v6mssdflt);
3707 }
3708 #endif
3709 #if defined(INET) && defined(INET6)
3710 else
3711 #endif
3712 #ifdef INET
3713 {
3714 mss = maxmtu - min_protoh;
3715 if (!V_path_mtu_discovery &&
3716 !in_localaddr(inp->inp_faddr))
3717 mss = min(mss, V_tcp_mssdflt);
3718 }
3719 #endif
3720 /*
3721 * XXX - The above conditional (mss = maxmtu - min_protoh)
3722 * probably violates the TCP spec.
3723 * The problem is that, since we don't know the
3724 * other end's MSS, we are supposed to use a conservative
3725 * default. But, if we do that, then MTU discovery will
3726 * never actually take place, because the conservative
3727 * default is much less than the MTUs typically seen
3728 * on the Internet today. For the moment, we'll sweep
3729 * this under the carpet.
3730 *
3731 * The conservative default might not actually be a problem
3732 * if the only case this occurs is when sending an initial
3733 * SYN with options and data to a host we've never talked
3734 * to before. Then, they will reply with an MSS value which
3735 * will get recorded and the new parameters should get
3736 * recomputed. For Further Study.
3737 */
3738 }
3739 mss = min(mss, offer);
3740
3741 /*
3742 * Sanity check: make sure that maxseg will be large
3743 * enough to allow some data on segments even if the
3744 * all the option space is used (40bytes). Otherwise
3745 * funny things may happen in tcp_output.
3746 *
3747 * XXXGL: shouldn't we reserve space for IP/IPv6 options?
3748 */
3749 mss = max(mss, 64);
3750
3751 tp->t_maxseg = mss;
3752 }
3753
3754 void
tcp_mss(struct tcpcb * tp,int offer)3755 tcp_mss(struct tcpcb *tp, int offer)
3756 {
3757 int mss;
3758 uint32_t bufsize;
3759 struct inpcb *inp;
3760 struct socket *so;
3761 struct hc_metrics_lite metrics;
3762 struct tcp_ifcap cap;
3763
3764 KASSERT(tp != NULL, ("%s: tp == NULL", __func__));
3765
3766 bzero(&cap, sizeof(cap));
3767 tcp_mss_update(tp, offer, -1, &metrics, &cap);
3768
3769 mss = tp->t_maxseg;
3770 inp = tp->t_inpcb;
3771
3772 /*
3773 * If there's a pipesize, change the socket buffer to that size,
3774 * don't change if sb_hiwat is different than default (then it
3775 * has been changed on purpose with setsockopt).
3776 * Make the socket buffers an integral number of mss units;
3777 * if the mss is larger than the socket buffer, decrease the mss.
3778 */
3779 so = inp->inp_socket;
3780 SOCKBUF_LOCK(&so->so_snd);
3781 if ((so->so_snd.sb_hiwat == V_tcp_sendspace) && metrics.rmx_sendpipe)
3782 bufsize = metrics.rmx_sendpipe;
3783 else
3784 bufsize = so->so_snd.sb_hiwat;
3785 if (bufsize < mss)
3786 mss = bufsize;
3787 else {
3788 bufsize = roundup(bufsize, mss);
3789 if (bufsize > sb_max)
3790 bufsize = sb_max;
3791 if (bufsize > so->so_snd.sb_hiwat)
3792 (void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
3793 }
3794 SOCKBUF_UNLOCK(&so->so_snd);
3795 /*
3796 * Sanity check: make sure that maxseg will be large
3797 * enough to allow some data on segments even if the
3798 * all the option space is used (40bytes). Otherwise
3799 * funny things may happen in tcp_output.
3800 *
3801 * XXXGL: shouldn't we reserve space for IP/IPv6 options?
3802 */
3803 tp->t_maxseg = max(mss, 64);
3804
3805 SOCKBUF_LOCK(&so->so_rcv);
3806 if ((so->so_rcv.sb_hiwat == V_tcp_recvspace) && metrics.rmx_recvpipe)
3807 bufsize = metrics.rmx_recvpipe;
3808 else
3809 bufsize = so->so_rcv.sb_hiwat;
3810 if (bufsize > mss) {
3811 bufsize = roundup(bufsize, mss);
3812 if (bufsize > sb_max)
3813 bufsize = sb_max;
3814 if (bufsize > so->so_rcv.sb_hiwat)
3815 (void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
3816 }
3817 SOCKBUF_UNLOCK(&so->so_rcv);
3818
3819 /* Check the interface for TSO capabilities. */
3820 if (cap.ifcap & CSUM_TSO) {
3821 tp->t_flags |= TF_TSO;
3822 tp->t_tsomax = cap.tsomax;
3823 tp->t_tsomaxsegcount = cap.tsomaxsegcount;
3824 tp->t_tsomaxsegsize = cap.tsomaxsegsize;
3825 }
3826 }
3827
3828 /*
3829 * Determine the MSS option to send on an outgoing SYN.
3830 */
3831 int
tcp_mssopt(struct in_conninfo * inc)3832 tcp_mssopt(struct in_conninfo *inc)
3833 {
3834 int mss = 0;
3835 uint32_t thcmtu = 0;
3836 uint32_t maxmtu = 0;
3837 size_t min_protoh;
3838
3839 KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
3840
3841 #ifdef INET6
3842 if (inc->inc_flags & INC_ISIPV6) {
3843 mss = V_tcp_v6mssdflt;
3844 maxmtu = tcp_maxmtu6(inc, NULL);
3845 min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
3846 }
3847 #endif
3848 #if defined(INET) && defined(INET6)
3849 else
3850 #endif
3851 #ifdef INET
3852 {
3853 mss = V_tcp_mssdflt;
3854 maxmtu = tcp_maxmtu(inc, NULL);
3855 min_protoh = sizeof(struct tcpiphdr);
3856 }
3857 #endif
3858 #if defined(INET6) || defined(INET)
3859 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3860 #endif
3861
3862 if (maxmtu && thcmtu)
3863 mss = min(maxmtu, thcmtu) - min_protoh;
3864 else if (maxmtu || thcmtu)
3865 mss = max(maxmtu, thcmtu) - min_protoh;
3866
3867 return (mss);
3868 }
3869
3870
3871 /*
3872 * On a partial ack arrives, force the retransmission of the
3873 * next unacknowledged segment. Do not clear tp->t_dupacks.
3874 * By setting snd_nxt to ti_ack, this forces retransmission timer to
3875 * be started again.
3876 */
3877 void
tcp_newreno_partial_ack(struct tcpcb * tp,struct tcphdr * th)3878 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
3879 {
3880 tcp_seq onxt = tp->snd_nxt;
3881 uint32_t ocwnd = tp->snd_cwnd;
3882 u_int maxseg = tcp_maxseg(tp);
3883
3884 INP_WLOCK_ASSERT(tp->t_inpcb);
3885
3886 tcp_timer_activate(tp, TT_REXMT, 0);
3887 tp->t_rtttime = 0;
3888 tp->snd_nxt = th->th_ack;
3889 /*
3890 * Set snd_cwnd to one segment beyond acknowledged offset.
3891 * (tp->snd_una has not yet been updated when this function is called.)
3892 */
3893 tp->snd_cwnd = maxseg + BYTES_THIS_ACK(tp, th);
3894 tp->t_flags |= TF_ACKNOW;
3895 (void) tp->t_fb->tfb_tcp_output(tp);
3896 tp->snd_cwnd = ocwnd;
3897 if (SEQ_GT(onxt, tp->snd_nxt))
3898 tp->snd_nxt = onxt;
3899 /*
3900 * Partial window deflation. Relies on fact that tp->snd_una
3901 * not updated yet.
3902 */
3903 if (tp->snd_cwnd > BYTES_THIS_ACK(tp, th))
3904 tp->snd_cwnd -= BYTES_THIS_ACK(tp, th);
3905 else
3906 tp->snd_cwnd = 0;
3907 tp->snd_cwnd += maxseg;
3908 }
3909
3910 int
tcp_compute_pipe(struct tcpcb * tp)3911 tcp_compute_pipe(struct tcpcb *tp)
3912 {
3913 return (tp->snd_max - tp->snd_una +
3914 tp->sackhint.sack_bytes_rexmit -
3915 tp->sackhint.sacked_bytes);
3916 }
3917