1 /*
2 * Copyright (c) 2000-2021 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 /*
29 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
30 * The Regents of the University of California. All rights reserved.
31 *
32 * Redistribution and use in source and binary forms, with or without
33 * modification, are permitted provided that the following conditions
34 * are met:
35 * 1. Redistributions of source code must retain the above copyright
36 * notice, this list of conditions and the following disclaimer.
37 * 2. Redistributions in binary form must reproduce the above copyright
38 * notice, this list of conditions and the following disclaimer in the
39 * documentation and/or other materials provided with the distribution.
40 * 3. All advertising materials mentioning features or use of this software
41 * must display the following acknowledgement:
42 * This product includes software developed by the University of
43 * California, Berkeley and its contributors.
44 * 4. Neither the name of the University nor the names of its contributors
45 * may be used to endorse or promote products derived from this software
46 * without specific prior written permission.
47 *
48 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58 * SUCH DAMAGE.
59 *
60 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
61 * $FreeBSD: src/sys/netinet/tcp_input.c,v 1.107.2.16 2001/08/22 00:59:12 silby Exp $
62 */
63 /*
64 * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
65 * support for mandatory and extensible security protections. This notice
66 * is included in support of clause 2.2 (b) of the Apple Public License,
67 * Version 2.0.
68 */
69
70 #include <sys/param.h>
71 #include <sys/systm.h>
72 #include <sys/kernel.h>
73 #include <sys/sysctl.h>
74 #include <sys/malloc.h>
75 #include <sys/mbuf.h>
76 #include <sys/proc.h> /* for proc0 declaration */
77 #include <sys/protosw.h>
78 #include <sys/socket.h>
79 #include <sys/socketvar.h>
80 #include <sys/syslog.h>
81 #include <sys/mcache.h>
82 #if XNU_TARGET_OS_OSX
83 #include <sys/kasl.h>
84 #endif /* XNU_TARGET_OS_OSX */
85 #include <sys/kauth.h>
86 #include <kern/cpu_number.h> /* before tcp_seq.h, for tcp_random18() */
87
88 #include <machine/endian.h>
89
90 #include <net/if.h>
91 #include <net/if_types.h>
92 #include <net/route.h>
93 #include <net/ntstat.h>
94 #include <net/content_filter.h>
95 #include <net/dlil.h>
96 #include <net/multi_layer_pkt_log.h>
97
98 #include <netinet/in.h>
99 #include <netinet/in_systm.h>
100 #include <netinet/ip.h>
101 #include <netinet/ip_icmp.h> /* for ICMP_BANDLIM */
102 #include <netinet/in_var.h>
103 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
104 #include <netinet/in_pcb.h>
105 #include <netinet/ip_var.h>
106 #include <mach/sdt.h>
107 #include <netinet/ip6.h>
108 #include <netinet/icmp6.h>
109 #include <netinet6/nd6.h>
110 #include <netinet6/ip6_var.h>
111 #include <netinet6/in6_pcb.h>
112 #include <netinet/tcp.h>
113 #include <netinet/tcp_cache.h>
114 #include <netinet/tcp_fsm.h>
115 #include <netinet/tcp_seq.h>
116 #include <netinet/tcp_timer.h>
117 #include <netinet/tcp_var.h>
118 #include <netinet/tcp_cc.h>
119 #include <dev/random/randomdev.h>
120 #include <kern/zalloc.h>
121 #include <netinet6/tcp6_var.h>
122 #include <netinet/tcpip.h>
123 #if TCPDEBUG
124 #include <netinet/tcp_debug.h>
125 u_char tcp_saveipgen[40]; /* the size must be of max ip header, now IPv6 */
126 struct tcphdr tcp_savetcp;
127 #endif /* TCPDEBUG */
128 #include <netinet/tcp_log.h>
129
130 #if IPSEC
131 #include <netinet6/ipsec.h>
132 #include <netinet6/ipsec6.h>
133 #include <netkey/key.h>
134 #endif /*IPSEC*/
135
136 #include <sys/kdebug.h>
137 #if MPTCP
138 #include <netinet/mptcp_var.h>
139 #include <netinet/mptcp.h>
140 #include <netinet/mptcp_opt.h>
141 #endif /* MPTCP */
142
143 #include <corecrypto/ccaes.h>
144
145 #define DBG_LAYER_BEG NETDBG_CODE(DBG_NETTCP, 0)
146 #define DBG_LAYER_END NETDBG_CODE(DBG_NETTCP, 2)
147 #define DBG_FNC_TCP_INPUT NETDBG_CODE(DBG_NETTCP, (3 << 8))
148 #define DBG_FNC_TCP_NEWCONN NETDBG_CODE(DBG_NETTCP, (7 << 8))
149
150 #define TCP_RTT_HISTORY_EXPIRE_TIME (60 * TCP_RETRANSHZ)
151 #define TCP_RECV_THROTTLE_WIN (5 * TCP_RETRANSHZ)
152 #define TCP_STRETCHACK_ENABLE_PKTCNT 2000
153
154 struct tcpstat tcpstat;
155
156 SYSCTL_SKMEM_TCP_INT(OID_AUTO, flow_control_response,
157 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_flow_control_response, 1,
158 "Improved response to Flow-control events");
159
160 static int log_in_vain = 0;
161 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain,
162 CTLFLAG_RW | CTLFLAG_LOCKED, &log_in_vain, 0,
163 "Log all incoming TCP connections");
164
165 SYSCTL_SKMEM_TCP_INT(OID_AUTO, ack_strategy,
166 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_ack_strategy, TCP_ACK_STRATEGY_MODERN,
167 "Revised TCP ACK-strategy, avoiding stretch-ACK implementation");
168
169 static int blackhole = 0;
170 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole,
171 CTLFLAG_RW | CTLFLAG_LOCKED, &blackhole, 0,
172 "Do not send RST when dropping refused connections");
173
174 SYSCTL_SKMEM_TCP_INT(OID_AUTO, aggressive_rcvwnd_inc,
175 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_aggressive_rcvwnd_inc, 1,
176 "Be more aggressive about increasing the receive-window.");
177
178 SYSCTL_SKMEM_TCP_INT(OID_AUTO, delayed_ack,
179 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_delack_enabled, 3,
180 "Delay ACK to try and piggyback it onto a data packet");
181
182 SYSCTL_SKMEM_TCP_INT(OID_AUTO, recvbg, CTLFLAG_RW | CTLFLAG_LOCKED,
183 int, tcp_recv_bg, 0, "Receive background");
184
185 SYSCTL_SKMEM_TCP_INT(OID_AUTO, drop_synfin,
186 CTLFLAG_RW | CTLFLAG_LOCKED, static int, drop_synfin, 1,
187 "Drop TCP packets with SYN+FIN set");
188
189 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, reass, CTLFLAG_RW | CTLFLAG_LOCKED, 0,
190 "TCP Segment Reassembly Queue");
191
192 static int tcp_reass_overflows = 0;
193 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, overflows,
194 CTLFLAG_RD | CTLFLAG_LOCKED, &tcp_reass_overflows, 0,
195 "Global number of TCP Segment Reassembly Queue Overflows");
196
197
198 SYSCTL_SKMEM_TCP_INT(OID_AUTO, slowlink_wsize, CTLFLAG_RW | CTLFLAG_LOCKED,
199 __private_extern__ int, slowlink_wsize, 8192,
200 "Maximum advertised window size for slowlink");
201
202 SYSCTL_SKMEM_TCP_INT(OID_AUTO, maxseg_unacked,
203 CTLFLAG_RW | CTLFLAG_LOCKED, int, maxseg_unacked, 8,
204 "Maximum number of outstanding segments left unacked");
205
206 SYSCTL_SKMEM_TCP_INT(OID_AUTO, rfc3465, CTLFLAG_RW | CTLFLAG_LOCKED,
207 int, tcp_do_rfc3465, 1, "");
208
209 SYSCTL_SKMEM_TCP_INT(OID_AUTO, rfc3465_lim2,
210 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_do_rfc3465_lim2, 1,
211 "Appropriate bytes counting w/ L=2*SMSS");
212
213 int rtt_samples_per_slot = 20;
214
215 int tcp_acc_iaj_high_thresh = ACC_IAJ_HIGH_THRESH;
216 u_int32_t tcp_autorcvbuf_inc_shift = 3;
217 SYSCTL_SKMEM_TCP_INT(OID_AUTO, recv_allowed_iaj,
218 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_allowed_iaj, ALLOWED_IAJ,
219 "Allowed inter-packet arrival jiter");
220
221 SYSCTL_SKMEM_TCP_INT(OID_AUTO, doautorcvbuf,
222 CTLFLAG_RW | CTLFLAG_LOCKED, u_int32_t, tcp_do_autorcvbuf, 1,
223 "Enable automatic socket buffer tuning");
224
225 SYSCTL_SKMEM_TCP_INT(OID_AUTO, autotunereorder,
226 CTLFLAG_RW | CTLFLAG_LOCKED, u_int32_t, tcp_autotune_reorder, 1,
227 "Enable automatic socket buffer tuning even when reordering is present");
228
229 SYSCTL_SKMEM_TCP_INT(OID_AUTO, autorcvbufmax,
230 CTLFLAG_RW | CTLFLAG_LOCKED, u_int32_t, tcp_autorcvbuf_max, 2 * 1024 * 1024,
231 "Maximum receive socket buffer size");
232
233 int tcp_disable_access_to_stats = 1;
234 SYSCTL_INT(_net_inet_tcp, OID_AUTO, disable_access_to_stats,
235 CTLFLAG_RW | CTLFLAG_LOCKED, &tcp_disable_access_to_stats, 0,
236 "Disable access to tcpstat");
237
238 SYSCTL_SKMEM_TCP_INT(OID_AUTO, challengeack_limit,
239 CTLFLAG_RW | CTLFLAG_LOCKED, uint32_t, tcp_challengeack_limit, 10,
240 "Maximum number of challenge ACKs per connection per second");
241
242 /* TO BE REMOVED */
243 SYSCTL_SKMEM_TCP_INT(OID_AUTO, do_rfc5961,
244 CTLFLAG_RW | CTLFLAG_LOCKED, static int, tcp_do_rfc5961, 1,
245 "Enable/Disable full RFC 5961 compliance");
246
247 SYSCTL_SKMEM_TCP_INT(OID_AUTO, do_better_lr,
248 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_do_better_lr, 1,
249 "Improved TCP Loss Recovery");
250
251 SYSCTL_SKMEM_TCP_INT(OID_AUTO, use_min_curr_rtt,
252 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_use_min_curr_rtt, 1,
253 "Use a min of k=4 RTT samples for congestion controllers");
254
255 extern int tcp_acc_iaj_high;
256 extern int tcp_acc_iaj_react_limit;
257 extern int tcp_fin_timeout;
258
259 uint8_t tcprexmtthresh = 3;
260
261 u_int32_t tcp_now;
262 struct timeval tcp_uptime; /* uptime when tcp_now was last updated */
263
264 /* Used to sychronize updates to tcp_now */
265 static LCK_GRP_DECLARE(tcp_uptime_mtx_grp, "tcpuptime");
266 LCK_SPIN_DECLARE(tcp_uptime_lock, &tcp_uptime_mtx_grp);
267
268 struct inpcbhead tcb;
269 #define tcb6 tcb /* for KAME src sync over BSD*'s */
270 struct inpcbinfo tcbinfo;
271
272 static void tcp_dooptions(struct tcpcb *, u_char *, int, struct tcphdr *,
273 struct tcpopt *);
274 static void tcp_finalize_options(struct tcpcb *, struct tcpopt *, unsigned int);
275 static void tcp_pulloutofband(struct socket *,
276 struct tcphdr *, struct mbuf *, int);
277 static void tcp_xmit_timer(struct tcpcb *, int, u_int32_t, tcp_seq);
278 static inline unsigned int tcp_maxmtu(struct rtentry *);
279 static inline int tcp_stretch_ack_enable(struct tcpcb *tp, int thflags);
280 static inline void tcp_adaptive_rwtimo_check(struct tcpcb *, int);
281
282 #if TRAFFIC_MGT
283 static inline void compute_iaj(struct tcpcb *tp);
284 static inline void compute_iaj_meat(struct tcpcb *tp, uint32_t cur_iaj);
285 #endif /* TRAFFIC_MGT */
286
287 static inline unsigned int tcp_maxmtu6(struct rtentry *);
288 unsigned int get_maxmtu(struct rtentry *);
289
290 static void tcp_sbrcv_grow(struct tcpcb *tp, struct sockbuf *sb,
291 struct tcpopt *to, uint32_t tlen);
292 void tcp_sbrcv_trim(struct tcpcb *tp, struct sockbuf *sb);
293 static void tcp_sbsnd_trim(struct sockbuf *sbsnd);
294 static inline void tcp_sbrcv_tstmp_check(struct tcpcb *tp);
295 static inline void tcp_sbrcv_reserve(struct tcpcb *tp, struct sockbuf *sb,
296 u_int32_t newsize, u_int32_t idealsize, u_int32_t rcvbuf_max);
297 static void tcp_bad_rexmt_restore_state(struct tcpcb *tp, struct tcphdr *th);
298 static void tcp_compute_rtt(struct tcpcb *tp, struct tcpopt *to,
299 struct tcphdr *th);
300 static void tcp_compute_rcv_rtt(struct tcpcb *tp, struct tcpopt *to,
301 struct tcphdr *th);
302 static void tcp_early_rexmt_check(struct tcpcb *tp, struct tcphdr *th);
303 static void tcp_bad_rexmt_check(struct tcpcb *tp, struct tcphdr *th,
304 struct tcpopt *to);
305 /*
306 * Constants used for resizing receive socket buffer
307 * when timestamps are not supported
308 */
309 #define TCPTV_RCVNOTS_QUANTUM 100
310 #define TCP_RCVNOTS_BYTELEVEL 204800
311
312 /*
313 * Constants used for limiting early retransmits
314 * to 10 per minute.
315 */
316 #define TCP_EARLY_REXMT_WIN (60 * TCP_RETRANSHZ) /* 60 seconds */
317 #define TCP_EARLY_REXMT_LIMIT 10
318
319 #define log_in_vain_log( a ) { log a; }
320
321 int tcp_rcvunackwin = TCPTV_UNACKWIN;
322 int tcp_maxrcvidle = TCPTV_MAXRCVIDLE;
323 SYSCTL_SKMEM_TCP_INT(OID_AUTO, rcvsspktcnt, CTLFLAG_RW | CTLFLAG_LOCKED,
324 int, tcp_rcvsspktcnt, TCP_RCV_SS_PKTCOUNT, "packets to be seen before receiver stretches acks");
325
326 #define DELAY_ACK(tp, th) \
327 (CC_ALGO(tp)->delay_ack != NULL && CC_ALGO(tp)->delay_ack(tp, th))
328
329 static int tcp_dropdropablreq(struct socket *head);
330 static void tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th);
331 static void update_base_rtt(struct tcpcb *tp, uint32_t rtt);
332 void tcp_set_background_cc(struct socket *so);
333 void tcp_set_foreground_cc(struct socket *so);
334 static void tcp_set_new_cc(struct socket *so, uint8_t cc_index);
335 static void tcp_bwmeas_check(struct tcpcb *tp);
336
337 #if TRAFFIC_MGT
338 void
reset_acc_iaj(struct tcpcb * tp)339 reset_acc_iaj(struct tcpcb *tp)
340 {
341 tp->acc_iaj = 0;
342 CLEAR_IAJ_STATE(tp);
343 }
344
345 static inline void
update_iaj_state(struct tcpcb * tp,int size,int rst_size)346 update_iaj_state(struct tcpcb *tp, int size, int rst_size)
347 {
348 if (rst_size > 0) {
349 tp->iaj_size = 0;
350 }
351 if (tp->iaj_size == 0 || size >= tp->iaj_size) {
352 tp->iaj_size = size;
353 tp->iaj_rcv_ts = tcp_now;
354 tp->iaj_small_pkt = 0;
355 }
356 }
357
358 /* For every 64-bit unsigned integer(v), this function will find the
359 * largest 32-bit integer n such that (n*n <= v). This takes at most 32 iterations
360 * irrespective of the value of v and does not involve multiplications.
361 */
362 static inline uint32_t
isqrt(uint64_t val)363 isqrt(uint64_t val)
364 {
365 uint32_t sqrt_cache[11] = {0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100};
366 uint64_t temp, g = 0, b = 1 << 31, bshft = 31;
367 if (val <= 100) {
368 for (g = 0; g <= 10; ++g) {
369 if (sqrt_cache[g] > val) {
370 g--;
371 break;
372 } else if (sqrt_cache[g] == val) {
373 break;
374 }
375 }
376 } else {
377 do {
378 temp = (((g << 1) + b) << (bshft--));
379 if (val >= temp) {
380 g += b;
381 val -= temp;
382 }
383 b >>= 1;
384 } while (b > 0 && val > 0);
385 }
386 return (uint32_t)g;
387 }
388
389 static inline void
compute_iaj_meat(struct tcpcb * tp,uint32_t cur_iaj)390 compute_iaj_meat(struct tcpcb *tp, uint32_t cur_iaj)
391 {
392 /* When accumulated IAJ reaches MAX_ACC_IAJ in milliseconds,
393 * throttle the receive window to a minimum of MIN_IAJ_WIN packets
394 */
395 #define MAX_ACC_IAJ (tcp_acc_iaj_high_thresh + tcp_acc_iaj_react_limit)
396 #define IAJ_DIV_SHIFT 4
397 #define IAJ_ROUNDUP_CONST (1 << (IAJ_DIV_SHIFT - 1))
398
399 uint32_t allowed_iaj, acc_iaj = 0;
400
401 /* Using 64-bit storage for the inter-arrival jitter deviation,
402 * to avoid accidentally rolling over if the inter-arrival time exceeds 62 seconds.
403 */
404 int64_t mean, temp, cur_iaj_dev;
405
406 cur_iaj_dev = (cur_iaj - tp->avg_iaj);
407
408 /* Allow a jitter of "allowed_iaj" milliseconds. Some connections
409 * may have a constant jitter more than that. We detect this by
410 * using standard deviation.
411 */
412 allowed_iaj = tp->avg_iaj + tp->std_dev_iaj;
413 if (allowed_iaj < tcp_allowed_iaj) {
414 allowed_iaj = tcp_allowed_iaj;
415 }
416
417 /* Initially when the connection starts, the senders congestion
418 * window is small. During this period we avoid throttling a
419 * connection because we do not have a good starting point for
420 * allowed_iaj. IAJ_IGNORE_PKTCNT is used to quietly gloss over
421 * the first few packets.
422 */
423 if (tp->iaj_pktcnt > IAJ_IGNORE_PKTCNT) {
424 if (cur_iaj <= allowed_iaj) {
425 if (tp->acc_iaj >= 2) {
426 acc_iaj = tp->acc_iaj - 2;
427 } else {
428 acc_iaj = 0;
429 }
430 } else {
431 acc_iaj = tp->acc_iaj + (cur_iaj - allowed_iaj);
432 }
433
434 if (acc_iaj > MAX_ACC_IAJ) {
435 acc_iaj = MAX_ACC_IAJ;
436 }
437 tp->acc_iaj = acc_iaj;
438 }
439
440 /* Compute weighted average where the history has a weight of
441 * 15 out of 16 and the current value has a weight of 1 out of 16.
442 * This will make the short-term measurements have more weight.
443 *
444 * The addition of 8 will help to round-up the value
445 * instead of round-down
446 */
447 tp->avg_iaj = (((tp->avg_iaj << IAJ_DIV_SHIFT) - tp->avg_iaj)
448 + cur_iaj + IAJ_ROUNDUP_CONST) >> IAJ_DIV_SHIFT;
449
450 /* Compute Root-mean-square of deviation where mean is a weighted
451 * average as described above.
452 */
453 temp = tp->std_dev_iaj * tp->std_dev_iaj;
454 mean = (((temp << IAJ_DIV_SHIFT) - temp)
455 + (cur_iaj_dev * cur_iaj_dev)
456 + IAJ_ROUNDUP_CONST) >> IAJ_DIV_SHIFT;
457
458 tp->std_dev_iaj = isqrt(mean);
459
460 DTRACE_TCP3(iaj, struct tcpcb *, tp, uint32_t, cur_iaj,
461 uint32_t, allowed_iaj);
462
463 return;
464 }
465
466 static inline void
compute_iaj(struct tcpcb * tp)467 compute_iaj(struct tcpcb *tp)
468 {
469 compute_iaj_meat(tp, (tcp_now - tp->iaj_rcv_ts));
470 }
471 #endif /* TRAFFIC_MGT */
472
473 /*
474 * Perform rate limit check per connection per second
475 * tp->t_challengeack_last is the last_time diff was greater than 1sec
476 * tp->t_challengeack_count is the number of ACKs sent (within 1sec)
477 * Return TRUE if we shouldn't send the ACK due to rate limitation
478 * Return FALSE if it is still ok to send challenge ACK
479 */
480 static boolean_t
tcp_is_ack_ratelimited(struct tcpcb * tp)481 tcp_is_ack_ratelimited(struct tcpcb *tp)
482 {
483 boolean_t ret = TRUE;
484 uint32_t now = tcp_now;
485 int32_t diff = 0;
486
487 diff = timer_diff(now, 0, tp->t_challengeack_last, 0);
488 /* If it is first time or diff > 1000ms,
489 * update the challengeack_last and reset the
490 * current count of ACKs
491 */
492 if (tp->t_challengeack_last == 0 || diff >= 1000) {
493 tp->t_challengeack_last = now;
494 tp->t_challengeack_count = 0;
495 ret = FALSE;
496 } else if (tp->t_challengeack_count < tcp_challengeack_limit) {
497 ret = FALSE;
498 }
499
500 /* Careful about wrap-around */
501 if (ret == FALSE && (tp->t_challengeack_count + 1 > 0)) {
502 tp->t_challengeack_count++;
503 }
504
505 return ret;
506 }
507
508 /* Check if enough amount of data has been acknowledged since
509 * bw measurement was started
510 */
511 static void
tcp_bwmeas_check(struct tcpcb * tp)512 tcp_bwmeas_check(struct tcpcb *tp)
513 {
514 int32_t bw_meas_bytes;
515 uint32_t bw, bytes, elapsed_time;
516
517 if (SEQ_LEQ(tp->snd_una, tp->t_bwmeas->bw_start)) {
518 return;
519 }
520
521 bw_meas_bytes = tp->snd_una - tp->t_bwmeas->bw_start;
522 if ((tp->t_flagsext & TF_BWMEAS_INPROGRESS) &&
523 bw_meas_bytes >= (int32_t)(tp->t_bwmeas->bw_size)) {
524 bytes = bw_meas_bytes;
525 elapsed_time = tcp_now - tp->t_bwmeas->bw_ts;
526 if (elapsed_time > 0) {
527 bw = bytes / elapsed_time;
528 if (bw > 0) {
529 if (tp->t_bwmeas->bw_sndbw > 0) {
530 tp->t_bwmeas->bw_sndbw =
531 (((tp->t_bwmeas->bw_sndbw << 3)
532 - tp->t_bwmeas->bw_sndbw)
533 + bw) >> 3;
534 } else {
535 tp->t_bwmeas->bw_sndbw = bw;
536 }
537
538 /* Store the maximum value */
539 if (tp->t_bwmeas->bw_sndbw_max == 0) {
540 tp->t_bwmeas->bw_sndbw_max =
541 tp->t_bwmeas->bw_sndbw;
542 } else {
543 tp->t_bwmeas->bw_sndbw_max =
544 max(tp->t_bwmeas->bw_sndbw,
545 tp->t_bwmeas->bw_sndbw_max);
546 }
547 }
548 }
549 tp->t_flagsext &= ~(TF_BWMEAS_INPROGRESS);
550 }
551 }
552
553 static int
tcp_reass(struct tcpcb * tp,struct tcphdr * th,int * tlenp,struct mbuf * m,struct ifnet * ifp,int * dowakeup)554 tcp_reass(struct tcpcb *tp, struct tcphdr *th, int *tlenp, struct mbuf *m,
555 struct ifnet *ifp, int *dowakeup)
556 {
557 struct tseg_qent *q;
558 struct tseg_qent *p = NULL;
559 struct tseg_qent *nq;
560 struct tseg_qent *te = NULL;
561 struct inpcb *inp = tp->t_inpcb;
562 struct socket *so = inp->inp_socket;
563 int flags = 0;
564 uint32_t qlimit;
565 boolean_t cell = IFNET_IS_CELLULAR(ifp);
566 boolean_t wifi = (!cell && IFNET_IS_WIFI(ifp));
567 boolean_t wired = (!wifi && IFNET_IS_WIRED(ifp));
568 boolean_t dsack_set = FALSE;
569
570 /*
571 * Call with th==0 after become established to
572 * force pre-ESTABLISHED data up to user socket.
573 */
574 if (th == NULL) {
575 goto present;
576 }
577
578 /*
579 * If the reassembly queue already has entries or if we are going
580 * to add a new one, then the connection has reached a loss state.
581 * Reset the stretch-ack algorithm at this point.
582 */
583 tcp_reset_stretch_ack(tp);
584 tp->t_forced_acks = TCP_FORCED_ACKS_COUNT;
585
586 #if TRAFFIC_MGT
587 if (tp->acc_iaj > 0) {
588 reset_acc_iaj(tp);
589 }
590 #endif /* TRAFFIC_MGT */
591
592 if (th->th_seq != tp->rcv_nxt) {
593 struct mbuf *tmp = m;
594 while (tmp != NULL) {
595 if (mbuf_class_under_pressure(tmp)) {
596 m_freem(m);
597 tcp_reass_overflows++;
598 tcpstat.tcps_rcvmemdrop++;
599 *tlenp = 0;
600 return 0;
601 }
602
603 tmp = tmp->m_next;
604 }
605 }
606
607 /*
608 * Limit the number of segments in the reassembly queue to prevent
609 * holding on to too many segments (and thus running out of mbufs).
610 * Make sure to let the missing segment through which caused this
611 * queue. Always keep one global queue entry spare to be able to
612 * process the missing segment.
613 */
614 qlimit = min(max(100, so->so_rcv.sb_hiwat >> 10),
615 (tcp_autorcvbuf_max >> 10));
616 if (th->th_seq != tp->rcv_nxt &&
617 (tp->t_reassqlen + 1) >= qlimit) {
618 tcp_reass_overflows++;
619 tcpstat.tcps_rcvmemdrop++;
620 m_freem(m);
621 *tlenp = 0;
622 return 0;
623 }
624
625 /* Allocate a new queue entry. If we can't, just drop the pkt. XXX */
626 te = zalloc_flags(tcp_reass_zone, Z_WAITOK | Z_NOFAIL);
627 tp->t_reassqlen++;
628
629 /*
630 * Find a segment which begins after this one does.
631 */
632 LIST_FOREACH(q, &tp->t_segq, tqe_q) {
633 if (SEQ_GT(q->tqe_th->th_seq, th->th_seq)) {
634 break;
635 }
636 p = q;
637 }
638
639 /*
640 * If there is a preceding segment, it may provide some of
641 * our data already. If so, drop the data from the incoming
642 * segment. If it provides all of our data, drop us.
643 */
644 if (p != NULL) {
645 int i;
646 /* conversion to int (in i) handles seq wraparound */
647 i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
648 if (i > 0) {
649 if (i > 1) {
650 /*
651 * Note duplicate data sequnce numbers
652 * to report in DSACK option
653 */
654 tp->t_dsack_lseq = th->th_seq;
655 tp->t_dsack_rseq = th->th_seq +
656 min(i, *tlenp);
657
658 /*
659 * Report only the first part of partial/
660 * non-contiguous duplicate sequence space
661 */
662 dsack_set = TRUE;
663 }
664 if (i >= *tlenp) {
665 tcpstat.tcps_rcvduppack++;
666 tcpstat.tcps_rcvdupbyte += *tlenp;
667 if (nstat_collect) {
668 nstat_route_rx(inp->inp_route.ro_rt,
669 1, *tlenp,
670 NSTAT_RX_FLAG_DUPLICATE);
671 INP_ADD_STAT(inp, cell, wifi, wired,
672 rxpackets, 1);
673 INP_ADD_STAT(inp, cell, wifi, wired,
674 rxbytes, *tlenp);
675 tp->t_stat.rxduplicatebytes += *tlenp;
676 inp_set_activity_bitmap(inp);
677 }
678 m_freem(m);
679 zfree(tcp_reass_zone, te);
680 te = NULL;
681 tp->t_reassqlen--;
682 /*
683 * Try to present any queued data
684 * at the left window edge to the user.
685 * This is needed after the 3-WHS
686 * completes.
687 */
688 goto present;
689 }
690 m_adj(m, i);
691 *tlenp -= i;
692 th->th_seq += i;
693 }
694 }
695 tp->t_rcvoopack++;
696 tcpstat.tcps_rcvoopack++;
697 tcpstat.tcps_rcvoobyte += *tlenp;
698 if (nstat_collect) {
699 nstat_route_rx(inp->inp_route.ro_rt, 1, *tlenp,
700 NSTAT_RX_FLAG_OUT_OF_ORDER);
701 INP_ADD_STAT(inp, cell, wifi, wired, rxpackets, 1);
702 INP_ADD_STAT(inp, cell, wifi, wired, rxbytes, *tlenp);
703 tp->t_stat.rxoutoforderbytes += *tlenp;
704 inp_set_activity_bitmap(inp);
705 }
706
707 /*
708 * While we overlap succeeding segments trim them or,
709 * if they are completely covered, dequeue them.
710 */
711 while (q) {
712 int i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
713 if (i <= 0) {
714 break;
715 }
716
717 /*
718 * Report only the first part of partial/non-contiguous
719 * duplicate segment in dsack option. The variable
720 * dsack_set will be true if a previous entry has some of
721 * the duplicate sequence space.
722 */
723 if (i > 1 && !dsack_set) {
724 if (tp->t_dsack_lseq == 0) {
725 tp->t_dsack_lseq = q->tqe_th->th_seq;
726 tp->t_dsack_rseq =
727 tp->t_dsack_lseq + min(i, q->tqe_len);
728 } else {
729 /*
730 * this segment overlaps data in multple
731 * entries in the reassembly queue, move
732 * the right sequence number further.
733 */
734 tp->t_dsack_rseq =
735 tp->t_dsack_rseq + min(i, q->tqe_len);
736 }
737 }
738 if (i < q->tqe_len) {
739 q->tqe_th->th_seq += i;
740 q->tqe_len -= i;
741 m_adj(q->tqe_m, i);
742 break;
743 }
744
745 nq = LIST_NEXT(q, tqe_q);
746 LIST_REMOVE(q, tqe_q);
747 m_freem(q->tqe_m);
748 zfree(tcp_reass_zone, q);
749 tp->t_reassqlen--;
750 q = nq;
751 }
752
753 /* Insert the new segment queue entry into place. */
754 te->tqe_m = m;
755 te->tqe_th = th;
756 te->tqe_len = *tlenp;
757
758 if (p == NULL) {
759 LIST_INSERT_HEAD(&tp->t_segq, te, tqe_q);
760 } else {
761 LIST_INSERT_AFTER(p, te, tqe_q);
762 }
763
764 present:
765 /*
766 * Present data to user, advancing rcv_nxt through
767 * completed sequence space.
768 */
769 if (!TCPS_HAVEESTABLISHED(tp->t_state)) {
770 return 0;
771 }
772 q = LIST_FIRST(&tp->t_segq);
773 if (!q || q->tqe_th->th_seq != tp->rcv_nxt) {
774 return 0;
775 }
776
777 /*
778 * If there is already another thread doing reassembly for this
779 * connection, it is better to let it finish the job --
780 * (radar 16316196)
781 */
782 if (tp->t_flagsext & TF_REASS_INPROG) {
783 return 0;
784 }
785
786 tp->t_flagsext |= TF_REASS_INPROG;
787 /* lost packet was recovered, so ooo data can be returned */
788 tcpstat.tcps_recovered_pkts++;
789
790 do {
791 tp->rcv_nxt += q->tqe_len;
792 flags = q->tqe_th->th_flags & TH_FIN;
793 LIST_REMOVE(q, tqe_q);
794 if (so->so_state & SS_CANTRCVMORE) {
795 m_freem(q->tqe_m);
796 } else {
797 so_recv_data_stat(so, q->tqe_m, 0); /* XXXX */
798 if (q->tqe_th->th_flags & TH_PUSH) {
799 tp->t_flagsext |= TF_LAST_IS_PSH;
800 } else {
801 tp->t_flagsext &= ~TF_LAST_IS_PSH;
802 }
803
804 if (sbappendstream_rcvdemux(so, q->tqe_m)) {
805 *dowakeup = 1;
806 }
807 }
808 zfree(tcp_reass_zone, q);
809 tp->t_reassqlen--;
810 q = LIST_FIRST(&tp->t_segq);
811 } while (q && q->tqe_th->th_seq == tp->rcv_nxt);
812 tp->t_flagsext &= ~TF_REASS_INPROG;
813
814 if ((inp->inp_vflag & INP_IPV6) != 0) {
815 KERNEL_DEBUG(DBG_LAYER_BEG,
816 ((inp->inp_fport << 16) | inp->inp_lport),
817 (((inp->in6p_laddr.s6_addr16[0] & 0xffff) << 16) |
818 (inp->in6p_faddr.s6_addr16[0] & 0xffff)),
819 0, 0, 0);
820 } else {
821 KERNEL_DEBUG(DBG_LAYER_BEG,
822 ((inp->inp_fport << 16) | inp->inp_lport),
823 (((inp->inp_laddr.s_addr & 0xffff) << 16) |
824 (inp->inp_faddr.s_addr & 0xffff)),
825 0, 0, 0);
826 }
827
828 return flags;
829 }
830
831 /*
832 * Reduce congestion window -- used when ECN is seen or when a tail loss
833 * probe recovers the last packet.
834 */
835 static void
tcp_reduce_congestion_window(struct tcpcb * tp)836 tcp_reduce_congestion_window(struct tcpcb *tp)
837 {
838 /*
839 * If the current tcp cc module has
840 * defined a hook for tasks to run
841 * before entering FR, call it
842 */
843 if (CC_ALGO(tp)->pre_fr != NULL) {
844 CC_ALGO(tp)->pre_fr(tp);
845 }
846 ENTER_FASTRECOVERY(tp);
847 if (tp->t_flags & TF_SENTFIN) {
848 tp->snd_recover = tp->snd_max - 1;
849 } else {
850 tp->snd_recover = tp->snd_max;
851 }
852 tp->t_timer[TCPT_REXMT] = 0;
853 tp->t_timer[TCPT_PTO] = 0;
854 tp->t_rtttime = 0;
855 if (tp->t_flagsext & TF_CWND_NONVALIDATED) {
856 tcp_cc_adjust_nonvalidated_cwnd(tp);
857 } else {
858 tp->snd_cwnd = tp->snd_ssthresh +
859 tp->t_maxseg * tcprexmtthresh;
860 }
861 }
862
863 /*
864 * This function is called upon reception of data on a socket. It's purpose is
865 * to handle the adaptive keepalive timers that monitor whether the connection
866 * is making progress. First the adaptive read-timer, second the TFO probe-timer.
867 *
868 * The application wants to get an event if there is a stall during read.
869 * Set the initial keepalive timeout to be equal to twice RTO.
870 *
871 * If the outgoing interface is in marginal conditions, we need to
872 * enable read probes for that too.
873 */
874 static inline void
tcp_adaptive_rwtimo_check(struct tcpcb * tp,int tlen)875 tcp_adaptive_rwtimo_check(struct tcpcb *tp, int tlen)
876 {
877 struct ifnet *outifp = tp->t_inpcb->inp_last_outifp;
878
879 if ((tp->t_adaptive_rtimo > 0 ||
880 (outifp != NULL &&
881 (outifp->if_eflags & IFEF_PROBE_CONNECTIVITY)))
882 && tlen > 0 &&
883 tp->t_state == TCPS_ESTABLISHED) {
884 tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp,
885 (TCP_REXMTVAL(tp) << 1));
886 tp->t_flagsext |= TF_DETECT_READSTALL;
887 tp->t_rtimo_probes = 0;
888 }
889 }
890
891 inline void
tcp_keepalive_reset(struct tcpcb * tp)892 tcp_keepalive_reset(struct tcpcb *tp)
893 {
894 tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp,
895 TCP_CONN_KEEPIDLE(tp));
896 tp->t_flagsext &= ~(TF_DETECT_READSTALL);
897 tp->t_rtimo_probes = 0;
898 }
899
900 void
tcp_set_finwait_timeout(struct tcpcb * tp)901 tcp_set_finwait_timeout(struct tcpcb *tp)
902 {
903 /*
904 * Starting the TCPT_2MSL timer is contrary to the
905 * specification, but if we don't get a FIN
906 * we'll hang forever.
907 */
908 ASSERT(tp->t_state == TCPS_FIN_WAIT_2);
909 ASSERT((tp->t_inpcb->inp_socket->so_state & (SS_CANTRCVMORE)) == SS_CANTRCVMORE);
910
911 if (tcp_fin_timeout > 0 &&
912 tcp_fin_timeout < TCP_CONN_MAXIDLE(tp)) {
913 tp->t_timer[TCPT_2MSL] = OFFSET_FROM_START(tp, tcp_fin_timeout);
914 } else {
915 tp->t_timer[TCPT_2MSL] = OFFSET_FROM_START(tp, TCP_CONN_MAXIDLE(tp));
916 }
917 }
918
919 /*
920 * TCP input routine, follows pages 65-76 of the
921 * protocol specification dated September, 1981 very closely.
922 */
923 int
tcp6_input(struct mbuf ** mp,int * offp,int proto)924 tcp6_input(struct mbuf **mp, int *offp, int proto)
925 {
926 #pragma unused(proto)
927 struct mbuf *m = *mp;
928 uint32_t ia6_flags;
929 struct ifnet *ifp = m->m_pkthdr.rcvif;
930
931 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), return IPPROTO_DONE);
932
933 /* Expect 32-bit aligned data pointer on strict-align platforms */
934 MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);
935
936 /*
937 * draft-itojun-ipv6-tcp-to-anycast
938 * better place to put this in?
939 */
940 if (ip6_getdstifaddr_info(m, NULL, &ia6_flags) == 0) {
941 if (ia6_flags & IN6_IFF_ANYCAST) {
942 struct ip6_hdr *ip6;
943
944 ip6 = mtod(m, struct ip6_hdr *);
945 icmp6_error(m, ICMP6_DST_UNREACH,
946 ICMP6_DST_UNREACH_ADDR,
947 (int)((caddr_t)&ip6->ip6_dst - (caddr_t)ip6));
948
949 IF_TCP_STATINC(ifp, icmp6unreach);
950
951 return IPPROTO_DONE;
952 }
953 }
954
955 tcp_input(m, *offp);
956 return IPPROTO_DONE;
957 }
958
959 /* Depending on the usage of mbuf space in the system, this function
960 * will return true or false. This is used to determine if a socket
961 * buffer can take more memory from the system for auto-tuning or not.
962 */
963 u_int8_t
tcp_cansbgrow(struct sockbuf * sb)964 tcp_cansbgrow(struct sockbuf *sb)
965 {
966 /* Calculate the host level space limit in terms of MSIZE buffers.
967 * We can use a maximum of half of the available mbuf space for
968 * socket buffers.
969 */
970 u_int32_t mblim = ((nmbclusters >> 1) << (MCLSHIFT - MSIZESHIFT));
971
972 /* Calculate per sb limit in terms of bytes. We optimize this limit
973 * for upto 16 socket buffers.
974 */
975
976 u_int32_t sbspacelim = ((nmbclusters >> 4) << MCLSHIFT);
977
978 if ((total_sbmb_cnt < mblim) &&
979 (sb->sb_hiwat < sbspacelim)) {
980 return 1;
981 } else {
982 OSIncrementAtomic64(&sbmb_limreached);
983 }
984 return 0;
985 }
986
987 static void
tcp_sbrcv_reserve(struct tcpcb * tp,struct sockbuf * sbrcv,u_int32_t newsize,u_int32_t idealsize,u_int32_t rcvbuf_max)988 tcp_sbrcv_reserve(struct tcpcb *tp, struct sockbuf *sbrcv,
989 u_int32_t newsize, u_int32_t idealsize, u_int32_t rcvbuf_max)
990 {
991 /* newsize should not exceed max */
992 newsize = min(newsize, rcvbuf_max);
993
994 /* The receive window scale negotiated at the
995 * beginning of the connection will also set a
996 * limit on the socket buffer size
997 */
998 newsize = min(newsize, TCP_MAXWIN << tp->rcv_scale);
999
1000 /* Set new socket buffer size */
1001 if (newsize > sbrcv->sb_hiwat &&
1002 (sbreserve(sbrcv, newsize) == 1)) {
1003 sbrcv->sb_idealsize = min(max(sbrcv->sb_idealsize,
1004 (idealsize != 0) ? idealsize : newsize), rcvbuf_max);
1005
1006 /* Again check the limit set by the advertised
1007 * window scale
1008 */
1009 sbrcv->sb_idealsize = min(sbrcv->sb_idealsize,
1010 TCP_MAXWIN << tp->rcv_scale);
1011 }
1012 }
1013
1014 /*
1015 * This function is used to grow a receive socket buffer. It
1016 * will take into account system-level memory usage and the
1017 * bandwidth available on the link to make a decision.
1018 */
1019 static void
tcp_sbrcv_grow(struct tcpcb * tp,struct sockbuf * sbrcv,struct tcpopt * to,uint32_t pktlen)1020 tcp_sbrcv_grow(struct tcpcb *tp, struct sockbuf *sbrcv,
1021 struct tcpopt *to, uint32_t pktlen)
1022 {
1023 struct socket *so = sbrcv->sb_so;
1024
1025 /*
1026 * Do not grow the receive socket buffer if
1027 * - auto resizing is disabled, globally or on this socket
1028 * - the high water mark already reached the maximum
1029 * - the stream is in background and receive side is being
1030 * throttled
1031 */
1032 if (tcp_do_autorcvbuf == 0 ||
1033 (sbrcv->sb_flags & SB_AUTOSIZE) == 0 ||
1034 tcp_cansbgrow(sbrcv) == 0 ||
1035 sbrcv->sb_hiwat >= tcp_autorcvbuf_max ||
1036 (tp->t_flagsext & TF_RECV_THROTTLE) ||
1037 (so->so_flags1 & SOF1_EXTEND_BK_IDLE_WANTED) ||
1038 (!tcp_autotune_reorder && !LIST_EMPTY(&tp->t_segq))) {
1039 /* Can not resize the socket buffer, just return */
1040 goto out;
1041 }
1042
1043 if (!TSTMP_SUPPORTED(tp)) {
1044 /*
1045 * Timestamp option is not supported on this connection,
1046 * use receiver's RTT. Socket buffer grows based on the
1047 * BDP of the link.
1048 */
1049 if (TSTMP_GEQ(tcp_now,
1050 tp->rfbuf_ts + (tp->rcv_srtt >> TCP_RTT_SHIFT))) {
1051 tp->rfbuf_cnt += pktlen;
1052 if (tp->rfbuf_cnt > tp->rfbuf_space) {
1053 int32_t rcvbuf_inc;
1054 uint32_t idealsize;
1055
1056 if (tp->rfbuf_cnt > tp->rfbuf_space + (tp->rfbuf_space >> 1)) {
1057 rcvbuf_inc = (tp->rfbuf_cnt << 2) - sbrcv->sb_hiwat;
1058 idealsize = (tp->rfbuf_cnt << 2);
1059 } else {
1060 rcvbuf_inc = (tp->rfbuf_cnt << 1) - sbrcv->sb_hiwat;
1061 idealsize = (tp->rfbuf_cnt << 1);
1062 }
1063
1064 if (rcvbuf_inc > 0) {
1065 rcvbuf_inc =
1066 (rcvbuf_inc / tp->t_maxseg) * tp->t_maxseg;
1067
1068 tcp_sbrcv_reserve(tp, sbrcv,
1069 sbrcv->sb_hiwat + rcvbuf_inc,
1070 idealsize, tcp_autorcvbuf_max);
1071
1072 tp->rfbuf_space = tp->rfbuf_cnt;
1073 }
1074 }
1075 goto out;
1076 } else {
1077 tp->rfbuf_cnt += pktlen;
1078 return;
1079 }
1080 } else if (to->to_tsecr != 0) {
1081 /*
1082 * If the timestamp shows that one RTT has
1083 * completed, we can stop counting the
1084 * bytes. Here we consider increasing
1085 * the socket buffer if the bandwidth measured in
1086 * last rtt, is more than half of sb_hiwat, this will
1087 * help to scale the buffer according to the bandwidth
1088 * on the link.
1089 */
1090 if (TSTMP_GEQ(to->to_tsecr, tp->rfbuf_ts)) {
1091 if (tcp_aggressive_rcvwnd_inc) {
1092 tp->rfbuf_cnt += pktlen;
1093 }
1094
1095 if ((tcp_aggressive_rcvwnd_inc == 0 &&
1096 tp->rfbuf_cnt + pktlen > (sbrcv->sb_hiwat -
1097 (sbrcv->sb_hiwat >> 1))) ||
1098 (tcp_aggressive_rcvwnd_inc &&
1099 tp->rfbuf_cnt > tp->rfbuf_space)) {
1100 int32_t rcvbuf_inc;
1101 uint32_t idealsize;
1102
1103 if (tcp_aggressive_rcvwnd_inc == 0) {
1104 int32_t min_incr;
1105
1106 tp->rfbuf_cnt += pktlen;
1107 /*
1108 * Increment the receive window by a
1109 * multiple of maximum sized segments.
1110 * This will prevent a connection from
1111 * sending smaller segments on wire if it
1112 * is limited by the receive window.
1113 *
1114 * Set the ideal size based on current
1115 * bandwidth measurements. We set the
1116 * ideal size on receive socket buffer to
1117 * be twice the bandwidth delay product.
1118 */
1119 rcvbuf_inc = (tp->rfbuf_cnt << 1)
1120 - sbrcv->sb_hiwat;
1121
1122 /*
1123 * Make the increment equal to 8 segments
1124 * at least
1125 */
1126 min_incr = tp->t_maxseg << tcp_autorcvbuf_inc_shift;
1127 if (rcvbuf_inc < min_incr) {
1128 rcvbuf_inc = min_incr;
1129 }
1130
1131 idealsize = (tp->rfbuf_cnt << 1);
1132 } else {
1133 if (tp->rfbuf_cnt > tp->rfbuf_space + (tp->rfbuf_space >> 1)) {
1134 rcvbuf_inc = (tp->rfbuf_cnt << 2) - sbrcv->sb_hiwat;
1135 idealsize = (tp->rfbuf_cnt << 2);
1136 } else {
1137 rcvbuf_inc = (tp->rfbuf_cnt << 1) - sbrcv->sb_hiwat;
1138 idealsize = (tp->rfbuf_cnt << 1);
1139 }
1140 }
1141
1142 tp->rfbuf_space = tp->rfbuf_cnt;
1143
1144 if (rcvbuf_inc > 0) {
1145 rcvbuf_inc =
1146 (rcvbuf_inc / tp->t_maxseg) * tp->t_maxseg;
1147
1148 tcp_sbrcv_reserve(tp, sbrcv,
1149 sbrcv->sb_hiwat + rcvbuf_inc,
1150 idealsize, tcp_autorcvbuf_max);
1151 }
1152 }
1153 /* Measure instantaneous receive bandwidth */
1154 if (tp->t_bwmeas != NULL && tp->rfbuf_cnt > 0 &&
1155 TSTMP_GT(tcp_now, tp->rfbuf_ts)) {
1156 u_int32_t rcv_bw;
1157 rcv_bw = tp->rfbuf_cnt /
1158 (int)(tcp_now - tp->rfbuf_ts);
1159 if (tp->t_bwmeas->bw_rcvbw_max == 0) {
1160 tp->t_bwmeas->bw_rcvbw_max = rcv_bw;
1161 } else {
1162 tp->t_bwmeas->bw_rcvbw_max = max(
1163 tp->t_bwmeas->bw_rcvbw_max, rcv_bw);
1164 }
1165 }
1166 goto out;
1167 } else {
1168 tp->rfbuf_cnt += pktlen;
1169 return;
1170 }
1171 }
1172 out:
1173 /* Restart the measurement */
1174 tp->rfbuf_ts = tcp_now;
1175 tp->rfbuf_cnt = 0;
1176 return;
1177 }
1178
1179 /* This function will trim the excess space added to the socket buffer
1180 * to help a slow-reading app. The ideal-size of a socket buffer depends
1181 * on the link bandwidth or it is set by an application and we aim to
1182 * reach that size.
1183 */
1184 void
tcp_sbrcv_trim(struct tcpcb * tp,struct sockbuf * sbrcv)1185 tcp_sbrcv_trim(struct tcpcb *tp, struct sockbuf *sbrcv)
1186 {
1187 if (tcp_do_autorcvbuf == 1 && sbrcv->sb_idealsize > 0 &&
1188 sbrcv->sb_hiwat > sbrcv->sb_idealsize) {
1189 int32_t trim;
1190 /* compute the difference between ideal and current sizes */
1191 u_int32_t diff = sbrcv->sb_hiwat - sbrcv->sb_idealsize;
1192
1193 /* Compute the maximum advertised window for
1194 * this connection.
1195 */
1196 u_int32_t advwin = tp->rcv_adv - tp->rcv_nxt;
1197
1198 /* How much can we trim the receive socket buffer?
1199 * 1. it can not be trimmed beyond the max rcv win advertised
1200 * 2. if possible, leave 1/16 of bandwidth*delay to
1201 * avoid closing the win completely
1202 */
1203 u_int32_t leave = max(advwin, (sbrcv->sb_idealsize >> 4));
1204
1205 /* Sometimes leave can be zero, in that case leave at least
1206 * a few segments worth of space.
1207 */
1208 if (leave == 0) {
1209 leave = tp->t_maxseg << tcp_autorcvbuf_inc_shift;
1210 }
1211
1212 trim = sbrcv->sb_hiwat - (sbrcv->sb_cc + leave);
1213 trim = imin(trim, (int32_t)diff);
1214
1215 if (trim > 0) {
1216 sbreserve(sbrcv, (sbrcv->sb_hiwat - trim));
1217 }
1218 }
1219 }
1220
1221 /* We may need to trim the send socket buffer size for two reasons:
1222 * 1. if the rtt seen on the connection is climbing up, we do not
1223 * want to fill the buffers any more.
1224 * 2. if the congestion win on the socket backed off, there is no need
1225 * to hold more mbufs for that connection than what the cwnd will allow.
1226 */
1227 void
tcp_sbsnd_trim(struct sockbuf * sbsnd)1228 tcp_sbsnd_trim(struct sockbuf *sbsnd)
1229 {
1230 if (((sbsnd->sb_flags & (SB_AUTOSIZE | SB_TRIM)) ==
1231 (SB_AUTOSIZE | SB_TRIM)) &&
1232 (sbsnd->sb_idealsize > 0) &&
1233 (sbsnd->sb_hiwat > sbsnd->sb_idealsize)) {
1234 u_int32_t trim = 0;
1235 if (sbsnd->sb_cc <= sbsnd->sb_idealsize) {
1236 trim = sbsnd->sb_hiwat - sbsnd->sb_idealsize;
1237 } else {
1238 trim = sbsnd->sb_hiwat - sbsnd->sb_cc;
1239 }
1240 sbreserve(sbsnd, (sbsnd->sb_hiwat - trim));
1241 }
1242 if (sbsnd->sb_hiwat <= sbsnd->sb_idealsize) {
1243 sbsnd->sb_flags &= ~(SB_TRIM);
1244 }
1245 }
1246
1247 /*
1248 * If timestamp option was not negotiated on this connection
1249 * and this connection is on the receiving side of a stream
1250 * then we can not measure the delay on the link accurately.
1251 * Instead of enabling automatic receive socket buffer
1252 * resizing, just give more space to the receive socket buffer.
1253 */
1254 static inline void
tcp_sbrcv_tstmp_check(struct tcpcb * tp)1255 tcp_sbrcv_tstmp_check(struct tcpcb *tp)
1256 {
1257 struct socket *so = tp->t_inpcb->inp_socket;
1258 u_int32_t newsize = 2 * tcp_recvspace;
1259 struct sockbuf *sbrcv = &so->so_rcv;
1260
1261 if ((tp->t_flags & (TF_REQ_TSTMP | TF_RCVD_TSTMP)) !=
1262 (TF_REQ_TSTMP | TF_RCVD_TSTMP) &&
1263 (sbrcv->sb_flags & SB_AUTOSIZE) != 0) {
1264 tcp_sbrcv_reserve(tp, sbrcv, newsize, 0, newsize);
1265 }
1266 }
1267
1268 /* A receiver will evaluate the flow of packets on a connection
1269 * to see if it can reduce ack traffic. The receiver will start
1270 * stretching acks if all of the following conditions are met:
1271 * 1. tcp_delack_enabled is set to 3
1272 * 2. If the bytes received in the last 100ms is greater than a threshold
1273 * defined by maxseg_unacked
1274 * 3. If the connection has not been idle for tcp_maxrcvidle period.
1275 * 4. If the connection has seen enough packets to let the slow-start
1276 * finish after connection establishment or after some packet loss.
1277 *
1278 * The receiver will stop stretching acks if there is congestion/reordering
1279 * as indicated by packets on reassembly queue or an ECN. If the delayed-ack
1280 * timer fires while stretching acks, it means that the packet flow has gone
1281 * below the threshold defined by maxseg_unacked and the receiver will stop
1282 * stretching acks. The receiver gets no indication when slow-start is completed
1283 * or when the connection reaches an idle state. That is why we use
1284 * tcp_rcvsspktcnt to cover slow-start and tcp_maxrcvidle to identify idle
1285 * state.
1286 */
1287 static inline int
tcp_stretch_ack_enable(struct tcpcb * tp,int thflags)1288 tcp_stretch_ack_enable(struct tcpcb *tp, int thflags)
1289 {
1290 if (tp->rcv_by_unackwin >= (maxseg_unacked * tp->t_maxseg) &&
1291 TSTMP_GEQ(tp->rcv_unackwin, tcp_now)) {
1292 tp->t_flags |= TF_STREAMING_ON;
1293 } else {
1294 tp->t_flags &= ~TF_STREAMING_ON;
1295 }
1296
1297 /* If there has been an idle time, reset streaming detection */
1298 if (TSTMP_GT(tcp_now, tp->rcv_unackwin + tcp_maxrcvidle)) {
1299 tp->t_flags &= ~TF_STREAMING_ON;
1300 }
1301
1302 /*
1303 * If there are flags other than TH_ACK set, reset streaming
1304 * detection
1305 */
1306 if (thflags & ~TH_ACK) {
1307 tp->t_flags &= ~TF_STREAMING_ON;
1308 }
1309
1310 if (tp->t_flagsext & TF_DISABLE_STRETCHACK) {
1311 if (tp->rcv_nostrack_pkts >= TCP_STRETCHACK_ENABLE_PKTCNT) {
1312 tp->t_flagsext &= ~TF_DISABLE_STRETCHACK;
1313 tp->rcv_nostrack_pkts = 0;
1314 tp->rcv_nostrack_ts = 0;
1315 } else {
1316 tp->rcv_nostrack_pkts++;
1317 }
1318 }
1319
1320 if (!(tp->t_flagsext & (TF_NOSTRETCHACK | TF_DISABLE_STRETCHACK)) &&
1321 (tp->t_flags & TF_STREAMING_ON) &&
1322 (!(tp->t_flagsext & TF_RCVUNACK_WAITSS) ||
1323 (tp->rcv_waitforss >= tcp_rcvsspktcnt))) {
1324 return 1;
1325 }
1326
1327 return 0;
1328 }
1329
1330 /*
1331 * Reset the state related to stretch-ack algorithm. This will make
1332 * the receiver generate an ack every other packet. The receiver
1333 * will start re-evaluating the rate at which packets come to decide
1334 * if it can benefit by lowering the ack traffic.
1335 */
1336 void
tcp_reset_stretch_ack(struct tcpcb * tp)1337 tcp_reset_stretch_ack(struct tcpcb *tp)
1338 {
1339 tp->t_flags &= ~(TF_STRETCHACK | TF_STREAMING_ON);
1340 tp->rcv_by_unackwin = 0;
1341 tp->rcv_by_unackhalfwin = 0;
1342 tp->rcv_unackwin = tcp_now + tcp_rcvunackwin;
1343
1344 /*
1345 * When there is packet loss or packet re-ordering or CWR due to
1346 * ECN, the sender's congestion window is reduced. In these states,
1347 * generate an ack for every other packet for some time to allow
1348 * the sender's congestion window to grow.
1349 */
1350 tp->t_flagsext |= TF_RCVUNACK_WAITSS;
1351 tp->rcv_waitforss = 0;
1352 }
1353
1354 /*
1355 * The last packet was a retransmission, check if this ack
1356 * indicates that the retransmission was spurious.
1357 *
1358 * If the connection supports timestamps, we could use it to
1359 * detect if the last retransmit was not needed. Otherwise,
1360 * we check if the ACK arrived within RTT/2 window, then it
1361 * was a mistake to do the retransmit in the first place.
1362 *
1363 * This function will return 1 if it is a spurious retransmit,
1364 * 0 otherwise.
1365 */
1366 int
tcp_detect_bad_rexmt(struct tcpcb * tp,struct tcphdr * th,struct tcpopt * to,u_int32_t rxtime)1367 tcp_detect_bad_rexmt(struct tcpcb *tp, struct tcphdr *th,
1368 struct tcpopt *to, u_int32_t rxtime)
1369 {
1370 int32_t tdiff, bad_rexmt_win;
1371 bad_rexmt_win = (tp->t_srtt >> (TCP_RTT_SHIFT + 1));
1372
1373 /* If the ack has ECN CE bit, then cwnd has to be adjusted */
1374 if (TCP_ECN_ENABLED(tp) && (th->th_flags & TH_ECE)) {
1375 return 0;
1376 }
1377 if (TSTMP_SUPPORTED(tp)) {
1378 if (rxtime > 0 && (to->to_flags & TOF_TS) && to->to_tsecr != 0 &&
1379 TSTMP_LT(to->to_tsecr, rxtime)) {
1380 return 1;
1381 }
1382 } else {
1383 if ((tp->t_rxtshift == 1 || (tp->t_flagsext & TF_SENT_TLPROBE)) &&
1384 rxtime > 0) {
1385 tdiff = (int32_t)(tcp_now - rxtime);
1386 if (tdiff < bad_rexmt_win) {
1387 return 1;
1388 }
1389 }
1390 }
1391 return 0;
1392 }
1393
1394
1395 /*
1396 * Restore congestion window state if a spurious timeout
1397 * was detected.
1398 */
1399 static void
tcp_bad_rexmt_restore_state(struct tcpcb * tp,struct tcphdr * th)1400 tcp_bad_rexmt_restore_state(struct tcpcb *tp, struct tcphdr *th)
1401 {
1402 if (TSTMP_SUPPORTED(tp)) {
1403 u_int32_t fsize, acked;
1404 fsize = tp->snd_max - th->th_ack;
1405 acked = BYTES_ACKED(th, tp);
1406
1407 /*
1408 * Implement bad retransmit recovery as
1409 * described in RFC 4015.
1410 */
1411 tp->snd_ssthresh = tp->snd_ssthresh_prev;
1412
1413 /* Initialize cwnd to the initial window */
1414 if (CC_ALGO(tp)->cwnd_init != NULL) {
1415 CC_ALGO(tp)->cwnd_init(tp);
1416 }
1417
1418 tp->snd_cwnd = fsize + min(acked, tp->snd_cwnd);
1419 } else {
1420 tp->snd_cwnd = tp->snd_cwnd_prev;
1421 tp->snd_ssthresh = tp->snd_ssthresh_prev;
1422 if (tp->t_flags & TF_WASFRECOVERY) {
1423 ENTER_FASTRECOVERY(tp);
1424 }
1425
1426 /* Do not use the loss flight size in this case */
1427 tp->t_lossflightsize = 0;
1428 }
1429 tp->snd_cwnd = max(tp->snd_cwnd, tcp_initial_cwnd(tp));
1430 tp->snd_recover = tp->snd_recover_prev;
1431 tp->snd_nxt = tp->snd_max;
1432
1433 /* Fix send socket buffer to reflect the change in cwnd */
1434 tcp_bad_rexmt_fix_sndbuf(tp);
1435
1436 /*
1437 * This RTT might reflect the extra delay induced
1438 * by the network. Skip using this sample for RTO
1439 * calculation and mark the connection so we can
1440 * recompute RTT when the next eligible sample is
1441 * found.
1442 */
1443 tp->t_flagsext |= TF_RECOMPUTE_RTT;
1444 tp->t_badrexmt_time = tcp_now;
1445 tp->t_rtttime = 0;
1446 }
1447
1448 /*
1449 * If the previous packet was sent in retransmission timer, and it was
1450 * not needed, then restore the congestion window to the state before that
1451 * transmission.
1452 *
1453 * If the last packet was sent in tail loss probe timeout, check if that
1454 * recovered the last packet. If so, that will indicate a real loss and
1455 * the congestion window needs to be lowered.
1456 */
1457 static void
tcp_bad_rexmt_check(struct tcpcb * tp,struct tcphdr * th,struct tcpopt * to)1458 tcp_bad_rexmt_check(struct tcpcb *tp, struct tcphdr *th, struct tcpopt *to)
1459 {
1460 if (tp->t_rxtshift > 0 &&
1461 tcp_detect_bad_rexmt(tp, th, to, tp->t_rxtstart)) {
1462 ++tcpstat.tcps_sndrexmitbad;
1463 tcp_bad_rexmt_restore_state(tp, th);
1464 tcp_ccdbg_trace(tp, th, TCP_CC_BAD_REXMT_RECOVERY);
1465 } else if ((tp->t_flagsext & TF_SENT_TLPROBE) && tp->t_tlphighrxt > 0 &&
1466 SEQ_GEQ(th->th_ack, tp->t_tlphighrxt) &&
1467 !tcp_detect_bad_rexmt(tp, th, to, tp->t_tlpstart)) {
1468 /*
1469 * check DSACK information also to make sure that
1470 * the TLP was indeed needed
1471 */
1472 if (tcp_rxtseg_dsack_for_tlp(tp)) {
1473 /*
1474 * received a DSACK to indicate that TLP was
1475 * not needed
1476 */
1477 tcp_rxtseg_clean(tp);
1478 goto out;
1479 }
1480
1481 /*
1482 * The tail loss probe recovered the last packet and
1483 * we need to adjust the congestion window to take
1484 * this loss into account.
1485 */
1486 ++tcpstat.tcps_tlp_recoverlastpkt;
1487 if (!IN_FASTRECOVERY(tp)) {
1488 tcp_reduce_congestion_window(tp);
1489 EXIT_FASTRECOVERY(tp);
1490 }
1491 tcp_ccdbg_trace(tp, th, TCP_CC_TLP_RECOVER_LASTPACKET);
1492 } else if (tcp_rxtseg_detect_bad_rexmt(tp, th->th_ack)) {
1493 /*
1494 * All of the retransmitted segments were duplicated, this
1495 * can be an indication of bad fast retransmit.
1496 */
1497 tcpstat.tcps_dsack_badrexmt++;
1498 tcp_bad_rexmt_restore_state(tp, th);
1499 tcp_ccdbg_trace(tp, th, TCP_CC_DSACK_BAD_REXMT);
1500 tcp_rxtseg_clean(tp);
1501 }
1502 out:
1503 tp->t_flagsext &= ~(TF_SENT_TLPROBE);
1504 tp->t_tlphighrxt = 0;
1505 tp->t_tlpstart = 0;
1506
1507 /*
1508 * check if the latest ack was for a segment sent during PMTU
1509 * blackhole detection. If the timestamp on the ack is before
1510 * PMTU blackhole detection, then revert the size of the max
1511 * segment to previous size.
1512 */
1513 if (tp->t_rxtshift > 0 && (tp->t_flags & TF_BLACKHOLE) &&
1514 tp->t_pmtud_start_ts > 0 && TSTMP_SUPPORTED(tp)) {
1515 if ((to->to_flags & TOF_TS) && to->to_tsecr != 0
1516 && TSTMP_LT(to->to_tsecr, tp->t_pmtud_start_ts)) {
1517 tcp_pmtud_revert_segment_size(tp);
1518 }
1519 }
1520 if (tp->t_pmtud_start_ts > 0) {
1521 tp->t_pmtud_start_ts = 0;
1522 }
1523
1524 tp->t_pmtud_lastseg_size = 0;
1525 }
1526
1527 /*
1528 * Check if early retransmit can be attempted according to RFC 5827.
1529 *
1530 * If packet reordering is detected on a connection, fast recovery will
1531 * be delayed until it is clear that the packet was lost and not reordered.
1532 * But reordering detection is done only when SACK is enabled.
1533 *
1534 * On connections that do not support SACK, there is a limit on the number
1535 * of early retransmits that can be done per minute. This limit is needed
1536 * to make sure that too many packets are not retransmitted when there is
1537 * packet reordering.
1538 */
1539 static void
tcp_early_rexmt_check(struct tcpcb * tp,struct tcphdr * th)1540 tcp_early_rexmt_check(struct tcpcb *tp, struct tcphdr *th)
1541 {
1542 u_int32_t obytes, snd_off;
1543 int32_t snd_len;
1544 struct socket *so = tp->t_inpcb->inp_socket;
1545
1546 if ((SACK_ENABLED(tp) || tp->t_early_rexmt_count < TCP_EARLY_REXMT_LIMIT) &&
1547 SEQ_GT(tp->snd_max, tp->snd_una) &&
1548 (tp->t_dupacks == 1 || (SACK_ENABLED(tp) && !TAILQ_EMPTY(&tp->snd_holes)))) {
1549 /*
1550 * If there are only a few outstanding
1551 * segments on the connection, we might need
1552 * to lower the retransmit threshold. This
1553 * will allow us to do Early Retransmit as
1554 * described in RFC 5827.
1555 */
1556 if (SACK_ENABLED(tp) &&
1557 !TAILQ_EMPTY(&tp->snd_holes)) {
1558 obytes = (tp->snd_max - tp->snd_fack) +
1559 tp->sackhint.sack_bytes_rexmit;
1560 } else {
1561 obytes = (tp->snd_max - tp->snd_una);
1562 }
1563
1564 /*
1565 * In order to lower retransmit threshold the
1566 * following two conditions must be met.
1567 * 1. the amount of outstanding data is less
1568 * than 4*SMSS bytes
1569 * 2. there is no unsent data ready for
1570 * transmission or the advertised window
1571 * will limit sending new segments.
1572 */
1573 snd_off = tp->snd_max - tp->snd_una;
1574 snd_len = min(so->so_snd.sb_cc, tp->snd_wnd) - snd_off;
1575 if (obytes < (tp->t_maxseg << 2) &&
1576 snd_len <= 0) {
1577 u_int32_t osegs;
1578
1579 osegs = obytes / tp->t_maxseg;
1580 if ((osegs * tp->t_maxseg) < obytes) {
1581 osegs++;
1582 }
1583
1584 /*
1585 * Since the connection might have already
1586 * received some dupacks, we add them to
1587 * to the outstanding segments count to get
1588 * the correct retransmit threshold.
1589 *
1590 * By checking for early retransmit after
1591 * receiving some duplicate acks when SACK
1592 * is supported, the connection will
1593 * enter fast recovery even if multiple
1594 * segments are lost in the same window.
1595 */
1596 osegs += tp->t_dupacks;
1597 if (osegs < 4) {
1598 tp->t_rexmtthresh =
1599 ((osegs - 1) > 1) ? ((uint8_t)osegs - 1) : 1;
1600 tp->t_rexmtthresh =
1601 MIN(tp->t_rexmtthresh, tcprexmtthresh);
1602 tp->t_rexmtthresh =
1603 MAX(tp->t_rexmtthresh,
1604 tp->t_dupacks > UINT8_MAX ? UINT8_MAX : (uint8_t)tp->t_dupacks);
1605
1606 if (tp->t_early_rexmt_count == 0) {
1607 tp->t_early_rexmt_win = tcp_now;
1608 }
1609
1610 if (tp->t_flagsext & TF_SENT_TLPROBE) {
1611 tcpstat.tcps_tlp_recovery++;
1612 tcp_ccdbg_trace(tp, th,
1613 TCP_CC_TLP_RECOVERY);
1614 } else {
1615 tcpstat.tcps_early_rexmt++;
1616 tp->t_early_rexmt_count++;
1617 tcp_ccdbg_trace(tp, th,
1618 TCP_CC_EARLY_RETRANSMIT);
1619 }
1620 }
1621 }
1622 }
1623
1624 /*
1625 * If we ever sent a TLP probe, the acknowledgement will trigger
1626 * early retransmit because the value of snd_fack will be close
1627 * to snd_max. This will take care of adjustments to the
1628 * congestion window. So we can reset TF_SENT_PROBE flag.
1629 */
1630 tp->t_flagsext &= ~(TF_SENT_TLPROBE);
1631 tp->t_tlphighrxt = 0;
1632 tp->t_tlpstart = 0;
1633 }
1634
1635 static boolean_t
tcp_tfo_syn(struct tcpcb * tp,struct tcpopt * to)1636 tcp_tfo_syn(struct tcpcb *tp, struct tcpopt *to)
1637 {
1638 u_char out[CCAES_BLOCK_SIZE];
1639 unsigned char len;
1640
1641 if (!(to->to_flags & (TOF_TFO | TOF_TFOREQ)) ||
1642 !(tcp_fastopen & TCP_FASTOPEN_SERVER)) {
1643 return FALSE;
1644 }
1645
1646 if ((to->to_flags & TOF_TFOREQ)) {
1647 tp->t_tfo_flags |= TFO_F_OFFER_COOKIE;
1648
1649 tp->t_tfo_stats |= TFO_S_COOKIEREQ_RECV;
1650 tcpstat.tcps_tfo_cookie_req_rcv++;
1651 return FALSE;
1652 }
1653
1654 /* Ok, then it must be an offered cookie. We need to check that ... */
1655 tcp_tfo_gen_cookie(tp->t_inpcb, out, sizeof(out));
1656
1657 len = *to->to_tfo - TCPOLEN_FASTOPEN_REQ;
1658 to->to_tfo++;
1659 if (memcmp(out, to->to_tfo, len)) {
1660 /* Cookies are different! Let's return and offer a new cookie */
1661 tp->t_tfo_flags |= TFO_F_OFFER_COOKIE;
1662
1663 tp->t_tfo_stats |= TFO_S_COOKIE_INVALID;
1664 tcpstat.tcps_tfo_cookie_invalid++;
1665 return FALSE;
1666 }
1667
1668 if (OSIncrementAtomic(&tcp_tfo_halfcnt) >= tcp_tfo_backlog) {
1669 /* Need to decrement again as we just increased it... */
1670 OSDecrementAtomic(&tcp_tfo_halfcnt);
1671 return FALSE;
1672 }
1673
1674 tp->t_tfo_flags |= TFO_F_COOKIE_VALID;
1675
1676 tp->t_tfo_stats |= TFO_S_SYNDATA_RCV;
1677 tcpstat.tcps_tfo_syn_data_rcv++;
1678
1679 return TRUE;
1680 }
1681
1682 static void
tcp_tfo_synack(struct tcpcb * tp,struct tcpopt * to)1683 tcp_tfo_synack(struct tcpcb *tp, struct tcpopt *to)
1684 {
1685 if (to->to_flags & TOF_TFO) {
1686 unsigned char len = *to->to_tfo - TCPOLEN_FASTOPEN_REQ;
1687
1688 /*
1689 * If this happens, things have gone terribly wrong. len should
1690 * have been checked in tcp_dooptions.
1691 */
1692 VERIFY(len <= TFO_COOKIE_LEN_MAX);
1693
1694 to->to_tfo++;
1695
1696 tcp_cache_set_cookie(tp, to->to_tfo, len);
1697 tcp_heuristic_tfo_success(tp);
1698
1699 tp->t_tfo_stats |= TFO_S_COOKIE_RCV;
1700 tcpstat.tcps_tfo_cookie_rcv++;
1701 if (tp->t_tfo_flags & TFO_F_COOKIE_SENT) {
1702 tcpstat.tcps_tfo_cookie_wrong++;
1703 tp->t_tfo_stats |= TFO_S_COOKIE_WRONG;
1704 }
1705 } else {
1706 /*
1707 * Thus, no cookie in the response, but we either asked for one
1708 * or sent SYN+DATA. Now, we need to check whether we had to
1709 * rexmit the SYN. If that's the case, it's better to start
1710 * backing of TFO-cookie requests.
1711 */
1712 if (!(tp->t_flagsext & TF_FASTOPEN_FORCE_ENABLE) &&
1713 tp->t_tfo_flags & TFO_F_SYN_LOSS) {
1714 tp->t_tfo_stats |= TFO_S_SYN_LOSS;
1715 tcpstat.tcps_tfo_syn_loss++;
1716
1717 tcp_heuristic_tfo_loss(tp);
1718 } else {
1719 if (tp->t_tfo_flags & TFO_F_COOKIE_REQ) {
1720 tp->t_tfo_stats |= TFO_S_NO_COOKIE_RCV;
1721 tcpstat.tcps_tfo_no_cookie_rcv++;
1722 }
1723
1724 tcp_heuristic_tfo_success(tp);
1725 }
1726 }
1727 }
1728
1729 static void
tcp_tfo_rcv_probe(struct tcpcb * tp,int tlen)1730 tcp_tfo_rcv_probe(struct tcpcb *tp, int tlen)
1731 {
1732 if (tlen != 0) {
1733 return;
1734 }
1735
1736 tp->t_tfo_probe_state = TFO_PROBE_PROBING;
1737
1738 /*
1739 * We send the probe out rather quickly (after one RTO). It does not
1740 * really hurt that much, it's only one additional segment on the wire.
1741 */
1742 tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp, (TCP_REXMTVAL(tp)));
1743 }
1744
1745 static void
tcp_tfo_rcv_data(struct tcpcb * tp)1746 tcp_tfo_rcv_data(struct tcpcb *tp)
1747 {
1748 /* Transition from PROBING to NONE as data has been received */
1749 if (tp->t_tfo_probe_state >= TFO_PROBE_PROBING) {
1750 tp->t_tfo_probe_state = TFO_PROBE_NONE;
1751 }
1752 }
1753
1754 static void
tcp_tfo_rcv_ack(struct tcpcb * tp,struct tcphdr * th)1755 tcp_tfo_rcv_ack(struct tcpcb *tp, struct tcphdr *th)
1756 {
1757 if (tp->t_tfo_probe_state == TFO_PROBE_PROBING &&
1758 tp->t_tfo_probes > 0) {
1759 if (th->th_seq == tp->rcv_nxt) {
1760 /* No hole, so stop probing */
1761 tp->t_tfo_probe_state = TFO_PROBE_NONE;
1762 } else if (SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1763 /* There is a hole! Wait a bit for data... */
1764 tp->t_tfo_probe_state = TFO_PROBE_WAIT_DATA;
1765 tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp,
1766 TCP_REXMTVAL(tp));
1767 }
1768 }
1769 }
1770
1771 /*
1772 * Update snd_wnd information.
1773 */
1774 static inline bool
tcp_update_window(struct tcpcb * tp,int thflags,struct tcphdr * th,u_int32_t tiwin,int tlen)1775 tcp_update_window(struct tcpcb *tp, int thflags, struct tcphdr * th,
1776 u_int32_t tiwin, int tlen)
1777 {
1778 /* Don't look at the window if there is no ACK flag */
1779 if ((thflags & TH_ACK) &&
1780 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
1781 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
1782 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
1783 /* keep track of pure window updates */
1784 if (tlen == 0 &&
1785 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd) {
1786 tcpstat.tcps_rcvwinupd++;
1787 }
1788 tp->snd_wnd = tiwin;
1789 tp->snd_wl1 = th->th_seq;
1790 tp->snd_wl2 = th->th_ack;
1791 if (tp->snd_wnd > tp->max_sndwnd) {
1792 tp->max_sndwnd = tp->snd_wnd;
1793 }
1794
1795 if (tp->t_inpcb->inp_socket->so_flags & SOF_MP_SUBFLOW) {
1796 mptcp_update_window_wakeup(tp);
1797 }
1798 return true;
1799 }
1800 return false;
1801 }
1802
1803 static void
tcp_handle_wakeup(struct socket * so,int read_wakeup,int write_wakeup)1804 tcp_handle_wakeup(struct socket *so, int read_wakeup, int write_wakeup)
1805 {
1806 if (read_wakeup != 0) {
1807 sorwakeup(so);
1808 }
1809 if (write_wakeup != 0) {
1810 sowwakeup(so);
1811 }
1812 }
1813
1814 static void
tcp_update_snd_una(struct tcpcb * tp,uint32_t ack)1815 tcp_update_snd_una(struct tcpcb *tp, uint32_t ack)
1816 {
1817 tp->snd_una = ack;
1818 if (SACK_ENABLED(tp) && SEQ_LT(tp->send_highest_sack, tp->snd_una)) {
1819 tp->send_highest_sack = tp->snd_una;
1820
1821 /* If we move our marker, we need to start fresh */
1822 tp->t_new_dupacks = 0;
1823 }
1824 }
1825
1826 static bool
tcp_syn_data_valid(struct tcpcb * tp,struct tcphdr * tcp_hdr,int tlen)1827 tcp_syn_data_valid(struct tcpcb *tp, struct tcphdr *tcp_hdr, int tlen)
1828 {
1829 /* No data? */
1830 if (tlen <= 0) {
1831 return false;
1832 }
1833
1834 /* Not the right sequence-number? */
1835 if (tcp_hdr->th_seq != tp->irs) {
1836 return false;
1837 }
1838
1839 /* We could have wrapped around, check that */
1840 if (tp->t_inpcb->inp_stat->rxbytes > INT32_MAX) {
1841 return false;
1842 }
1843
1844 return true;
1845 }
1846
1847 void
tcp_input(struct mbuf * m,int off0)1848 tcp_input(struct mbuf *m, int off0)
1849 {
1850 int exiting_fr = 0;
1851 struct tcphdr *th;
1852 struct ip *ip = NULL;
1853 struct inpcb *inp;
1854 u_char *optp = NULL;
1855 int optlen = 0;
1856 int tlen, off;
1857 int drop_hdrlen;
1858 struct tcpcb *tp = 0;
1859 int thflags;
1860 struct socket *so = 0;
1861 int todrop, acked, ourfinisacked, needoutput = 0;
1862 int read_wakeup = 0;
1863 int write_wakeup = 0;
1864 struct in_addr laddr;
1865 struct in6_addr laddr6;
1866 int dropsocket = 0;
1867 int iss = 0, nosock = 0;
1868 u_int32_t tiwin, sack_bytes_acked = 0, sack_bytes_newly_acked = 0;
1869 struct tcpopt to; /* options in this segment */
1870 #if TCPDEBUG
1871 short ostate = 0;
1872 #endif
1873 u_char ip_ecn = IPTOS_ECN_NOTECT;
1874 unsigned int ifscope;
1875 uint8_t isconnected, isdisconnected;
1876 struct ifnet *ifp = m->m_pkthdr.rcvif;
1877 int segment_count = m->m_pkthdr.seg_cnt ? : 1;
1878 int win;
1879 u_int16_t pf_tag = 0;
1880 #if MPTCP
1881 struct mptcb *mp_tp = NULL;
1882 #endif /* MPTCP */
1883 boolean_t cell = IFNET_IS_CELLULAR(ifp);
1884 boolean_t wifi = (!cell && IFNET_IS_WIFI(ifp));
1885 boolean_t wired = (!wifi && IFNET_IS_WIRED(ifp));
1886 boolean_t recvd_dsack = FALSE;
1887 struct tcp_respond_args tra;
1888 int prev_t_state;
1889 boolean_t check_cfil = cfil_filter_present();
1890 bool findpcb_iterated = false;
1891 /*
1892 * The mbuf may be freed after it has been added to the receive socket
1893 * buffer or the reassembly queue, so we reinitialize th to point to a
1894 * safe copy of the TCP header
1895 */
1896 struct tcphdr saved_tcphdr = {};
1897 /*
1898 * Save copy of the IPv4/IPv6 header.
1899 * Note: use array of uint32_t to silence compiler warning when casting
1900 * to a struct ip6_hdr pointer.
1901 */
1902 #define MAX_IPWORDS ((sizeof(struct ip) + MAX_IPOPTLEN) / sizeof(uint32_t))
1903 uint32_t saved_hdr[MAX_IPWORDS];
1904
1905 #define TCP_INC_VAR(stat, npkts) do { \
1906 stat += npkts; \
1907 } while (0)
1908
1909 if (tcp_ack_strategy == TCP_ACK_STRATEGY_LEGACY) {
1910 segment_count = 1;
1911 }
1912 TCP_INC_VAR(tcpstat.tcps_rcvtotal, segment_count);
1913
1914 struct ip6_hdr *ip6 = NULL;
1915 int isipv6;
1916 struct proc *kernel_proc = current_proc();
1917
1918 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_START, 0, 0, 0, 0, 0);
1919
1920 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
1921 bzero((char *)&to, sizeof(to));
1922
1923 m_add_crumb(m, PKT_CRUMB_TCP_INPUT);
1924
1925 if (m->m_flags & M_PKTHDR) {
1926 pf_tag = m_pftag(m)->pftag_tag;
1927 }
1928
1929 if (isipv6) {
1930 /*
1931 * Expect 32-bit aligned data pointer on
1932 * strict-align platforms
1933 */
1934 MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);
1935
1936 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
1937 ip6 = mtod(m, struct ip6_hdr *);
1938 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
1939 th = (struct tcphdr *)(void *)((caddr_t)ip6 + off0);
1940
1941 if (tcp_input_checksum(AF_INET6, m, th, off0, tlen)) {
1942 TCP_LOG_DROP_PKT(ip6, th, ifp, "IPv6 bad tcp checksum");
1943 goto dropnosock;
1944 }
1945
1946 KERNEL_DEBUG(DBG_LAYER_BEG, ((th->th_dport << 16) | th->th_sport),
1947 (((ip6->ip6_src.s6_addr16[0]) << 16) | (ip6->ip6_dst.s6_addr16[0])),
1948 th->th_seq, th->th_ack, th->th_win);
1949 /*
1950 * Be proactive about unspecified IPv6 address in source.
1951 * As we use all-zero to indicate unbounded/unconnected pcb,
1952 * unspecified IPv6 address can be used to confuse us.
1953 *
1954 * Note that packets with unspecified IPv6 destination is
1955 * already dropped in ip6_input.
1956 */
1957 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
1958 /* XXX stat */
1959 IF_TCP_STATINC(ifp, unspecv6);
1960 TCP_LOG_DROP_PKT(ip6, th, ifp, "src IPv6 address unspecified");
1961 goto dropnosock;
1962 }
1963 DTRACE_TCP5(receive, struct mbuf *, m, struct inpcb *, NULL,
1964 struct ip6_hdr *, ip6, struct tcpcb *, NULL,
1965 struct tcphdr *, th);
1966
1967 ip_ecn = (ntohl(ip6->ip6_flow) >> 20) & IPTOS_ECN_MASK;
1968 } else {
1969 /*
1970 * Get IP and TCP header together in first mbuf.
1971 * Note: IP leaves IP header in first mbuf.
1972 */
1973 if (off0 > sizeof(struct ip)) {
1974 ip_stripoptions(m);
1975 off0 = sizeof(struct ip);
1976 }
1977 if (m->m_len < sizeof(struct tcpiphdr)) {
1978 if ((m = m_pullup(m, sizeof(struct tcpiphdr))) == 0) {
1979 tcpstat.tcps_rcvshort++;
1980 return;
1981 }
1982 }
1983
1984 /* Expect 32-bit aligned data pointer on strict-align platforms */
1985 MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);
1986
1987 ip = mtod(m, struct ip *);
1988 th = (struct tcphdr *)(void *)((caddr_t)ip + off0);
1989 tlen = ip->ip_len;
1990
1991 if (tcp_input_checksum(AF_INET, m, th, off0, tlen)) {
1992 TCP_LOG_DROP_PKT(ip, th, ifp, "IPv4 bad tcp checksum");
1993 goto dropnosock;
1994 }
1995
1996 /* Re-initialization for later version check */
1997 ip->ip_v = IPVERSION;
1998 ip_ecn = (ip->ip_tos & IPTOS_ECN_MASK);
1999
2000 DTRACE_TCP5(receive, struct mbuf *, m, struct inpcb *, NULL,
2001 struct ip *, ip, struct tcpcb *, NULL, struct tcphdr *, th);
2002
2003 KERNEL_DEBUG(DBG_LAYER_BEG, ((th->th_dport << 16) | th->th_sport),
2004 (((ip->ip_src.s_addr & 0xffff) << 16) | (ip->ip_dst.s_addr & 0xffff)),
2005 th->th_seq, th->th_ack, th->th_win);
2006 }
2007
2008 #define TCP_LOG_HDR (isipv6 ? (void *)ip6 : (void *)ip)
2009
2010 /*
2011 * Check that TCP offset makes sense,
2012 * pull out TCP options and adjust length.
2013 */
2014 off = th->th_off << 2;
2015 if (off < sizeof(struct tcphdr) || off > tlen) {
2016 tcpstat.tcps_rcvbadoff++;
2017 IF_TCP_STATINC(ifp, badformat);
2018 TCP_LOG_DROP_PKT(TCP_LOG_HDR, th, ifp, "bad tcp offset");
2019 goto dropnosock;
2020 }
2021 tlen -= off; /* tlen is used instead of ti->ti_len */
2022 if (off > sizeof(struct tcphdr)) {
2023 if (isipv6) {
2024 IP6_EXTHDR_CHECK(m, off0, off, return );
2025 ip6 = mtod(m, struct ip6_hdr *);
2026 th = (struct tcphdr *)(void *)((caddr_t)ip6 + off0);
2027 } else {
2028 if (m->m_len < sizeof(struct ip) + off) {
2029 if ((m = m_pullup(m, sizeof(struct ip) + off)) == 0) {
2030 tcpstat.tcps_rcvshort++;
2031 return;
2032 }
2033 ip = mtod(m, struct ip *);
2034 th = (struct tcphdr *)(void *)((caddr_t)ip + off0);
2035 }
2036 }
2037 optlen = off - sizeof(struct tcphdr);
2038 optp = (u_char *)(th + 1);
2039 /*
2040 * Do quick retrieval of timestamp options ("options
2041 * prediction?"). If timestamp is the only option and it's
2042 * formatted as recommended in RFC 1323 appendix A, we
2043 * quickly get the values now and not bother calling
2044 * tcp_dooptions(), etc.
2045 */
2046 if ((optlen == TCPOLEN_TSTAMP_APPA ||
2047 (optlen > TCPOLEN_TSTAMP_APPA &&
2048 optp[TCPOLEN_TSTAMP_APPA] == TCPOPT_EOL)) &&
2049 *(u_int32_t *)(void *)optp == htonl(TCPOPT_TSTAMP_HDR) &&
2050 (th->th_flags & TH_SYN) == 0) {
2051 to.to_flags |= TOF_TS;
2052 to.to_tsval = ntohl(*(u_int32_t *)(void *)(optp + 4));
2053 to.to_tsecr = ntohl(*(u_int32_t *)(void *)(optp + 8));
2054 optp = NULL; /* we've parsed the options */
2055 }
2056 }
2057 thflags = th->th_flags;
2058
2059 /*
2060 * Drop all packets with both the SYN and FIN bits set.
2061 * This prevents e.g. nmap from identifying the TCP/IP stack.
2062 *
2063 * This is a violation of the TCP specification.
2064 */
2065 if ((thflags & (TH_SYN | TH_FIN)) == (TH_SYN | TH_FIN)) {
2066 IF_TCP_STATINC(ifp, synfin);
2067 TCP_LOG_DROP_PKT(TCP_LOG_HDR, th, ifp, "drop SYN FIN");
2068 goto dropnosock;
2069 }
2070
2071 /*
2072 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options,
2073 * until after ip6_savecontrol() is called and before other functions
2074 * which don't want those proto headers.
2075 * Because ip6_savecontrol() is going to parse the mbuf to
2076 * search for data to be passed up to user-land, it wants mbuf
2077 * parameters to be unchanged.
2078 */
2079 drop_hdrlen = off0 + off;
2080
2081 /* Since this is an entry point for input processing of tcp packets, we
2082 * can update the tcp clock here.
2083 */
2084 calculate_tcp_clock();
2085
2086 /*
2087 * Record the interface where this segment arrived on; this does not
2088 * affect normal data output (for non-detached TCP) as it provides a
2089 * hint about which route and interface to use for sending in the
2090 * absence of a PCB, when scoped routing (and thus source interface
2091 * selection) are enabled.
2092 */
2093 if ((m->m_pkthdr.pkt_flags & PKTF_LOOP) || m->m_pkthdr.rcvif == NULL) {
2094 ifscope = IFSCOPE_NONE;
2095 } else {
2096 ifscope = m->m_pkthdr.rcvif->if_index;
2097 }
2098
2099 /*
2100 * Convert TCP protocol specific fields to host format.
2101 */
2102
2103 #if BYTE_ORDER != BIG_ENDIAN
2104 NTOHL(th->th_seq);
2105 NTOHL(th->th_ack);
2106 NTOHS(th->th_win);
2107 NTOHS(th->th_urp);
2108 #endif
2109
2110 /*
2111 * Locate pcb for segment.
2112 */
2113 findpcb:
2114
2115 isconnected = FALSE;
2116 isdisconnected = FALSE;
2117
2118 if (isipv6) {
2119 inp = in6_pcblookup_hash(&tcbinfo, &ip6->ip6_src, th->th_sport, ip6_input_getsrcifscope(m),
2120 &ip6->ip6_dst, th->th_dport, ip6_input_getdstifscope(m), 1,
2121 m->m_pkthdr.rcvif);
2122 } else {
2123 inp = in_pcblookup_hash(&tcbinfo, ip->ip_src, th->th_sport,
2124 ip->ip_dst, th->th_dport, 1, m->m_pkthdr.rcvif);
2125 }
2126
2127 /*
2128 * Use the interface scope information from the PCB for outbound
2129 * segments. If the PCB isn't present and if scoped routing is
2130 * enabled, tcp_respond will use the scope of the interface where
2131 * the segment arrived on.
2132 */
2133 if (inp != NULL && (inp->inp_flags & INP_BOUND_IF)) {
2134 ifscope = inp->inp_boundifp->if_index;
2135 }
2136
2137 /*
2138 * If the state is CLOSED (i.e., TCB does not exist) then
2139 * all data in the incoming segment is discarded.
2140 * If the TCB exists but is in CLOSED state, it is embryonic,
2141 * but should either do a listen or a connect soon.
2142 */
2143 if (inp == NULL) {
2144 if (log_in_vain) {
2145 char dbuf[MAX_IPv6_STR_LEN], sbuf[MAX_IPv6_STR_LEN];
2146
2147 if (isipv6) {
2148 inet_ntop(AF_INET6, &ip6->ip6_dst, dbuf, sizeof(dbuf));
2149 inet_ntop(AF_INET6, &ip6->ip6_src, sbuf, sizeof(sbuf));
2150 } else {
2151 inet_ntop(AF_INET, &ip->ip_dst, dbuf, sizeof(dbuf));
2152 inet_ntop(AF_INET, &ip->ip_src, sbuf, sizeof(sbuf));
2153 }
2154 switch (log_in_vain) {
2155 case 1:
2156 if (thflags & TH_SYN) {
2157 log(LOG_INFO,
2158 "Connection attempt to TCP %s:%d from %s:%d\n",
2159 dbuf, ntohs(th->th_dport),
2160 sbuf,
2161 ntohs(th->th_sport));
2162 }
2163 break;
2164 case 2:
2165 log(LOG_INFO,
2166 "Connection attempt to TCP %s:%d from %s:%d flags:0x%x\n",
2167 dbuf, ntohs(th->th_dport), sbuf,
2168 ntohs(th->th_sport), thflags);
2169 break;
2170 case 3:
2171 case 4:
2172 if ((thflags & TH_SYN) && !(thflags & TH_ACK) &&
2173 !(m->m_flags & (M_BCAST | M_MCAST)) &&
2174 ((isipv6 && !in6_are_addr_equal_scoped(&ip6->ip6_dst, &ip6->ip6_src, ip6_input_getdstifscope(m), ip6_input_getsrcifscope(m))) ||
2175 (!isipv6 && ip->ip_dst.s_addr != ip->ip_src.s_addr))) {
2176 log_in_vain_log((LOG_INFO,
2177 "Stealth Mode connection attempt to TCP %s:%d from %s:%d\n",
2178 dbuf, ntohs(th->th_dport),
2179 sbuf,
2180 ntohs(th->th_sport)));
2181 }
2182 break;
2183 default:
2184 break;
2185 }
2186 }
2187 if (blackhole) {
2188 if (m->m_pkthdr.rcvif && m->m_pkthdr.rcvif->if_type != IFT_LOOP) {
2189 switch (blackhole) {
2190 case 1:
2191 if (thflags & TH_SYN) {
2192 TCP_LOG_DROP_PKT(TCP_LOG_HDR, th, ifp, "blackhole 1 syn for closed port");
2193 goto dropnosock;
2194 }
2195 break;
2196 case 2:
2197 TCP_LOG_DROP_PKT(TCP_LOG_HDR, th, ifp, "blackhole 2 closed port");
2198 goto dropnosock;
2199 default:
2200 TCP_LOG_DROP_PKT(TCP_LOG_HDR, th, ifp, "blackhole closed port");
2201 goto dropnosock;
2202 }
2203 }
2204 }
2205 IF_TCP_STATINC(ifp, noconnnolist);
2206 TCP_LOG_DROP_PKT(TCP_LOG_HDR, th, ifp, "closed port");
2207 goto dropwithresetnosock;
2208 }
2209 so = inp->inp_socket;
2210 if (so == NULL) {
2211 /* This case shouldn't happen as the socket shouldn't be null
2212 * if inp_state isn't set to INPCB_STATE_DEAD
2213 * But just in case, we pretend we didn't find the socket if we hit this case
2214 * as this isn't cause for a panic (the socket might be leaked however)...
2215 */
2216 inp = NULL;
2217 #if TEMPDEBUG
2218 printf("tcp_input: no more socket for inp=%x. This shouldn't happen\n", inp);
2219 #endif
2220 TCP_LOG_DROP_PKT(TCP_LOG_HDR, th, ifp, "inp_socket NULL");
2221 goto dropnosock;
2222 }
2223
2224 socket_lock(so, 1);
2225 if (in_pcb_checkstate(inp, WNT_RELEASE, 1) == WNT_STOPUSING) {
2226 socket_unlock(so, 1);
2227 inp = NULL; // pretend we didn't find it
2228 TCP_LOG_DROP_PKT(TCP_LOG_HDR, th, ifp, "inp state WNT_STOPUSING");
2229 goto dropnosock;
2230 }
2231
2232 if (!isipv6 && inp->inp_faddr.s_addr != INADDR_ANY) {
2233 if (inp->inp_faddr.s_addr != ip->ip_src.s_addr ||
2234 inp->inp_laddr.s_addr != ip->ip_dst.s_addr ||
2235 inp->inp_fport != th->th_sport ||
2236 inp->inp_lport != th->th_dport) {
2237 os_log_error(OS_LOG_DEFAULT, "%s 5-tuple does not match: %u:%u %u:%u\n",
2238 __func__,
2239 ntohs(inp->inp_fport), ntohs(th->th_sport),
2240 ntohs(inp->inp_lport), ntohs(th->th_dport));
2241 if (findpcb_iterated) {
2242 goto drop;
2243 }
2244 findpcb_iterated = true;
2245 socket_unlock(so, 1);
2246 inp = NULL;
2247 goto findpcb;
2248 }
2249 } else if (isipv6 && !IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
2250 if (!in6_are_addr_equal_scoped(&inp->in6p_faddr, &ip6->ip6_src, inp->inp_fifscope, ip6_input_getsrcifscope(m)) ||
2251 !in6_are_addr_equal_scoped(&inp->in6p_laddr, &ip6->ip6_dst, inp->inp_lifscope, ip6_input_getdstifscope(m)) ||
2252 inp->inp_fport != th->th_sport ||
2253 inp->inp_lport != th->th_dport) {
2254 os_log_error(OS_LOG_DEFAULT, "%s 5-tuple does not match: %u:%u %u:%u\n",
2255 __func__,
2256 ntohs(inp->inp_fport), ntohs(th->th_sport),
2257 ntohs(inp->inp_lport), ntohs(th->th_dport));
2258 if (findpcb_iterated) {
2259 goto drop;
2260 }
2261 findpcb_iterated = true;
2262 socket_unlock(so, 1);
2263 inp = NULL;
2264 goto findpcb;
2265 }
2266 }
2267
2268 tp = intotcpcb(inp);
2269 if (tp == NULL) {
2270 IF_TCP_STATINC(ifp, noconnlist);
2271 TCP_LOG_DROP_PKT(TCP_LOG_HDR, th, ifp, "tp is NULL");
2272 goto dropwithreset;
2273 }
2274
2275 /* Now that we found the tcpcb, we can adjust the TCP timestamp */
2276 if (to.to_flags & TOF_TS) {
2277 to.to_tsecr -= tp->t_ts_offset;
2278 }
2279
2280 TCP_LOG_TH_FLAGS(TCP_LOG_HDR, th, tp, false, ifp);
2281
2282 if (tp->t_state == TCPS_CLOSED) {
2283 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "tp state TCPS_CLOSED");
2284 goto drop;
2285 }
2286
2287 #if NECP
2288 if (so->so_state & SS_ISCONNECTED) {
2289 // Connected TCP sockets have a fully-bound local and remote,
2290 // so the policy check doesn't need to override addresses
2291 if (!necp_socket_is_allowed_to_send_recv(inp, ifp, pf_tag, NULL, NULL, NULL, NULL)) {
2292 TCP_LOG_DROP_NECP(TCP_LOG_HDR, th, intotcpcb(inp), false);
2293 IF_TCP_STATINC(ifp, badformat);
2294 goto drop;
2295 }
2296 } else {
2297 /*
2298 * If the proc_uuid_policy table has been updated since the last use
2299 * of the listening socket (i.e., the proc_uuid_policy_table_gencount
2300 * has been updated), the flags in the socket may be out of date.
2301 * If INP2_WANT_APP_POLICY is stale, inbound packets may
2302 * be dropped by NECP if the socket should now match a per-app
2303 * exception policy.
2304 * In order to avoid this refresh the proc_uuid_policy state to
2305 * potentially recalculate the socket's flags before checking
2306 * with NECP.
2307 */
2308 (void) inp_update_policy(inp);
2309
2310 if (isipv6) {
2311 if (!necp_socket_is_allowed_to_send_recv_v6(inp,
2312 th->th_dport, th->th_sport, &ip6->ip6_dst,
2313 &ip6->ip6_src, ifp, pf_tag, NULL, NULL, NULL, NULL)) {
2314 TCP_LOG_DROP_NECP(TCP_LOG_HDR, th, intotcpcb(inp), false);
2315 IF_TCP_STATINC(ifp, badformat);
2316 goto drop;
2317 }
2318 } else {
2319 if (!necp_socket_is_allowed_to_send_recv_v4(inp,
2320 th->th_dport, th->th_sport, &ip->ip_dst, &ip->ip_src,
2321 ifp, pf_tag, NULL, NULL, NULL, NULL)) {
2322 TCP_LOG_DROP_NECP(TCP_LOG_HDR, th, intotcpcb(inp), false);
2323 IF_TCP_STATINC(ifp, badformat);
2324 goto drop;
2325 }
2326 }
2327 }
2328 #endif /* NECP */
2329
2330 prev_t_state = tp->t_state;
2331
2332 /* If none of the FIN|SYN|RST|ACK flag is set, drop */
2333 if ((thflags & TH_ACCEPT) == 0) {
2334 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "rfc5961 TH_ACCEPT == 0");
2335 goto drop;
2336 }
2337
2338 /* Unscale the window into a 32-bit value. */
2339 if ((thflags & TH_SYN) == 0) {
2340 tiwin = th->th_win << tp->snd_scale;
2341 } else {
2342 tiwin = th->th_win;
2343 }
2344
2345 /* Avoid processing packets while closing a listen socket */
2346 if (tp->t_state == TCPS_LISTEN &&
2347 (so->so_options & SO_ACCEPTCONN) == 0) {
2348 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "closing a listening socket");
2349 goto drop;
2350 }
2351
2352 if (so->so_options & (SO_DEBUG | SO_ACCEPTCONN)) {
2353 #if TCPDEBUG
2354 if (so->so_options & SO_DEBUG) {
2355 ostate = tp->t_state;
2356 if (isipv6) {
2357 bcopy((char *)ip6, (char *)tcp_saveipgen,
2358 sizeof(*ip6));
2359 } else {
2360 bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
2361 }
2362 tcp_savetcp = *th;
2363 }
2364 #endif
2365 if (so->so_options & SO_ACCEPTCONN) {
2366 struct tcpcb *tp0 = tp;
2367 struct socket *so2;
2368 struct socket *oso;
2369 struct sockaddr_storage from;
2370 struct sockaddr_storage to2;
2371 struct inpcb *oinp = sotoinpcb(so);
2372 struct ifnet *head_ifscope;
2373 unsigned int head_nocell, head_recvanyif,
2374 head_noexpensive, head_awdl_unrestricted,
2375 head_intcoproc_allowed, head_external_port,
2376 head_noconstrained;
2377
2378 /* Get listener's bound-to-interface, if any */
2379 head_ifscope = (inp->inp_flags & INP_BOUND_IF) ?
2380 inp->inp_boundifp : NULL;
2381 /* Get listener's no-cellular information, if any */
2382 head_nocell = INP_NO_CELLULAR(inp);
2383 /* Get listener's recv-any-interface, if any */
2384 head_recvanyif = (inp->inp_flags & INP_RECV_ANYIF);
2385 /* Get listener's no-expensive information, if any */
2386 head_noexpensive = INP_NO_EXPENSIVE(inp);
2387 head_noconstrained = INP_NO_CONSTRAINED(inp);
2388 head_awdl_unrestricted = INP_AWDL_UNRESTRICTED(inp);
2389 head_intcoproc_allowed = INP_INTCOPROC_ALLOWED(inp);
2390 head_external_port = (inp->inp_flags2 & INP2_EXTERNAL_PORT);
2391
2392 /*
2393 * If the state is LISTEN then ignore segment if it contains an RST.
2394 * If the segment contains an ACK then it is bad and send a RST.
2395 * If it does not contain a SYN then it is not interesting; drop it.
2396 * If it is from this socket, drop it, it must be forged.
2397 */
2398 if ((thflags & (TH_RST | TH_ACK | TH_SYN)) != TH_SYN) {
2399 IF_TCP_STATINC(ifp, listbadsyn);
2400
2401 if (thflags & TH_RST) {
2402 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false,
2403 thflags & TH_SYN ? "ignore SYN with RST" : "ignore RST");
2404 goto drop;
2405 }
2406 if (thflags & TH_ACK) {
2407 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false,
2408 thflags & TH_SYN ? "bad SYN with ACK" : "bad ACK");
2409 tp = NULL;
2410 tcpstat.tcps_badsyn++;
2411 goto dropwithreset;
2412 }
2413
2414 /* We come here if there is no SYN set */
2415 tcpstat.tcps_badsyn++;
2416 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "bad SYN");
2417 goto drop;
2418 }
2419 KERNEL_DEBUG(DBG_FNC_TCP_NEWCONN | DBG_FUNC_START, 0, 0, 0, 0, 0);
2420 if (th->th_dport == th->th_sport) {
2421 if (isipv6) {
2422 if (in6_are_addr_equal_scoped(&ip6->ip6_dst, &ip6->ip6_src, ip6_input_getdstifscope(m), ip6_input_getsrcifscope(m))) {
2423 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "bad tuple same port");
2424 goto drop;
2425 }
2426 } else if (ip->ip_dst.s_addr == ip->ip_src.s_addr) {
2427 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "bad tuple same IPv4 address");
2428 goto drop;
2429 }
2430 }
2431 /*
2432 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
2433 * in_broadcast() should never return true on a received
2434 * packet with M_BCAST not set.
2435 *
2436 * Packets with a multicast source address should also
2437 * be discarded.
2438 */
2439 if (m->m_flags & (M_BCAST | M_MCAST)) {
2440 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "mbuf M_BCAST | M_MCAST");
2441 goto drop;
2442 }
2443 if (isipv6) {
2444 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2445 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
2446 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "IN6_IS_ADDR_MULTICAST");
2447 goto drop;
2448 }
2449 } else if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2450 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2451 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2452 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
2453 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "multicast or broadcast address");
2454 goto drop;
2455 }
2456
2457
2458 /*
2459 * If deprecated address is forbidden,
2460 * we do not accept SYN to deprecated interface
2461 * address to prevent any new inbound connection from
2462 * getting established.
2463 * When we do not accept SYN, we send a TCP RST,
2464 * with deprecated source address (instead of dropping
2465 * it). We compromise it as it is much better for peer
2466 * to send a RST, and RST will be the final packet
2467 * for the exchange.
2468 *
2469 * If we do not forbid deprecated addresses, we accept
2470 * the SYN packet. RFC 4862 forbids dropping SYN in
2471 * this case.
2472 */
2473 if (isipv6 && !ip6_use_deprecated) {
2474 uint32_t ia6_flags;
2475
2476 if (ip6_getdstifaddr_info(m, NULL,
2477 &ia6_flags) == 0) {
2478 if (ia6_flags & IN6_IFF_DEPRECATED) {
2479 tp = NULL;
2480 IF_TCP_STATINC(ifp, deprecate6);
2481 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "deprecated IPv6 address");
2482 goto dropwithreset;
2483 }
2484 }
2485 }
2486 if (so->so_filt || check_cfil) {
2487 if (isipv6) {
2488 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&from;
2489
2490 sin6->sin6_len = sizeof(*sin6);
2491 sin6->sin6_family = AF_INET6;
2492 sin6->sin6_port = th->th_sport;
2493 sin6->sin6_flowinfo = 0;
2494 sin6->sin6_addr = ip6->ip6_src;
2495 sin6->sin6_scope_id = 0;
2496
2497 sin6 = (struct sockaddr_in6*)&to2;
2498
2499 sin6->sin6_len = sizeof(struct sockaddr_in6);
2500 sin6->sin6_family = AF_INET6;
2501 sin6->sin6_port = th->th_dport;
2502 sin6->sin6_flowinfo = 0;
2503 sin6->sin6_addr = ip6->ip6_dst;
2504 sin6->sin6_scope_id = 0;
2505 } else {
2506 struct sockaddr_in *sin = (struct sockaddr_in*)&from;
2507
2508 sin->sin_len = sizeof(*sin);
2509 sin->sin_family = AF_INET;
2510 sin->sin_port = th->th_sport;
2511 sin->sin_addr = ip->ip_src;
2512
2513 sin = (struct sockaddr_in*)&to2;
2514
2515 sin->sin_len = sizeof(struct sockaddr_in);
2516 sin->sin_family = AF_INET;
2517 sin->sin_port = th->th_dport;
2518 sin->sin_addr = ip->ip_dst;
2519 }
2520 }
2521
2522 if (so->so_filt) {
2523 so2 = sonewconn(so, 0, (struct sockaddr*)&from);
2524 } else {
2525 so2 = sonewconn(so, 0, NULL);
2526 }
2527 if (so2 == 0) {
2528 tcpstat.tcps_listendrop++;
2529 if (tcp_dropdropablreq(so)) {
2530 if (so->so_filt) {
2531 so2 = sonewconn(so, 0, (struct sockaddr*)&from);
2532 } else {
2533 so2 = sonewconn(so, 0, NULL);
2534 }
2535 }
2536 if (!so2) {
2537 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, " listen drop");
2538 goto drop;
2539 }
2540 }
2541
2542 /* Point "inp" and "tp" in tandem to new socket */
2543 inp = (struct inpcb *)so2->so_pcb;
2544 tp = intotcpcb(inp);
2545
2546 oso = so;
2547 socket_unlock(so, 0); /* Unlock but keep a reference on listener for now */
2548
2549 so = so2;
2550 socket_lock(so, 1);
2551 /*
2552 * Mark socket as temporary until we're
2553 * committed to keeping it. The code at
2554 * ``drop'' and ``dropwithreset'' check the
2555 * flag dropsocket to see if the temporary
2556 * socket created here should be discarded.
2557 * We mark the socket as discardable until
2558 * we're committed to it below in TCPS_LISTEN.
2559 * There are some error conditions in which we
2560 * have to drop the temporary socket.
2561 */
2562 dropsocket++;
2563 /*
2564 * Inherit INP_BOUND_IF from listener; testing if
2565 * head_ifscope is non-NULL is sufficient, since it
2566 * can only be set to a non-zero value earlier if
2567 * the listener has such a flag set.
2568 */
2569 if (head_ifscope != NULL) {
2570 inp->inp_flags |= INP_BOUND_IF;
2571 inp->inp_boundifp = head_ifscope;
2572 } else {
2573 inp->inp_flags &= ~INP_BOUND_IF;
2574 }
2575 /*
2576 * Inherit restrictions from listener.
2577 */
2578 if (head_nocell) {
2579 inp_set_nocellular(inp);
2580 }
2581 if (head_noexpensive) {
2582 inp_set_noexpensive(inp);
2583 }
2584 if (head_noconstrained) {
2585 inp_set_noconstrained(inp);
2586 }
2587 if (head_awdl_unrestricted) {
2588 inp_set_awdl_unrestricted(inp);
2589 }
2590 if (head_intcoproc_allowed) {
2591 inp_set_intcoproc_allowed(inp);
2592 }
2593 /*
2594 * Inherit {IN,IN6}_RECV_ANYIF from listener.
2595 */
2596 if (head_recvanyif) {
2597 inp->inp_flags |= INP_RECV_ANYIF;
2598 } else {
2599 inp->inp_flags &= ~INP_RECV_ANYIF;
2600 }
2601
2602 if (head_external_port) {
2603 inp->inp_flags2 |= INP2_EXTERNAL_PORT;
2604 }
2605 if (isipv6) {
2606 inp->in6p_laddr = ip6->ip6_dst;
2607 inp->inp_lifscope = in6_addr2scopeid(ifp, &inp->in6p_laddr);
2608 in6_verify_ifscope(&ip6->ip6_dst, inp->inp_lifscope);
2609 } else {
2610 inp->inp_vflag &= ~INP_IPV6;
2611 inp->inp_vflag |= INP_IPV4;
2612 inp->inp_laddr = ip->ip_dst;
2613 }
2614 inp->inp_lport = th->th_dport;
2615 if (in_pcbinshash(inp, 0) != 0) {
2616 /*
2617 * Undo the assignments above if we failed to
2618 * put the PCB on the hash lists.
2619 */
2620 if (isipv6) {
2621 inp->in6p_laddr = in6addr_any;
2622 inp->inp_lifscope = IFSCOPE_NONE;
2623 } else {
2624 inp->inp_laddr.s_addr = INADDR_ANY;
2625 }
2626 #if SKYWALK
2627 netns_release(&inp->inp_netns_token);
2628 #endif /* SKYWALK */
2629 inp->inp_lport = 0;
2630 socket_lock(oso, 0); /* release ref on parent */
2631 socket_unlock(oso, 1);
2632 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, " in_pcbinshash failed");
2633 goto drop;
2634 }
2635 socket_lock(oso, 0);
2636 if (isipv6) {
2637 /*
2638 * Inherit socket options from the listening
2639 * socket.
2640 * Note that in6p_inputopts are not (even
2641 * should not be) copied, since it stores
2642 * previously received options and is used to
2643 * detect if each new option is different than
2644 * the previous one and hence should be passed
2645 * to a user.
2646 * If we copied in6p_inputopts, a user would
2647 * not be able to receive options just after
2648 * calling the accept system call.
2649 */
2650 inp->inp_flags |=
2651 oinp->inp_flags & INP_CONTROLOPTS;
2652 if (oinp->in6p_outputopts) {
2653 inp->in6p_outputopts =
2654 ip6_copypktopts(oinp->in6p_outputopts,
2655 Z_NOWAIT);
2656 }
2657 } else {
2658 inp->inp_options = ip_srcroute();
2659 inp->inp_ip_tos = oinp->inp_ip_tos;
2660 }
2661 #if IPSEC
2662 /* copy old policy into new socket's */
2663 if (sotoinpcb(oso)->inp_sp) {
2664 int error = 0;
2665 /* Is it a security hole here to silently fail to copy the policy? */
2666 if (inp->inp_sp == NULL) {
2667 error = ipsec_init_policy(so, &inp->inp_sp);
2668 }
2669 if (error != 0 || ipsec_copy_policy(sotoinpcb(oso)->inp_sp, inp->inp_sp)) {
2670 printf("tcp_input: could not copy policy\n");
2671 }
2672 }
2673 #endif
2674 /* inherit states from the listener */
2675 DTRACE_TCP4(state__change, void, NULL, struct inpcb *, inp,
2676 struct tcpcb *, tp, int32_t, TCPS_LISTEN);
2677 tp->t_state = TCPS_LISTEN;
2678 tp->t_flags |= tp0->t_flags & (TF_NOPUSH | TF_NOOPT | TF_NODELAY);
2679 tp->t_flagsext |= (tp0->t_flagsext & (TF_RXTFINDROP | TF_NOTIMEWAIT | TF_FASTOPEN));
2680 tp->t_keepinit = tp0->t_keepinit;
2681 tp->t_keepcnt = tp0->t_keepcnt;
2682 tp->t_keepintvl = tp0->t_keepintvl;
2683 tp->t_adaptive_wtimo = tp0->t_adaptive_wtimo;
2684 tp->t_adaptive_rtimo = tp0->t_adaptive_rtimo;
2685 tp->t_inpcb->inp_ip_ttl = tp0->t_inpcb->inp_ip_ttl;
2686 if ((so->so_flags & SOF_NOTSENT_LOWAT) != 0) {
2687 tp->t_notsent_lowat = tp0->t_notsent_lowat;
2688 }
2689 tp->t_inpcb->inp_flags2 |=
2690 tp0->t_inpcb->inp_flags2 & INP2_KEEPALIVE_OFFLOAD;
2691
2692 /* now drop the reference on the listener */
2693 socket_unlock(oso, 1);
2694
2695 tcp_set_max_rwinscale(tp, so);
2696
2697 #if CONTENT_FILTER
2698 if (check_cfil) {
2699 int error = cfil_sock_attach(so2, (struct sockaddr*)&to2, (struct sockaddr*)&from,
2700 CFS_CONNECTION_DIR_IN);
2701 if (error != 0) {
2702 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, " cfil_sock_attach failed");
2703 goto drop;
2704 }
2705 }
2706 #endif /* CONTENT_FILTER */
2707
2708 KERNEL_DEBUG(DBG_FNC_TCP_NEWCONN | DBG_FUNC_END, 0, 0, 0, 0, 0);
2709 }
2710 }
2711 socket_lock_assert_owned(so);
2712
2713 if (net_mpklog_enabled && (m->m_pkthdr.rcvif->if_xflags & IFXF_MPK_LOG)) {
2714 MPKL_TCP_INPUT(tcp_mpkl_log_object,
2715 ntohs(tp->t_inpcb->inp_lport), ntohs(tp->t_inpcb->inp_fport),
2716 th->th_seq, th->th_ack, tlen, thflags,
2717 so->last_pid, so->so_log_seqn++);
2718 }
2719
2720 if (tp->t_state == TCPS_ESTABLISHED && tlen > 0) {
2721 /*
2722 * Evaluate the rate of arrival of packets to see if the
2723 * receiver can reduce the ack traffic. The algorithm to
2724 * stretch acks will be enabled if the connection meets
2725 * certain criteria defined in tcp_stretch_ack_enable function.
2726 */
2727 if ((tp->t_flagsext & TF_RCVUNACK_WAITSS) != 0) {
2728 TCP_INC_VAR(tp->rcv_waitforss, segment_count);
2729 }
2730 if (tcp_stretch_ack_enable(tp, thflags)) {
2731 tp->t_flags |= TF_STRETCHACK;
2732 tp->t_flagsext &= ~(TF_RCVUNACK_WAITSS);
2733 tp->rcv_waitforss = 0;
2734 } else {
2735 tp->t_flags &= ~(TF_STRETCHACK);
2736 }
2737 if (TSTMP_GT(tp->rcv_unackwin - (tcp_rcvunackwin >> 1), tcp_now)) {
2738 tp->rcv_by_unackhalfwin += (tlen + off);
2739 tp->rcv_by_unackwin += (tlen + off);
2740 } else {
2741 tp->rcv_unackwin = tcp_now + tcp_rcvunackwin;
2742 tp->rcv_by_unackwin = tp->rcv_by_unackhalfwin + tlen + off;
2743 tp->rcv_by_unackhalfwin = tlen + off;
2744 }
2745 }
2746
2747 /*
2748 * Clear TE_SENDECE if TH_CWR is set. This is harmless, so we don't
2749 * bother doing extensive checks for state and whatnot.
2750 */
2751 if (thflags & TH_CWR) {
2752 tp->ecn_flags &= ~TE_SENDECE;
2753 tp->t_ecn_recv_cwr++;
2754 }
2755
2756 /*
2757 * Explicit Congestion Notification - Flag that we need to send ECT if
2758 * + The IP Congestion experienced flag was set.
2759 * + Socket is in established state
2760 * + We negotiated ECN in the TCP setup
2761 * + This isn't a pure ack (tlen > 0)
2762 * + The data is in the valid window
2763 *
2764 * TE_SENDECE will be cleared when we receive a packet with TH_CWR set.
2765 */
2766 if (ip_ecn == IPTOS_ECN_CE && tp->t_state == TCPS_ESTABLISHED &&
2767 TCP_ECN_ENABLED(tp) && tlen > 0 &&
2768 SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
2769 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
2770 tp->t_ecn_recv_ce++;
2771 tcpstat.tcps_ecn_recv_ce++;
2772 INP_INC_IFNET_STAT(inp, ecn_recv_ce);
2773 /* Mark this connection as it received CE from network */
2774 tp->ecn_flags |= TE_RECV_ECN_CE;
2775 tp->ecn_flags |= TE_SENDECE;
2776 }
2777
2778 /*
2779 * If we received an explicit notification of congestion in
2780 * ip tos ecn bits or by the CWR bit in TCP header flags, reset
2781 * the ack-stretching state. We need to handle ECN notification if
2782 * an ECN setup SYN was sent even once.
2783 */
2784 if (tp->t_state == TCPS_ESTABLISHED &&
2785 (tp->ecn_flags & TE_SETUPSENT) &&
2786 (ip_ecn == IPTOS_ECN_CE || (thflags & TH_CWR))) {
2787 tcp_reset_stretch_ack(tp);
2788 tp->t_forced_acks = TCP_FORCED_ACKS_COUNT;
2789 CLEAR_IAJ_STATE(tp);
2790 }
2791
2792 if (ip_ecn == IPTOS_ECN_CE && tp->t_state == TCPS_ESTABLISHED &&
2793 !TCP_ECN_ENABLED(tp) && !(tp->ecn_flags & TE_CEHEURI_SET)) {
2794 tcpstat.tcps_ecn_fallback_ce++;
2795 tcp_heuristic_ecn_aggressive(tp);
2796 tp->ecn_flags |= TE_CEHEURI_SET;
2797 }
2798
2799 if (tp->t_state == TCPS_ESTABLISHED && TCP_ECN_ENABLED(tp) &&
2800 ip_ecn == IPTOS_ECN_CE && !(tp->ecn_flags & TE_CEHEURI_SET)) {
2801 if (inp->inp_stat->rxpackets < ECN_MIN_CE_PROBES) {
2802 tp->t_ecn_recv_ce_pkt++;
2803 } else if (tp->t_ecn_recv_ce_pkt > ECN_MAX_CE_RATIO) {
2804 tcpstat.tcps_ecn_fallback_ce++;
2805 tcp_heuristic_ecn_aggressive(tp);
2806 tp->ecn_flags |= TE_CEHEURI_SET;
2807 INP_INC_IFNET_STAT(inp, ecn_fallback_ce);
2808 } else {
2809 /* We tracked the first ECN_MIN_CE_PROBES segments, we
2810 * now know that the path is good.
2811 */
2812 tp->ecn_flags |= TE_CEHEURI_SET;
2813 }
2814 }
2815
2816 /* Update rcvtime as a new segment was received on the connection */
2817 tp->t_rcvtime = tcp_now;
2818
2819 /*
2820 * Segment received on connection.
2821 * Reset idle time and keep-alive timer.
2822 */
2823 if (TCPS_HAVEESTABLISHED(tp->t_state)) {
2824 tcp_keepalive_reset(tp);
2825
2826 if (tp->t_mpsub) {
2827 mptcp_reset_keepalive(tp);
2828 }
2829 }
2830
2831 /*
2832 * Process options if not in LISTEN state,
2833 * else do it below (after getting remote address).
2834 */
2835 if (tp->t_state != TCPS_LISTEN && optp) {
2836 tcp_dooptions(tp, optp, optlen, th, &to);
2837 }
2838 #if MPTCP
2839 if (tp->t_state != TCPS_LISTEN && (so->so_flags & SOF_MP_SUBFLOW) &&
2840 mptcp_input_preproc(tp, m, th, drop_hdrlen) != 0) {
2841 tp->t_flags |= TF_ACKNOW;
2842 (void) tcp_output(tp);
2843 tcp_check_timer_state(tp);
2844 socket_unlock(so, 1);
2845 return;
2846 }
2847 #endif /* MPTCP */
2848 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
2849 if (!(thflags & TH_ACK) ||
2850 (SEQ_GT(th->th_ack, tp->iss) &&
2851 SEQ_LEQ(th->th_ack, tp->snd_max))) {
2852 tcp_finalize_options(tp, &to, ifscope);
2853 }
2854 }
2855
2856 #if TRAFFIC_MGT
2857 /*
2858 * Compute inter-packet arrival jitter. According to RFC 3550,
2859 * inter-packet arrival jitter is defined as the difference in
2860 * packet spacing at the receiver compared to the sender for a
2861 * pair of packets. When two packets of maximum segment size come
2862 * one after the other with consecutive sequence numbers, we
2863 * consider them as packets sent together at the sender and use
2864 * them as a pair to compute inter-packet arrival jitter. This
2865 * metric indicates the delay induced by the network components due
2866 * to queuing in edge/access routers.
2867 */
2868 if (tp->t_state == TCPS_ESTABLISHED &&
2869 (thflags & (TH_SYN | TH_FIN | TH_RST | TH_URG | TH_ACK | TH_ECE | TH_PUSH)) == TH_ACK &&
2870 ((tp->t_flags & TF_NEEDFIN) == 0) &&
2871 ((to.to_flags & TOF_TS) == 0 ||
2872 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
2873 th->th_seq == tp->rcv_nxt && LIST_EMPTY(&tp->t_segq)) {
2874 int seg_size = tlen;
2875 if (tp->iaj_pktcnt <= IAJ_IGNORE_PKTCNT) {
2876 TCP_INC_VAR(tp->iaj_pktcnt, segment_count);
2877 }
2878
2879 if (tp->iaj_size == 0 || seg_size > tp->iaj_size ||
2880 (seg_size == tp->iaj_size && tp->iaj_rcv_ts == 0)) {
2881 /*
2882 * State related to inter-arrival jitter is
2883 * uninitialized or we are trying to find a good
2884 * first packet to start computing the metric
2885 */
2886 update_iaj_state(tp, seg_size, 0);
2887 } else {
2888 if (seg_size == tp->iaj_size) {
2889 /*
2890 * Compute inter-arrival jitter taking
2891 * this packet as the second packet
2892 */
2893 compute_iaj(tp);
2894 }
2895 if (seg_size < tp->iaj_size) {
2896 /*
2897 * There is a smaller packet in the stream.
2898 * Some times the maximum size supported
2899 * on a path can change if there is a new
2900 * link with smaller MTU. The receiver will
2901 * not know about this change. If there
2902 * are too many packets smaller than
2903 * iaj_size, we try to learn the iaj_size
2904 * again.
2905 */
2906 TCP_INC_VAR(tp->iaj_small_pkt, segment_count);
2907 if (tp->iaj_small_pkt > RESET_IAJ_SIZE_THRESH) {
2908 update_iaj_state(tp, seg_size, 1);
2909 } else {
2910 CLEAR_IAJ_STATE(tp);
2911 }
2912 } else {
2913 update_iaj_state(tp, seg_size, 0);
2914 }
2915 }
2916 } else {
2917 CLEAR_IAJ_STATE(tp);
2918 }
2919 #endif /* TRAFFIC_MGT */
2920
2921 /*
2922 * Header prediction: check for the two common cases
2923 * of a uni-directional data xfer. If the packet has
2924 * no control flags, is in-sequence, the window didn't
2925 * change and we're not retransmitting, it's a
2926 * candidate. If the length is zero and the ack moved
2927 * forward, we're the sender side of the xfer. Just
2928 * free the data acked & wake any higher level process
2929 * that was blocked waiting for space. If the length
2930 * is non-zero and the ack didn't move, we're the
2931 * receiver side. If we're getting packets in-order
2932 * (the reassembly queue is empty), add the data to
2933 * the socket buffer and note that we need a delayed ack.
2934 * Make sure that the hidden state-flags are also off.
2935 * Since we check for TCPS_ESTABLISHED above, it can only
2936 * be TH_NEEDSYN.
2937 */
2938 if (tp->t_state == TCPS_ESTABLISHED &&
2939 !(so->so_state & SS_CANTRCVMORE) &&
2940 (thflags & TH_FLAGS) == TH_ACK &&
2941 ((tp->t_flags & TF_NEEDFIN) == 0) &&
2942 ((to.to_flags & TOF_TS) == 0 ||
2943 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
2944 th->th_seq == tp->rcv_nxt &&
2945 tiwin && tiwin == tp->snd_wnd &&
2946 tp->snd_nxt == tp->snd_max) {
2947 /*
2948 * If last ACK falls within this segment's sequence numbers,
2949 * record the timestamp.
2950 * NOTE that the test is modified according to the latest
2951 * proposal of the [email protected] list (Braden 1993/04/26).
2952 */
2953 if ((to.to_flags & TOF_TS) != 0 &&
2954 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
2955 tp->ts_recent_age = tcp_now;
2956 tp->ts_recent = to.to_tsval;
2957 }
2958
2959 if (tlen == 0) {
2960 if (SEQ_GT(th->th_ack, tp->snd_una) &&
2961 SEQ_LEQ(th->th_ack, tp->snd_max) &&
2962 tp->snd_cwnd >= tp->snd_ssthresh &&
2963 (!IN_FASTRECOVERY(tp) &&
2964 ((!(SACK_ENABLED(tp)) &&
2965 tp->t_dupacks < tp->t_rexmtthresh) ||
2966 (SACK_ENABLED(tp) && to.to_nsacks == 0 &&
2967 TAILQ_EMPTY(&tp->snd_holes))))) {
2968 /*
2969 * this is a pure ack for outstanding data.
2970 */
2971 ++tcpstat.tcps_predack;
2972
2973 tcp_bad_rexmt_check(tp, th, &to);
2974
2975 /* Recalculate the RTT */
2976 tcp_compute_rtt(tp, &to, th);
2977
2978 VERIFY(SEQ_GEQ(th->th_ack, tp->snd_una));
2979 acked = BYTES_ACKED(th, tp);
2980 tcpstat.tcps_rcvackpack++;
2981 tcpstat.tcps_rcvackbyte += acked;
2982
2983 /*
2984 * Handle an ack that is in sequence during
2985 * congestion avoidance phase. The
2986 * calculations in this function
2987 * assume that snd_una is not updated yet.
2988 */
2989 if (CC_ALGO(tp)->congestion_avd != NULL) {
2990 CC_ALGO(tp)->congestion_avd(tp, th);
2991 }
2992 tcp_ccdbg_trace(tp, th, TCP_CC_INSEQ_ACK_RCVD);
2993 sbdrop(&so->so_snd, acked);
2994 tcp_sbsnd_trim(&so->so_snd);
2995
2996 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
2997 SEQ_LEQ(th->th_ack, tp->snd_recover)) {
2998 tp->snd_recover = th->th_ack - 1;
2999 }
3000
3001 tcp_update_snd_una(tp, th->th_ack);
3002
3003 TCP_RESET_REXMT_STATE(tp);
3004
3005 /*
3006 * pull snd_wl2 up to prevent seq wrap relative
3007 * to th_ack.
3008 */
3009 tp->snd_wl2 = th->th_ack;
3010
3011 if (tp->t_dupacks > 0) {
3012 tp->t_dupacks = 0;
3013 tp->t_rexmtthresh = tcprexmtthresh;
3014 tp->t_new_dupacks = 0;
3015 }
3016
3017 tp->sackhint.sack_bytes_acked = 0;
3018
3019 /*
3020 * If all outstanding data are acked, stop
3021 * retransmit timer, otherwise restart timer
3022 * using current (possibly backed-off) value.
3023 * If process is waiting for space,
3024 * wakeup/selwakeup/signal. If data
3025 * are ready to send, let tcp_output
3026 * decide between more output or persist.
3027 */
3028 if (tp->snd_una == tp->snd_max) {
3029 tp->t_timer[TCPT_REXMT] = 0;
3030 tp->t_timer[TCPT_PTO] = 0;
3031 } else if (tp->t_timer[TCPT_PERSIST] == 0) {
3032 tp->t_timer[TCPT_REXMT] = OFFSET_FROM_START(tp, tp->t_rxtcur);
3033 }
3034 if (!SLIST_EMPTY(&tp->t_rxt_segments) &&
3035 !TCP_DSACK_SEQ_IN_WINDOW(tp,
3036 tp->t_dsack_lastuna, tp->snd_una)) {
3037 tcp_rxtseg_clean(tp);
3038 }
3039
3040 if ((tp->t_flagsext & TF_MEASURESNDBW) != 0 &&
3041 tp->t_bwmeas != NULL) {
3042 tcp_bwmeas_check(tp);
3043 }
3044
3045 write_wakeup = 1;
3046 if (!SLIST_EMPTY(&tp->t_notify_ack)) {
3047 tcp_notify_acknowledgement(tp, so);
3048 }
3049
3050 if ((so->so_snd.sb_cc) || (tp->t_flags & TF_ACKNOW)) {
3051 (void) tcp_output(tp);
3052 }
3053
3054 tcp_tfo_rcv_ack(tp, th);
3055
3056 m_freem(m);
3057
3058 tcp_check_timer_state(tp);
3059
3060 tcp_handle_wakeup(so, read_wakeup, write_wakeup);
3061
3062 socket_unlock(so, 1);
3063 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
3064 return;
3065 }
3066 } else if (th->th_ack == tp->snd_una && LIST_EMPTY(&tp->t_segq) &&
3067 tlen <= tcp_sbspace(tp)) {
3068 /*
3069 * this is a pure, in-sequence data packet
3070 * with nothing on the reassembly queue and
3071 * we have enough buffer space to take it.
3072 */
3073
3074 /* Clean receiver SACK report if present */
3075 if (SACK_ENABLED(tp) && tp->rcv_numsacks) {
3076 tcp_clean_sackreport(tp);
3077 }
3078 ++tcpstat.tcps_preddat;
3079 tp->rcv_nxt += tlen;
3080 /* Update highest received sequence and its timestamp */
3081 if (SEQ_LT(tp->rcv_high, tp->rcv_nxt)) {
3082 tp->rcv_high = tp->rcv_nxt;
3083 if (to.to_flags & TOF_TS) {
3084 tp->tsv_high = to.to_tsval;
3085 }
3086 }
3087
3088 /*
3089 * Pull snd_wl1 up to prevent seq wrap relative to
3090 * th_seq.
3091 */
3092 tp->snd_wl1 = th->th_seq;
3093 /*
3094 * Pull rcv_up up to prevent seq wrap relative to
3095 * rcv_nxt.
3096 */
3097 tp->rcv_up = tp->rcv_nxt;
3098 TCP_INC_VAR(tcpstat.tcps_rcvpack, segment_count);
3099 tcpstat.tcps_rcvbyte += tlen;
3100 if (nstat_collect) {
3101 INP_ADD_STAT(inp, cell, wifi, wired,
3102 rxpackets, 1);
3103 INP_ADD_STAT(inp, cell, wifi, wired, rxbytes,
3104 tlen);
3105 inp_set_activity_bitmap(inp);
3106 }
3107
3108 /* Calculate the RTT on the receiver */
3109 tcp_compute_rcv_rtt(tp, &to, th);
3110
3111 tcp_sbrcv_grow(tp, &so->so_rcv, &to, tlen);
3112 if (TCP_USE_RLEDBAT(tp, so) && tcp_cc_rledbat.data_rcvd != NULL) {
3113 tcp_cc_rledbat.data_rcvd(tp, th, &to, tlen);
3114 }
3115
3116 /*
3117 * Add data to socket buffer.
3118 */
3119 so_recv_data_stat(so, m, 0);
3120 m_adj(m, drop_hdrlen); /* delayed header drop */
3121
3122 if (isipv6) {
3123 memcpy(&saved_hdr, ip6, sizeof(struct ip6_hdr));
3124 ip6 = (struct ip6_hdr *)&saved_hdr[0];
3125 } else {
3126 memcpy(&saved_hdr, ip, ip->ip_hl << 2);
3127 ip = (struct ip *)&saved_hdr[0];
3128 }
3129 memcpy(&saved_tcphdr, th, sizeof(struct tcphdr));
3130
3131 if (th->th_flags & TH_PUSH) {
3132 tp->t_flagsext |= TF_LAST_IS_PSH;
3133 } else {
3134 tp->t_flagsext &= ~TF_LAST_IS_PSH;
3135 }
3136
3137 if (sbappendstream_rcvdemux(so, m)) {
3138 mptcp_handle_input(so);
3139 read_wakeup = 1;
3140 }
3141 th = &saved_tcphdr;
3142
3143 if (isipv6) {
3144 KERNEL_DEBUG(DBG_LAYER_END, ((th->th_dport << 16) | th->th_sport),
3145 (((ip6->ip6_src.s6_addr16[0]) << 16) | (ip6->ip6_dst.s6_addr16[0])),
3146 th->th_seq, th->th_ack, th->th_win);
3147 } else {
3148 KERNEL_DEBUG(DBG_LAYER_END, ((th->th_dport << 16) | th->th_sport),
3149 (((ip->ip_src.s_addr & 0xffff) << 16) | (ip->ip_dst.s_addr & 0xffff)),
3150 th->th_seq, th->th_ack, th->th_win);
3151 }
3152 TCP_INC_VAR(tp->t_unacksegs, segment_count);
3153 if (DELAY_ACK(tp, th)) {
3154 if ((tp->t_flags & TF_DELACK) == 0) {
3155 tp->t_flags |= TF_DELACK;
3156 tp->t_timer[TCPT_DELACK] = OFFSET_FROM_START(tp, tcp_delack);
3157 }
3158 } else {
3159 tp->t_flags |= TF_ACKNOW;
3160 tcp_output(tp);
3161 }
3162
3163 tcp_adaptive_rwtimo_check(tp, tlen);
3164
3165 if (tlen > 0) {
3166 tcp_tfo_rcv_data(tp);
3167 }
3168
3169 tcp_check_timer_state(tp);
3170
3171 tcp_handle_wakeup(so, read_wakeup, write_wakeup);
3172
3173 socket_unlock(so, 1);
3174 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
3175 return;
3176 }
3177 }
3178
3179 /*
3180 * Calculate amount of space in receive window,
3181 * and then do TCP input processing.
3182 * Receive window is amount of space in rcv queue,
3183 * but not less than advertised window.
3184 */
3185 socket_lock_assert_owned(so);
3186 win = tcp_sbspace(tp);
3187 if (win < 0) {
3188 win = 0;
3189 } else { /* clip rcv window to 4K for modems */
3190 if (tp->t_flags & TF_SLOWLINK && slowlink_wsize > 0) {
3191 win = min(win, slowlink_wsize);
3192 }
3193 }
3194 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
3195 #if MPTCP
3196 /*
3197 * Ensure that the subflow receive window isn't greater
3198 * than the connection level receive window.
3199 */
3200 if ((tp->t_mpflags & TMPF_MPTCP_TRUE) && (mp_tp = tptomptp(tp))) {
3201 socket_lock_assert_owned(mptetoso(mp_tp->mpt_mpte));
3202 int64_t recwin_conn = (int64_t)(mp_tp->mpt_rcvadv - mp_tp->mpt_rcvnxt);
3203
3204 VERIFY(recwin_conn < INT32_MAX && recwin_conn > INT32_MIN);
3205 if (recwin_conn > 0 && tp->rcv_wnd > (uint32_t)recwin_conn) {
3206 tp->rcv_wnd = (uint32_t)recwin_conn;
3207 tcpstat.tcps_mp_reducedwin++;
3208 }
3209 }
3210 #endif /* MPTCP */
3211
3212 switch (tp->t_state) {
3213 /*
3214 * Initialize tp->rcv_nxt, and tp->irs, select an initial
3215 * tp->iss, and send a segment:
3216 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
3217 * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
3218 * Fill in remote peer address fields if not previously specified.
3219 * Enter SYN_RECEIVED state, and process any other fields of this
3220 * segment in this state.
3221 */
3222 case TCPS_LISTEN: {
3223 struct sockaddr_in *sin;
3224 struct sockaddr_in6 *sin6;
3225
3226 socket_lock_assert_owned(so);
3227
3228 /* Clear the logging flags inherited from the listening socket */
3229 tp->t_log_flags = 0;
3230 tp->t_flagsext &= ~TF_LOGGED_CONN_SUMMARY;
3231
3232 if (isipv6) {
3233 sin6 = kalloc_type(struct sockaddr_in6, Z_NOWAIT | Z_ZERO);
3234 if (sin6 == NULL) {
3235 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "LISTEN kalloc_type failed");
3236 goto drop;
3237 }
3238 sin6->sin6_family = AF_INET6;
3239 sin6->sin6_len = sizeof(*sin6);
3240 sin6->sin6_addr = ip6->ip6_src;
3241 sin6->sin6_port = th->th_sport;
3242 if (!in6_embedded_scope && IN6_IS_SCOPE_EMBED(&ip6->ip6_src)) {
3243 sin6->sin6_scope_id = ip6_input_getsrcifscope(m);
3244 }
3245 laddr6 = inp->in6p_laddr;
3246 uint32_t lifscope = inp->inp_lifscope;
3247 if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) {
3248 inp->in6p_laddr = ip6->ip6_dst;
3249 inp->inp_lifscope = in6_addr2scopeid(ifp, &inp->in6p_laddr);
3250 in6_verify_ifscope(&inp->in6p_laddr, inp->inp_lifscope);
3251 }
3252 if (in6_pcbconnect(inp, (struct sockaddr *)sin6,
3253 kernel_proc)) {
3254 inp->in6p_laddr = laddr6;
3255 kfree_type(struct sockaddr_in6, sin6);
3256 inp->inp_lifscope = lifscope;
3257 in6_verify_ifscope(&inp->in6p_laddr, inp->inp_lifscope);
3258 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, " LISTEN in6_pcbconnect failed");
3259 goto drop;
3260 }
3261 kfree_type(struct sockaddr_in6, sin6);
3262 } else {
3263 socket_lock_assert_owned(so);
3264 sin = kalloc_type(struct sockaddr_in, Z_NOWAIT);
3265 if (sin == NULL) {
3266 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "LISTEN kalloc_type failed");
3267 goto drop;
3268 }
3269 sin->sin_family = AF_INET;
3270 sin->sin_len = sizeof(*sin);
3271 sin->sin_addr = ip->ip_src;
3272 sin->sin_port = th->th_sport;
3273 bzero((caddr_t)sin->sin_zero, sizeof(sin->sin_zero));
3274 laddr = inp->inp_laddr;
3275 if (inp->inp_laddr.s_addr == INADDR_ANY) {
3276 inp->inp_laddr = ip->ip_dst;
3277 }
3278 if (in_pcbconnect(inp, (struct sockaddr *)sin, kernel_proc,
3279 IFSCOPE_NONE, NULL)) {
3280 inp->inp_laddr = laddr;
3281 kfree_type(struct sockaddr_in, sin);
3282 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, " LISTEN in_pcbconnect failed");
3283 goto drop;
3284 }
3285 kfree_type(struct sockaddr_in, sin);
3286 }
3287
3288 tcp_dooptions(tp, optp, optlen, th, &to);
3289 tcp_finalize_options(tp, &to, ifscope);
3290
3291 if (tfo_enabled(tp) && tcp_tfo_syn(tp, &to)) {
3292 isconnected = TRUE;
3293 }
3294
3295 if (iss) {
3296 tp->iss = iss;
3297 } else {
3298 tp->iss = tcp_new_isn(tp);
3299 }
3300 tp->irs = th->th_seq;
3301 tcp_sendseqinit(tp);
3302 tcp_rcvseqinit(tp);
3303 tp->snd_recover = tp->snd_una;
3304 /*
3305 * Initialization of the tcpcb for transaction;
3306 * set SND.WND = SEG.WND,
3307 * initialize CCsend and CCrecv.
3308 */
3309 tp->snd_wnd = tiwin; /* initial send-window */
3310 tp->max_sndwnd = tp->snd_wnd;
3311 tp->t_flags |= TF_ACKNOW;
3312 tp->t_unacksegs = 0;
3313 DTRACE_TCP4(state__change, void, NULL, struct inpcb *, inp,
3314 struct tcpcb *, tp, int32_t, TCPS_SYN_RECEIVED);
3315 tp->t_state = TCPS_SYN_RECEIVED;
3316 tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp,
3317 TCP_CONN_KEEPINIT(tp));
3318 tp->t_connect_time = tcp_now;
3319 dropsocket = 0; /* committed to socket */
3320
3321 if (inp->inp_flowhash == 0) {
3322 inp->inp_flowhash = inp_calc_flowhash(inp);
3323 }
3324 /* update flowinfo - RFC 6437 */
3325 if (inp->inp_flow == 0 &&
3326 inp->in6p_flags & IN6P_AUTOFLOWLABEL) {
3327 inp->inp_flow &= ~IPV6_FLOWLABEL_MASK;
3328 inp->inp_flow |=
3329 (htonl(ip6_randomflowlabel()) & IPV6_FLOWLABEL_MASK);
3330 }
3331
3332 /* reset the incomp processing flag */
3333 so->so_flags &= ~(SOF_INCOMP_INPROGRESS);
3334 tcpstat.tcps_accepts++;
3335 if ((thflags & (TH_ECE | TH_CWR)) == (TH_ECE | TH_CWR)) {
3336 /* ECN-setup SYN */
3337 tp->ecn_flags |= (TE_SETUPRECEIVED | TE_SENDIPECT);
3338 }
3339
3340 /*
3341 * The address and connection state are finalized
3342 */
3343 TCP_LOG_CONNECT(tp, false, 0);
3344
3345 tcp_add_fsw_flow(tp, ifp);
3346
3347 goto trimthenstep6;
3348 }
3349
3350 /*
3351 * If the state is SYN_RECEIVED and the seg contains an ACK,
3352 * but not for our SYN/ACK, send a RST.
3353 */
3354 case TCPS_SYN_RECEIVED:
3355 if ((thflags & TH_ACK) &&
3356 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
3357 SEQ_GT(th->th_ack, tp->snd_max))) {
3358 IF_TCP_STATINC(ifp, ooopacket);
3359 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SYN_RECEIVED bad ACK");
3360 goto dropwithreset;
3361 }
3362
3363 /*
3364 * In SYN_RECEIVED state, if we recv some SYNS with
3365 * window scale and others without, window scaling should
3366 * be disabled. Otherwise the window advertised will be
3367 * lower if we assume scaling and the other end does not.
3368 */
3369 if ((thflags & TH_SYN) &&
3370 (tp->irs == th->th_seq) &&
3371 !(to.to_flags & TOF_SCALE)) {
3372 tp->t_flags &= ~TF_RCVD_SCALE;
3373 }
3374 break;
3375
3376 /*
3377 * If the state is SYN_SENT:
3378 * if seg contains an ACK, but not for our SYN, drop the input.
3379 * if seg contains a RST, then drop the connection.
3380 * if seg does not contain SYN, then drop it.
3381 * Otherwise this is an acceptable SYN segment
3382 * initialize tp->rcv_nxt and tp->irs
3383 * if seg contains ack then advance tp->snd_una
3384 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
3385 * arrange for segment to be acked (eventually)
3386 * continue processing rest of data/controls, beginning with URG
3387 */
3388 case TCPS_SYN_SENT:
3389 if ((thflags & TH_ACK) &&
3390 (SEQ_LEQ(th->th_ack, tp->iss) ||
3391 SEQ_GT(th->th_ack, tp->snd_max))) {
3392 IF_TCP_STATINC(ifp, ooopacket);
3393 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SYN_SENT bad ACK");
3394 goto dropwithreset;
3395 }
3396 if (thflags & TH_RST) {
3397 if ((thflags & TH_ACK) != 0) {
3398 if (tfo_enabled(tp) &&
3399 !(tp->t_flagsext & TF_FASTOPEN_FORCE_ENABLE)) {
3400 tcp_heuristic_tfo_rst(tp);
3401 }
3402 if ((tp->ecn_flags & (TE_SETUPSENT | TE_RCVD_SYN_RST)) == TE_SETUPSENT) {
3403 /*
3404 * On local connections, send
3405 * non-ECN syn one time before
3406 * dropping the connection
3407 */
3408 if (tp->t_flags & TF_LOCAL) {
3409 tp->ecn_flags |= TE_RCVD_SYN_RST;
3410 goto drop;
3411 } else {
3412 tcp_heuristic_ecn_synrst(tp);
3413 }
3414 }
3415 soevent(so,
3416 (SO_FILT_HINT_LOCKED |
3417 SO_FILT_HINT_CONNRESET));
3418 tp = tcp_drop(tp, ECONNREFUSED);
3419 }
3420 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SYN_SENT got RST");
3421 goto drop;
3422 }
3423 if ((thflags & TH_SYN) == 0) {
3424 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SYN_SENT no SYN");
3425 goto drop;
3426 }
3427 tp->snd_wnd = th->th_win; /* initial send window */
3428 tp->max_sndwnd = tp->snd_wnd;
3429
3430 tp->irs = th->th_seq;
3431 tcp_rcvseqinit(tp);
3432 if (thflags & TH_ACK) {
3433 tcpstat.tcps_connects++;
3434
3435 if ((thflags & (TH_ECE | TH_CWR)) == (TH_ECE)) {
3436 /* ECN-setup SYN-ACK */
3437 tp->ecn_flags |= TE_SETUPRECEIVED;
3438 if (TCP_ECN_ENABLED(tp)) {
3439 tcp_heuristic_ecn_success(tp);
3440 tcpstat.tcps_ecn_client_success++;
3441 }
3442 } else {
3443 if (tp->ecn_flags & TE_SETUPSENT &&
3444 tp->t_rxtshift == 0) {
3445 tcp_heuristic_ecn_success(tp);
3446 tcpstat.tcps_ecn_not_supported++;
3447 }
3448 if (tp->ecn_flags & TE_SETUPSENT &&
3449 tp->t_rxtshift > 0) {
3450 tcp_heuristic_ecn_loss(tp);
3451 }
3452
3453 /* non-ECN-setup SYN-ACK */
3454 tp->ecn_flags &= ~TE_SENDIPECT;
3455 }
3456
3457 /* Do window scaling on this connection? */
3458 if (TCP_WINDOW_SCALE_ENABLED(tp)) {
3459 tp->snd_scale = tp->requested_s_scale;
3460 tp->rcv_scale = tp->request_r_scale;
3461 }
3462
3463 uint32_t recwin = min(tp->rcv_wnd, TCP_MAXWIN << tp->rcv_scale);
3464 if (TCP_USE_RLEDBAT(tp, so) && tcp_cc_rledbat.get_rlwin != NULL) {
3465 /* For a LBE receiver, also use rledbat_win */
3466 uint32_t rledbat_win = tcp_cc_rledbat.get_rlwin(tp);
3467 if (rledbat_win > 0) {
3468 recwin = min(recwin, rledbat_win);
3469 }
3470 }
3471 tp->rcv_adv += recwin;
3472
3473 tp->snd_una++; /* SYN is acked */
3474 if (SEQ_LT(tp->snd_nxt, tp->snd_una)) {
3475 tp->snd_nxt = tp->snd_una;
3476 }
3477
3478 /*
3479 * We have sent more in the SYN than what is being
3480 * acked. (e.g., TFO)
3481 * We should restart the sending from what the receiver
3482 * has acknowledged immediately.
3483 */
3484 if (SEQ_GT(tp->snd_nxt, th->th_ack)) {
3485 /*
3486 * rdar://problem/33214601
3487 * There is a middlebox that acks all but one
3488 * byte and still drops the data.
3489 */
3490 if (!(tp->t_flagsext & TF_FASTOPEN_FORCE_ENABLE) &&
3491 (tp->t_tfo_stats & TFO_S_SYN_DATA_SENT) &&
3492 tp->snd_max == th->th_ack + 1 &&
3493 tp->snd_max > tp->snd_una + 1) {
3494 tcp_heuristic_tfo_middlebox(tp);
3495
3496 so->so_error = ENODATA;
3497 soevent(so,
3498 (SO_FILT_HINT_LOCKED | SO_FILT_HINT_MP_SUB_ERROR));
3499
3500 tp->t_tfo_stats |= TFO_S_ONE_BYTE_PROXY;
3501 }
3502
3503 tp->snd_max = tp->snd_nxt = th->th_ack;
3504 }
3505
3506 /*
3507 * If there's data, delay ACK; if there's also a FIN
3508 * ACKNOW will be turned on later.
3509 */
3510 TCP_INC_VAR(tp->t_unacksegs, segment_count);
3511 if (DELAY_ACK(tp, th) && tlen != 0) {
3512 if ((tp->t_flags & TF_DELACK) == 0) {
3513 tp->t_flags |= TF_DELACK;
3514 tp->t_timer[TCPT_DELACK] = OFFSET_FROM_START(tp, tcp_delack);
3515 }
3516 } else {
3517 tp->t_flags |= TF_ACKNOW;
3518 }
3519 /*
3520 * Received <SYN,ACK> in SYN_SENT[*] state.
3521 * Transitions:
3522 * SYN_SENT --> ESTABLISHED
3523 * SYN_SENT* --> FIN_WAIT_1
3524 */
3525 tp->t_starttime = tcp_now;
3526 tcp_sbrcv_tstmp_check(tp);
3527 if (tp->t_flags & TF_NEEDFIN) {
3528 DTRACE_TCP4(state__change, void, NULL,
3529 struct inpcb *, inp,
3530 struct tcpcb *, tp, int32_t,
3531 TCPS_FIN_WAIT_1);
3532 tp->t_state = TCPS_FIN_WAIT_1;
3533 tp->t_flags &= ~TF_NEEDFIN;
3534 thflags &= ~TH_SYN;
3535
3536 TCP_LOG_CONNECTION_SUMMARY(tp);
3537 } else {
3538 DTRACE_TCP4(state__change, void, NULL,
3539 struct inpcb *, inp, struct tcpcb *,
3540 tp, int32_t, TCPS_ESTABLISHED);
3541 tp->t_state = TCPS_ESTABLISHED;
3542 tp->t_timer[TCPT_KEEP] =
3543 OFFSET_FROM_START(tp,
3544 TCP_CONN_KEEPIDLE(tp));
3545 if (nstat_collect) {
3546 nstat_route_connect_success(
3547 inp->inp_route.ro_rt);
3548 }
3549 /*
3550 * The SYN is acknowledged but una is not
3551 * updated yet. So pass the value of
3552 * ack to compute sndbytes correctly
3553 */
3554 inp_count_sndbytes(inp, th->th_ack);
3555 }
3556 tp->t_forced_acks = TCP_FORCED_ACKS_COUNT;
3557 #if MPTCP
3558 /*
3559 * Do not send the connect notification for additional
3560 * subflows until ACK for 3-way handshake arrives.
3561 */
3562 if ((!(tp->t_mpflags & TMPF_MPTCP_TRUE)) &&
3563 (tp->t_mpflags & TMPF_SENT_JOIN)) {
3564 isconnected = FALSE;
3565 } else
3566 #endif /* MPTCP */
3567 isconnected = TRUE;
3568
3569 if ((tp->t_tfo_flags & (TFO_F_COOKIE_REQ | TFO_F_COOKIE_SENT)) ||
3570 (tp->t_tfo_stats & TFO_S_SYN_DATA_SENT)) {
3571 tcp_tfo_synack(tp, &to);
3572
3573 if ((tp->t_tfo_stats & TFO_S_SYN_DATA_SENT) &&
3574 SEQ_LT(tp->snd_una, th->th_ack)) {
3575 tp->t_tfo_stats |= TFO_S_SYN_DATA_ACKED;
3576 tcpstat.tcps_tfo_syn_data_acked++;
3577 #if MPTCP
3578 if (so->so_flags & SOF_MP_SUBFLOW) {
3579 so->so_flags1 |= SOF1_TFO_REWIND;
3580 }
3581 #endif
3582 tcp_tfo_rcv_probe(tp, tlen);
3583 }
3584 }
3585 } else {
3586 /*
3587 * Received initial SYN in SYN-SENT[*] state => simul-
3588 * taneous open.
3589 * Do 3-way handshake:
3590 * SYN-SENT -> SYN-RECEIVED
3591 * SYN-SENT* -> SYN-RECEIVED*
3592 */
3593 tp->t_flags |= TF_ACKNOW;
3594 tp->t_timer[TCPT_REXMT] = 0;
3595 DTRACE_TCP4(state__change, void, NULL, struct inpcb *, inp,
3596 struct tcpcb *, tp, int32_t, TCPS_SYN_RECEIVED);
3597 tp->t_state = TCPS_SYN_RECEIVED;
3598
3599 /*
3600 * During simultaneous open, TFO should not be used.
3601 * So, we disable it here, to prevent that data gets
3602 * sent on the SYN/ACK.
3603 */
3604 tcp_disable_tfo(tp);
3605 }
3606
3607 trimthenstep6:
3608 /*
3609 * Advance th->th_seq to correspond to first data byte.
3610 * If data, trim to stay within window,
3611 * dropping FIN if necessary.
3612 */
3613 th->th_seq++;
3614 if (tlen > tp->rcv_wnd) {
3615 todrop = tlen - tp->rcv_wnd;
3616 m_adj(m, -todrop);
3617 tlen = tp->rcv_wnd;
3618 thflags &= ~TH_FIN;
3619 tcpstat.tcps_rcvpackafterwin++;
3620 tcpstat.tcps_rcvbyteafterwin += todrop;
3621 }
3622 tp->snd_wl1 = th->th_seq - 1;
3623 tp->rcv_up = th->th_seq;
3624 /*
3625 * Client side of transaction: already sent SYN and data.
3626 * If the remote host used T/TCP to validate the SYN,
3627 * our data will be ACK'd; if so, enter normal data segment
3628 * processing in the middle of step 5, ack processing.
3629 * Otherwise, goto step 6.
3630 */
3631 if (thflags & TH_ACK) {
3632 goto process_ACK;
3633 }
3634 goto step6;
3635 /*
3636 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
3637 * do normal processing.
3638 *
3639 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
3640 */
3641 case TCPS_LAST_ACK:
3642 case TCPS_CLOSING:
3643 case TCPS_TIME_WAIT:
3644 break; /* continue normal processing */
3645
3646 /* Received a SYN while connection is already established.
3647 * This is a "half open connection and other anomalies" described
3648 * in RFC793 page 34, send an ACK so the remote reset the connection
3649 * or recovers by adjusting its sequence numbering. Sending an ACK is
3650 * in accordance with RFC 5961 Section 4.2
3651 */
3652 case TCPS_ESTABLISHED:
3653 if (thflags & TH_SYN && tlen <= 0) {
3654 /* Drop the packet silently if we have reached the limit */
3655 if (tcp_is_ack_ratelimited(tp)) {
3656 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "ESTABLISHED rfc5961 rate limited");
3657 goto drop;
3658 } else {
3659 /* Send challenge ACK */
3660 tcpstat.tcps_synchallenge++;
3661 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "ESTABLISHED rfc5961 challenge ACK");
3662 goto dropafterack;
3663 }
3664 }
3665 break;
3666 }
3667
3668 /*
3669 * States other than LISTEN or SYN_SENT.
3670 * First check the RST flag and sequence number since reset segments
3671 * are exempt from the timestamp and connection count tests. This
3672 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
3673 * below which allowed reset segments in half the sequence space
3674 * to fall though and be processed (which gives forged reset
3675 * segments with a random sequence number a 50 percent chance of
3676 * killing a connection).
3677 * Then check timestamp, if present.
3678 * Then check the connection count, if present.
3679 * Then check that at least some bytes of segment are within
3680 * receive window. If segment begins before rcv_nxt,
3681 * drop leading data (and SYN); if nothing left, just ack.
3682 *
3683 *
3684 * If the RST bit is set, check the sequence number to see
3685 * if this is a valid reset segment.
3686 * RFC 793 page 37:
3687 * In all states except SYN-SENT, all reset (RST) segments
3688 * are validated by checking their SEQ-fields. A reset is
3689 * valid if its sequence number is in the window.
3690 * Note: this does not take into account delayed ACKs, so
3691 * we should test against last_ack_sent instead of rcv_nxt.
3692 * The sequence number in the reset segment is normally an
3693 * echo of our outgoing acknowlegement numbers, but some hosts
3694 * send a reset with the sequence number at the rightmost edge
3695 * of our receive window, and we have to handle this case.
3696 * Note 2: Paul Watson's paper "Slipping in the Window" has shown
3697 * that brute force RST attacks are possible. To combat this,
3698 * we use a much stricter check while in the ESTABLISHED state,
3699 * only accepting RSTs where the sequence number is equal to
3700 * last_ack_sent. In all other states (the states in which a
3701 * RST is more likely), the more permissive check is used.
3702 * RFC 5961 Section 3.2: if the RST bit is set, sequence # is
3703 * within the receive window and last_ack_sent == seq,
3704 * then reset the connection. Otherwise if the seq doesn't
3705 * match last_ack_sent, TCP must send challenge ACK. Perform
3706 * rate limitation when sending the challenge ACK.
3707 * If we have multiple segments in flight, the intial reset
3708 * segment sequence numbers will be to the left of last_ack_sent,
3709 * but they will eventually catch up.
3710 * In any case, it never made sense to trim reset segments to
3711 * fit the receive window since RFC 1122 says:
3712 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
3713 *
3714 * A TCP SHOULD allow a received RST segment to include data.
3715 *
3716 * DISCUSSION
3717 * It has been suggested that a RST segment could contain
3718 * ASCII text that encoded and explained the cause of the
3719 * RST. No standard has yet been established for such
3720 * data.
3721 *
3722 * If the reset segment passes the sequence number test examine
3723 * the state:
3724 * SYN_RECEIVED STATE:
3725 * If passive open, return to LISTEN state.
3726 * If active open, inform user that connection was refused.
3727 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
3728 * Inform user that connection was reset, and close tcb.
3729 * CLOSING, LAST_ACK STATES:
3730 * Close the tcb.
3731 * TIME_WAIT STATE:
3732 * Drop the segment - see Stevens, vol. 2, p. 964 and
3733 * RFC 1337.
3734 *
3735 * Radar 4803931: Allows for the case where we ACKed the FIN but
3736 * there is already a RST in flight from the peer.
3737 * In that case, accept the RST for non-established
3738 * state if it's one off from last_ack_sent.
3739 *
3740 */
3741 if (thflags & TH_RST) {
3742 if ((SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
3743 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) ||
3744 (tp->rcv_wnd == 0 &&
3745 ((tp->last_ack_sent == th->th_seq) ||
3746 ((tp->last_ack_sent - 1) == th->th_seq)))) {
3747 if (tp->last_ack_sent == th->th_seq) {
3748 switch (tp->t_state) {
3749 case TCPS_SYN_RECEIVED:
3750 IF_TCP_STATINC(ifp, rstinsynrcv);
3751 so->so_error = ECONNREFUSED;
3752 goto close;
3753
3754 case TCPS_ESTABLISHED:
3755 if (TCP_ECN_ENABLED(tp) &&
3756 tp->snd_una == tp->iss + 1 &&
3757 SEQ_GT(tp->snd_max, tp->snd_una)) {
3758 /*
3759 * If the first data packet on an
3760 * ECN connection, receives a RST
3761 * increment the heuristic
3762 */
3763 tcp_heuristic_ecn_droprst(tp);
3764 }
3765 OS_FALLTHROUGH;
3766 case TCPS_FIN_WAIT_1:
3767 case TCPS_CLOSE_WAIT:
3768 case TCPS_FIN_WAIT_2:
3769 so->so_error = ECONNRESET;
3770 close:
3771 soevent(so,
3772 (SO_FILT_HINT_LOCKED |
3773 SO_FILT_HINT_CONNRESET));
3774
3775 tcpstat.tcps_drops++;
3776 tp = tcp_close(tp);
3777 break;
3778
3779 case TCPS_CLOSING:
3780 case TCPS_LAST_ACK:
3781 tp = tcp_close(tp);
3782 break;
3783
3784 case TCPS_TIME_WAIT:
3785 break;
3786 }
3787 } else {
3788 tcpstat.tcps_badrst++;
3789 /* Drop if we have reached the ACK limit */
3790 if (tcp_is_ack_ratelimited(tp)) {
3791 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "ESTABLISHED rfc5961 rate limited");
3792 goto drop;
3793 } else {
3794 /* Send challenge ACK */
3795 tcpstat.tcps_rstchallenge++;
3796 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "ESTABLISHED rfc5961 challenge ACK");
3797 goto dropafterack;
3798 }
3799 }
3800 }
3801 goto drop;
3802 }
3803
3804 /*
3805 * RFC 1323 PAWS: If we have a timestamp reply on this segment
3806 * and it's less than ts_recent, drop it.
3807 */
3808 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
3809 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
3810 /* Check to see if ts_recent is over 24 days old. */
3811 if ((int)(tcp_now - tp->ts_recent_age) > TCP_PAWS_IDLE) {
3812 /*
3813 * Invalidate ts_recent. If this segment updates
3814 * ts_recent, the age will be reset later and ts_recent
3815 * will get a valid value. If it does not, setting
3816 * ts_recent to zero will at least satisfy the
3817 * requirement that zero be placed in the timestamp
3818 * echo reply when ts_recent isn't valid. The
3819 * age isn't reset until we get a valid ts_recent
3820 * because we don't want out-of-order segments to be
3821 * dropped when ts_recent is old.
3822 */
3823 tp->ts_recent = 0;
3824 } else {
3825 tcpstat.tcps_rcvduppack++;
3826 tcpstat.tcps_rcvdupbyte += tlen;
3827 tp->t_pawsdrop++;
3828 tcpstat.tcps_pawsdrop++;
3829
3830 /*
3831 * PAWS-drop when ECN is being used? That indicates
3832 * that ECT-marked packets take a different path, with
3833 * different congestion-characteristics.
3834 *
3835 * Only fallback when we did send less than 2GB as PAWS
3836 * really has no reason to kick in earlier.
3837 */
3838 if (TCP_ECN_ENABLED(tp) &&
3839 inp->inp_stat->rxbytes < 2147483648) {
3840 INP_INC_IFNET_STAT(inp, ecn_fallback_reorder);
3841 tcpstat.tcps_ecn_fallback_reorder++;
3842 tcp_heuristic_ecn_aggressive(tp);
3843 }
3844
3845 if (nstat_collect) {
3846 nstat_route_rx(tp->t_inpcb->inp_route.ro_rt,
3847 1, tlen, NSTAT_RX_FLAG_DUPLICATE);
3848 INP_ADD_STAT(inp, cell, wifi, wired,
3849 rxpackets, 1);
3850 INP_ADD_STAT(inp, cell, wifi, wired,
3851 rxbytes, tlen);
3852 tp->t_stat.rxduplicatebytes += tlen;
3853 inp_set_activity_bitmap(inp);
3854 }
3855 if (tlen > 0) {
3856 goto dropafterack;
3857 }
3858 goto drop;
3859 }
3860 }
3861
3862 /*
3863 * In the SYN-RECEIVED state, validate that the packet belongs to
3864 * this connection before trimming the data to fit the receive
3865 * window. Check the sequence number versus IRS since we know
3866 * the sequence numbers haven't wrapped. This is a partial fix
3867 * for the "LAND" DoS attack.
3868 */
3869 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
3870 IF_TCP_STATINC(ifp, dospacket);
3871 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SYN_RECEIVED bad SEQ");
3872 goto dropwithreset;
3873 }
3874
3875 /*
3876 * Check if there is old data at the beginning of the window
3877 * i.e. the sequence number is before rcv_nxt
3878 */
3879 todrop = tp->rcv_nxt - th->th_seq;
3880 if (todrop > 0) {
3881 boolean_t is_syn_set = FALSE;
3882
3883 if (thflags & TH_SYN) {
3884 is_syn_set = TRUE;
3885 thflags &= ~TH_SYN;
3886 th->th_seq++;
3887 if (th->th_urp > 1) {
3888 th->th_urp--;
3889 } else {
3890 thflags &= ~TH_URG;
3891 }
3892 todrop--;
3893 }
3894 /*
3895 * Following if statement from Stevens, vol. 2, p. 960.
3896 * The amount of duplicate data is greater than or equal
3897 * to the size of the segment - entire segment is duplicate
3898 */
3899 if (todrop > tlen
3900 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
3901 /*
3902 * Any valid FIN must be to the left of the window.
3903 * At this point the FIN must be a duplicate or out
3904 * of sequence; drop it.
3905 */
3906 thflags &= ~TH_FIN;
3907
3908 /*
3909 * Send an ACK to resynchronize and drop any data.
3910 * But keep on processing for RST or ACK.
3911 *
3912 * If the SYN bit was originally set, then only send
3913 * an ACK if we are not rate-limiting this connection.
3914 */
3915 if (is_syn_set) {
3916 if (!tcp_is_ack_ratelimited(tp)) {
3917 tcpstat.tcps_synchallenge++;
3918 tp->t_flags |= TF_ACKNOW;
3919 }
3920 } else {
3921 tp->t_flags |= TF_ACKNOW;
3922 }
3923
3924 if (todrop == 1) {
3925 /* This could be a keepalive */
3926 soevent(so, SO_FILT_HINT_LOCKED |
3927 SO_FILT_HINT_KEEPALIVE);
3928 }
3929 todrop = tlen;
3930 tcpstat.tcps_rcvduppack++;
3931 tcpstat.tcps_rcvdupbyte += todrop;
3932 } else {
3933 tcpstat.tcps_rcvpartduppack++;
3934 tcpstat.tcps_rcvpartdupbyte += todrop;
3935 }
3936
3937 if (todrop > 1) {
3938 /*
3939 * Note the duplicate data sequence space so that
3940 * it can be reported in DSACK option.
3941 */
3942 tp->t_dsack_lseq = th->th_seq;
3943 tp->t_dsack_rseq = th->th_seq + todrop;
3944 tp->t_flags |= TF_ACKNOW;
3945 }
3946 if (nstat_collect) {
3947 nstat_route_rx(tp->t_inpcb->inp_route.ro_rt, 1,
3948 todrop, NSTAT_RX_FLAG_DUPLICATE);
3949 INP_ADD_STAT(inp, cell, wifi, wired, rxpackets, 1);
3950 INP_ADD_STAT(inp, cell, wifi, wired, rxbytes, todrop);
3951 tp->t_stat.rxduplicatebytes += todrop;
3952 inp_set_activity_bitmap(inp);
3953 }
3954 drop_hdrlen += todrop; /* drop from the top afterwards */
3955 th->th_seq += todrop;
3956 tlen -= todrop;
3957 if (th->th_urp > todrop) {
3958 th->th_urp -= todrop;
3959 } else {
3960 thflags &= ~TH_URG;
3961 th->th_urp = 0;
3962 }
3963 }
3964
3965 /*
3966 * If new data are received on a connection after the user
3967 * processes are gone, then RST the other end.
3968 * Send also a RST when we received a data segment after we've
3969 * sent our FIN when the socket is defunct.
3970 * Note that an MPTCP subflow socket would have SS_NOFDREF set
3971 * by default. So, if it's an MPTCP-subflow we rather check the
3972 * MPTCP-level's socket state for SS_NOFDREF.
3973 */
3974 if (tlen) {
3975 boolean_t close_it = FALSE;
3976
3977 if (!(so->so_flags & SOF_MP_SUBFLOW) && (so->so_state & SS_NOFDREF) &&
3978 tp->t_state > TCPS_CLOSE_WAIT) {
3979 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SS_NOFDREF");
3980 close_it = TRUE;
3981 }
3982
3983 if ((so->so_flags & SOF_MP_SUBFLOW) && (mptetoso(tptomptp(tp)->mpt_mpte)->so_state & SS_NOFDREF) &&
3984 tp->t_state > TCPS_CLOSE_WAIT) {
3985 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SOF_MP_SUBFLOW SS_NOFDREF");
3986 close_it = TRUE;
3987 }
3988
3989 if ((so->so_flags & SOF_DEFUNCT) && tp->t_state > TCPS_FIN_WAIT_1) {
3990 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SOF_DEFUNCT");
3991 close_it = TRUE;
3992 }
3993
3994 if (so->so_state & SS_CANTRCVMORE) {
3995 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SS_CANTRCVMORE");
3996 close_it = TRUE;
3997 }
3998
3999 if (close_it) {
4000 tp = tcp_close(tp);
4001 tcpstat.tcps_rcvafterclose++;
4002 IF_TCP_STATINC(ifp, cleanup);
4003 goto dropwithreset;
4004 }
4005 }
4006
4007 /*
4008 * If segment ends after window, drop trailing data
4009 * (and PUSH and FIN); if nothing left, just ACK.
4010 */
4011 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
4012 if (todrop > 0) {
4013 tcpstat.tcps_rcvpackafterwin++;
4014 if (todrop >= tlen) {
4015 tcpstat.tcps_rcvbyteafterwin += tlen;
4016 /*
4017 * If a new connection request is received
4018 * while in TIME_WAIT, drop the old connection
4019 * and start over if the sequence numbers
4020 * are above the previous ones.
4021 */
4022 if (thflags & TH_SYN &&
4023 tp->t_state == TCPS_TIME_WAIT &&
4024 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
4025 iss = tcp_new_isn(tp);
4026 tp = tcp_close(tp);
4027 socket_unlock(so, 1);
4028 goto findpcb;
4029 }
4030 /*
4031 * If window is closed can only take segments at
4032 * window edge, and have to drop data and PUSH from
4033 * incoming segments. Continue processing, but
4034 * remember to ack. Otherwise, drop segment
4035 * and ack.
4036 */
4037 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
4038 tp->t_flags |= TF_ACKNOW;
4039 tcpstat.tcps_rcvwinprobe++;
4040 } else {
4041 goto dropafterack;
4042 }
4043 } else {
4044 tcpstat.tcps_rcvbyteafterwin += todrop;
4045 }
4046 m_adj(m, -todrop);
4047 tlen -= todrop;
4048 thflags &= ~(TH_PUSH | TH_FIN);
4049 }
4050
4051 /*
4052 * If last ACK falls within this segment's sequence numbers,
4053 * record its timestamp.
4054 * NOTE:
4055 * 1) That the test incorporates suggestions from the latest
4056 * proposal of the [email protected] list (Braden 1993/04/26).
4057 * 2) That updating only on newer timestamps interferes with
4058 * our earlier PAWS tests, so this check should be solely
4059 * predicated on the sequence space of this segment.
4060 * 3) That we modify the segment boundary check to be
4061 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
4062 * instead of RFC1323's
4063 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
4064 * This modified check allows us to overcome RFC1323's
4065 * limitations as described in Stevens TCP/IP Illustrated
4066 * Vol. 2 p.869. In such cases, we can still calculate the
4067 * RTT correctly when RCV.NXT == Last.ACK.Sent.
4068 */
4069 if ((to.to_flags & TOF_TS) != 0 &&
4070 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
4071 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
4072 ((thflags & (TH_SYN | TH_FIN)) != 0))) {
4073 tp->ts_recent_age = tcp_now;
4074 tp->ts_recent = to.to_tsval;
4075 }
4076
4077 /*
4078 * Stevens: If a SYN is in the window, then this is an
4079 * error and we send an RST and drop the connection.
4080 *
4081 * RFC 5961 Section 4.2
4082 * Send challenge ACK for any SYN in synchronized state
4083 * Perform rate limitation in doing so.
4084 */
4085 if (thflags & TH_SYN) {
4086 if (!tcp_syn_data_valid(tp, th, tlen)) {
4087 tcpstat.tcps_badsyn++;
4088 /* Drop if we have reached ACK limit */
4089 if (tcp_is_ack_ratelimited(tp)) {
4090 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "rfc5961 bad SYN rate limited");
4091 goto drop;
4092 } else {
4093 /* Send challenge ACK */
4094 tcpstat.tcps_synchallenge++;
4095 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "rfc5961 bad SYN challenge ack");
4096 goto dropafterack;
4097 }
4098 } else {
4099 /*
4100 * Received SYN (/ACK) with data.
4101 * Move sequence number along to process the data.
4102 */
4103 th->th_seq++;
4104 thflags &= ~TH_SYN;
4105 }
4106 }
4107
4108 /*
4109 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
4110 * flag is on (half-synchronized state), then queue data for
4111 * later processing; else drop segment and return.
4112 */
4113 if ((thflags & TH_ACK) == 0) {
4114 if (tp->t_state == TCPS_SYN_RECEIVED) {
4115 if ((tfo_enabled(tp))) {
4116 /*
4117 * So, we received a valid segment while in
4118 * SYN-RECEIVED.
4119 * As this cannot be an RST (see that if a bit
4120 * higher), and it does not have the ACK-flag
4121 * set, we want to retransmit the SYN/ACK.
4122 * Thus, we have to reset snd_nxt to snd_una to
4123 * trigger the going back to sending of the
4124 * SYN/ACK. This is more consistent with the
4125 * behavior of tcp_output(), which expects
4126 * to send the segment that is pointed to by
4127 * snd_nxt.
4128 */
4129 tp->snd_nxt = tp->snd_una;
4130
4131 /*
4132 * We need to make absolutely sure that we are
4133 * going to reply upon a duplicate SYN-segment.
4134 */
4135 if (th->th_flags & TH_SYN) {
4136 needoutput = 1;
4137 }
4138 }
4139
4140 goto step6;
4141 } else if (tp->t_flags & TF_ACKNOW) {
4142 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "bad ACK");
4143 goto dropafterack;
4144 } else {
4145 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "bad ACK");
4146 goto drop;
4147 }
4148 }
4149
4150 /*
4151 * Ack processing.
4152 */
4153
4154 switch (tp->t_state) {
4155 /*
4156 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
4157 * ESTABLISHED state and continue processing.
4158 * The ACK was checked above.
4159 */
4160 case TCPS_SYN_RECEIVED:
4161
4162 tcpstat.tcps_connects++;
4163
4164 /* Do window scaling? */
4165 if (TCP_WINDOW_SCALE_ENABLED(tp)) {
4166 tp->snd_scale = tp->requested_s_scale;
4167 tp->rcv_scale = tp->request_r_scale;
4168 tp->snd_wnd = th->th_win << tp->snd_scale;
4169 tp->max_sndwnd = tp->snd_wnd;
4170 tiwin = tp->snd_wnd;
4171 }
4172 /*
4173 * Make transitions:
4174 * SYN-RECEIVED -> ESTABLISHED
4175 * SYN-RECEIVED* -> FIN-WAIT-1
4176 */
4177 tp->t_starttime = tcp_now;
4178 tcp_sbrcv_tstmp_check(tp);
4179 if (tp->t_flags & TF_NEEDFIN) {
4180 DTRACE_TCP4(state__change, void, NULL,
4181 struct inpcb *, inp,
4182 struct tcpcb *, tp, int32_t, TCPS_FIN_WAIT_1);
4183 tp->t_state = TCPS_FIN_WAIT_1;
4184 tp->t_flags &= ~TF_NEEDFIN;
4185
4186 TCP_LOG_CONNECTION_SUMMARY(tp);
4187 } else {
4188 DTRACE_TCP4(state__change, void, NULL,
4189 struct inpcb *, inp,
4190 struct tcpcb *, tp, int32_t, TCPS_ESTABLISHED);
4191 tp->t_state = TCPS_ESTABLISHED;
4192 tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp,
4193 TCP_CONN_KEEPIDLE(tp));
4194 if (nstat_collect) {
4195 nstat_route_connect_success(
4196 tp->t_inpcb->inp_route.ro_rt);
4197 }
4198
4199 /*
4200 * The SYN is acknowledged but una is not updated
4201 * yet. So pass the value of ack to compute
4202 * sndbytes correctly
4203 */
4204 inp_count_sndbytes(inp, th->th_ack);
4205 }
4206 tp->t_forced_acks = TCP_FORCED_ACKS_COUNT;
4207 /*
4208 * If segment contains data or ACK, will call tcp_reass()
4209 * later; if not, do so now to pass queued data to user.
4210 */
4211 if (tlen == 0 && (thflags & TH_FIN) == 0) {
4212 if (isipv6) {
4213 memcpy(&saved_hdr, ip6, sizeof(struct ip6_hdr));
4214 ip6 = (struct ip6_hdr *)&saved_hdr[0];
4215 } else {
4216 memcpy(&saved_hdr, ip, ip->ip_hl << 2);
4217 ip = (struct ip *)&saved_hdr[0];
4218 }
4219 memcpy(&saved_tcphdr, th, sizeof(struct tcphdr));
4220 (void) tcp_reass(tp, (struct tcphdr *)0, &tlen,
4221 NULL, ifp, &read_wakeup);
4222 th = &saved_tcphdr;
4223 }
4224 tp->snd_wl1 = th->th_seq - 1;
4225
4226 #if MPTCP
4227 /*
4228 * Do not send the connect notification for additional subflows
4229 * until ACK for 3-way handshake arrives.
4230 */
4231 if ((!(tp->t_mpflags & TMPF_MPTCP_TRUE)) &&
4232 (tp->t_mpflags & TMPF_SENT_JOIN)) {
4233 isconnected = FALSE;
4234 } else
4235 #endif /* MPTCP */
4236 isconnected = TRUE;
4237 if ((tp->t_tfo_flags & TFO_F_COOKIE_VALID)) {
4238 /* Done this when receiving the SYN */
4239 isconnected = FALSE;
4240
4241 OSDecrementAtomic(&tcp_tfo_halfcnt);
4242
4243 /* Panic if something has gone terribly wrong. */
4244 VERIFY(tcp_tfo_halfcnt >= 0);
4245
4246 tp->t_tfo_flags &= ~TFO_F_COOKIE_VALID;
4247 }
4248
4249 /*
4250 * In case there is data in the send-queue (e.g., TFO is being
4251 * used, or connectx+data has been done), then if we would
4252 * "FALLTHROUGH", we would handle this ACK as if data has been
4253 * acknowledged. But, we have to prevent this. And this
4254 * can be prevented by increasing snd_una by 1, so that the
4255 * SYN is not considered as data (snd_una++ is actually also
4256 * done in SYN_SENT-state as part of the regular TCP stack).
4257 *
4258 * In case there is data on this ack as well, the data will be
4259 * handled by the label "dodata" right after step6.
4260 */
4261 if (so->so_snd.sb_cc) {
4262 tp->snd_una++; /* SYN is acked */
4263 if (SEQ_LT(tp->snd_nxt, tp->snd_una)) {
4264 tp->snd_nxt = tp->snd_una;
4265 }
4266
4267 /*
4268 * No duplicate-ACK handling is needed. So, we
4269 * directly advance to processing the ACK (aka,
4270 * updating the RTT estimation,...)
4271 *
4272 * But, we first need to handle eventual SACKs,
4273 * because TFO will start sending data with the
4274 * SYN/ACK, so it might be that the client
4275 * includes a SACK with its ACK.
4276 */
4277 if (SACK_ENABLED(tp) &&
4278 (to.to_nsacks > 0 || !TAILQ_EMPTY(&tp->snd_holes))) {
4279 tcp_sack_doack(tp, &to, th, &sack_bytes_acked, &sack_bytes_newly_acked);
4280 }
4281
4282 goto process_ACK;
4283 }
4284
4285 OS_FALLTHROUGH;
4286
4287 /*
4288 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
4289 * ACKs. If the ack is in the range
4290 * tp->snd_una < th->th_ack <= tp->snd_max
4291 * then advance tp->snd_una to th->th_ack and drop
4292 * data from the retransmission queue. If this ACK reflects
4293 * more up to date window information we update our window information.
4294 */
4295 case TCPS_ESTABLISHED:
4296 case TCPS_FIN_WAIT_1:
4297 case TCPS_FIN_WAIT_2:
4298 case TCPS_CLOSE_WAIT:
4299 case TCPS_CLOSING:
4300 case TCPS_LAST_ACK:
4301 case TCPS_TIME_WAIT:
4302 if (SEQ_GT(th->th_ack, tp->snd_max)) {
4303 tcpstat.tcps_rcvacktoomuch++;
4304 if (tcp_is_ack_ratelimited(tp)) {
4305 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "rfc5961 rcvacktoomuch");
4306 goto drop;
4307 } else {
4308 goto dropafterack;
4309 }
4310 }
4311 if (SEQ_LT(th->th_ack, tp->snd_una - tp->max_sndwnd)) {
4312 if (tcp_is_ack_ratelimited(tp)) {
4313 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "rfc5961 bad ACK");
4314 goto drop;
4315 } else {
4316 goto dropafterack;
4317 }
4318 }
4319 if (SACK_ENABLED(tp) && to.to_nsacks > 0) {
4320 recvd_dsack = tcp_sack_process_dsack(tp, &to, th);
4321 /*
4322 * If DSACK is received and this packet has no
4323 * other SACK information, it can be dropped.
4324 * We do not want to treat it as a duplicate ack.
4325 */
4326 if (recvd_dsack &&
4327 SEQ_LEQ(th->th_ack, tp->snd_una) &&
4328 to.to_nsacks == 0) {
4329 tcp_bad_rexmt_check(tp, th, &to);
4330 goto drop;
4331 }
4332 }
4333
4334 if (SACK_ENABLED(tp) &&
4335 (to.to_nsacks > 0 || !TAILQ_EMPTY(&tp->snd_holes))) {
4336 tcp_sack_doack(tp, &to, th, &sack_bytes_acked, &sack_bytes_newly_acked);
4337 }
4338
4339 #if MPTCP
4340 if (tp->t_mpuna && SEQ_GEQ(th->th_ack, tp->t_mpuna)) {
4341 if (tp->t_mpflags & TMPF_PREESTABLISHED) {
4342 /* MP TCP establishment succeeded */
4343 tp->t_mpuna = 0;
4344 if (tp->t_mpflags & TMPF_JOINED_FLOW) {
4345 if (tp->t_mpflags & TMPF_SENT_JOIN) {
4346 tp->t_mpflags &=
4347 ~TMPF_PREESTABLISHED;
4348 tp->t_mpflags |=
4349 TMPF_MPTCP_TRUE;
4350
4351 tp->t_timer[TCPT_JACK_RXMT] = 0;
4352 tp->t_mprxtshift = 0;
4353 isconnected = TRUE;
4354 } else {
4355 isconnected = FALSE;
4356 }
4357 } else {
4358 isconnected = TRUE;
4359 }
4360 }
4361 }
4362 #endif /* MPTCP */
4363
4364 tcp_tfo_rcv_ack(tp, th);
4365
4366 /*
4367 * If we have outstanding data (other than
4368 * a window probe), this is a completely
4369 * duplicate ack and the ack is the biggest we've seen.
4370 *
4371 * Need to accommodate a change in window on duplicate acks
4372 * to allow operating systems that update window during
4373 * recovery with SACK
4374 */
4375 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
4376 if (tlen == 0 && (tiwin == tp->snd_wnd ||
4377 (to.to_nsacks > 0 && sack_bytes_acked > 0))) {
4378 uint32_t old_dupacks;
4379 /*
4380 * If both ends send FIN at the same time,
4381 * then the ack will be a duplicate ack
4382 * but we have to process the FIN. Check
4383 * for this condition and process the FIN
4384 * instead of the dupack
4385 */
4386 if ((thflags & TH_FIN) &&
4387 !TCPS_HAVERCVDFIN(tp->t_state)) {
4388 break;
4389 }
4390 process_dupack:
4391 old_dupacks = tp->t_dupacks;
4392 #if MPTCP
4393 /*
4394 * MPTCP options that are ignored must
4395 * not be treated as duplicate ACKs.
4396 */
4397 if (to.to_flags & TOF_MPTCP) {
4398 goto drop;
4399 }
4400
4401 if ((isconnected) && (tp->t_mpflags & TMPF_JOINED_FLOW)) {
4402 mptcplog((LOG_DEBUG, "MPTCP "
4403 "Sockets: bypass ack recovery\n"),
4404 MPTCP_SOCKET_DBG,
4405 MPTCP_LOGLVL_VERBOSE);
4406 break;
4407 }
4408 #endif /* MPTCP */
4409 /*
4410 * If a duplicate acknowledgement was seen
4411 * after ECN, it indicates packet loss in
4412 * addition to ECN. Reset INRECOVERY flag
4413 * so that we can process partial acks
4414 * correctly
4415 */
4416 if (tp->ecn_flags & TE_INRECOVERY) {
4417 tp->ecn_flags &= ~TE_INRECOVERY;
4418 }
4419
4420 tcpstat.tcps_rcvdupack++;
4421 if (SACK_ENABLED(tp) && tcp_do_better_lr) {
4422 tp->t_dupacks += max(1, sack_bytes_acked / tp->t_maxseg);
4423 } else {
4424 ++tp->t_dupacks;
4425 }
4426
4427 tp->sackhint.sack_bytes_acked += sack_bytes_acked;
4428
4429 if (SACK_ENABLED(tp) && tcp_do_better_lr) {
4430 tp->t_new_dupacks += (sack_bytes_newly_acked / tp->t_maxseg);
4431
4432 if (tp->t_new_dupacks >= tp->t_rexmtthresh && IN_FASTRECOVERY(tp)) {
4433 /* Let's restart the retransmission */
4434 tcp_sack_lost_rexmit(tp);
4435
4436 /*
4437 * If the current tcp cc module has
4438 * defined a hook for tasks to run
4439 * before entering FR, call it
4440 */
4441 if (CC_ALGO(tp)->pre_fr != NULL) {
4442 CC_ALGO(tp)->pre_fr(tp);
4443 }
4444
4445 ENTER_FASTRECOVERY(tp);
4446
4447 if (tp->t_flags & TF_SENTFIN) {
4448 tp->snd_recover = tp->snd_max - 1;
4449 } else {
4450 tp->snd_recover = tp->snd_max;
4451 }
4452 tp->t_rtttime = 0;
4453
4454 if (TCP_ECN_ENABLED(tp)) {
4455 tp->ecn_flags |= TE_SENDCWR;
4456 }
4457
4458 if (tp->t_flagsext & TF_CWND_NONVALIDATED) {
4459 tcp_cc_adjust_nonvalidated_cwnd(tp);
4460 } else {
4461 tp->snd_cwnd = tp->snd_ssthresh;
4462 }
4463 }
4464 }
4465
4466 /*
4467 * Check if we need to reset the limit on
4468 * early retransmit
4469 */
4470 if (tp->t_early_rexmt_count > 0 &&
4471 TSTMP_GEQ(tcp_now,
4472 (tp->t_early_rexmt_win +
4473 TCP_EARLY_REXMT_WIN))) {
4474 tp->t_early_rexmt_count = 0;
4475 }
4476
4477 /*
4478 * Is early retransmit needed? We check for
4479 * this when the connection is waiting for
4480 * duplicate acks to enter fast recovery.
4481 */
4482 if (!IN_FASTRECOVERY(tp)) {
4483 tcp_early_rexmt_check(tp, th);
4484 }
4485
4486 /*
4487 * If we've seen exactly rexmt threshold
4488 * of duplicate acks, assume a packet
4489 * has been dropped and retransmit it.
4490 * Kludge snd_nxt & the congestion
4491 * window so we send only this one
4492 * packet.
4493 *
4494 * We know we're losing at the current
4495 * window size so do congestion avoidance
4496 * (set ssthresh to half the current window
4497 * and pull our congestion window back to
4498 * the new ssthresh).
4499 *
4500 * Dup acks mean that packets have left the
4501 * network (they're now cached at the receiver)
4502 * so bump cwnd by the amount in the receiver
4503 * to keep a constant cwnd packets in the
4504 * network.
4505 */
4506 if (tp->t_timer[TCPT_REXMT] == 0 ||
4507 (th->th_ack != tp->snd_una && sack_bytes_acked == 0)) {
4508 tp->t_dupacks = 0;
4509 tp->t_rexmtthresh = tcprexmtthresh;
4510 tp->t_new_dupacks = 0;
4511 } else if ((tp->t_dupacks > tp->t_rexmtthresh && (!tcp_do_better_lr || old_dupacks >= tp->t_rexmtthresh)) ||
4512 IN_FASTRECOVERY(tp)) {
4513 /*
4514 * If this connection was seeing packet
4515 * reordering, then recovery might be
4516 * delayed to disambiguate between
4517 * reordering and loss
4518 */
4519 if (SACK_ENABLED(tp) && !IN_FASTRECOVERY(tp) &&
4520 (tp->t_flagsext &
4521 (TF_PKTS_REORDERED | TF_DELAY_RECOVERY)) ==
4522 (TF_PKTS_REORDERED | TF_DELAY_RECOVERY)) {
4523 /*
4524 * Since the SACK information is already
4525 * updated, this ACK will be dropped
4526 */
4527 break;
4528 }
4529
4530 /*
4531 * Dup acks mean that packets have left the
4532 * network (they're now cached at the receiver)
4533 * so bump cwnd by the amount in the receiver
4534 * to keep a constant cwnd packets in the
4535 * network.
4536 */
4537 if (SACK_ENABLED(tp) && IN_FASTRECOVERY(tp)) {
4538 int awnd;
4539
4540 /*
4541 * Compute the amount of data in flight first.
4542 * We can inject new data into the pipe iff
4543 * we have less than snd_ssthres worth of data in
4544 * flight.
4545 */
4546 awnd = (tp->snd_nxt - tp->snd_fack) + tp->sackhint.sack_bytes_rexmit;
4547 if (awnd < tp->snd_ssthresh) {
4548 tp->snd_cwnd += tp->t_maxseg;
4549 if (tp->snd_cwnd > tp->snd_ssthresh) {
4550 tp->snd_cwnd = tp->snd_ssthresh;
4551 }
4552 }
4553 } else {
4554 tp->snd_cwnd += tp->t_maxseg;
4555 }
4556
4557 /* Process any window updates */
4558 if (tiwin > tp->snd_wnd) {
4559 tcp_update_window(tp, thflags,
4560 th, tiwin, tlen);
4561 }
4562 tcp_ccdbg_trace(tp, th,
4563 TCP_CC_IN_FASTRECOVERY);
4564
4565 (void) tcp_output(tp);
4566
4567 goto drop;
4568 } else if ((!tcp_do_better_lr && tp->t_dupacks == tp->t_rexmtthresh) ||
4569 (tcp_do_better_lr && tp->t_dupacks >= tp->t_rexmtthresh)) {
4570 tcp_seq onxt = tp->snd_nxt;
4571
4572 /*
4573 * If we're doing sack, check to
4574 * see if we're already in sack
4575 * recovery. If we're not doing sack,
4576 * check to see if we're in newreno
4577 * recovery.
4578 */
4579 if (SACK_ENABLED(tp)) {
4580 if (IN_FASTRECOVERY(tp)) {
4581 tp->t_dupacks = 0;
4582 break;
4583 } else if (tp->t_flagsext & TF_DELAY_RECOVERY) {
4584 break;
4585 }
4586 } else {
4587 if (SEQ_LEQ(th->th_ack, tp->snd_recover)) {
4588 tp->t_dupacks = 0;
4589 break;
4590 }
4591 }
4592 if (tp->t_flags & TF_SENTFIN) {
4593 tp->snd_recover = tp->snd_max - 1;
4594 } else {
4595 tp->snd_recover = tp->snd_max;
4596 }
4597 tp->t_timer[TCPT_PTO] = 0;
4598 tp->t_rtttime = 0;
4599
4600 /*
4601 * If the connection has seen pkt
4602 * reordering, delay recovery until
4603 * it is clear that the packet
4604 * was lost.
4605 */
4606 if (SACK_ENABLED(tp) &&
4607 (tp->t_flagsext &
4608 (TF_PKTS_REORDERED | TF_DELAY_RECOVERY))
4609 == TF_PKTS_REORDERED &&
4610 !IN_FASTRECOVERY(tp) &&
4611 tp->t_reorderwin > 0 &&
4612 (tp->t_state == TCPS_ESTABLISHED ||
4613 tp->t_state == TCPS_FIN_WAIT_1)) {
4614 tp->t_timer[TCPT_DELAYFR] =
4615 OFFSET_FROM_START(tp,
4616 tp->t_reorderwin);
4617 tp->t_flagsext |= TF_DELAY_RECOVERY;
4618 tcpstat.tcps_delay_recovery++;
4619 tcp_ccdbg_trace(tp, th,
4620 TCP_CC_DELAY_FASTRECOVERY);
4621 break;
4622 }
4623
4624 tcp_rexmt_save_state(tp);
4625 /*
4626 * If the current tcp cc module has
4627 * defined a hook for tasks to run
4628 * before entering FR, call it
4629 */
4630 if (CC_ALGO(tp)->pre_fr != NULL) {
4631 CC_ALGO(tp)->pre_fr(tp);
4632 }
4633 ENTER_FASTRECOVERY(tp);
4634 tp->t_timer[TCPT_REXMT] = 0;
4635 if (TCP_ECN_ENABLED(tp)) {
4636 tp->ecn_flags |= TE_SENDCWR;
4637 }
4638
4639 if (SACK_ENABLED(tp)) {
4640 tcpstat.tcps_sack_recovery_episode++;
4641 tp->t_sack_recovery_episode++;
4642 tp->sack_newdata = tp->snd_nxt;
4643 if (tcp_do_better_lr) {
4644 tp->snd_cwnd = tp->snd_ssthresh;
4645 } else {
4646 tp->snd_cwnd = tp->t_maxseg;
4647 }
4648 tp->t_flagsext &= ~TF_CWND_NONVALIDATED;
4649
4650 /* Process any window updates */
4651 if (tiwin > tp->snd_wnd) {
4652 tcp_update_window(tp, thflags, th, tiwin, tlen);
4653 }
4654
4655 tcp_ccdbg_trace(tp, th, TCP_CC_ENTER_FASTRECOVERY);
4656 (void) tcp_output(tp);
4657 goto drop;
4658 }
4659 tp->snd_nxt = th->th_ack;
4660 tp->snd_cwnd = tp->t_maxseg;
4661
4662 /* Process any window updates */
4663 if (tiwin > tp->snd_wnd) {
4664 tcp_update_window(tp, thflags, th, tiwin, tlen);
4665 }
4666
4667 (void) tcp_output(tp);
4668 if (tp->t_flagsext & TF_CWND_NONVALIDATED) {
4669 tcp_cc_adjust_nonvalidated_cwnd(tp);
4670 } else {
4671 tp->snd_cwnd = tp->snd_ssthresh + tp->t_maxseg * tp->t_dupacks;
4672 }
4673 if (SEQ_GT(onxt, tp->snd_nxt)) {
4674 tp->snd_nxt = onxt;
4675 }
4676
4677 tcp_ccdbg_trace(tp, th, TCP_CC_ENTER_FASTRECOVERY);
4678 goto drop;
4679 } else if (ALLOW_LIMITED_TRANSMIT(tp) &&
4680 (!(SACK_ENABLED(tp)) || sack_bytes_acked > 0) &&
4681 (so->so_snd.sb_cc - (tp->snd_max - tp->snd_una)) > 0) {
4682 u_int32_t incr = (tp->t_maxseg * tp->t_dupacks);
4683
4684 /* Use Limited Transmit algorithm on the first two
4685 * duplicate acks when there is new data to transmit
4686 */
4687 tp->snd_cwnd += incr;
4688 tcpstat.tcps_limited_txt++;
4689 (void) tcp_output(tp);
4690
4691 tcp_ccdbg_trace(tp, th, TCP_CC_LIMITED_TRANSMIT);
4692
4693 /* Reset snd_cwnd back to normal */
4694 tp->snd_cwnd -= incr;
4695 }
4696 }
4697 break;
4698 }
4699 /*
4700 * If the congestion window was inflated to account
4701 * for the other side's cached packets, retract it.
4702 */
4703 if (IN_FASTRECOVERY(tp)) {
4704 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
4705 /*
4706 * If we received an ECE and entered
4707 * recovery, the subsequent ACKs should
4708 * not be treated as partial acks.
4709 */
4710 if (tp->ecn_flags & TE_INRECOVERY) {
4711 goto process_ACK;
4712 }
4713
4714 if (SACK_ENABLED(tp)) {
4715 tcp_sack_partialack(tp, th);
4716 } else {
4717 tcp_newreno_partial_ack(tp, th);
4718 }
4719 tcp_ccdbg_trace(tp, th, TCP_CC_PARTIAL_ACK);
4720 } else {
4721 if (tcp_cubic_minor_fixes) {
4722 exiting_fr = 1;
4723 }
4724 EXIT_FASTRECOVERY(tp);
4725 if (CC_ALGO(tp)->post_fr != NULL) {
4726 CC_ALGO(tp)->post_fr(tp, th);
4727 }
4728 tp->t_pipeack = 0;
4729 tcp_clear_pipeack_state(tp);
4730 tcp_ccdbg_trace(tp, th,
4731 TCP_CC_EXIT_FASTRECOVERY);
4732 }
4733 } else if ((tp->t_flagsext &
4734 (TF_PKTS_REORDERED | TF_DELAY_RECOVERY))
4735 == (TF_PKTS_REORDERED | TF_DELAY_RECOVERY)) {
4736 /*
4737 * If the ack acknowledges upto snd_recover or if
4738 * it acknowledges all the snd holes, exit
4739 * recovery and cancel the timer. Otherwise,
4740 * this is a partial ack. Wait for recovery timer
4741 * to enter recovery. The snd_holes have already
4742 * been updated.
4743 */
4744 if (SEQ_GEQ(th->th_ack, tp->snd_recover) ||
4745 TAILQ_EMPTY(&tp->snd_holes)) {
4746 tp->t_timer[TCPT_DELAYFR] = 0;
4747 tp->t_flagsext &= ~TF_DELAY_RECOVERY;
4748 EXIT_FASTRECOVERY(tp);
4749 tcp_ccdbg_trace(tp, th,
4750 TCP_CC_EXIT_FASTRECOVERY);
4751 }
4752 } else {
4753 /*
4754 * We were not in fast recovery. Reset the
4755 * duplicate ack counter.
4756 */
4757 tp->t_dupacks = 0;
4758 tp->t_rexmtthresh = tcprexmtthresh;
4759 tp->t_new_dupacks = 0;
4760 }
4761
4762 process_ACK:
4763 VERIFY(SEQ_GEQ(th->th_ack, tp->snd_una));
4764 acked = BYTES_ACKED(th, tp);
4765 tcpstat.tcps_rcvackpack++;
4766 tcpstat.tcps_rcvackbyte += acked;
4767
4768 /*
4769 * If the last packet was a retransmit, make sure
4770 * it was not spurious.
4771 *
4772 * This will also take care of congestion window
4773 * adjustment if a last packet was recovered due to a
4774 * tail loss probe.
4775 */
4776 tcp_bad_rexmt_check(tp, th, &to);
4777
4778 /* Recalculate the RTT */
4779 tcp_compute_rtt(tp, &to, th);
4780
4781 /*
4782 * If all outstanding data is acked, stop retransmit
4783 * timer and remember to restart (more output or persist).
4784 * If there is more data to be acked, restart retransmit
4785 * timer, using current (possibly backed-off) value.
4786 */
4787 TCP_RESET_REXMT_STATE(tp);
4788 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
4789 tp->t_rttmin, TCPTV_REXMTMAX,
4790 TCP_ADD_REXMTSLOP(tp));
4791 if (th->th_ack == tp->snd_max) {
4792 tp->t_timer[TCPT_REXMT] = 0;
4793 tp->t_timer[TCPT_PTO] = 0;
4794 needoutput = 1;
4795 } else if (tp->t_timer[TCPT_PERSIST] == 0) {
4796 tp->t_timer[TCPT_REXMT] = OFFSET_FROM_START(tp,
4797 tp->t_rxtcur);
4798 }
4799
4800 if ((prev_t_state == TCPS_SYN_SENT ||
4801 prev_t_state == TCPS_SYN_RECEIVED) &&
4802 tp->t_state == TCPS_ESTABLISHED) {
4803 TCP_LOG_RTT_INFO(tp);
4804 }
4805
4806 /*
4807 * If no data (only SYN) was ACK'd, skip rest of ACK
4808 * processing.
4809 */
4810 if (acked == 0) {
4811 goto step6;
4812 }
4813
4814 /*
4815 * When outgoing data has been acked (except the SYN+data), we
4816 * mark this connection as "sending good" for TFO.
4817 */
4818 if ((tp->t_tfo_stats & TFO_S_SYN_DATA_SENT) &&
4819 !(tp->t_tfo_flags & TFO_F_NO_SNDPROBING) &&
4820 !(th->th_flags & TH_SYN)) {
4821 tp->t_tfo_flags |= TFO_F_NO_SNDPROBING;
4822 }
4823
4824 /*
4825 * If TH_ECE is received, make sure that ECN is enabled
4826 * on that connection and we have sent ECT on data packets.
4827 */
4828 if ((thflags & TH_ECE) != 0 && TCP_ECN_ENABLED(tp) &&
4829 (tp->ecn_flags & TE_SENDIPECT)) {
4830 /*
4831 * Reduce the congestion window if we haven't
4832 * done so.
4833 */
4834 if (!IN_FASTRECOVERY(tp)) {
4835 tcp_reduce_congestion_window(tp);
4836 tp->ecn_flags |= (TE_INRECOVERY | TE_SENDCWR);
4837 /*
4838 * Also note that the connection received
4839 * ECE atleast once
4840 */
4841 tp->ecn_flags |= TE_RECV_ECN_ECE;
4842 INP_INC_IFNET_STAT(inp, ecn_recv_ece);
4843 tcpstat.tcps_ecn_recv_ece++;
4844 tcp_ccdbg_trace(tp, th, TCP_CC_ECN_RCVD);
4845 }
4846 }
4847
4848 /*
4849 * When new data is acked, open the congestion window.
4850 * The specifics of how this is achieved are up to the
4851 * congestion control algorithm in use for this connection.
4852 *
4853 * The calculations in this function assume that snd_una is
4854 * not updated yet.
4855 */
4856 if (!IN_FASTRECOVERY(tp) && !exiting_fr) {
4857 if (CC_ALGO(tp)->ack_rcvd != NULL) {
4858 CC_ALGO(tp)->ack_rcvd(tp, th);
4859 }
4860 tcp_ccdbg_trace(tp, th, TCP_CC_ACK_RCVD);
4861 }
4862 if (acked > so->so_snd.sb_cc) {
4863 tp->snd_wnd -= so->so_snd.sb_cc;
4864 sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
4865 ourfinisacked = 1;
4866 } else {
4867 sbdrop(&so->so_snd, acked);
4868 tcp_sbsnd_trim(&so->so_snd);
4869 tp->snd_wnd -= acked;
4870 ourfinisacked = 0;
4871 }
4872 /* detect una wraparound */
4873 if (!IN_FASTRECOVERY(tp) &&
4874 SEQ_GT(tp->snd_una, tp->snd_recover) &&
4875 SEQ_LEQ(th->th_ack, tp->snd_recover)) {
4876 tp->snd_recover = th->th_ack - 1;
4877 }
4878
4879 if (IN_FASTRECOVERY(tp) &&
4880 SEQ_GEQ(th->th_ack, tp->snd_recover)) {
4881 EXIT_FASTRECOVERY(tp);
4882 }
4883
4884 tcp_update_snd_una(tp, th->th_ack);
4885
4886 if (SACK_ENABLED(tp)) {
4887 if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
4888 tp->snd_recover = tp->snd_una;
4889 }
4890 }
4891 if (SEQ_LT(tp->snd_nxt, tp->snd_una)) {
4892 tp->snd_nxt = tp->snd_una;
4893 }
4894 if (!SLIST_EMPTY(&tp->t_rxt_segments) &&
4895 !TCP_DSACK_SEQ_IN_WINDOW(tp, tp->t_dsack_lastuna,
4896 tp->snd_una)) {
4897 tcp_rxtseg_clean(tp);
4898 }
4899 if ((tp->t_flagsext & TF_MEASURESNDBW) != 0 &&
4900 tp->t_bwmeas != NULL) {
4901 tcp_bwmeas_check(tp);
4902 }
4903
4904 write_wakeup = 1;
4905
4906 if (!SLIST_EMPTY(&tp->t_notify_ack)) {
4907 tcp_notify_acknowledgement(tp, so);
4908 }
4909
4910 switch (tp->t_state) {
4911 /*
4912 * In FIN_WAIT_1 STATE in addition to the processing
4913 * for the ESTABLISHED state if our FIN is now acknowledged
4914 * then enter FIN_WAIT_2.
4915 */
4916 case TCPS_FIN_WAIT_1:
4917 if (ourfinisacked) {
4918 /*
4919 * If we can't receive any more
4920 * data, then closing user can proceed.
4921 * Starting the TCPT_2MSL timer is contrary to the
4922 * specification, but if we don't get a FIN
4923 * we'll hang forever.
4924 */
4925 DTRACE_TCP4(state__change, void, NULL,
4926 struct inpcb *, inp,
4927 struct tcpcb *, tp,
4928 int32_t, TCPS_FIN_WAIT_2);
4929 tp->t_state = TCPS_FIN_WAIT_2;
4930 if (so->so_state & SS_CANTRCVMORE) {
4931 isconnected = FALSE;
4932 isdisconnected = TRUE;
4933 tcp_set_finwait_timeout(tp);
4934 }
4935 /*
4936 * fall through and make sure we also recognize
4937 * data ACKed with the FIN
4938 */
4939 }
4940 break;
4941
4942 /*
4943 * In CLOSING STATE in addition to the processing for
4944 * the ESTABLISHED state if the ACK acknowledges our FIN
4945 * then enter the TIME-WAIT state, otherwise ignore
4946 * the segment.
4947 */
4948 case TCPS_CLOSING:
4949 if (ourfinisacked) {
4950 DTRACE_TCP4(state__change, void, NULL,
4951 struct inpcb *, inp,
4952 struct tcpcb *, tp,
4953 int32_t, TCPS_TIME_WAIT);
4954 tp->t_state = TCPS_TIME_WAIT;
4955 tcp_canceltimers(tp);
4956 if (tp->t_flagsext & TF_NOTIMEWAIT) {
4957 tp->t_flags |= TF_CLOSING;
4958 } else {
4959 add_to_time_wait(tp, 2 * tcp_msl);
4960 }
4961 isconnected = FALSE;
4962 isdisconnected = TRUE;
4963 }
4964 break;
4965
4966 /*
4967 * In LAST_ACK, we may still be waiting for data to drain
4968 * and/or to be acked, as well as for the ack of our FIN.
4969 * If our FIN is now acknowledged, delete the TCB,
4970 * enter the closed state and return.
4971 */
4972 case TCPS_LAST_ACK:
4973 if (ourfinisacked) {
4974 tp = tcp_close(tp);
4975 goto drop;
4976 }
4977 break;
4978
4979 /*
4980 * In TIME_WAIT state the only thing that should arrive
4981 * is a retransmission of the remote FIN. Acknowledge
4982 * it and restart the finack timer.
4983 */
4984 case TCPS_TIME_WAIT:
4985 add_to_time_wait(tp, 2 * tcp_msl);
4986 goto dropafterack;
4987 }
4988
4989 /*
4990 * If there is a SACK option on the ACK and we
4991 * haven't seen any duplicate acks before, count
4992 * it as a duplicate ack even if the cumulative
4993 * ack is advanced. If the receiver delayed an
4994 * ack and detected loss afterwards, then the ack
4995 * will advance cumulative ack and will also have
4996 * a SACK option. So counting it as one duplicate
4997 * ack is ok.
4998 */
4999 if (tp->t_state == TCPS_ESTABLISHED &&
5000 SACK_ENABLED(tp) && sack_bytes_acked > 0 &&
5001 to.to_nsacks > 0 && tp->t_dupacks == 0 &&
5002 SEQ_LEQ(th->th_ack, tp->snd_una) && tlen == 0 &&
5003 !(tp->t_flagsext & TF_PKTS_REORDERED)) {
5004 tcpstat.tcps_sack_ackadv++;
5005 goto process_dupack;
5006 }
5007 }
5008
5009 step6:
5010 /*
5011 * Update window information.
5012 */
5013 if (tcp_update_window(tp, thflags, th, tiwin, tlen)) {
5014 needoutput = 1;
5015 }
5016
5017 /*
5018 * Process segments with URG.
5019 */
5020 if ((thflags & TH_URG) && th->th_urp &&
5021 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
5022 /*
5023 * This is a kludge, but if we receive and accept
5024 * random urgent pointers, we'll crash in
5025 * soreceive. It's hard to imagine someone
5026 * actually wanting to send this much urgent data.
5027 */
5028 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
5029 th->th_urp = 0; /* XXX */
5030 thflags &= ~TH_URG; /* XXX */
5031 goto dodata; /* XXX */
5032 }
5033 /*
5034 * If this segment advances the known urgent pointer,
5035 * then mark the data stream. This should not happen
5036 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
5037 * a FIN has been received from the remote side.
5038 * In these states we ignore the URG.
5039 *
5040 * According to RFC961 (Assigned Protocols),
5041 * the urgent pointer points to the last octet
5042 * of urgent data. We continue, however,
5043 * to consider it to indicate the first octet
5044 * of data past the urgent section as the original
5045 * spec states (in one of two places).
5046 */
5047 if (SEQ_GT(th->th_seq + th->th_urp, tp->rcv_up)) {
5048 tp->rcv_up = th->th_seq + th->th_urp;
5049 so->so_oobmark = so->so_rcv.sb_cc +
5050 (tp->rcv_up - tp->rcv_nxt) - 1;
5051 if (so->so_oobmark == 0) {
5052 so->so_state |= SS_RCVATMARK;
5053 }
5054 sohasoutofband(so);
5055 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
5056 }
5057 /*
5058 * Remove out of band data so doesn't get presented to user.
5059 * This can happen independent of advancing the URG pointer,
5060 * but if two URG's are pending at once, some out-of-band
5061 * data may creep in... ick.
5062 */
5063 if (th->th_urp <= (u_int32_t)tlen
5064 #if SO_OOBINLINE
5065 && (so->so_options & SO_OOBINLINE) == 0
5066 #endif
5067 ) {
5068 tcp_pulloutofband(so, th, m,
5069 drop_hdrlen); /* hdr drop is delayed */
5070 }
5071 } else {
5072 /*
5073 * If no out of band data is expected,
5074 * pull receive urgent pointer along
5075 * with the receive window.
5076 */
5077 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up)) {
5078 tp->rcv_up = tp->rcv_nxt;
5079 }
5080 }
5081 dodata:
5082
5083 /* Set socket's connect or disconnect state correcly before doing data.
5084 * The following might unlock the socket if there is an upcall or a socket
5085 * filter.
5086 */
5087 if (isconnected) {
5088 soisconnected(so);
5089 } else if (isdisconnected) {
5090 soisdisconnected(so);
5091 }
5092
5093 /* Let's check the state of pcb just to make sure that it did not get closed
5094 * when we unlocked above
5095 */
5096 if (inp->inp_state == INPCB_STATE_DEAD) {
5097 /* Just drop the packet that we are processing and return */
5098 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "INPCB_STATE_DEAD");
5099 goto drop;
5100 }
5101
5102 /*
5103 * Process the segment text, merging it into the TCP sequencing queue,
5104 * and arranging for acknowledgment of receipt if necessary.
5105 * This process logically involves adjusting tp->rcv_wnd as data
5106 * is presented to the user (this happens in tcp_usrreq.c,
5107 * case PRU_RCVD). If a FIN has already been received on this
5108 * connection then we just ignore the text.
5109 *
5110 * If we are in SYN-received state and got a valid TFO cookie, we want
5111 * to process the data.
5112 */
5113 if ((tlen || (thflags & TH_FIN)) &&
5114 TCPS_HAVERCVDFIN(tp->t_state) == 0 &&
5115 (TCPS_HAVEESTABLISHED(tp->t_state) ||
5116 (tp->t_state == TCPS_SYN_RECEIVED &&
5117 (tp->t_tfo_flags & TFO_F_COOKIE_VALID)))) {
5118 tcp_seq save_start = th->th_seq;
5119 tcp_seq save_end = th->th_seq + tlen;
5120 m_adj(m, drop_hdrlen); /* delayed header drop */
5121 /*
5122 * Insert segment which includes th into TCP reassembly queue
5123 * with control block tp. Set thflags to whether reassembly now
5124 * includes a segment with FIN. This handles the common case
5125 * inline (segment is the next to be received on an established
5126 * connection, and the queue is empty), avoiding linkage into
5127 * and removal from the queue and repetition of various
5128 * conversions.
5129 * Set DELACK for segments received in order, but ack
5130 * immediately when segments are out of order (so
5131 * fast retransmit can work).
5132 */
5133 if (th->th_seq == tp->rcv_nxt && LIST_EMPTY(&tp->t_segq)) {
5134 TCP_INC_VAR(tp->t_unacksegs, segment_count);
5135
5136 /* Calculate the RTT on the receiver */
5137 tcp_compute_rcv_rtt(tp, &to, th);
5138
5139 if (DELAY_ACK(tp, th) &&
5140 ((tp->t_flags & TF_ACKNOW) == 0)) {
5141 if ((tp->t_flags & TF_DELACK) == 0) {
5142 tp->t_flags |= TF_DELACK;
5143 tp->t_timer[TCPT_DELACK] =
5144 OFFSET_FROM_START(tp, tcp_delack);
5145 }
5146 } else {
5147 tp->t_flags |= TF_ACKNOW;
5148 }
5149 tp->rcv_nxt += tlen;
5150 /* Update highest received sequence and its timestamp */
5151 if (SEQ_LT(tp->rcv_high, tp->rcv_nxt)) {
5152 tp->rcv_high = tp->rcv_nxt;
5153 if (to.to_flags & TOF_TS) {
5154 tp->tsv_high = to.to_tsval;
5155 }
5156 }
5157
5158 thflags = th->th_flags & TH_FIN;
5159 TCP_INC_VAR(tcpstat.tcps_rcvpack, segment_count);
5160 tcpstat.tcps_rcvbyte += tlen;
5161 if (nstat_collect) {
5162 INP_ADD_STAT(inp, cell, wifi, wired,
5163 rxpackets, 1);
5164 INP_ADD_STAT(inp, cell, wifi, wired,
5165 rxbytes, tlen);
5166 inp_set_activity_bitmap(inp);
5167 }
5168 tcp_sbrcv_grow(tp, &so->so_rcv, &to, tlen);
5169 if (TCP_USE_RLEDBAT(tp, so) &&
5170 tcp_cc_rledbat.data_rcvd != NULL) {
5171 tcp_cc_rledbat.data_rcvd(tp, th, &to, tlen);
5172 }
5173
5174 so_recv_data_stat(so, m, drop_hdrlen);
5175
5176 if (isipv6) {
5177 memcpy(&saved_hdr, ip6, sizeof(struct ip6_hdr));
5178 ip6 = (struct ip6_hdr *)&saved_hdr[0];
5179 } else {
5180 memcpy(&saved_hdr, ip, ip->ip_hl << 2);
5181 ip = (struct ip *)&saved_hdr[0];
5182 }
5183 memcpy(&saved_tcphdr, th, sizeof(struct tcphdr));
5184
5185 if (th->th_flags & TH_PUSH) {
5186 tp->t_flagsext |= TF_LAST_IS_PSH;
5187 } else {
5188 tp->t_flagsext &= ~TF_LAST_IS_PSH;
5189 }
5190
5191 if (sbappendstream_rcvdemux(so, m)) {
5192 read_wakeup = 1;
5193 }
5194 th = &saved_tcphdr;
5195 } else {
5196 if (isipv6) {
5197 memcpy(&saved_hdr, ip6, sizeof(struct ip6_hdr));
5198 ip6 = (struct ip6_hdr *)&saved_hdr[0];
5199 } else {
5200 memcpy(&saved_hdr, ip, ip->ip_hl << 2);
5201 ip = (struct ip *)&saved_hdr[0];
5202 }
5203
5204 /* Update highest received sequence and its timestamp */
5205 if (SEQ_LT(tp->rcv_high, th->th_seq + tlen)) {
5206 tp->rcv_high = th->th_seq + tlen;
5207 if (to.to_flags & TOF_TS) {
5208 tp->tsv_high = to.to_tsval;
5209 }
5210 }
5211
5212 /*
5213 * Calculate the RTT on the receiver,
5214 * even if OOO segment is received.
5215 */
5216 tcp_compute_rcv_rtt(tp, &to, th);
5217
5218 if (tcp_autotune_reorder) {
5219 tcp_sbrcv_grow(tp, &so->so_rcv, &to, tlen);
5220 }
5221 if (TCP_USE_RLEDBAT(tp, so) &&
5222 tcp_cc_rledbat.data_rcvd != NULL) {
5223 tcp_cc_rledbat.data_rcvd(tp, th, &to, tlen);
5224 }
5225
5226 memcpy(&saved_tcphdr, th, sizeof(struct tcphdr));
5227 thflags = tcp_reass(tp, th, &tlen, m, ifp, &read_wakeup);
5228 th = &saved_tcphdr;
5229 tp->t_flags |= TF_ACKNOW;
5230 }
5231
5232 if ((tlen > 0 || (th->th_flags & TH_FIN)) && SACK_ENABLED(tp)) {
5233 if (th->th_flags & TH_FIN) {
5234 save_end++;
5235 }
5236 tcp_update_sack_list(tp, save_start, save_end);
5237 }
5238
5239 tcp_adaptive_rwtimo_check(tp, tlen);
5240
5241 if (tlen > 0) {
5242 tcp_tfo_rcv_data(tp);
5243 }
5244
5245 if (tp->t_flags & TF_DELACK) {
5246 if (isipv6) {
5247 KERNEL_DEBUG(DBG_LAYER_END, ((th->th_dport << 16) | th->th_sport),
5248 (((ip6->ip6_src.s6_addr16[0]) << 16) | (ip6->ip6_dst.s6_addr16[0])),
5249 th->th_seq, th->th_ack, th->th_win);
5250 } else {
5251 KERNEL_DEBUG(DBG_LAYER_END, ((th->th_dport << 16) | th->th_sport),
5252 (((ip->ip_src.s_addr & 0xffff) << 16) | (ip->ip_dst.s_addr & 0xffff)),
5253 th->th_seq, th->th_ack, th->th_win);
5254 }
5255 }
5256 } else {
5257 if ((so->so_flags & SOF_MP_SUBFLOW) && tlen == 0 &&
5258 (m->m_pkthdr.pkt_flags & PKTF_MPTCP_DFIN) &&
5259 (m->m_pkthdr.pkt_flags & PKTF_MPTCP)) {
5260 m_adj(m, drop_hdrlen); /* delayed header drop */
5261 /*
5262 * 0-length DATA_FIN. The rlen is actually 0. We special-case the
5263 * byte consumed by the dfin in mptcp_input and mptcp_reass_present
5264 */
5265 m->m_pkthdr.mp_rlen = 0;
5266 mptcp_input(tptomptp(tp)->mpt_mpte, m);
5267 tp->t_flags |= TF_ACKNOW;
5268 } else {
5269 m_freem(m);
5270 }
5271 thflags &= ~TH_FIN;
5272 }
5273
5274 /*
5275 * If FIN is received ACK the FIN and let the user know
5276 * that the connection is closing.
5277 */
5278 if (thflags & TH_FIN) {
5279 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
5280 socantrcvmore(so);
5281 /*
5282 * If connection is half-synchronized
5283 * (ie NEEDSYN flag on) then delay ACK,
5284 * so it may be piggybacked when SYN is sent.
5285 * Otherwise, since we received a FIN then no
5286 * more input can be expected, send ACK now.
5287 */
5288 TCP_INC_VAR(tp->t_unacksegs, segment_count);
5289 tp->t_flags |= TF_ACKNOW;
5290 tp->rcv_nxt++;
5291 }
5292 switch (tp->t_state) {
5293 /*
5294 * In SYN_RECEIVED and ESTABLISHED STATES
5295 * enter the CLOSE_WAIT state.
5296 */
5297 case TCPS_SYN_RECEIVED:
5298 tp->t_starttime = tcp_now;
5299 OS_FALLTHROUGH;
5300 case TCPS_ESTABLISHED:
5301 DTRACE_TCP4(state__change, void, NULL, struct inpcb *, inp,
5302 struct tcpcb *, tp, int32_t, TCPS_CLOSE_WAIT);
5303 tp->t_state = TCPS_CLOSE_WAIT;
5304 break;
5305
5306 /*
5307 * If still in FIN_WAIT_1 STATE FIN has not been acked so
5308 * enter the CLOSING state.
5309 */
5310 case TCPS_FIN_WAIT_1:
5311 DTRACE_TCP4(state__change, void, NULL, struct inpcb *, inp,
5312 struct tcpcb *, tp, int32_t, TCPS_CLOSING);
5313 tp->t_state = TCPS_CLOSING;
5314 break;
5315
5316 /*
5317 * In FIN_WAIT_2 state enter the TIME_WAIT state,
5318 * starting the time-wait timer, turning off the other
5319 * standard timers.
5320 */
5321 case TCPS_FIN_WAIT_2:
5322 DTRACE_TCP4(state__change, void, NULL,
5323 struct inpcb *, inp,
5324 struct tcpcb *, tp,
5325 int32_t, TCPS_TIME_WAIT);
5326 tp->t_state = TCPS_TIME_WAIT;
5327 tcp_canceltimers(tp);
5328 tp->t_flags |= TF_ACKNOW;
5329 if (tp->t_flagsext & TF_NOTIMEWAIT) {
5330 tp->t_flags |= TF_CLOSING;
5331 } else {
5332 add_to_time_wait(tp, 2 * tcp_msl);
5333 }
5334 soisdisconnected(so);
5335 break;
5336
5337 /*
5338 * In TIME_WAIT state restart the 2 MSL time_wait timer.
5339 */
5340 case TCPS_TIME_WAIT:
5341 add_to_time_wait(tp, 2 * tcp_msl);
5342 break;
5343 }
5344 }
5345 #if TCPDEBUG
5346 if (so->so_options & SO_DEBUG) {
5347 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
5348 &tcp_savetcp, 0);
5349 }
5350 #endif
5351
5352 if (read_wakeup) {
5353 mptcp_handle_input(so);
5354 }
5355
5356 /*
5357 * Return any desired output.
5358 */
5359 if (needoutput || (tp->t_flags & TF_ACKNOW)) {
5360 (void) tcp_output(tp);
5361 }
5362
5363 tcp_check_timer_state(tp);
5364
5365 tcp_handle_wakeup(so, read_wakeup, write_wakeup);
5366
5367 socket_unlock(so, 1);
5368 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
5369 return;
5370
5371 dropafterack:
5372 /*
5373 * Generate an ACK dropping incoming segment if it occupies
5374 * sequence space, where the ACK reflects our state.
5375 *
5376 * We can now skip the test for the RST flag since all
5377 * paths to this code happen after packets containing
5378 * RST have been dropped.
5379 *
5380 * In the SYN-RECEIVED state, don't send an ACK unless the
5381 * segment we received passes the SYN-RECEIVED ACK test.
5382 * If it fails send a RST. This breaks the loop in the
5383 * "LAND" DoS attack, and also prevents an ACK storm
5384 * between two listening ports that have been sent forged
5385 * SYN segments, each with the source address of the other.
5386 */
5387 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
5388 (SEQ_GT(tp->snd_una, th->th_ack) ||
5389 SEQ_GT(th->th_ack, tp->snd_max))) {
5390 IF_TCP_STATINC(ifp, dospacket);
5391 goto dropwithreset;
5392 }
5393 #if TCPDEBUG
5394 if (so->so_options & SO_DEBUG) {
5395 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
5396 &tcp_savetcp, 0);
5397 }
5398 #endif
5399 m_freem(m);
5400 tp->t_flags |= TF_ACKNOW;
5401
5402 (void) tcp_output(tp);
5403
5404 tcp_handle_wakeup(so, read_wakeup, write_wakeup);
5405
5406 /* Don't need to check timer state as we should have done it during tcp_output */
5407 socket_unlock(so, 1);
5408 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
5409 return;
5410 dropwithresetnosock:
5411 nosock = 1;
5412 dropwithreset:
5413 /*
5414 * Generate a RST, dropping incoming segment.
5415 * Make ACK acceptable to originator of segment.
5416 * Don't bother to respond if destination was broadcast/multicast.
5417 */
5418 if ((thflags & TH_RST) || m->m_flags & (M_BCAST | M_MCAST)) {
5419 goto drop;
5420 }
5421 if (isipv6) {
5422 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
5423 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
5424 goto drop;
5425 }
5426 } else if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
5427 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
5428 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
5429 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
5430 goto drop;
5431 }
5432 /* IPv6 anycast check is done at tcp6_input() */
5433
5434 #if TCPDEBUG
5435 if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG)) {
5436 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
5437 &tcp_savetcp, 0);
5438 }
5439 #endif
5440 bzero(&tra, sizeof(tra));
5441 tra.ifscope = ifscope;
5442 tra.awdl_unrestricted = 1;
5443 tra.intcoproc_allowed = 1;
5444 if (thflags & TH_ACK) {
5445 /* mtod() below is safe as long as hdr dropping is delayed */
5446 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
5447 TH_RST, &tra);
5448 } else {
5449 if (thflags & TH_SYN) {
5450 tlen++;
5451 }
5452 /* mtod() below is safe as long as hdr dropping is delayed */
5453 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq + tlen,
5454 (tcp_seq)0, TH_RST | TH_ACK, &tra);
5455 }
5456 /* destroy temporarily created socket */
5457 if (dropsocket) {
5458 (void) soabort(so);
5459 socket_unlock(so, 1);
5460 } else if ((inp != NULL) && (nosock == 0)) {
5461 tcp_handle_wakeup(so, read_wakeup, write_wakeup);
5462
5463 socket_unlock(so, 1);
5464 }
5465 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
5466 return;
5467 dropnosock:
5468 nosock = 1;
5469 drop:
5470 /*
5471 * Drop space held by incoming segment and return.
5472 */
5473 #if TCPDEBUG
5474 if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG)) {
5475 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
5476 &tcp_savetcp, 0);
5477 }
5478 #endif
5479 m_freem(m);
5480 /* destroy temporarily created socket */
5481 if (dropsocket) {
5482 (void) soabort(so);
5483 socket_unlock(so, 1);
5484 } else if (nosock == 0) {
5485 tcp_handle_wakeup(so, read_wakeup, write_wakeup);
5486
5487 socket_unlock(so, 1);
5488 }
5489 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
5490 return;
5491 }
5492
5493 /*
5494 * Parse TCP options and place in tcpopt.
5495 */
5496 static void
tcp_dooptions(struct tcpcb * tp,u_char * cp,int cnt,struct tcphdr * th,struct tcpopt * to)5497 tcp_dooptions(struct tcpcb *tp, u_char *cp, int cnt, struct tcphdr *th,
5498 struct tcpopt *to)
5499 {
5500 u_short mss = 0;
5501 uint8_t opt, optlen;
5502
5503 for (; cnt > 0; cnt -= optlen, cp += optlen) {
5504 opt = cp[0];
5505 if (opt == TCPOPT_EOL) {
5506 break;
5507 }
5508 if (opt == TCPOPT_NOP) {
5509 optlen = 1;
5510 } else {
5511 if (cnt < 2) {
5512 break;
5513 }
5514 optlen = cp[1];
5515 if (optlen < 2 || optlen > cnt) {
5516 break;
5517 }
5518 }
5519 switch (opt) {
5520 default:
5521 continue;
5522
5523 case TCPOPT_MAXSEG:
5524 if (optlen != TCPOLEN_MAXSEG) {
5525 continue;
5526 }
5527 if (!(th->th_flags & TH_SYN)) {
5528 continue;
5529 }
5530 bcopy((char *) cp + 2, (char *) &mss, sizeof(mss));
5531 NTOHS(mss);
5532 to->to_mss = mss;
5533 to->to_flags |= TOF_MSS;
5534 break;
5535
5536 case TCPOPT_WINDOW:
5537 if (optlen != TCPOLEN_WINDOW) {
5538 continue;
5539 }
5540 if (!(th->th_flags & TH_SYN)) {
5541 continue;
5542 }
5543 to->to_flags |= TOF_SCALE;
5544 to->to_requested_s_scale = MIN(cp[2], TCP_MAX_WINSHIFT);
5545 break;
5546
5547 case TCPOPT_TIMESTAMP:
5548 if (optlen != TCPOLEN_TIMESTAMP) {
5549 continue;
5550 }
5551 to->to_flags |= TOF_TS;
5552 bcopy((char *)cp + 2,
5553 (char *)&to->to_tsval, sizeof(to->to_tsval));
5554 NTOHL(to->to_tsval);
5555 bcopy((char *)cp + 6,
5556 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
5557 NTOHL(to->to_tsecr);
5558 to->to_tsecr -= tp->t_ts_offset;
5559 /* Re-enable sending Timestamps if we received them */
5560 if (!(tp->t_flags & TF_REQ_TSTMP)) {
5561 tp->t_flags |= TF_REQ_TSTMP;
5562 }
5563 break;
5564 case TCPOPT_SACK_PERMITTED:
5565 if (optlen != TCPOLEN_SACK_PERMITTED) {
5566 continue;
5567 }
5568 if (th->th_flags & TH_SYN) {
5569 to->to_flags |= TOF_SACK;
5570 }
5571 break;
5572 case TCPOPT_SACK:
5573 if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0) {
5574 continue;
5575 }
5576 to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
5577 to->to_sacks = cp + 2;
5578 tcpstat.tcps_sack_rcv_blocks++;
5579
5580 break;
5581 case TCPOPT_FASTOPEN:
5582 if (optlen == TCPOLEN_FASTOPEN_REQ) {
5583 if (tp->t_state != TCPS_LISTEN) {
5584 continue;
5585 }
5586
5587 to->to_flags |= TOF_TFOREQ;
5588 } else {
5589 if (optlen < TCPOLEN_FASTOPEN_REQ ||
5590 (optlen - TCPOLEN_FASTOPEN_REQ) > TFO_COOKIE_LEN_MAX ||
5591 (optlen - TCPOLEN_FASTOPEN_REQ) < TFO_COOKIE_LEN_MIN) {
5592 continue;
5593 }
5594 if (tp->t_state != TCPS_LISTEN &&
5595 tp->t_state != TCPS_SYN_SENT) {
5596 continue;
5597 }
5598
5599 to->to_flags |= TOF_TFO;
5600 to->to_tfo = cp + 1;
5601 }
5602
5603 break;
5604 #if MPTCP
5605 case TCPOPT_MULTIPATH:
5606 tcp_do_mptcp_options(tp, cp, th, to, optlen);
5607 break;
5608 #endif /* MPTCP */
5609 }
5610 }
5611 }
5612
5613 static void
tcp_finalize_options(struct tcpcb * tp,struct tcpopt * to,unsigned int ifscope)5614 tcp_finalize_options(struct tcpcb *tp, struct tcpopt *to, unsigned int ifscope)
5615 {
5616 if (to->to_flags & TOF_TS) {
5617 tp->t_flags |= TF_RCVD_TSTMP;
5618 tp->ts_recent = to->to_tsval;
5619 tp->ts_recent_age = tcp_now;
5620 }
5621 if (to->to_flags & TOF_MSS) {
5622 tcp_mss(tp, to->to_mss, ifscope);
5623 }
5624 if (SACK_ENABLED(tp)) {
5625 if (!(to->to_flags & TOF_SACK)) {
5626 tp->t_flagsext &= ~(TF_SACK_ENABLE);
5627 } else {
5628 tp->t_flags |= TF_SACK_PERMIT;
5629 }
5630 }
5631 if (to->to_flags & TOF_SCALE) {
5632 tp->t_flags |= TF_RCVD_SCALE;
5633 tp->requested_s_scale = to->to_requested_s_scale;
5634
5635 /* Re-enable window scaling, if the option is received */
5636 if (tp->request_r_scale > 0) {
5637 tp->t_flags |= TF_REQ_SCALE;
5638 }
5639 }
5640 }
5641
5642 /*
5643 * Pull out of band byte out of a segment so
5644 * it doesn't appear in the user's data queue.
5645 * It is still reflected in the segment length for
5646 * sequencing purposes.
5647 *
5648 * @param off delayed to be droped hdrlen
5649 */
5650 static void
tcp_pulloutofband(struct socket * so,struct tcphdr * th,struct mbuf * m,int off)5651 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m, int off)
5652 {
5653 int cnt = off + th->th_urp - 1;
5654
5655 while (cnt >= 0) {
5656 if (m->m_len > cnt) {
5657 char *cp = mtod(m, caddr_t) + cnt;
5658 struct tcpcb *tp = sototcpcb(so);
5659
5660 tp->t_iobc = *cp;
5661 tp->t_oobflags |= TCPOOB_HAVEDATA;
5662 bcopy(cp + 1, cp, (unsigned)(m->m_len - cnt - 1));
5663 m->m_len--;
5664 if (m->m_flags & M_PKTHDR) {
5665 m->m_pkthdr.len--;
5666 }
5667 return;
5668 }
5669 cnt -= m->m_len;
5670 m = m->m_next;
5671 if (m == 0) {
5672 break;
5673 }
5674 }
5675 panic("tcp_pulloutofband");
5676 }
5677
5678 uint32_t
get_base_rtt(struct tcpcb * tp)5679 get_base_rtt(struct tcpcb *tp)
5680 {
5681 struct rtentry *rt = tp->t_inpcb->inp_route.ro_rt;
5682 return (rt == NULL) ? 0 : rt->rtt_min;
5683 }
5684
5685 static void
update_curr_rtt(struct tcpcb * tp,uint32_t rtt)5686 update_curr_rtt(struct tcpcb * tp, uint32_t rtt)
5687 {
5688 tp->curr_rtt_index = (tp->curr_rtt_index + 1) % NCURR_RTT_HIST;
5689 tp->curr_rtt_hist[tp->curr_rtt_index] = rtt;
5690
5691 /* forget the old value and update minimum */
5692 tp->curr_rtt_min = 0;
5693 for (int i = 0; i < NCURR_RTT_HIST; ++i) {
5694 if (tp->curr_rtt_hist[i] != 0 && (tp->curr_rtt_min == 0 ||
5695 tp->curr_rtt_hist[i] < tp->curr_rtt_min)) {
5696 tp->curr_rtt_min = tp->curr_rtt_hist[i];
5697 }
5698 }
5699 }
5700
5701 /* Each value of RTT base represents the minimum RTT seen in a minute.
5702 * We keep upto N_RTT_BASE minutes worth of history.
5703 */
5704 void
update_base_rtt(struct tcpcb * tp,uint32_t rtt)5705 update_base_rtt(struct tcpcb *tp, uint32_t rtt)
5706 {
5707 u_int32_t base_rtt, i;
5708 struct rtentry *rt;
5709
5710 if ((rt = tp->t_inpcb->inp_route.ro_rt) == NULL) {
5711 return;
5712 }
5713 if (rt->rtt_expire_ts == 0) {
5714 RT_LOCK_SPIN(rt);
5715 if (rt->rtt_expire_ts != 0) {
5716 RT_UNLOCK(rt);
5717 goto update;
5718 }
5719 rt->rtt_expire_ts = tcp_now;
5720 rt->rtt_index = 0;
5721 rt->rtt_hist[0] = rtt;
5722 rt->rtt_min = rtt;
5723 RT_UNLOCK(rt);
5724
5725 tp->curr_rtt_index = 0;
5726 tp->curr_rtt_hist[0] = rtt;
5727 tp->curr_rtt_min = rtt;
5728 return;
5729 }
5730 update:
5731 #if TRAFFIC_MGT
5732 /*
5733 * If the recv side is being throttled, check if the
5734 * current RTT is closer to the base RTT seen in
5735 * first (recent) two slots. If so, unthrottle the stream.
5736 */
5737 if ((tp->t_flagsext & TF_RECV_THROTTLE) &&
5738 (int)(tcp_now - tp->t_recv_throttle_ts) >= TCP_RECV_THROTTLE_WIN) {
5739 base_rtt = rt->rtt_min;
5740 if (tp->t_rttcur <= (base_rtt + target_qdelay)) {
5741 tp->t_flagsext &= ~TF_RECV_THROTTLE;
5742 tp->t_recv_throttle_ts = 0;
5743 }
5744 }
5745 #endif /* TRAFFIC_MGT */
5746
5747 /* Update the next current RTT sample */
5748 update_curr_rtt(tp, rtt);
5749
5750 if ((int)(tcp_now - rt->rtt_expire_ts) >=
5751 TCP_RTT_HISTORY_EXPIRE_TIME) {
5752 RT_LOCK_SPIN(rt);
5753 /* check the condition again to avoid race */
5754 if ((int)(tcp_now - rt->rtt_expire_ts) >=
5755 TCP_RTT_HISTORY_EXPIRE_TIME) {
5756 /* Set the base rtt to 0 for idle periods */
5757 uint32_t times = MIN((tcp_now - rt->rtt_expire_ts) /
5758 TCP_RTT_HISTORY_EXPIRE_TIME, NRTT_HIST + 1);
5759
5760 for (i = rt->rtt_index + 1; i < rt->rtt_index + times; i++) {
5761 rt->rtt_hist[i % NRTT_HIST] = 0;
5762 }
5763
5764 rt->rtt_index = i % NRTT_HIST;
5765 rt->rtt_hist[rt->rtt_index] = rtt;
5766 rt->rtt_expire_ts = tcp_now;
5767 } else {
5768 rt->rtt_hist[rt->rtt_index] =
5769 min(rt->rtt_hist[rt->rtt_index], rtt);
5770 }
5771 /* forget the old value and update minimum */
5772 rt->rtt_min = 0;
5773 for (i = 0; i < NRTT_HIST; ++i) {
5774 if (rt->rtt_hist[i] != 0 &&
5775 (rt->rtt_min == 0 ||
5776 rt->rtt_hist[i] < rt->rtt_min)) {
5777 rt->rtt_min = rt->rtt_hist[i];
5778 }
5779 }
5780 RT_UNLOCK(rt);
5781 } else {
5782 rt->rtt_hist[rt->rtt_index] =
5783 min(rt->rtt_hist[rt->rtt_index], rtt);
5784 if (rt->rtt_min == 0) {
5785 rt->rtt_min = rtt;
5786 } else {
5787 rt->rtt_min = min(rt->rtt_min, rtt);
5788 }
5789 }
5790 }
5791
5792 /*
5793 * If we have a timestamp reply, update smoothed RTT. If no timestamp is
5794 * present but transmit timer is running and timed sequence number was
5795 * acked, update smoothed RTT.
5796 *
5797 * If timestamps are supported, a receiver can update RTT even if
5798 * there is no outstanding data.
5799 *
5800 * Some boxes send broken timestamp replies during the SYN+ACK phase,
5801 * ignore timestamps of 0or we could calculate a huge RTT and blow up
5802 * the retransmit timer.
5803 */
5804 static void
tcp_compute_rtt(struct tcpcb * tp,struct tcpopt * to,struct tcphdr * th)5805 tcp_compute_rtt(struct tcpcb *tp, struct tcpopt *to, struct tcphdr *th)
5806 {
5807 int rtt = 0;
5808 VERIFY(to != NULL && th != NULL);
5809 if (tp->t_rtttime != 0 && SEQ_GT(th->th_ack, tp->t_rtseq)) {
5810 u_int32_t pipe_ack_val;
5811 rtt = tcp_now - tp->t_rtttime;
5812 if (rtt == 0) {
5813 /*
5814 * Make adjustment for sub ms RTT when
5815 * timestamps are not used.
5816 */
5817 rtt = 1;
5818 }
5819 /*
5820 * Compute pipe ack -- the amount of data acknowledged
5821 * in the last RTT -- only works for sender
5822 */
5823 if (SEQ_GT(th->th_ack, tp->t_pipeack_lastuna)) {
5824 pipe_ack_val = th->th_ack - tp->t_pipeack_lastuna;
5825 /* Update the sample */
5826 tp->t_pipeack_sample[tp->t_pipeack_ind++] =
5827 pipe_ack_val;
5828 tp->t_pipeack_ind %= TCP_PIPEACK_SAMPLE_COUNT;
5829
5830 /* Compute the max of the pipeack samples */
5831 pipe_ack_val = tcp_get_max_pipeack(tp);
5832 tp->t_pipeack = (pipe_ack_val >
5833 tcp_initial_cwnd(tp)) ?
5834 pipe_ack_val : 0;
5835 }
5836 /* start another measurement */
5837 tp->t_rtttime = 0;
5838 }
5839 if (((to->to_flags & TOF_TS) != 0) &&
5840 (to->to_tsecr != 0) &&
5841 TSTMP_GEQ(tcp_now, to->to_tsecr)) {
5842 tcp_xmit_timer(tp, (tcp_now - to->to_tsecr),
5843 to->to_tsecr, th->th_ack);
5844 } else if (rtt > 0) {
5845 tcp_xmit_timer(tp, rtt, 0, th->th_ack);
5846 }
5847 }
5848
5849 static void
tcp_compute_rcv_rtt(struct tcpcb * tp,struct tcpopt * to,struct tcphdr * th)5850 tcp_compute_rcv_rtt(struct tcpcb *tp, struct tcpopt *to, struct tcphdr *th)
5851 {
5852 uint32_t rtt = 0, delta = 0;
5853 VERIFY(to != NULL && th != NULL);
5854
5855 /* Calculate RTT */
5856 if (((to->to_flags & TOF_TS) != 0) && (to->to_tsecr != 0) &&
5857 TSTMP_GEQ(tcp_now, to->to_tsecr)) {
5858 /* Timestamp is supported */
5859 rtt = tcp_now - to->to_tsecr;
5860 if (rtt == 0) {
5861 /* Make adjustment for sub ms RTT */
5862 rtt = 1;
5863 }
5864 } else if ((to->to_flags & TOF_TS) == 0) {
5865 /*
5866 * Timestamp is not supported, 1RTT is roughly
5867 * the time to receive one full window of data
5868 * Currently, RTT calculated this way is only used
5869 * for auto-tuning.
5870 */
5871 if (tp->rcv_rtt_est_ts != 0) {
5872 if (SEQ_LT(tp->rcv_nxt, tp->rcv_rtt_est_seq)) {
5873 /* Haven't received a full window yet */
5874 return;
5875 } else {
5876 rtt = tcp_now - tp->rcv_rtt_est_ts;
5877 if (rtt == 0) {
5878 /* Make adjustment for sub ms RTT */
5879 rtt = 1;
5880 }
5881 }
5882 } else {
5883 /* Use default value when no RTT measurement */
5884 rtt = TCPTV_RCVNOTS_QUANTUM;
5885 }
5886 /* Restart the measurement */
5887 tp->rcv_rtt_est_ts = tcp_now;
5888 tp->rcv_rtt_est_seq = tp->rcv_nxt + tp->rcv_wnd;
5889 }
5890
5891 /* Update receiver's SRTT */
5892 if (tp->rcv_srtt != 0) {
5893 /*
5894 * Use the smoothed rtt formula,
5895 * (srtt = rtt/8 + srtt*7/8) in fixed point
5896 */
5897 delta = (rtt << TCP_DELTA_SHIFT)
5898 - (tp->rcv_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
5899
5900 if ((tp->rcv_srtt += delta) <= 0) {
5901 tp->rcv_srtt = 1;
5902 }
5903 } else {
5904 /* No previous measurement */
5905 tp->rcv_srtt = rtt << TCP_RTT_SHIFT;
5906 }
5907
5908 /*
5909 * For current RTT, base RTT and current RTT over k samples,
5910 * we are using the same state for both sender and receiver
5911 * as the most recent sample is always updated before any
5912 * other processing, i.e. the sender will not end up with
5913 * a high RTT due to the receiver.
5914 */
5915 tp->t_rttcur = rtt;
5916 update_base_rtt(tp, rtt);
5917 }
5918
5919 /*
5920 * Collect new round-trip time estimate and update averages and
5921 * current timeout.
5922 */
5923 static void
tcp_xmit_timer(struct tcpcb * tp,int rtt,u_int32_t tsecr,tcp_seq th_ack)5924 tcp_xmit_timer(struct tcpcb *tp, int rtt,
5925 u_int32_t tsecr, tcp_seq th_ack)
5926 {
5927 VERIFY(rtt >= 0);
5928 int delta;
5929 int old_srtt = tp->t_srtt;
5930 int old_rttvar = tp->t_rttvar;
5931 bool log_rtt = false;
5932
5933 if (rtt == 0) {
5934 /*
5935 * As rtt has millisecond precision,
5936 * make adjustment for sub ms RTT
5937 */
5938 rtt = 1;
5939 }
5940 /*
5941 * On AWDL interface, the initial RTT measurement on SYN
5942 * can be wrong due to peer caching. Avoid the first RTT
5943 * measurement as it might skew up the RTO.
5944 * <rdar://problem/28739046>
5945 */
5946 if (tp->t_inpcb->inp_last_outifp != NULL &&
5947 (tp->t_inpcb->inp_last_outifp->if_eflags & IFEF_AWDL) &&
5948 th_ack == tp->iss + 1) {
5949 return;
5950 }
5951
5952 if (tp->t_flagsext & TF_RECOMPUTE_RTT) {
5953 if (SEQ_GT(th_ack, tp->snd_una) &&
5954 SEQ_LEQ(th_ack, tp->snd_max) &&
5955 (tsecr == 0 ||
5956 TSTMP_GEQ(tsecr, tp->t_badrexmt_time))) {
5957 /*
5958 * We received a new ACK after a
5959 * spurious timeout. Adapt retransmission
5960 * timer as described in rfc 4015.
5961 */
5962 tp->t_flagsext &= ~(TF_RECOMPUTE_RTT);
5963 tp->t_badrexmt_time = 0;
5964 tp->t_srtt = max(tp->t_srtt_prev, rtt);
5965 tp->t_srtt = tp->t_srtt << TCP_RTT_SHIFT;
5966 tp->t_rttvar = max(tp->t_rttvar_prev, (rtt >> 1));
5967 tp->t_rttvar = tp->t_rttvar << TCP_RTTVAR_SHIFT;
5968
5969 if (tp->t_rttbest > (tp->t_srtt + tp->t_rttvar)) {
5970 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
5971 }
5972
5973 goto compute_rto;
5974 } else {
5975 return;
5976 }
5977 }
5978
5979 tcpstat.tcps_rttupdated++;
5980 tp->t_rttupdated++;
5981
5982 tp->t_rttcur = rtt;
5983 update_base_rtt(tp, rtt);
5984
5985 if (tp->t_srtt != 0) {
5986 /*
5987 * srtt is stored as fixed point with 5 bits after the
5988 * binary point (i.e., scaled by 32). The following magic
5989 * is equivalent to the smoothing algorithm in rfc793 with
5990 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
5991 * point).
5992 *
5993 * Freebsd adjusts rtt to origin 0 by subtracting 1
5994 * from the provided rtt value. This was required because
5995 * of the way t_rtttime was initiailised to 1 before.
5996 * Since we changed t_rtttime to be based on
5997 * tcp_now, this extra adjustment is not needed.
5998 */
5999 delta = (rtt << TCP_DELTA_SHIFT)
6000 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
6001
6002 if ((tp->t_srtt += delta) <= 0) {
6003 tp->t_srtt = 1;
6004 }
6005
6006 /*
6007 * We accumulate a smoothed rtt variance (actually, a
6008 * smoothed mean difference), then set the retransmit
6009 * timer to smoothed rtt + 4 times the smoothed variance.
6010 * rttvar is stored as fixed point with 4 bits after the
6011 * binary point (scaled by 16). The following is
6012 * equivalent to rfc793 smoothing with an alpha of .75
6013 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
6014 * rfc793's wired-in beta.
6015 */
6016 if (delta < 0) {
6017 delta = -delta;
6018 }
6019 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
6020 if ((tp->t_rttvar += delta) <= 0) {
6021 tp->t_rttvar = 1;
6022 }
6023 if (tp->t_rttbest == 0 ||
6024 tp->t_rttbest > (tp->t_srtt + tp->t_rttvar)) {
6025 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
6026 }
6027 } else {
6028 /*
6029 * No rtt measurement yet - use the unsmoothed rtt.
6030 * Set the variance to half the rtt (so our first
6031 * retransmit happens at 3*rtt).
6032 */
6033 tp->t_srtt = rtt << TCP_RTT_SHIFT;
6034 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
6035 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
6036
6037 /* Initialize the receive SRTT */
6038 if (tp->rcv_srtt == 0) {
6039 tp->rcv_srtt = tp->t_srtt;
6040 }
6041 }
6042
6043 compute_rto:
6044 nstat_route_rtt(tp->t_inpcb->inp_route.ro_rt, tp->t_srtt,
6045 tp->t_rttvar);
6046
6047 /*
6048 * the retransmit should happen at rtt + 4 * rttvar.
6049 * Because of the way we do the smoothing, srtt and rttvar
6050 * will each average +1/2 tick of bias. When we compute
6051 * the retransmit timer, we want 1/2 tick of rounding and
6052 * 1 extra tick because of +-1/2 tick uncertainty in the
6053 * firing of the timer. The bias will give us exactly the
6054 * 1.5 tick we need. But, because the bias is
6055 * statistical, we have to test that we don't drop below
6056 * the minimum feasible timer (which is 2 ticks).
6057 */
6058 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
6059 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX,
6060 TCP_ADD_REXMTSLOP(tp));
6061
6062 /*
6063 * We received an ack for a packet that wasn't retransmitted;
6064 * it is probably safe to discard any error indications we've
6065 * received recently. This isn't quite right, but close enough
6066 * for now (a route might have failed after we sent a segment,
6067 * and the return path might not be symmetrical).
6068 */
6069 tp->t_softerror = 0;
6070
6071 if (log_rtt) {
6072 TCP_LOG_RTT_INFO(tp);
6073 }
6074
6075 TCP_LOG_RTT_CHANGE(tp, old_srtt, old_rttvar);
6076 }
6077
6078 static inline unsigned int
tcp_maxmtu(struct rtentry * rt)6079 tcp_maxmtu(struct rtentry *rt)
6080 {
6081 unsigned int maxmtu;
6082 int interface_mtu = 0;
6083
6084 RT_LOCK_ASSERT_HELD(rt);
6085 interface_mtu = rt->rt_ifp->if_mtu;
6086
6087 if (rt_key(rt)->sa_family == AF_INET &&
6088 INTF_ADJUST_MTU_FOR_CLAT46(rt->rt_ifp)) {
6089 interface_mtu = IN6_LINKMTU(rt->rt_ifp);
6090 /* Further adjust the size for CLAT46 expansion */
6091 interface_mtu -= CLAT46_HDR_EXPANSION_OVERHD;
6092 }
6093
6094 if (rt->rt_rmx.rmx_mtu == 0) {
6095 maxmtu = interface_mtu;
6096 } else {
6097 maxmtu = MIN(rt->rt_rmx.rmx_mtu, interface_mtu);
6098 }
6099
6100 return maxmtu;
6101 }
6102
6103 static inline unsigned int
tcp_maxmtu6(struct rtentry * rt)6104 tcp_maxmtu6(struct rtentry *rt)
6105 {
6106 unsigned int maxmtu;
6107 struct nd_ifinfo *ndi = NULL;
6108
6109 RT_LOCK_ASSERT_HELD(rt);
6110 if ((ndi = ND_IFINFO(rt->rt_ifp)) != NULL && !ndi->initialized) {
6111 ndi = NULL;
6112 }
6113 if (ndi != NULL) {
6114 lck_mtx_lock(&ndi->lock);
6115 }
6116 if (rt->rt_rmx.rmx_mtu == 0) {
6117 maxmtu = IN6_LINKMTU(rt->rt_ifp);
6118 } else {
6119 maxmtu = MIN(rt->rt_rmx.rmx_mtu, IN6_LINKMTU(rt->rt_ifp));
6120 }
6121 if (ndi != NULL) {
6122 lck_mtx_unlock(&ndi->lock);
6123 }
6124
6125 return maxmtu;
6126 }
6127
6128 unsigned int
get_maxmtu(struct rtentry * rt)6129 get_maxmtu(struct rtentry *rt)
6130 {
6131 unsigned int maxmtu = 0;
6132
6133 RT_LOCK_ASSERT_NOTHELD(rt);
6134
6135 RT_LOCK(rt);
6136
6137 if (rt_key(rt)->sa_family == AF_INET6) {
6138 maxmtu = tcp_maxmtu6(rt);
6139 } else {
6140 maxmtu = tcp_maxmtu(rt);
6141 }
6142
6143 RT_UNLOCK(rt);
6144
6145 return maxmtu;
6146 }
6147
6148 /*
6149 * Determine a reasonable value for maxseg size.
6150 * If the route is known, check route for mtu.
6151 * If none, use an mss that can be handled on the outgoing
6152 * interface without forcing IP to fragment; if bigger than
6153 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
6154 * to utilize large mbufs. If no route is found, route has no mtu,
6155 * or the destination isn't local, use a default, hopefully conservative
6156 * size (usually 512 or the default IP max size, but no more than the mtu
6157 * of the interface), as we can't discover anything about intervening
6158 * gateways or networks. We also initialize the congestion/slow start
6159 * window. While looking at the routing entry, we also initialize
6160 * other path-dependent parameters from pre-set or cached values
6161 * in the routing entry.
6162 *
6163 * Also take into account the space needed for options that we
6164 * send regularly. Make maxseg shorter by that amount to assure
6165 * that we can send maxseg amount of data even when the options
6166 * are present. Store the upper limit of the length of options plus
6167 * data in maxopd.
6168 *
6169 * NOTE that this routine is only called when we process an incoming
6170 * segment, for outgoing segments only tcp_mssopt is called.
6171 *
6172 */
6173 void
tcp_mss(struct tcpcb * tp,int offer,unsigned int input_ifscope)6174 tcp_mss(struct tcpcb *tp, int offer, unsigned int input_ifscope)
6175 {
6176 struct rtentry *rt;
6177 struct ifnet *ifp;
6178 int rtt, mss;
6179 uint32_t bufsize;
6180 struct inpcb *inp;
6181 struct socket *so;
6182 int origoffer = offer;
6183 uint32_t sb_max_corrected;
6184 int isnetlocal = 0;
6185 int isipv6;
6186 int min_protoh;
6187
6188 inp = tp->t_inpcb;
6189
6190 so = inp->inp_socket;
6191 /*
6192 * Nothing left to send after the socket is defunct or TCP is in the closed state
6193 */
6194 if ((so->so_state & SS_DEFUNCT) || tp->t_state == TCPS_CLOSED) {
6195 return;
6196 }
6197
6198 isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
6199 min_protoh = isipv6 ? sizeof(struct ip6_hdr) + sizeof(struct tcphdr)
6200 : sizeof(struct tcpiphdr);
6201
6202 if (isipv6) {
6203 rt = tcp_rtlookup6(inp, input_ifscope);
6204 } else {
6205 rt = tcp_rtlookup(inp, input_ifscope);
6206 }
6207 isnetlocal = (tp->t_flags & TF_LOCAL);
6208
6209 if (rt == NULL) {
6210 tp->t_maxopd = tp->t_maxseg = isipv6 ? tcp_v6mssdflt : tcp_mssdflt;
6211 return;
6212 }
6213 ifp = rt->rt_ifp;
6214 /*
6215 * Slower link window correction:
6216 * If a value is specificied for slowlink_wsize use it for
6217 * PPP links believed to be on a serial modem (speed <128Kbps).
6218 * Excludes 9600bps as it is the default value adversized
6219 * by pseudo-devices over ppp.
6220 */
6221 if (ifp->if_type == IFT_PPP && slowlink_wsize > 0 &&
6222 ifp->if_baudrate > 9600 && ifp->if_baudrate <= 128000) {
6223 tp->t_flags |= TF_SLOWLINK;
6224 }
6225
6226 /*
6227 * Offer == -1 means that we didn't receive SYN yet. Use 0 then.
6228 */
6229 if (offer == -1) {
6230 offer = rt->rt_rmx.rmx_filler[0];
6231 }
6232 /*
6233 * Offer == 0 means that there was no MSS on the SYN segment,
6234 * in this case we use tcp_mssdflt.
6235 */
6236 if (offer == 0) {
6237 offer = isipv6 ? tcp_v6mssdflt : tcp_mssdflt;
6238 } else {
6239 /*
6240 * Prevent DoS attack with too small MSS. Round up
6241 * to at least minmss.
6242 */
6243 offer = max(offer, tcp_minmss);
6244 /*
6245 * Sanity check: make sure that maxopd will be large
6246 * enough to allow some data on segments even is the
6247 * all the option space is used (40bytes). Otherwise
6248 * funny things may happen in tcp_output.
6249 */
6250 offer = max(offer, 64);
6251 }
6252 rt->rt_rmx.rmx_filler[0] = offer;
6253
6254 /*
6255 * While we're here, check if there's an initial rtt
6256 * or rttvar. Convert from the route-table units
6257 * to scaled multiples of the slow timeout timer.
6258 */
6259 if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt) != 0) {
6260 tcp_getrt_rtt(tp, rt);
6261 } else {
6262 tp->t_rttmin = isnetlocal ? tcp_TCPTV_MIN : TCPTV_REXMTMIN;
6263 }
6264
6265 mss = (isipv6 ? tcp_maxmtu6(rt) : tcp_maxmtu(rt));
6266
6267 #if NECP
6268 // At this point, the mss is just the MTU. Adjust if necessary.
6269 mss = necp_socket_get_effective_mtu(inp, mss);
6270 #endif /* NECP */
6271
6272 mss -= min_protoh;
6273
6274 if (rt->rt_rmx.rmx_mtu == 0) {
6275 if (isipv6) {
6276 if (!isnetlocal) {
6277 mss = min(mss, tcp_v6mssdflt);
6278 }
6279 } else if (!isnetlocal) {
6280 mss = min(mss, tcp_mssdflt);
6281 }
6282 }
6283
6284 mss = min(mss, offer);
6285 /*
6286 * maxopd stores the maximum length of data AND options
6287 * in a segment; maxseg is the amount of data in a normal
6288 * segment. We need to store this value (maxopd) apart
6289 * from maxseg, because now every segment carries options
6290 * and thus we normally have somewhat less data in segments.
6291 */
6292 tp->t_maxopd = mss;
6293
6294 /*
6295 * origoffer==-1 indicates, that no segments were received yet.
6296 * In this case we just guess.
6297 */
6298 if ((tp->t_flags & (TF_REQ_TSTMP | TF_NOOPT)) == TF_REQ_TSTMP &&
6299 (origoffer == -1 ||
6300 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP)) {
6301 mss -= TCPOLEN_TSTAMP_APPA;
6302 }
6303
6304 #if MPTCP
6305 mss -= mptcp_adj_mss(tp, FALSE);
6306 #endif /* MPTCP */
6307 tp->t_maxseg = mss;
6308
6309 /*
6310 * Calculate corrected value for sb_max; ensure to upgrade the
6311 * numerator for large sb_max values else it will overflow.
6312 */
6313 sb_max_corrected = (sb_max * (u_int64_t)MCLBYTES) / (MSIZE + MCLBYTES);
6314
6315 /*
6316 * If there's a pipesize (ie loopback), change the socket
6317 * buffer to that size only if it's bigger than the current
6318 * sockbuf size. Make the socket buffers an integral
6319 * number of mss units; if the mss is larger than
6320 * the socket buffer, decrease the mss.
6321 */
6322 #if RTV_SPIPE
6323 bufsize = rt->rt_rmx.rmx_sendpipe;
6324 if (bufsize < so->so_snd.sb_hiwat)
6325 #endif
6326 bufsize = so->so_snd.sb_hiwat;
6327 if (bufsize < mss) {
6328 mss = bufsize;
6329 } else {
6330 bufsize = (((bufsize + mss - 1) / mss) * mss);
6331 if (bufsize > sb_max_corrected) {
6332 bufsize = sb_max_corrected;
6333 }
6334 (void)sbreserve(&so->so_snd, bufsize);
6335 }
6336 tp->t_maxseg = mss;
6337
6338 ASSERT(tp->t_maxseg);
6339
6340 /*
6341 * Update MSS using recommendation from link status report. This is
6342 * temporary
6343 */
6344 tcp_update_mss_locked(so, ifp);
6345
6346 #if RTV_RPIPE
6347 bufsize = rt->rt_rmx.rmx_recvpipe;
6348 if (bufsize < so->so_rcv.sb_hiwat)
6349 #endif
6350 bufsize = so->so_rcv.sb_hiwat;
6351 if (bufsize > mss) {
6352 bufsize = (((bufsize + mss - 1) / mss) * mss);
6353 if (bufsize > sb_max_corrected) {
6354 bufsize = sb_max_corrected;
6355 }
6356 (void)sbreserve(&so->so_rcv, bufsize);
6357 }
6358
6359 set_tcp_stream_priority(so);
6360
6361 if (rt->rt_rmx.rmx_ssthresh) {
6362 /*
6363 * There's some sort of gateway or interface
6364 * buffer limit on the path. Use this to set
6365 * slow-start threshold, but set the threshold to
6366 * no less than 2*mss.
6367 */
6368 tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
6369 tcpstat.tcps_usedssthresh++;
6370 } else {
6371 tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
6372 }
6373
6374 /*
6375 * Set the slow-start flight size depending on whether this
6376 * is a local network or not.
6377 */
6378 if (CC_ALGO(tp)->cwnd_init != NULL) {
6379 CC_ALGO(tp)->cwnd_init(tp);
6380 }
6381
6382 tcp_ccdbg_trace(tp, NULL, TCP_CC_CWND_INIT);
6383
6384 if (TCP_USE_RLEDBAT(tp, so) && tcp_cc_rledbat.rwnd_init != NULL) {
6385 tcp_cc_rledbat.rwnd_init(tp);
6386 }
6387
6388 /* Route locked during lookup above */
6389 RT_UNLOCK(rt);
6390 }
6391
6392 /*
6393 * Determine the MSS option to send on an outgoing SYN.
6394 */
6395 int
tcp_mssopt(struct tcpcb * tp)6396 tcp_mssopt(struct tcpcb *tp)
6397 {
6398 struct rtentry *rt;
6399 int mss;
6400 int isipv6;
6401 int min_protoh;
6402
6403 isipv6 = ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
6404 min_protoh = isipv6 ? sizeof(struct ip6_hdr) + sizeof(struct tcphdr)
6405 : sizeof(struct tcpiphdr);
6406
6407 if (isipv6) {
6408 rt = tcp_rtlookup6(tp->t_inpcb, IFSCOPE_NONE);
6409 } else {
6410 rt = tcp_rtlookup(tp->t_inpcb, IFSCOPE_NONE);
6411 }
6412 if (rt == NULL) {
6413 return isipv6 ? tcp_v6mssdflt : tcp_mssdflt;
6414 }
6415 /*
6416 * Slower link window correction:
6417 * If a value is specificied for slowlink_wsize use it for PPP links
6418 * believed to be on a serial modem (speed <128Kbps). Excludes 9600bps as
6419 * it is the default value adversized by pseudo-devices over ppp.
6420 */
6421 if (rt->rt_ifp->if_type == IFT_PPP && slowlink_wsize > 0 &&
6422 rt->rt_ifp->if_baudrate > 9600 && rt->rt_ifp->if_baudrate <= 128000) {
6423 tp->t_flags |= TF_SLOWLINK;
6424 }
6425
6426 mss = (isipv6 ? tcp_maxmtu6(rt) : tcp_maxmtu(rt));
6427 /* Route locked during lookup above */
6428 RT_UNLOCK(rt);
6429
6430 #if NECP
6431 // At this point, the mss is just the MTU. Adjust if necessary.
6432 mss = necp_socket_get_effective_mtu(tp->t_inpcb, mss);
6433 #endif /* NECP */
6434
6435 return mss - min_protoh;
6436 }
6437
6438 /*
6439 * On a partial ack arrives, force the retransmission of the
6440 * next unacknowledged segment. Do not clear tp->t_dupacks.
6441 * By setting snd_nxt to th_ack, this forces retransmission timer to
6442 * be started again.
6443 */
6444 static void
tcp_newreno_partial_ack(struct tcpcb * tp,struct tcphdr * th)6445 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
6446 {
6447 tcp_seq onxt = tp->snd_nxt;
6448 u_int32_t ocwnd = tp->snd_cwnd;
6449 tp->t_timer[TCPT_REXMT] = 0;
6450 tp->t_timer[TCPT_PTO] = 0;
6451 tp->t_rtttime = 0;
6452 tp->snd_nxt = th->th_ack;
6453 /*
6454 * Set snd_cwnd to one segment beyond acknowledged offset
6455 * (tp->snd_una has not yet been updated when this function
6456 * is called)
6457 */
6458 tp->snd_cwnd = tp->t_maxseg + BYTES_ACKED(th, tp);
6459 (void) tcp_output(tp);
6460 tp->snd_cwnd = ocwnd;
6461 if (SEQ_GT(onxt, tp->snd_nxt)) {
6462 tp->snd_nxt = onxt;
6463 }
6464 /*
6465 * Partial window deflation. Relies on fact that tp->snd_una
6466 * not updated yet.
6467 */
6468 if (tp->snd_cwnd > BYTES_ACKED(th, tp)) {
6469 tp->snd_cwnd -= BYTES_ACKED(th, tp);
6470 } else {
6471 tp->snd_cwnd = 0;
6472 }
6473 tp->snd_cwnd += tp->t_maxseg;
6474 }
6475
6476 /*
6477 * Drop a random TCP connection that hasn't been serviced yet and
6478 * is eligible for discard. There is a one in qlen chance that
6479 * we will return a null, saying that there are no dropable
6480 * requests. In this case, the protocol specific code should drop
6481 * the new request. This insures fairness.
6482 *
6483 * The listening TCP socket "head" must be locked
6484 */
6485 static int
tcp_dropdropablreq(struct socket * head)6486 tcp_dropdropablreq(struct socket *head)
6487 {
6488 struct socket *so, *sonext;
6489 unsigned int j, qlen;
6490 static uint32_t rnd = 0;
6491 static uint64_t old_runtime;
6492 static unsigned int cur_cnt, old_cnt;
6493 uint64_t now_sec, i;
6494 struct inpcb *inp = NULL;
6495 struct tcpcb *tp;
6496
6497 if ((head->so_options & SO_ACCEPTCONN) == 0) {
6498 return 0;
6499 }
6500
6501 if (TAILQ_EMPTY(&head->so_incomp)) {
6502 return 0;
6503 }
6504
6505 so_acquire_accept_list(head, NULL);
6506 socket_unlock(head, 0);
6507
6508 /*
6509 * Check if there is any socket in the incomp queue
6510 * that is closed because of a reset from the peer and is
6511 * waiting to be garbage collected. If so, pick that as
6512 * the victim
6513 */
6514 TAILQ_FOREACH_SAFE(so, &head->so_incomp, so_list, sonext) {
6515 inp = sotoinpcb(so);
6516 tp = intotcpcb(inp);
6517 if (tp != NULL && tp->t_state == TCPS_CLOSED &&
6518 so->so_head != NULL &&
6519 (so->so_state & (SS_INCOMP | SS_CANTSENDMORE | SS_CANTRCVMORE)) ==
6520 (SS_INCOMP | SS_CANTSENDMORE | SS_CANTRCVMORE)) {
6521 /*
6522 * The listen socket is already locked but we
6523 * can lock this socket here without lock ordering
6524 * issues because it is in the incomp queue and
6525 * is not visible to others.
6526 */
6527 if (socket_try_lock(so)) {
6528 so->so_usecount++;
6529 goto found_victim;
6530 } else {
6531 continue;
6532 }
6533 }
6534 }
6535
6536 so = TAILQ_FIRST(&head->so_incomp);
6537
6538 now_sec = net_uptime();
6539 if ((i = (now_sec - old_runtime)) != 0) {
6540 old_runtime = now_sec;
6541 old_cnt = cur_cnt / i;
6542 cur_cnt = 0;
6543 }
6544
6545 qlen = head->so_incqlen;
6546 if (rnd == 0) {
6547 rnd = RandomULong();
6548 }
6549
6550 if (++cur_cnt > qlen || old_cnt > qlen) {
6551 rnd = (314159 * rnd + 66329) & 0xffff;
6552 j = ((qlen + 1) * rnd) >> 16;
6553
6554 while (j-- && so) {
6555 so = TAILQ_NEXT(so, so_list);
6556 }
6557 }
6558 /* Find a connection that is not already closing (or being served) */
6559 while (so) {
6560 inp = (struct inpcb *)so->so_pcb;
6561
6562 sonext = TAILQ_NEXT(so, so_list);
6563
6564 if (in_pcb_checkstate(inp, WNT_ACQUIRE, 0) != WNT_STOPUSING) {
6565 /*
6566 * Avoid the issue of a socket being accepted
6567 * by one input thread and being dropped by
6568 * another input thread. If we can't get a hold
6569 * on this mutex, then grab the next socket in
6570 * line.
6571 */
6572 if (socket_try_lock(so)) {
6573 so->so_usecount++;
6574 if ((so->so_usecount == 2) &&
6575 (so->so_state & SS_INCOMP) &&
6576 !(so->so_flags & SOF_INCOMP_INPROGRESS)) {
6577 break;
6578 } else {
6579 /*
6580 * don't use if being accepted or
6581 * used in any other way
6582 */
6583 in_pcb_checkstate(inp, WNT_RELEASE, 1);
6584 socket_unlock(so, 1);
6585 }
6586 } else {
6587 /*
6588 * do not try to lock the inp in
6589 * in_pcb_checkstate because the lock
6590 * is already held in some other thread.
6591 * Only drop the inp_wntcnt reference.
6592 */
6593 in_pcb_checkstate(inp, WNT_RELEASE, 1);
6594 }
6595 }
6596 so = sonext;
6597 }
6598 if (so == NULL) {
6599 socket_lock(head, 0);
6600 so_release_accept_list(head);
6601 return 0;
6602 }
6603
6604 /* Makes sure socket is still in the right state to be discarded */
6605
6606 if (in_pcb_checkstate(inp, WNT_RELEASE, 1) == WNT_STOPUSING) {
6607 socket_unlock(so, 1);
6608 socket_lock(head, 0);
6609 so_release_accept_list(head);
6610 return 0;
6611 }
6612
6613 found_victim:
6614 if (so->so_usecount != 2 || !(so->so_state & SS_INCOMP)) {
6615 /* do not discard: that socket is being accepted */
6616 socket_unlock(so, 1);
6617 socket_lock(head, 0);
6618 so_release_accept_list(head);
6619 return 0;
6620 }
6621
6622 socket_lock(head, 0);
6623 TAILQ_REMOVE(&head->so_incomp, so, so_list);
6624 head->so_incqlen--;
6625 head->so_qlen--;
6626 so->so_state &= ~SS_INCOMP;
6627 so->so_flags |= SOF_OVERFLOW;
6628 so->so_head = NULL;
6629 so_release_accept_list(head);
6630 socket_unlock(head, 0);
6631
6632 socket_lock_assert_owned(so);
6633 tp = sototcpcb(so);
6634
6635 tcp_close(tp);
6636 if (inp->inp_wantcnt > 0 && inp->inp_wantcnt != WNT_STOPUSING) {
6637 /*
6638 * Some one has a wantcnt on this pcb. Since WNT_ACQUIRE
6639 * doesn't require a lock, it could have happened while
6640 * we are holding the lock. This pcb will have to
6641 * be garbage collected later.
6642 * Release the reference held for so_incomp queue
6643 */
6644 VERIFY(so->so_usecount > 0);
6645 so->so_usecount--;
6646 socket_unlock(so, 1);
6647 } else {
6648 /*
6649 * Unlock this socket and leave the reference on.
6650 * We need to acquire the pcbinfo lock in order to
6651 * fully dispose it off
6652 */
6653 socket_unlock(so, 0);
6654
6655 lck_rw_lock_exclusive(&tcbinfo.ipi_lock);
6656
6657 socket_lock(so, 0);
6658 /* Release the reference held for so_incomp queue */
6659 VERIFY(so->so_usecount > 0);
6660 so->so_usecount--;
6661
6662 if (so->so_usecount != 1 ||
6663 (inp->inp_wantcnt > 0 &&
6664 inp->inp_wantcnt != WNT_STOPUSING)) {
6665 /*
6666 * There is an extra wantcount or usecount
6667 * that must have been added when the socket
6668 * was unlocked. This socket will have to be
6669 * garbage collected later
6670 */
6671 socket_unlock(so, 1);
6672 } else {
6673 /* Drop the reference held for this function */
6674 VERIFY(so->so_usecount > 0);
6675 so->so_usecount--;
6676
6677 in_pcbdispose(inp);
6678 }
6679 lck_rw_done(&tcbinfo.ipi_lock);
6680 }
6681 tcpstat.tcps_drops++;
6682
6683 socket_lock(head, 0);
6684 return 1;
6685 }
6686
6687 /* Set background congestion control on a socket */
6688 void
tcp_set_background_cc(struct socket * so)6689 tcp_set_background_cc(struct socket *so)
6690 {
6691 tcp_set_new_cc(so, TCP_CC_ALGO_BACKGROUND_INDEX);
6692 }
6693
6694 /* Set foreground congestion control on a socket */
6695 void
tcp_set_foreground_cc(struct socket * so)6696 tcp_set_foreground_cc(struct socket *so)
6697 {
6698 if (tcp_use_newreno) {
6699 tcp_set_new_cc(so, TCP_CC_ALGO_NEWRENO_INDEX);
6700 #if (DEVELOPMENT || DEBUG)
6701 } else if (tcp_use_ledbat) {
6702 /* Only used for testing */
6703 tcp_set_new_cc(so, TCP_CC_ALGO_BACKGROUND_INDEX);
6704 #endif
6705 } else {
6706 tcp_set_new_cc(so, TCP_CC_ALGO_CUBIC_INDEX);
6707 }
6708 }
6709
6710 static void
tcp_set_new_cc(struct socket * so,uint8_t cc_index)6711 tcp_set_new_cc(struct socket *so, uint8_t cc_index)
6712 {
6713 struct inpcb *inp = sotoinpcb(so);
6714 struct tcpcb *tp = intotcpcb(inp);
6715
6716 if (tp->tcp_cc_index != cc_index) {
6717 if (CC_ALGO(tp)->cleanup != NULL) {
6718 CC_ALGO(tp)->cleanup(tp);
6719 }
6720 tp->tcp_cc_index = cc_index;
6721
6722 tcp_cc_allocate_state(tp);
6723
6724 if (CC_ALGO(tp)->switch_to != NULL) {
6725 CC_ALGO(tp)->switch_to(tp);
6726 }
6727
6728 tcp_ccdbg_trace(tp, NULL, TCP_CC_CHANGE_ALGO);
6729 }
6730 }
6731
6732 void
tcp_set_recv_bg(struct socket * so)6733 tcp_set_recv_bg(struct socket *so)
6734 {
6735 if (!IS_TCP_RECV_BG(so)) {
6736 so->so_flags1 |= SOF1_TRAFFIC_MGT_TCP_RECVBG;
6737
6738 struct inpcb *inp = sotoinpcb(so);
6739 struct tcpcb *tp = intotcpcb(inp);
6740
6741 if (TCP_RLEDBAT_ENABLED(tp) && tcp_cc_rledbat.switch_to != NULL) {
6742 tcp_cc_rledbat.switch_to(tp);
6743 }
6744 }
6745 }
6746
6747 void
tcp_clear_recv_bg(struct socket * so)6748 tcp_clear_recv_bg(struct socket *so)
6749 {
6750 if (IS_TCP_RECV_BG(so)) {
6751 so->so_flags1 &= ~(SOF1_TRAFFIC_MGT_TCP_RECVBG);
6752 }
6753 }
6754
6755 void
inp_fc_throttle_tcp(struct inpcb * inp)6756 inp_fc_throttle_tcp(struct inpcb *inp)
6757 {
6758 struct tcpcb *tp = inp->inp_ppcb;
6759
6760 if (!tcp_flow_control_response) {
6761 return;
6762 }
6763
6764 /*
6765 * Back off the slow-start threshold and enter
6766 * congestion avoidance phase
6767 */
6768 if (CC_ALGO(tp)->pre_fr != NULL) {
6769 CC_ALGO(tp)->pre_fr(tp);
6770 }
6771 }
6772
6773 void
inp_fc_unthrottle_tcp(struct inpcb * inp)6774 inp_fc_unthrottle_tcp(struct inpcb *inp)
6775 {
6776 struct tcpcb *tp = inp->inp_ppcb;
6777
6778 if (tcp_flow_control_response) {
6779 if (CC_ALGO(tp)->post_fr != NULL) {
6780 CC_ALGO(tp)->post_fr(tp, NULL);
6781 }
6782
6783 tp->t_bytes_acked = 0;
6784
6785 /*
6786 * Reset retransmit shift as we know that the reason
6787 * for delay in sending a packet is due to flow
6788 * control on the outgoing interface. There is no need
6789 * to backoff retransmit timer.
6790 */
6791 TCP_RESET_REXMT_STATE(tp);
6792
6793 tp->t_flagsext &= ~TF_CWND_NONVALIDATED;
6794
6795 /*
6796 * Start the output stream again. Since we are
6797 * not retransmitting data, do not reset the
6798 * retransmit timer or rtt calculation.
6799 */
6800 tcp_output(tp);
6801 return;
6802 }
6803
6804 /*
6805 * Back off the slow-start threshold and enter
6806 * congestion avoidance phase
6807 */
6808 if (CC_ALGO(tp)->pre_fr != NULL) {
6809 CC_ALGO(tp)->pre_fr(tp);
6810 }
6811
6812 tp->snd_cwnd = tp->snd_ssthresh;
6813 tp->t_flagsext &= ~TF_CWND_NONVALIDATED;
6814 /*
6815 * Restart counting for ABC as we changed the
6816 * congestion window just now.
6817 */
6818 tp->t_bytes_acked = 0;
6819
6820 /* Reset retransmit shift as we know that the reason
6821 * for delay in sending a packet is due to flow
6822 * control on the outgoing interface. There is no need
6823 * to backoff retransmit timer.
6824 */
6825 TCP_RESET_REXMT_STATE(tp);
6826
6827 /*
6828 * Start the output stream again. Since we are
6829 * not retransmitting data, do not reset the
6830 * retransmit timer or rtt calculation.
6831 */
6832 tcp_output(tp);
6833 }
6834
6835 static int
6836 tcp_getstat SYSCTL_HANDLER_ARGS
6837 {
6838 #pragma unused(oidp, arg1, arg2)
6839
6840 int error;
6841 struct tcpstat *stat;
6842 stat = &tcpstat;
6843 #if XNU_TARGET_OS_OSX
6844 struct tcpstat zero_stat;
6845
6846 if (tcp_disable_access_to_stats &&
6847 !kauth_cred_issuser(kauth_cred_get())) {
6848 bzero(&zero_stat, sizeof(zero_stat));
6849 stat = &zero_stat;
6850 }
6851
6852 #endif /* XNU_TARGET_OS_OSX */
6853
6854 if (req->oldptr == 0) {
6855 req->oldlen = (size_t)sizeof(struct tcpstat);
6856 }
6857
6858 error = SYSCTL_OUT(req, stat, MIN(sizeof(tcpstat), req->oldlen));
6859
6860 return error;
6861 }
6862
6863 /*
6864 * Checksum extended TCP header and data.
6865 */
6866 int
tcp_input_checksum(int af,struct mbuf * m,struct tcphdr * th,int off,int tlen)6867 tcp_input_checksum(int af, struct mbuf *m, struct tcphdr *th, int off, int tlen)
6868 {
6869 struct ifnet *ifp = m->m_pkthdr.rcvif;
6870
6871 switch (af) {
6872 case AF_INET: {
6873 struct ip *ip = mtod(m, struct ip *);
6874 struct ipovly *ipov = (struct ipovly *)ip;
6875
6876 /* ip_stripoptions() must have been called before we get here */
6877 ASSERT((ip->ip_hl << 2) == sizeof(*ip));
6878
6879 if ((hwcksum_rx || (ifp->if_flags & IFF_LOOPBACK) ||
6880 (m->m_pkthdr.pkt_flags & PKTF_LOOP)) &&
6881 (m->m_pkthdr.csum_flags & CSUM_DATA_VALID)) {
6882 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
6883 th->th_sum = m->m_pkthdr.csum_rx_val;
6884 } else {
6885 uint32_t sum = m->m_pkthdr.csum_rx_val;
6886 uint32_t start = m->m_pkthdr.csum_rx_start;
6887 int32_t trailer = (m_pktlen(m) - (off + tlen));
6888
6889 /*
6890 * Perform 1's complement adjustment of octets
6891 * that got included/excluded in the hardware-
6892 * calculated checksum value. Ignore cases
6893 * where the value already includes the entire
6894 * IP header span, as the sum for those octets
6895 * would already be 0 by the time we get here;
6896 * IP has already performed its header checksum
6897 * checks. If we do need to adjust, restore
6898 * the original fields in the IP header when
6899 * computing the adjustment value. Also take
6900 * care of any trailing bytes and subtract out
6901 * their partial sum.
6902 */
6903 ASSERT(trailer >= 0);
6904 if ((m->m_pkthdr.csum_flags & CSUM_PARTIAL) &&
6905 ((start != 0 && start != off) || trailer)) {
6906 uint32_t swbytes = (uint32_t)trailer;
6907
6908 if (start < off) {
6909 ip->ip_len += sizeof(*ip);
6910 #if BYTE_ORDER != BIG_ENDIAN
6911 HTONS(ip->ip_len);
6912 HTONS(ip->ip_off);
6913 #endif /* BYTE_ORDER != BIG_ENDIAN */
6914 }
6915 /* callee folds in sum */
6916 sum = m_adj_sum16(m, start, off,
6917 tlen, sum);
6918 if (off > start) {
6919 swbytes += (off - start);
6920 } else {
6921 swbytes += (start - off);
6922 }
6923
6924 if (start < off) {
6925 #if BYTE_ORDER != BIG_ENDIAN
6926 NTOHS(ip->ip_off);
6927 NTOHS(ip->ip_len);
6928 #endif /* BYTE_ORDER != BIG_ENDIAN */
6929 ip->ip_len -= sizeof(*ip);
6930 }
6931
6932 if (swbytes != 0) {
6933 tcp_in_cksum_stats(swbytes);
6934 }
6935 if (trailer != 0) {
6936 m_adj(m, -trailer);
6937 }
6938 }
6939
6940 /* callee folds in sum */
6941 th->th_sum = in_pseudo(ip->ip_src.s_addr,
6942 ip->ip_dst.s_addr,
6943 sum + htonl(tlen + IPPROTO_TCP));
6944 }
6945 th->th_sum ^= 0xffff;
6946 } else {
6947 uint16_t ip_sum;
6948 int len;
6949 char b[9];
6950
6951 bcopy(ipov->ih_x1, b, sizeof(ipov->ih_x1));
6952 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
6953 ip_sum = ipov->ih_len;
6954 ipov->ih_len = (u_short)tlen;
6955 #if BYTE_ORDER != BIG_ENDIAN
6956 HTONS(ipov->ih_len);
6957 #endif
6958 len = sizeof(struct ip) + tlen;
6959 th->th_sum = in_cksum(m, len);
6960 bcopy(b, ipov->ih_x1, sizeof(ipov->ih_x1));
6961 ipov->ih_len = ip_sum;
6962
6963 tcp_in_cksum_stats(len);
6964 }
6965 break;
6966 }
6967 case AF_INET6: {
6968 struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
6969
6970 if ((hwcksum_rx || (ifp->if_flags & IFF_LOOPBACK) ||
6971 (m->m_pkthdr.pkt_flags & PKTF_LOOP)) &&
6972 (m->m_pkthdr.csum_flags & CSUM_DATA_VALID)) {
6973 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
6974 th->th_sum = m->m_pkthdr.csum_rx_val;
6975 } else {
6976 uint32_t sum = m->m_pkthdr.csum_rx_val;
6977 uint32_t start = m->m_pkthdr.csum_rx_start;
6978 int32_t trailer = (m_pktlen(m) - (off + tlen));
6979
6980 /*
6981 * Perform 1's complement adjustment of octets
6982 * that got included/excluded in the hardware-
6983 * calculated checksum value. Also take care
6984 * of any trailing bytes and subtract out their
6985 * partial sum.
6986 */
6987 ASSERT(trailer >= 0);
6988 if ((m->m_pkthdr.csum_flags & CSUM_PARTIAL) &&
6989 (start != off || trailer != 0)) {
6990 uint16_t s = 0, d = 0;
6991 uint32_t swbytes = (uint32_t)trailer;
6992
6993 if (IN6_IS_SCOPE_EMBED(&ip6->ip6_src)) {
6994 s = ip6->ip6_src.s6_addr16[1];
6995 ip6->ip6_src.s6_addr16[1] = 0;
6996 }
6997 if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst)) {
6998 d = ip6->ip6_dst.s6_addr16[1];
6999 ip6->ip6_dst.s6_addr16[1] = 0;
7000 }
7001
7002 /* callee folds in sum */
7003 sum = m_adj_sum16(m, start, off,
7004 tlen, sum);
7005 if (off > start) {
7006 swbytes += (off - start);
7007 } else {
7008 swbytes += (start - off);
7009 }
7010
7011 if (IN6_IS_SCOPE_EMBED(&ip6->ip6_src)) {
7012 ip6->ip6_src.s6_addr16[1] = s;
7013 }
7014 if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst)) {
7015 ip6->ip6_dst.s6_addr16[1] = d;
7016 }
7017
7018 if (swbytes != 0) {
7019 tcp_in6_cksum_stats(swbytes);
7020 }
7021 if (trailer != 0) {
7022 m_adj(m, -trailer);
7023 }
7024 }
7025
7026 th->th_sum = in6_pseudo(
7027 &ip6->ip6_src, &ip6->ip6_dst,
7028 sum + htonl(tlen + IPPROTO_TCP));
7029 }
7030 th->th_sum ^= 0xffff;
7031 } else {
7032 tcp_in6_cksum_stats(tlen);
7033 th->th_sum = in6_cksum(m, IPPROTO_TCP, off, tlen);
7034 }
7035 break;
7036 }
7037 default:
7038 VERIFY(0);
7039 /* NOTREACHED */
7040 }
7041
7042 if (th->th_sum != 0) {
7043 tcpstat.tcps_rcvbadsum++;
7044 IF_TCP_STATINC(ifp, badformat);
7045 return -1;
7046 }
7047
7048 return 0;
7049 }
7050
7051
7052 SYSCTL_PROC(_net_inet_tcp, TCPCTL_STATS, stats,
7053 CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0, tcp_getstat,
7054 "S,tcpstat", "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
7055
7056 static int
7057 sysctl_rexmtthresh SYSCTL_HANDLER_ARGS
7058 {
7059 #pragma unused(arg1, arg2)
7060
7061 int error, val = tcprexmtthresh;
7062
7063 error = sysctl_handle_int(oidp, &val, 0, req);
7064 if (error || !req->newptr) {
7065 return error;
7066 }
7067
7068 /*
7069 * Constrain the number of duplicate ACKs
7070 * to consider for TCP fast retransmit
7071 * to either 2 or 3
7072 */
7073
7074 if (val < 2 || val > 3) {
7075 return EINVAL;
7076 }
7077
7078 tcprexmtthresh = (uint8_t)val;
7079
7080 return 0;
7081 }
7082
7083 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, rexmt_thresh, CTLTYPE_INT | CTLFLAG_RW |
7084 CTLFLAG_LOCKED, &tcprexmtthresh, 0, &sysctl_rexmtthresh, "I",
7085 "Duplicate ACK Threshold for Fast Retransmit");
7086