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