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