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