2 * Copyright (c) 2000-2008 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
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.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
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.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
29 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
30 * The Regents of the University of California. All rights reserved.
32 * Redistribution and use in source and binary forms, with or without
33 * modification, are permitted provided that the following conditions
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.
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
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 $
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,
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>
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>
82 #include <kern/cpu_number.h> /* before tcp_seq.h, for tcp_random18() */
84 #include <machine/endian.h>
87 #include <net/if_types.h>
88 #include <net/route.h>
90 #include <netinet/in.h>
91 #include <netinet/in_systm.h>
92 #include <netinet/ip.h>
93 #include <netinet/ip_icmp.h> /* for ICMP_BANDLIM */
94 #include <netinet/in_var.h>
95 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
96 #include <netinet/in_pcb.h>
97 #include <netinet/ip_var.h>
99 #include <netinet/ip6.h>
100 #include <netinet/icmp6.h>
101 #include <netinet6/nd6.h>
102 #include <netinet6/ip6_var.h>
103 #include <netinet6/in6_pcb.h>
105 #include <netinet/tcp.h>
106 #include <netinet/tcp_fsm.h>
107 #include <netinet/tcp_seq.h>
108 #include <netinet/tcp_timer.h>
109 #include <netinet/tcp_var.h>
111 #include <netinet6/tcp6_var.h>
113 #include <netinet/tcpip.h>
115 #include <netinet/tcp_debug.h>
116 u_char tcp_saveipgen
[40]; /* the size must be of max ip header, now IPv6 */
117 struct tcphdr tcp_savetcp
;
118 #endif /* TCPDEBUG */
121 #include <netinet6/ipsec.h>
123 #include <netinet6/ipsec6.h>
125 #include <netkey/key.h>
128 #if CONFIG_MACF_NET || CONFIG_MACF_SOCKET
129 #include <security/mac_framework.h>
130 #endif /* CONFIG_MACF_NET || CONFIG_MACF_SOCKET */
132 #include <sys/kdebug.h>
135 MALLOC_DEFINE(M_TSEGQ
, "tseg_qent", "TCP segment queue entry");
138 #define DBG_LAYER_BEG NETDBG_CODE(DBG_NETTCP, 0)
139 #define DBG_LAYER_END NETDBG_CODE(DBG_NETTCP, 2)
140 #define DBG_FNC_TCP_INPUT NETDBG_CODE(DBG_NETTCP, (3 << 8))
141 #define DBG_FNC_TCP_NEWCONN NETDBG_CODE(DBG_NETTCP, (7 << 8))
143 static int tcprexmtthresh
= 2;
147 extern int ipsec_bypass
;
150 struct tcpstat tcpstat
;
152 static int log_in_vain
= 0;
153 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, log_in_vain
, CTLFLAG_RW
,
154 &log_in_vain
, 0, "Log all incoming TCP connections");
156 static int blackhole
= 0;
157 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, blackhole
, CTLFLAG_RW
,
158 &blackhole
, 0, "Do not send RST when dropping refused connections");
160 int tcp_delack_enabled
= 3;
161 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, delayed_ack
, CTLFLAG_RW
,
162 &tcp_delack_enabled
, 0,
163 "Delay ACK to try and piggyback it onto a data packet");
165 int tcp_lq_overflow
= 1;
166 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, tcp_lq_overflow
, CTLFLAG_RW
,
168 "Listen Queue Overflow");
171 static int drop_synfin
= 1;
172 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, drop_synfin
, CTLFLAG_RW
,
173 &drop_synfin
, 0, "Drop TCP packets with SYN+FIN set");
176 SYSCTL_NODE(_net_inet_tcp
, OID_AUTO
, reass
, CTLFLAG_RW
|CTLFLAG_LOCKED
, 0,
177 "TCP Segment Reassembly Queue");
179 __private_extern__
int tcp_reass_maxseg
= 0;
180 SYSCTL_INT(_net_inet_tcp_reass
, OID_AUTO
, maxsegments
, CTLFLAG_RW
,
181 &tcp_reass_maxseg
, 0,
182 "Global maximum number of TCP Segments in Reassembly Queue");
184 __private_extern__
int tcp_reass_qsize
= 0;
185 SYSCTL_INT(_net_inet_tcp_reass
, OID_AUTO
, cursegments
, CTLFLAG_RD
,
187 "Global number of TCP Segments currently in Reassembly Queue");
189 static int tcp_reass_overflows
= 0;
190 SYSCTL_INT(_net_inet_tcp_reass
, OID_AUTO
, overflows
, CTLFLAG_RD
,
191 &tcp_reass_overflows
, 0,
192 "Global number of TCP Segment Reassembly Queue Overflows");
195 __private_extern__
int slowlink_wsize
= 8192;
196 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, slowlink_wsize
, CTLFLAG_RW
,
197 &slowlink_wsize
, 0, "Maximum advertised window size for slowlink");
199 static int maxseg_unacked
= 8;
200 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, maxseg_unacked
, CTLFLAG_RW
,
201 &maxseg_unacked
, 0, "Maximum number of outstanding segments left unacked");
203 static int tcp_do_rfc3465
= 1;
204 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, rfc3465
, CTLFLAG_RW
,
205 &tcp_do_rfc3465
, 0, "");
207 static int tcp_do_rfc3465_lim2
= 1;
208 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, rfc3465_lim2
, CTLFLAG_RW
,
209 &tcp_do_rfc3465_lim2
, 0, "Appropriate bytes counting w/ L=2*SMSS");
211 #if CONFIG_IFEF_NOWINDOWSCALE
212 int tcp_obey_ifef_nowindowscale
= 0;
213 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, obey_ifef_nowindowscale
, CTLFLAG_RW
,
214 &tcp_obey_ifef_nowindowscale
, 0, "");
217 extern int tcp_TCPTV_MIN
;
221 struct inpcbhead tcb
;
222 #define tcb6 tcb /* for KAME src sync over BSD*'s */
223 struct inpcbinfo tcbinfo
;
225 static void tcp_dooptions(struct tcpcb
*,
226 u_char
*, int, struct tcphdr
*, struct tcpopt
*, unsigned int);
227 static void tcp_pulloutofband(struct socket
*,
228 struct tcphdr
*, struct mbuf
*, int);
229 static int tcp_reass(struct tcpcb
*, struct tcphdr
*, int *,
231 static void tcp_xmit_timer(struct tcpcb
*, int);
232 static inline unsigned int tcp_maxmtu(struct rtentry
*);
234 static inline unsigned int tcp_maxmtu6(struct rtentry
*);
237 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
239 #define ND6_HINT(tp) \
241 if ((tp) && (tp)->t_inpcb && \
242 ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0 && \
243 (tp)->t_inpcb->in6p_route.ro_rt) \
244 nd6_nud_hint((tp)->t_inpcb->in6p_route.ro_rt, NULL, 0); \
250 extern u_int32_t
*delack_bitmask
;
252 extern void add_to_time_wait(struct tcpcb
*);
253 extern void postevent(struct socket
*, struct sockbuf
*, int);
255 extern void ipfwsyslog( int level
, const char *format
,...);
256 extern int ChkAddressOK( __uint32_t dstaddr
, __uint32_t srcaddr
);
257 extern int fw_verbose
;
258 __private_extern__
int tcp_sockthreshold
;
259 __private_extern__
int tcp_win_scale
;
262 #define log_in_vain_log( a ) { \
263 if ( (log_in_vain == 3 ) && (fw_verbose == 2)) { /* Apple logging, log to ipfw.log */ \
269 #define log_in_vain_log( a ) { log a; }
274 * Indicate whether this ack should be delayed.
275 * We can delay the ack if:
276 * - delayed acks are enabled (set to 1) and
277 * - our last ack wasn't a 0-sized window. We never want to delay
278 * the ack that opens up a 0-sized window.
279 * - delayed acks are enabled (set to 2, "more compatible") and
280 * - our last ack wasn't a 0-sized window.
281 * - if the peer hasn't sent us a TH_PUSH data packet (this solves 3649245)
282 * - the peer hasn't sent us a TH_PUSH data packet, if he did, take this as a clue that we
283 * need to ACK with no delay. This helps higher level protocols who won't send
284 * us more data even if the window is open because their last "segment" hasn't been ACKed
285 * - delayed acks are enabled (set to 3, "streaming detection") and
286 * - if we receive more than "maxseg_unacked" full packets per second on this socket
287 * - if we don't have more than "maxseg_unacked" delayed so far
288 * - if those criteria aren't met, acts like "2". Allowing faster acking while browsing for example.
291 #define DELAY_ACK(tp) \
292 (((tcp_delack_enabled == 1) && ((tp->t_flags & TF_RXWIN0SENT) == 0)) || \
293 (((tcp_delack_enabled == 2) && (tp->t_flags & TF_RXWIN0SENT) == 0) && \
294 ((thflags & TH_PUSH) == 0) && ((tp->t_flags & TF_DELACK) == 0)) || \
295 (((tcp_delack_enabled == 3) && (tp->t_flags & TF_RXWIN0SENT) == 0) && \
296 (tp->t_rcvtime == 0) && ((thflags & TH_PUSH) == 0) && \
297 (((tp->t_unacksegs == 0)) || \
298 ((tp->rcv_byps > (maxseg_unacked * tp->t_maxseg)) && (tp->t_unacksegs < maxseg_unacked)))))
300 static int tcp_dropdropablreq(struct socket
*head
);
301 static void tcp_newreno_partial_ack(struct tcpcb
*tp
, struct tcphdr
*th
);
305 tcp_reass(tp
, th
, tlenp
, m
)
306 register struct tcpcb
*tp
;
307 register struct tcphdr
*th
;
312 struct tseg_qent
*p
= NULL
;
313 struct tseg_qent
*nq
;
314 struct tseg_qent
*te
= NULL
;
315 struct socket
*so
= tp
->t_inpcb
->inp_socket
;
320 * Call with th==0 after become established to
321 * force pre-ESTABLISHED data up to user socket.
327 * Limit the number of segments in the reassembly queue to prevent
328 * holding on to too many segments (and thus running out of mbufs).
329 * Make sure to let the missing segment through which caused this
330 * queue. Always keep one global queue entry spare to be able to
331 * process the missing segment.
333 if (th
->th_seq
!= tp
->rcv_nxt
&&
334 tcp_reass_qsize
+ 1 >= tcp_reass_maxseg
) {
335 tcp_reass_overflows
++;
336 tcpstat
.tcps_rcvmemdrop
++;
342 /* Allocate a new queue entry. If we can't, just drop the pkt. XXX */
343 MALLOC(te
, struct tseg_qent
*, sizeof (struct tseg_qent
), M_TSEGQ
,
346 tcpstat
.tcps_rcvmemdrop
++;
353 * Find a segment which begins after this one does.
355 LIST_FOREACH(q
, &tp
->t_segq
, tqe_q
) {
356 if (SEQ_GT(q
->tqe_th
->th_seq
, th
->th_seq
))
362 * If there is a preceding segment, it may provide some of
363 * our data already. If so, drop the data from the incoming
364 * segment. If it provides all of our data, drop us.
368 /* conversion to int (in i) handles seq wraparound */
369 i
= p
->tqe_th
->th_seq
+ p
->tqe_len
- th
->th_seq
;
372 tcpstat
.tcps_rcvduppack
++;
373 tcpstat
.tcps_rcvdupbyte
+= *tlenp
;
378 * Try to present any queued data
379 * at the left window edge to the user.
380 * This is needed after the 3-WHS
383 goto present
; /* ??? */
390 tcpstat
.tcps_rcvoopack
++;
391 tcpstat
.tcps_rcvoobyte
+= *tlenp
;
394 * While we overlap succeeding segments trim them or,
395 * if they are completely covered, dequeue them.
398 register int i
= (th
->th_seq
+ *tlenp
) - q
->tqe_th
->th_seq
;
401 if (i
< q
->tqe_len
) {
402 q
->tqe_th
->th_seq
+= i
;
408 nq
= LIST_NEXT(q
, tqe_q
);
409 LIST_REMOVE(q
, tqe_q
);
416 /* Insert the new segment queue entry into place. */
419 te
->tqe_len
= *tlenp
;
422 LIST_INSERT_HEAD(&tp
->t_segq
, te
, tqe_q
);
424 LIST_INSERT_AFTER(p
, te
, tqe_q
);
429 * Present data to user, advancing rcv_nxt through
430 * completed sequence space.
432 if (!TCPS_HAVEESTABLISHED(tp
->t_state
))
434 q
= LIST_FIRST(&tp
->t_segq
);
435 if (!q
|| q
->tqe_th
->th_seq
!= tp
->rcv_nxt
)
438 tp
->rcv_nxt
+= q
->tqe_len
;
439 flags
= q
->tqe_th
->th_flags
& TH_FIN
;
440 nq
= LIST_NEXT(q
, tqe_q
);
441 LIST_REMOVE(q
, tqe_q
);
442 if (so
->so_state
& SS_CANTRCVMORE
)
445 if (sbappendstream(&so
->so_rcv
, q
->tqe_m
))
451 } while (q
&& q
->tqe_th
->th_seq
== tp
->rcv_nxt
);
455 if ((tp
->t_inpcb
->inp_vflag
& INP_IPV6
) != 0) {
457 KERNEL_DEBUG(DBG_LAYER_BEG
,
458 ((tp
->t_inpcb
->inp_fport
<< 16) | tp
->t_inpcb
->inp_lport
),
459 (((tp
->t_inpcb
->in6p_laddr
.s6_addr16
[0] & 0xffff) << 16) |
460 (tp
->t_inpcb
->in6p_faddr
.s6_addr16
[0] & 0xffff)),
466 KERNEL_DEBUG(DBG_LAYER_BEG
,
467 ((tp
->t_inpcb
->inp_fport
<< 16) | tp
->t_inpcb
->inp_lport
),
468 (((tp
->t_inpcb
->inp_laddr
.s_addr
& 0xffff) << 16) |
469 (tp
->t_inpcb
->inp_faddr
.s_addr
& 0xffff)),
473 sorwakeup(so
); /* done with socket lock held */
479 * Reduce congestion window.
482 tcp_reduce_congestion_window(
487 win
= min(tp
->snd_wnd
, tp
->snd_cwnd
) /
491 tp
->snd_ssthresh
= win
* tp
->t_maxseg
;
492 ENTER_FASTRECOVERY(tp
);
493 tp
->snd_recover
= tp
->snd_max
;
494 tp
->t_timer
[TCPT_REXMT
] = 0;
496 tp
->ecn_flags
|= TE_SENDCWR
;
497 tp
->snd_cwnd
= tp
->snd_ssthresh
+
498 tp
->t_maxseg
* tcprexmtthresh
;
503 * TCP input routine, follows pages 65-76 of the
504 * protocol specification dated September, 1981 very closely.
512 register struct mbuf
*m
= *mp
;
513 struct in6_ifaddr
*ia6
;
515 IP6_EXTHDR_CHECK(m
, *offp
, sizeof(struct tcphdr
), return IPPROTO_DONE
);
518 * draft-itojun-ipv6-tcp-to-anycast
519 * better place to put this in?
521 ia6
= ip6_getdstifaddr(m
);
522 if (ia6
&& (ia6
->ia6_flags
& IN6_IFF_ANYCAST
)) {
525 ip6
= mtod(m
, struct ip6_hdr
*);
526 icmp6_error(m
, ICMP6_DST_UNREACH
, ICMP6_DST_UNREACH_ADDR
,
527 (caddr_t
)&ip6
->ip6_dst
- (caddr_t
)ip6
);
541 register struct tcphdr
*th
;
542 register struct ip
*ip
= NULL
;
543 register struct ipovly
*ipov
;
544 register struct inpcb
*inp
;
549 register struct tcpcb
*tp
= 0;
550 register int thflags
;
551 struct socket
*so
= 0;
552 int todrop
, acked
, ourfinisacked
, needoutput
= 0;
553 struct in_addr laddr
;
555 struct in6_addr laddr6
;
561 struct tcpopt to
; /* options in this segment */
562 struct sockaddr_in
*next_hop
= NULL
;
566 struct m_tag
*fwd_tag
;
567 u_char ip_ecn
= IPTOS_ECN_NOTECT
;
568 unsigned int ifscope
;
571 * Record the interface where this segment arrived on; this does not
572 * affect normal data output (for non-detached TCP) as it provides a
573 * hint about which route and interface to use for sending in the
574 * absence of a PCB, when scoped routing (and thus source interface
575 * selection) are enabled.
577 if ((m
->m_flags
& M_PKTHDR
) && m
->m_pkthdr
.rcvif
!= NULL
)
578 ifscope
= m
->m_pkthdr
.rcvif
->if_index
;
580 ifscope
= IFSCOPE_NONE
;
582 /* Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain. */
583 if (!SLIST_EMPTY(&m
->m_pkthdr
.tags
)) {
584 fwd_tag
= m_tag_locate(m
, KERNEL_MODULE_TAG_ID
,
585 KERNEL_TAG_TYPE_IPFORWARD
, NULL
);
589 if (fwd_tag
!= NULL
) {
590 struct ip_fwd_tag
*ipfwd_tag
= (struct ip_fwd_tag
*)(fwd_tag
+1);
592 next_hop
= ipfwd_tag
->next_hop
;
593 m_tag_delete(m
, fwd_tag
);
597 struct ip6_hdr
*ip6
= NULL
;
600 int rstreason
; /* For badport_bandlim accounting purposes */
601 struct proc
*proc0
=current_proc();
603 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_START
,0,0,0,0,0);
606 isipv6
= (mtod(m
, struct ip
*)->ip_v
== 6) ? 1 : 0;
608 bzero((char *)&to
, sizeof(to
));
610 tcpstat
.tcps_rcvtotal
++;
616 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
617 ip6
= mtod(m
, struct ip6_hdr
*);
618 tlen
= sizeof(*ip6
) + ntohs(ip6
->ip6_plen
) - off0
;
619 if (in6_cksum(m
, IPPROTO_TCP
, off0
, tlen
)) {
620 tcpstat
.tcps_rcvbadsum
++;
623 th
= (struct tcphdr
*)((caddr_t
)ip6
+ off0
);
625 KERNEL_DEBUG(DBG_LAYER_BEG
, ((th
->th_dport
<< 16) | th
->th_sport
),
626 (((ip6
->ip6_src
.s6_addr16
[0]) << 16) | (ip6
->ip6_dst
.s6_addr16
[0])),
627 th
->th_seq
, th
->th_ack
, th
->th_win
);
629 * Be proactive about unspecified IPv6 address in source.
630 * As we use all-zero to indicate unbounded/unconnected pcb,
631 * unspecified IPv6 address can be used to confuse us.
633 * Note that packets with unspecified IPv6 destination is
634 * already dropped in ip6_input.
636 if (IN6_IS_ADDR_UNSPECIFIED(&ip6
->ip6_src
)) {
644 * Get IP and TCP header together in first mbuf.
645 * Note: IP leaves IP header in first mbuf.
647 if (off0
> sizeof (struct ip
)) {
648 ip_stripoptions(m
, (struct mbuf
*)0);
649 off0
= sizeof(struct ip
);
650 if (m
->m_pkthdr
.csum_flags
& CSUM_TCP_SUM16
)
651 m
->m_pkthdr
.csum_flags
= 0; /* invalidate hwcksuming */
654 if (m
->m_len
< sizeof (struct tcpiphdr
)) {
655 if ((m
= m_pullup(m
, sizeof (struct tcpiphdr
))) == 0) {
656 tcpstat
.tcps_rcvshort
++;
660 ip
= mtod(m
, struct ip
*);
661 ipov
= (struct ipovly
*)ip
;
662 th
= (struct tcphdr
*)((caddr_t
)ip
+ off0
);
665 KERNEL_DEBUG(DBG_LAYER_BEG
, ((th
->th_dport
<< 16) | th
->th_sport
),
666 (((ip
->ip_src
.s_addr
& 0xffff) << 16) | (ip
->ip_dst
.s_addr
& 0xffff)),
667 th
->th_seq
, th
->th_ack
, th
->th_win
);
669 if (m
->m_pkthdr
.csum_flags
& CSUM_DATA_VALID
) {
670 if (m
->m_pkthdr
.csum_flags
& CSUM_TCP_SUM16
) {
673 *(uint32_t*)&b
[0] = *(uint32_t*)&ipov
->ih_x1
[0];
674 *(uint32_t*)&b
[4] = *(uint32_t*)&ipov
->ih_x1
[4];
675 *(uint8_t*)&b
[8] = *(uint8_t*)&ipov
->ih_x1
[8];
677 bzero(ipov
->ih_x1
, sizeof(ipov
->ih_x1
));
678 ipov
->ih_len
= (u_short
)tlen
;
680 #if BYTE_ORDER != BIG_ENDIAN
684 pseudo
= in_cksum(m
, sizeof (struct ip
));
686 *(uint32_t*)&ipov
->ih_x1
[0] = *(uint32_t*)&b
[0];
687 *(uint32_t*)&ipov
->ih_x1
[4] = *(uint32_t*)&b
[4];
688 *(uint8_t*)&ipov
->ih_x1
[8] = *(uint8_t*)&b
[8];
690 th
->th_sum
= in_addword(pseudo
, (m
->m_pkthdr
.csum_data
& 0xFFFF));
692 if (m
->m_pkthdr
.csum_flags
& CSUM_PSEUDO_HDR
)
693 th
->th_sum
= m
->m_pkthdr
.csum_data
;
695 th
->th_sum
= in_pseudo(ip
->ip_src
.s_addr
,
696 ip
->ip_dst
.s_addr
, htonl(m
->m_pkthdr
.csum_data
+
697 ip
->ip_len
+ IPPROTO_TCP
));
699 th
->th_sum
^= 0xffff;
703 * Checksum extended TCP header and data.
705 *(uint32_t*)&b
[0] = *(uint32_t*)&ipov
->ih_x1
[0];
706 *(uint32_t*)&b
[4] = *(uint32_t*)&ipov
->ih_x1
[4];
707 *(uint8_t*)&b
[8] = *(uint8_t*)&ipov
->ih_x1
[8];
709 len
= sizeof (struct ip
) + tlen
;
710 bzero(ipov
->ih_x1
, sizeof(ipov
->ih_x1
));
711 ipov
->ih_len
= (u_short
)tlen
;
713 #if BYTE_ORDER != BIG_ENDIAN
717 th
->th_sum
= in_cksum(m
, len
);
719 *(uint32_t*)&ipov
->ih_x1
[0] = *(uint32_t*)&b
[0];
720 *(uint32_t*)&ipov
->ih_x1
[4] = *(uint32_t*)&b
[4];
721 *(uint8_t*)&ipov
->ih_x1
[8] = *(uint8_t*)&b
[8];
723 tcp_in_cksum_stats(len
);
726 tcpstat
.tcps_rcvbadsum
++;
730 /* Re-initialization for later version check */
731 ip
->ip_v
= IPVERSION
;
733 ip_ecn
= (ip
->ip_tos
& IPTOS_ECN_MASK
);
737 * Check that TCP offset makes sense,
738 * pull out TCP options and adjust length. XXX
740 off
= th
->th_off
<< 2;
741 if (off
< sizeof (struct tcphdr
) || off
> tlen
) {
742 tcpstat
.tcps_rcvbadoff
++;
745 tlen
-= off
; /* tlen is used instead of ti->ti_len */
746 if (off
> sizeof (struct tcphdr
)) {
749 IP6_EXTHDR_CHECK(m
, off0
, off
, return);
750 ip6
= mtod(m
, struct ip6_hdr
*);
751 th
= (struct tcphdr
*)((caddr_t
)ip6
+ off0
);
755 if (m
->m_len
< sizeof(struct ip
) + off
) {
756 if ((m
= m_pullup(m
, sizeof (struct ip
) + off
)) == 0) {
757 tcpstat
.tcps_rcvshort
++;
760 ip
= mtod(m
, struct ip
*);
761 ipov
= (struct ipovly
*)ip
;
762 th
= (struct tcphdr
*)((caddr_t
)ip
+ off0
);
765 optlen
= off
- sizeof (struct tcphdr
);
766 optp
= (u_char
*)(th
+ 1);
768 * Do quick retrieval of timestamp options ("options
769 * prediction?"). If timestamp is the only option and it's
770 * formatted as recommended in RFC 1323 appendix A, we
771 * quickly get the values now and not bother calling
772 * tcp_dooptions(), etc.
774 if ((optlen
== TCPOLEN_TSTAMP_APPA
||
775 (optlen
> TCPOLEN_TSTAMP_APPA
&&
776 optp
[TCPOLEN_TSTAMP_APPA
] == TCPOPT_EOL
)) &&
777 *(u_int32_t
*)optp
== htonl(TCPOPT_TSTAMP_HDR
) &&
778 (th
->th_flags
& TH_SYN
) == 0) {
779 to
.to_flags
|= TOF_TS
;
780 to
.to_tsval
= ntohl(*(u_int32_t
*)(optp
+ 4));
781 to
.to_tsecr
= ntohl(*(u_int32_t
*)(optp
+ 8));
782 optp
= NULL
; /* we've parsed the options */
785 thflags
= th
->th_flags
;
789 * If the drop_synfin option is enabled, drop all packets with
790 * both the SYN and FIN bits set. This prevents e.g. nmap from
791 * identifying the TCP/IP stack.
793 * This is a violation of the TCP specification.
795 if (drop_synfin
&& (thflags
& (TH_SYN
|TH_FIN
)) == (TH_SYN
|TH_FIN
))
800 * Convert TCP protocol specific fields to host format.
803 #if BYTE_ORDER != BIG_ENDIAN
811 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options,
812 * until after ip6_savecontrol() is called and before other functions
813 * which don't want those proto headers.
814 * Because ip6_savecontrol() is going to parse the mbuf to
815 * search for data to be passed up to user-land, it wants mbuf
816 * parameters to be unchanged.
818 drop_hdrlen
= off0
+ off
;
821 * Locate pcb for segment.
824 #if IPFIREWALL_FORWARD
827 && isipv6
== 0 /* IPv6 support is not yet */
831 * Diverted. Pretend to be the destination.
832 * already got one like this?
834 inp
= in_pcblookup_hash(&tcbinfo
, ip
->ip_src
, th
->th_sport
,
835 ip
->ip_dst
, th
->th_dport
, 0, m
->m_pkthdr
.rcvif
);
838 * No, then it's new. Try find the ambushing socket
840 if (!next_hop
->sin_port
) {
841 inp
= in_pcblookup_hash(&tcbinfo
, ip
->ip_src
,
842 th
->th_sport
, next_hop
->sin_addr
,
843 th
->th_dport
, 1, m
->m_pkthdr
.rcvif
);
845 inp
= in_pcblookup_hash(&tcbinfo
,
846 ip
->ip_src
, th
->th_sport
,
848 ntohs(next_hop
->sin_port
), 1,
853 #endif /* IPFIREWALL_FORWARD */
857 inp
= in6_pcblookup_hash(&tcbinfo
, &ip6
->ip6_src
, th
->th_sport
,
858 &ip6
->ip6_dst
, th
->th_dport
, 1,
862 inp
= in_pcblookup_hash(&tcbinfo
, ip
->ip_src
, th
->th_sport
,
863 ip
->ip_dst
, th
->th_dport
, 1, m
->m_pkthdr
.rcvif
);
867 * Use the interface scope information from the PCB for outbound
868 * segments. If the PCB isn't present and if scoped routing is
869 * enabled, tcp_respond will use the scope of the interface where
870 * the segment arrived on.
872 if (inp
!= NULL
&& (inp
->inp_flags
& INP_BOUND_IF
))
873 ifscope
= inp
->inp_boundif
;
875 if (ipsec_bypass
== 0) {
878 if (inp
!= NULL
&& ipsec6_in_reject_so(m
, inp
->inp_socket
)) {
879 IPSEC_STAT_INCREMENT(ipsec6stat
.in_polvio
);
880 if (in_pcb_checkstate(inp
, WNT_RELEASE
, 0) == WNT_STOPUSING
)
881 inp
= NULL
; // pretend we didn't find it
886 if (inp
!= NULL
&& ipsec4_in_reject_so(m
, inp
->inp_socket
)) {
887 IPSEC_STAT_INCREMENT(ipsecstat
.in_polvio
);
888 if (in_pcb_checkstate(inp
, WNT_RELEASE
, 0) == WNT_STOPUSING
)
889 inp
= NULL
; // pretend we didn't find it
896 * If the state is CLOSED (i.e., TCB does not exist) then
897 * all data in the incoming segment is discarded.
898 * If the TCB exists but is in CLOSED state, it is embryonic,
899 * but should either do a listen or a connect soon.
904 char dbuf
[MAX_IPv6_STR_LEN
], sbuf
[MAX_IPv6_STR_LEN
];
906 char dbuf
[MAX_IPv4_STR_LEN
], sbuf
[MAX_IPv4_STR_LEN
];
911 inet_ntop(AF_INET6
, &ip6
->ip6_dst
, dbuf
, sizeof(dbuf
));
912 inet_ntop(AF_INET6
, &ip6
->ip6_src
, sbuf
, sizeof(sbuf
));
916 inet_ntop(AF_INET
, &ip
->ip_dst
, dbuf
, sizeof(dbuf
));
917 inet_ntop(AF_INET
, &ip
->ip_src
, sbuf
, sizeof(sbuf
));
919 switch (log_in_vain
) {
923 "Connection attempt to TCP %s:%d from %s:%d\n",
924 dbuf
, ntohs(th
->th_dport
),
926 ntohs(th
->th_sport
));
930 "Connection attempt to TCP %s:%d from %s:%d flags:0x%x\n",
931 dbuf
, ntohs(th
->th_dport
), sbuf
,
932 ntohs(th
->th_sport
), thflags
);
935 if ((thflags
& TH_SYN
) &&
936 !(m
->m_flags
& (M_BCAST
| M_MCAST
)) &&
938 ((isipv6
&& !IN6_ARE_ADDR_EQUAL(&ip6
->ip6_dst
, &ip6
->ip6_src
)) ||
939 (!isipv6
&& ip
->ip_dst
.s_addr
!= ip
->ip_src
.s_addr
))
941 ip
->ip_dst
.s_addr
!= ip
->ip_src
.s_addr
944 log_in_vain_log((LOG_INFO
,
945 "Stealth Mode connection attempt to TCP %s:%d from %s:%d\n",
946 dbuf
, ntohs(th
->th_dport
),
948 ntohs(th
->th_sport
)));
955 if (m
->m_pkthdr
.rcvif
&& m
->m_pkthdr
.rcvif
->if_type
!= IFT_LOOP
)
958 if (thflags
& TH_SYN
)
967 rstreason
= BANDLIM_RST_CLOSEDPORT
;
968 goto dropwithresetnosock
;
970 so
= inp
->inp_socket
;
972 /* This case shouldn't happen as the socket shouldn't be null
973 * if inp_state isn't set to INPCB_STATE_DEAD
974 * But just in case, we pretend we didn't find the socket if we hit this case
975 * as this isn't cause for a panic (the socket might be leaked however)...
979 printf("tcp_input: no more socket for inp=%x. This shouldn't happen\n", inp
);
984 tcp_lock(so
, 1, (void *)2);
985 if (in_pcb_checkstate(inp
, WNT_RELEASE
, 1) == WNT_STOPUSING
) {
986 tcp_unlock(so
, 1, (void *)2);
987 inp
= NULL
; // pretend we didn't find it
993 rstreason
= BANDLIM_RST_CLOSEDPORT
;
996 if (tp
->t_state
== TCPS_CLOSED
)
999 /* Unscale the window into a 32-bit value. */
1000 if ((thflags
& TH_SYN
) == 0)
1001 tiwin
= th
->th_win
<< tp
->snd_scale
;
1006 if (mac_inpcb_check_deliver(inp
, m
, AF_INET
, SOCK_STREAM
))
1010 if (so
->so_options
& (SO_DEBUG
|SO_ACCEPTCONN
)) {
1012 if (so
->so_options
& SO_DEBUG
) {
1013 ostate
= tp
->t_state
;
1016 bcopy((char *)ip6
, (char *)tcp_saveipgen
,
1020 bcopy((char *)ip
, (char *)tcp_saveipgen
, sizeof(*ip
));
1024 if (so
->so_options
& SO_ACCEPTCONN
) {
1025 register struct tcpcb
*tp0
= tp
;
1028 struct sockaddr_storage from
;
1030 struct inpcb
*oinp
= sotoinpcb(so
);
1032 unsigned int head_ifscope
;
1034 /* Get listener's bound-to-interface, if any */
1035 head_ifscope
= (inp
->inp_flags
& INP_BOUND_IF
) ?
1036 inp
->inp_boundif
: IFSCOPE_NONE
;
1040 * Current IPsec implementation makes incorrect IPsec
1041 * cache if this check is done here.
1042 * So delay this until duplicated socket is created.
1044 if ((thflags
& (TH_RST
|TH_ACK
|TH_SYN
)) != TH_SYN
) {
1046 * Note: dropwithreset makes sure we don't
1047 * send a RST in response to a RST.
1049 if (thflags
& TH_ACK
) {
1050 tcpstat
.tcps_badsyn
++;
1051 rstreason
= BANDLIM_RST_OPENPORT
;
1057 KERNEL_DEBUG(DBG_FNC_TCP_NEWCONN
| DBG_FUNC_START
,0,0,0,0,0);
1061 * If deprecated address is forbidden,
1062 * we do not accept SYN to deprecated interface
1063 * address to prevent any new inbound connection from
1064 * getting established.
1065 * When we do not accept SYN, we send a TCP RST,
1066 * with deprecated source address (instead of dropping
1067 * it). We compromise it as it is much better for peer
1068 * to send a RST, and RST will be the final packet
1071 * If we do not forbid deprecated addresses, we accept
1072 * the SYN packet. RFC2462 does not suggest dropping
1074 * If we decipher RFC2462 5.5.4, it says like this:
1075 * 1. use of deprecated addr with existing
1076 * communication is okay - "SHOULD continue to be
1078 * 2. use of it with new communication:
1079 * (2a) "SHOULD NOT be used if alternate address
1080 * with sufficient scope is available"
1081 * (2b) nothing mentioned otherwise.
1082 * Here we fall into (2b) case as we have no choice in
1083 * our source address selection - we must obey the peer.
1085 * The wording in RFC2462 is confusing, and there are
1086 * multiple description text for deprecated address
1087 * handling - worse, they are not exactly the same.
1088 * I believe 5.5.4 is the best one, so we follow 5.5.4.
1090 if (isipv6
&& !ip6_use_deprecated
) {
1091 struct in6_ifaddr
*ia6
;
1093 if ((ia6
= ip6_getdstifaddr(m
)) &&
1094 (ia6
->ia6_flags
& IN6_IFF_DEPRECATED
)) {
1096 rstreason
= BANDLIM_RST_OPENPORT
;
1104 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*)&from
;
1106 sin6
->sin6_len
= sizeof(*sin6
);
1107 sin6
->sin6_family
= AF_INET6
;
1108 sin6
->sin6_port
= th
->th_sport
;
1109 sin6
->sin6_flowinfo
= 0;
1110 sin6
->sin6_addr
= ip6
->ip6_src
;
1111 sin6
->sin6_scope_id
= 0;
1116 struct sockaddr_in
*sin
= (struct sockaddr_in
*)&from
;
1118 sin
->sin_len
= sizeof(*sin
);
1119 sin
->sin_family
= AF_INET
;
1120 sin
->sin_port
= th
->th_sport
;
1121 sin
->sin_addr
= ip
->ip_src
;
1123 so2
= sonewconn(so
, 0, (struct sockaddr
*)&from
);
1125 so2
= sonewconn(so
, 0, NULL
);
1128 tcpstat
.tcps_listendrop
++;
1129 if (tcp_dropdropablreq(so
)) {
1131 so2
= sonewconn(so
, 0, (struct sockaddr
*)&from
);
1133 so2
= sonewconn(so
, 0, NULL
);
1139 /* Point "inp" and "tp" in tandem to new socket */
1140 inp
= (struct inpcb
*)so2
->so_pcb
;
1141 tp
= intotcpcb(inp
);
1144 tcp_unlock(so
, 0, 0); /* Unlock but keep a reference on listener for now */
1149 * This is ugly, but ....
1151 * Mark socket as temporary until we're
1152 * committed to keeping it. The code at
1153 * ``drop'' and ``dropwithreset'' check the
1154 * flag dropsocket to see if the temporary
1155 * socket created here should be discarded.
1156 * We mark the socket as discardable until
1157 * we're committed to it below in TCPS_LISTEN.
1162 * Inherit INP_BOUND_IF from listener; testing if
1163 * head_ifscope is non-zero is sufficient, since it
1164 * can only be set to a non-zero value earlier if
1165 * the listener has such a flag set.
1168 if (head_ifscope
!= IFSCOPE_NONE
&& !isipv6
) {
1170 if (head_ifscope
!= IFSCOPE_NONE
) {
1172 inp
->inp_flags
|= INP_BOUND_IF
;
1173 inp
->inp_boundif
= head_ifscope
;
1177 inp
->in6p_laddr
= ip6
->ip6_dst
;
1179 inp
->inp_vflag
&= ~INP_IPV6
;
1180 inp
->inp_vflag
|= INP_IPV4
;
1182 inp
->inp_laddr
= ip
->ip_dst
;
1186 inp
->inp_lport
= th
->th_dport
;
1187 if (in_pcbinshash(inp
, 0) != 0) {
1189 * Undo the assignments above if we failed to
1190 * put the PCB on the hash lists.
1194 inp
->in6p_laddr
= in6addr_any
;
1197 inp
->inp_laddr
.s_addr
= INADDR_ANY
;
1199 tcp_lock(oso
, 0, 0); /* release ref on parent */
1200 tcp_unlock(oso
, 1, 0);
1205 * To avoid creating incorrectly cached IPsec
1206 * association, this is need to be done here.
1208 * Subject: (KAME-snap 748)
1209 * From: Wayne Knowles <w.knowles@niwa.cri.nz>
1210 * ftp://ftp.kame.net/pub/mail-list/snap-users/748
1212 if ((thflags
& (TH_RST
|TH_ACK
|TH_SYN
)) != TH_SYN
) {
1214 * Note: dropwithreset makes sure we don't
1215 * send a RST in response to a RST.
1217 tcp_lock(oso
, 0, 0); /* release ref on parent */
1218 tcp_unlock(oso
, 1, 0);
1219 if (thflags
& TH_ACK
) {
1220 tcpstat
.tcps_badsyn
++;
1221 rstreason
= BANDLIM_RST_OPENPORT
;
1230 * Inherit socket options from the listening
1232 * Note that in6p_inputopts are not (even
1233 * should not be) copied, since it stores
1234 * previously received options and is used to
1235 * detect if each new option is different than
1236 * the previous one and hence should be passed
1238 * If we copied in6p_inputopts, a user would
1239 * not be able to receive options just after
1240 * calling the accept system call.
1243 oinp
->inp_flags
& INP_CONTROLOPTS
;
1244 if (oinp
->in6p_outputopts
)
1245 inp
->in6p_outputopts
=
1246 ip6_copypktopts(oinp
->in6p_outputopts
,
1250 inp
->inp_options
= ip_srcroute();
1251 tcp_lock(oso
, 0, 0);
1253 /* copy old policy into new socket's */
1254 if (sotoinpcb(oso
)->inp_sp
)
1257 /* Is it a security hole here to silently fail to copy the policy? */
1258 if (inp
->inp_sp
!= NULL
)
1259 error
= ipsec_init_policy(so
, &inp
->inp_sp
);
1260 if (error
!= 0 || ipsec_copy_policy(sotoinpcb(oso
)->inp_sp
, inp
->inp_sp
))
1261 printf("tcp_input: could not copy policy\n");
1264 /* inherit states from the listener */
1265 tp
->t_state
= TCPS_LISTEN
;
1266 tp
->t_flags
|= tp0
->t_flags
& (TF_NOPUSH
|TF_NOOPT
|TF_NODELAY
);
1267 tp
->t_keepinit
= tp0
->t_keepinit
;
1268 tp
->t_inpcb
->inp_ip_ttl
= tp0
->t_inpcb
->inp_ip_ttl
;
1270 /* now drop the reference on the listener */
1271 tcp_unlock(oso
, 1, 0);
1273 /* Compute proper scaling value from buffer space */
1274 if (inp
->inp_pcbinfo
->ipi_count
< tcp_sockthreshold
) {
1275 tp
->request_r_scale
= max(tcp_win_scale
, tp
->request_r_scale
);
1276 so
->so_rcv
.sb_hiwat
= imin(TCP_MAXWIN
<< tp
->request_r_scale
, (sb_max
/ (MSIZE
+MCLBYTES
)) * MCLBYTES
);
1279 while (tp
->request_r_scale
< TCP_MAX_WINSHIFT
&&
1280 TCP_MAXWIN
<< tp
->request_r_scale
<
1281 so
->so_rcv
.sb_hiwat
)
1282 tp
->request_r_scale
++;
1285 KERNEL_DEBUG(DBG_FNC_TCP_NEWCONN
| DBG_FUNC_END
,0,0,0,0,0);
1290 lck_mtx_assert(((struct inpcb
*)so
->so_pcb
)->inpcb_mtx
, LCK_MTX_ASSERT_OWNED
);
1294 * This is the second part of the MSS DoS prevention code (after
1295 * minmss on the sending side) and it deals with too many too small
1296 * tcp packets in a too short timeframe (1 second).
1298 * For every full second we count the number of received packets
1299 * and bytes. If we get a lot of packets per second for this connection
1300 * (tcp_minmssoverload) we take a closer look at it and compute the
1301 * average packet size for the past second. If that is less than
1302 * tcp_minmss we get too many packets with very small payload which
1303 * is not good and burdens our system (and every packet generates
1304 * a wakeup to the process connected to our socket). We can reasonable
1305 * expect this to be small packet DoS attack to exhaust our CPU
1308 * Care has to be taken for the minimum packet overload value. This
1309 * value defines the minimum number of packets per second before we
1310 * start to worry. This must not be too low to avoid killing for
1311 * example interactive connections with many small packets like
1314 * Setting either tcp_minmssoverload or tcp_minmss to "0" disables
1317 * Account for packet if payload packet, skip over ACK, etc.
1319 * The packet per second count is done all the time and is also used
1320 * by "DELAY_ACK" to detect streaming situations.
1323 if (tp
->t_state
== TCPS_ESTABLISHED
&& tlen
> 0) {
1324 if (tp
->rcv_reset
> tcp_now
) {
1326 tp
->rcv_byps
+= tlen
+ off
;
1327 if (tp
->rcv_byps
> tp
->rcv_maxbyps
)
1328 tp
->rcv_maxbyps
= tp
->rcv_byps
;
1330 * Setting either tcp_minmssoverload or tcp_minmss to "0" disables
1333 if (tcp_minmss
&& tcp_minmssoverload
&& tp
->rcv_pps
> tcp_minmssoverload
) {
1334 if ((tp
->rcv_byps
/ tp
->rcv_pps
) < tcp_minmss
) {
1335 char ipstrbuf
[MAX_IPv6_STR_LEN
];
1336 printf("too many small tcp packets from "
1337 "%s:%u, av. %ubyte/packet, "
1338 "dropping connection\n",
1341 inet_ntop(AF_INET6
, &inp
->in6p_faddr
, ipstrbuf
,
1344 inet_ntop(AF_INET
, &inp
->inp_faddr
, ipstrbuf
,
1347 tp
->rcv_byps
/ tp
->rcv_pps
);
1348 tp
= tcp_drop(tp
, ECONNRESET
);
1349 /* tcpstat.tcps_minmssdrops++; */
1354 tp
->rcv_reset
= tcp_now
+ TCP_RETRANSHZ
;
1356 tp
->rcv_byps
= tlen
+ off
;
1361 if (so
->so_traffic_mgt_flags
& TRAFFIC_MGT_SO_BACKGROUND
) {
1362 tcpstat
.tcps_bg_rcvtotal
++;
1364 /* Take snapshots of pkts recv;
1365 * tcpcb should have been initialized to 0 when allocated,
1366 * so if 0 then this is the first time we're doing this
1368 if (!tp
->tot_recv_snapshot
) {
1369 tp
->tot_recv_snapshot
= tcpstat
.tcps_rcvtotal
;
1371 if (!tp
->bg_recv_snapshot
) {
1372 tp
->bg_recv_snapshot
= tcpstat
.tcps_bg_rcvtotal
;
1375 #endif /* TRAFFIC_MGT */
1378 Explicit Congestion Notification - Flag that we need to send ECT if
1379 + The IP Congestion experienced flag was set.
1380 + Socket is in established state
1381 + We negotiated ECN in the TCP setup
1382 + This isn't a pure ack (tlen > 0)
1383 + The data is in the valid window
1385 TE_SENDECE will be cleared when we receive a packet with TH_CWR set.
1387 if (ip_ecn
== IPTOS_ECN_CE
&& tp
->t_state
== TCPS_ESTABLISHED
&&
1388 (tp
->ecn_flags
& (TE_SETUPSENT
| TE_SETUPRECEIVED
)) ==
1389 (TE_SETUPSENT
| TE_SETUPRECEIVED
) && tlen
> 0 &&
1390 SEQ_GEQ(th
->th_seq
, tp
->last_ack_sent
) &&
1391 SEQ_LT(th
->th_seq
, tp
->last_ack_sent
+ tp
->rcv_wnd
)) {
1392 tp
->ecn_flags
|= TE_SENDECE
;
1396 Clear TE_SENDECE if TH_CWR is set. This is harmless, so we don't
1397 bother doing extensive checks for state and whatnot.
1399 if ((thflags
& TH_CWR
) == TH_CWR
) {
1400 tp
->ecn_flags
&= ~TE_SENDECE
;
1404 * Segment received on connection.
1405 * Reset idle time and keep-alive timer.
1408 if (TCPS_HAVEESTABLISHED(tp
->t_state
))
1409 tp
->t_timer
[TCPT_KEEP
] = TCP_KEEPIDLE(tp
);
1412 * Process options if not in LISTEN state,
1413 * else do it below (after getting remote address).
1415 if (tp
->t_state
!= TCPS_LISTEN
&& optp
)
1416 tcp_dooptions(tp
, optp
, optlen
, th
, &to
, ifscope
);
1418 if (tp
->t_state
== TCPS_SYN_SENT
&& (thflags
& TH_SYN
)) {
1419 if (to
.to_flags
& TOF_SCALE
) {
1420 tp
->t_flags
|= TF_RCVD_SCALE
;
1421 tp
->requested_s_scale
= to
.to_requested_s_scale
;
1422 tp
->snd_wnd
= th
->th_win
<< tp
->snd_scale
;
1423 tiwin
= tp
->snd_wnd
;
1425 if (to
.to_flags
& TOF_TS
) {
1426 tp
->t_flags
|= TF_RCVD_TSTMP
;
1427 tp
->ts_recent
= to
.to_tsval
;
1428 tp
->ts_recent_age
= tcp_now
;
1430 if (to
.to_flags
& TOF_MSS
)
1431 tcp_mss(tp
, to
.to_mss
, ifscope
);
1432 if (tp
->sack_enable
) {
1433 if (!(to
.to_flags
& TOF_SACK
))
1434 tp
->sack_enable
= 0;
1436 tp
->t_flags
|= TF_SACK_PERMIT
;
1441 * Header prediction: check for the two common cases
1442 * of a uni-directional data xfer. If the packet has
1443 * no control flags, is in-sequence, the window didn't
1444 * change and we're not retransmitting, it's a
1445 * candidate. If the length is zero and the ack moved
1446 * forward, we're the sender side of the xfer. Just
1447 * free the data acked & wake any higher level process
1448 * that was blocked waiting for space. If the length
1449 * is non-zero and the ack didn't move, we're the
1450 * receiver side. If we're getting packets in-order
1451 * (the reassembly queue is empty), add the data to
1452 * the socket buffer and note that we need a delayed ack.
1453 * Make sure that the hidden state-flags are also off.
1454 * Since we check for TCPS_ESTABLISHED above, it can only
1457 if (tp
->t_state
== TCPS_ESTABLISHED
&&
1458 (thflags
& (TH_SYN
|TH_FIN
|TH_RST
|TH_URG
|TH_ACK
|TH_ECE
)) == TH_ACK
&&
1459 ((tp
->t_flags
& (TF_NEEDSYN
|TF_NEEDFIN
)) == 0) &&
1460 ((to
.to_flags
& TOF_TS
) == 0 ||
1461 TSTMP_GEQ(to
.to_tsval
, tp
->ts_recent
)) &&
1462 th
->th_seq
== tp
->rcv_nxt
&&
1463 tiwin
&& tiwin
== tp
->snd_wnd
&&
1464 tp
->snd_nxt
== tp
->snd_max
) {
1467 * If last ACK falls within this segment's sequence numbers,
1468 * record the timestamp.
1469 * NOTE that the test is modified according to the latest
1470 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1472 if ((to
.to_flags
& TOF_TS
) != 0 &&
1473 SEQ_LEQ(th
->th_seq
, tp
->last_ack_sent
)) {
1474 tp
->ts_recent_age
= tcp_now
;
1475 tp
->ts_recent
= to
.to_tsval
;
1478 /* Force acknowledgment if we received a FIN */
1480 if (thflags
& TH_FIN
)
1481 tp
->t_flags
|= TF_ACKNOW
;
1484 if (SEQ_GT(th
->th_ack
, tp
->snd_una
) &&
1485 SEQ_LEQ(th
->th_ack
, tp
->snd_max
) &&
1486 tp
->snd_cwnd
>= tp
->snd_ssthresh
&&
1487 ((!tcp_do_newreno
&& !tp
->sack_enable
&&
1488 tp
->t_dupacks
< tcprexmtthresh
) ||
1489 ((tcp_do_newreno
|| tp
->sack_enable
) &&
1490 !IN_FASTRECOVERY(tp
) && to
.to_nsacks
== 0 &&
1491 TAILQ_EMPTY(&tp
->snd_holes
)))) {
1493 * this is a pure ack for outstanding data.
1495 ++tcpstat
.tcps_predack
;
1497 * "bad retransmit" recovery
1499 if (tp
->t_rxtshift
== 1 &&
1500 tcp_now
< tp
->t_badrxtwin
) {
1501 ++tcpstat
.tcps_sndrexmitbad
;
1502 tp
->snd_cwnd
= tp
->snd_cwnd_prev
;
1504 tp
->snd_ssthresh_prev
;
1505 tp
->snd_recover
= tp
->snd_recover_prev
;
1506 if (tp
->t_flags
& TF_WASFRECOVERY
)
1507 ENTER_FASTRECOVERY(tp
);
1508 tp
->snd_nxt
= tp
->snd_max
;
1509 tp
->t_badrxtwin
= 0;
1512 * Recalculate the transmit timer / rtt.
1514 * Some boxes send broken timestamp replies
1515 * during the SYN+ACK phase, ignore
1516 * timestamps of 0 or we could calculate a
1517 * huge RTT and blow up the retransmit timer.
1519 if (((to
.to_flags
& TOF_TS
) != 0) && (to
.to_tsecr
!= 0)) { /* Makes sure we already have a TS */
1520 if (!tp
->t_rttlow
||
1521 tp
->t_rttlow
> tcp_now
- to
.to_tsecr
)
1522 tp
->t_rttlow
= tcp_now
- to
.to_tsecr
;
1524 tcp_now
- to
.to_tsecr
);
1525 } else if (tp
->t_rtttime
&&
1526 SEQ_GT(th
->th_ack
, tp
->t_rtseq
)) {
1527 if (!tp
->t_rttlow
||
1528 tp
->t_rttlow
> tcp_now
- tp
->t_rtttime
)
1529 tp
->t_rttlow
= tcp_now
- tp
->t_rtttime
;
1530 tcp_xmit_timer(tp
, tp
->t_rtttime
);
1532 acked
= th
->th_ack
- tp
->snd_una
;
1533 tcpstat
.tcps_rcvackpack
++;
1534 tcpstat
.tcps_rcvackbyte
+= acked
;
1536 * Grow the congestion window, if the
1537 * connection is cwnd bound.
1539 if (tp
->snd_cwnd
< tp
->snd_wnd
) {
1540 tp
->t_bytes_acked
+= acked
;
1541 if (tp
->t_bytes_acked
> tp
->snd_cwnd
) {
1542 tp
->t_bytes_acked
-= tp
->snd_cwnd
;
1543 tp
->snd_cwnd
+= tp
->t_maxseg
;
1546 sbdrop(&so
->so_snd
, acked
);
1547 if (SEQ_GT(tp
->snd_una
, tp
->snd_recover
) &&
1548 SEQ_LEQ(th
->th_ack
, tp
->snd_recover
))
1549 tp
->snd_recover
= th
->th_ack
- 1;
1550 tp
->snd_una
= th
->th_ack
;
1552 * pull snd_wl2 up to prevent seq wrap relative
1555 tp
->snd_wl2
= th
->th_ack
;
1558 ND6_HINT(tp
); /* some progress has been done */
1561 * If all outstanding data are acked, stop
1562 * retransmit timer, otherwise restart timer
1563 * using current (possibly backed-off) value.
1564 * If process is waiting for space,
1565 * wakeup/selwakeup/signal. If data
1566 * are ready to send, let tcp_output
1567 * decide between more output or persist.
1569 if (tp
->snd_una
== tp
->snd_max
)
1570 tp
->t_timer
[TCPT_REXMT
] = 0;
1571 else if (tp
->t_timer
[TCPT_PERSIST
] == 0)
1572 tp
->t_timer
[TCPT_REXMT
] = tp
->t_rxtcur
;
1574 sowwakeup(so
); /* has to be done with socket lock held */
1575 if ((so
->so_snd
.sb_cc
) || (tp
->t_flags
& TF_ACKNOW
)) {
1576 tp
->t_unacksegs
= 0;
1577 (void) tcp_output(tp
);
1579 tcp_unlock(so
, 1, 0);
1580 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
1583 } else if (th
->th_ack
== tp
->snd_una
&&
1584 LIST_EMPTY(&tp
->t_segq
) &&
1585 tlen
<= tcp_sbspace(tp
)) {
1587 * this is a pure, in-sequence data packet
1588 * with nothing on the reassembly queue and
1589 * we have enough buffer space to take it.
1591 /* Clean receiver SACK report if present */
1592 if (tp
->sack_enable
&& tp
->rcv_numsacks
)
1593 tcp_clean_sackreport(tp
);
1594 ++tcpstat
.tcps_preddat
;
1595 tp
->rcv_nxt
+= tlen
;
1597 * Pull snd_wl1 up to prevent seq wrap relative to
1600 tp
->snd_wl1
= th
->th_seq
;
1602 * Pull rcv_up up to prevent seq wrap relative to
1605 tp
->rcv_up
= tp
->rcv_nxt
;
1606 tcpstat
.tcps_rcvpack
++;
1607 tcpstat
.tcps_rcvbyte
+= tlen
;
1608 ND6_HINT(tp
); /* some progress has been done */
1610 * Add data to socket buffer.
1612 m_adj(m
, drop_hdrlen
); /* delayed header drop */
1613 if (sbappendstream(&so
->so_rcv
, m
))
1617 KERNEL_DEBUG(DBG_LAYER_END
, ((th
->th_dport
<< 16) | th
->th_sport
),
1618 (((ip6
->ip6_src
.s6_addr16
[0]) << 16) | (ip6
->ip6_dst
.s6_addr16
[0])),
1619 th
->th_seq
, th
->th_ack
, th
->th_win
);
1624 KERNEL_DEBUG(DBG_LAYER_END
, ((th
->th_dport
<< 16) | th
->th_sport
),
1625 (((ip
->ip_src
.s_addr
& 0xffff) << 16) | (ip
->ip_dst
.s_addr
& 0xffff)),
1626 th
->th_seq
, th
->th_ack
, th
->th_win
);
1628 if (DELAY_ACK(tp
)) {
1629 tp
->t_flags
|= TF_DELACK
;
1632 tp
->t_unacksegs
= 0;
1633 tp
->t_flags
|= TF_ACKNOW
;
1636 tcp_unlock(so
, 1, 0);
1637 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
1643 * Calculate amount of space in receive window,
1644 * and then do TCP input processing.
1645 * Receive window is amount of space in rcv queue,
1646 * but not less than advertised window.
1649 lck_mtx_assert(((struct inpcb
*)so
->so_pcb
)->inpcb_mtx
, LCK_MTX_ASSERT_OWNED
);
1653 win
= tcp_sbspace(tp
);
1657 else { /* clip rcv window to 4K for modems */
1658 if (tp
->t_flags
& TF_SLOWLINK
&& slowlink_wsize
> 0)
1659 win
= min(win
, slowlink_wsize
);
1661 tp
->rcv_wnd
= imax(win
, (int)(tp
->rcv_adv
- tp
->rcv_nxt
));
1664 switch (tp
->t_state
) {
1667 * If the state is LISTEN then ignore segment if it contains an RST.
1668 * If the segment contains an ACK then it is bad and send a RST.
1669 * If it does not contain a SYN then it is not interesting; drop it.
1670 * If it is from this socket, drop it, it must be forged.
1671 * Don't bother responding if the destination was a broadcast.
1672 * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial
1673 * tp->iss, and send a segment:
1674 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
1675 * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
1676 * Fill in remote peer address fields if not previously specified.
1677 * Enter SYN_RECEIVED state, and process any other fields of this
1678 * segment in this state.
1681 register struct sockaddr_in
*sin
;
1683 register struct sockaddr_in6
*sin6
;
1687 lck_mtx_assert(((struct inpcb
*)so
->so_pcb
)->inpcb_mtx
, LCK_MTX_ASSERT_OWNED
);
1689 if (thflags
& TH_RST
)
1691 if (thflags
& TH_ACK
) {
1692 rstreason
= BANDLIM_RST_OPENPORT
;
1695 if ((thflags
& TH_SYN
) == 0)
1697 if (th
->th_dport
== th
->th_sport
) {
1700 if (IN6_ARE_ADDR_EQUAL(&ip6
->ip6_dst
,
1705 if (ip
->ip_dst
.s_addr
== ip
->ip_src
.s_addr
)
1709 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
1710 * in_broadcast() should never return true on a received
1711 * packet with M_BCAST not set.
1713 * Packets with a multicast source address should also
1716 if (m
->m_flags
& (M_BCAST
|M_MCAST
))
1720 if (IN6_IS_ADDR_MULTICAST(&ip6
->ip6_dst
) ||
1721 IN6_IS_ADDR_MULTICAST(&ip6
->ip6_src
))
1725 if (IN_MULTICAST(ntohl(ip
->ip_dst
.s_addr
)) ||
1726 IN_MULTICAST(ntohl(ip
->ip_src
.s_addr
)) ||
1727 ip
->ip_src
.s_addr
== htonl(INADDR_BROADCAST
) ||
1728 in_broadcast(ip
->ip_dst
, m
->m_pkthdr
.rcvif
))
1732 MALLOC(sin6
, struct sockaddr_in6
*, sizeof *sin6
,
1733 M_SONAME
, M_NOWAIT
);
1736 bzero(sin6
, sizeof(*sin6
));
1737 sin6
->sin6_family
= AF_INET6
;
1738 sin6
->sin6_len
= sizeof(*sin6
);
1739 sin6
->sin6_addr
= ip6
->ip6_src
;
1740 sin6
->sin6_port
= th
->th_sport
;
1741 laddr6
= inp
->in6p_laddr
;
1742 if (IN6_IS_ADDR_UNSPECIFIED(&inp
->in6p_laddr
))
1743 inp
->in6p_laddr
= ip6
->ip6_dst
;
1744 if (in6_pcbconnect(inp
, (struct sockaddr
*)sin6
,
1746 inp
->in6p_laddr
= laddr6
;
1747 FREE(sin6
, M_SONAME
);
1750 FREE(sin6
, M_SONAME
);
1755 lck_mtx_assert(((struct inpcb
*)so
->so_pcb
)->inpcb_mtx
, LCK_MTX_ASSERT_OWNED
);
1757 MALLOC(sin
, struct sockaddr_in
*, sizeof *sin
, M_SONAME
,
1761 sin
->sin_family
= AF_INET
;
1762 sin
->sin_len
= sizeof(*sin
);
1763 sin
->sin_addr
= ip
->ip_src
;
1764 sin
->sin_port
= th
->th_sport
;
1765 bzero((caddr_t
)sin
->sin_zero
, sizeof(sin
->sin_zero
));
1766 laddr
= inp
->inp_laddr
;
1767 if (inp
->inp_laddr
.s_addr
== INADDR_ANY
)
1768 inp
->inp_laddr
= ip
->ip_dst
;
1769 if (in_pcbconnect(inp
, (struct sockaddr
*)sin
, proc0
)) {
1770 inp
->inp_laddr
= laddr
;
1771 FREE(sin
, M_SONAME
);
1774 FREE(sin
, M_SONAME
);
1777 tcp_dooptions(tp
, optp
, optlen
, th
, &to
, ifscope
);
1779 if (tp
->sack_enable
) {
1780 if (!(to
.to_flags
& TOF_SACK
))
1781 tp
->sack_enable
= 0;
1783 tp
->t_flags
|= TF_SACK_PERMIT
;
1789 tp
->iss
= tcp_new_isn(tp
);
1791 tp
->irs
= th
->th_seq
;
1792 tcp_sendseqinit(tp
);
1794 tp
->snd_recover
= tp
->snd_una
;
1796 * Initialization of the tcpcb for transaction;
1797 * set SND.WND = SEG.WND,
1798 * initialize CCsend and CCrecv.
1800 tp
->snd_wnd
= tiwin
; /* initial send-window */
1801 tp
->t_flags
|= TF_ACKNOW
;
1802 tp
->t_unacksegs
= 0;
1803 tp
->t_state
= TCPS_SYN_RECEIVED
;
1804 tp
->t_timer
[TCPT_KEEP
] = tp
->t_keepinit
? tp
->t_keepinit
: tcp_keepinit
;
1805 dropsocket
= 0; /* committed to socket */
1806 tcpstat
.tcps_accepts
++;
1807 if ((thflags
& (TH_ECE
| TH_CWR
)) == (TH_ECE
| TH_CWR
)) {
1809 tp
->ecn_flags
|= (TE_SETUPRECEIVED
| TE_SENDIPECT
);
1811 #if CONFIG_IFEF_NOWINDOWSCALE
1812 if (tcp_obey_ifef_nowindowscale
&& m
->m_pkthdr
.rcvif
!= NULL
&&
1813 (m
->m_pkthdr
.rcvif
->if_eflags
& IFEF_NOWINDOWSCALE
)) {
1814 /* Window scaling is not enabled on this interface */
1815 tp
->t_flags
&= ~TF_REQ_SCALE
;
1822 * If the state is SYN_RECEIVED:
1823 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1825 case TCPS_SYN_RECEIVED
:
1826 if ((thflags
& TH_ACK
) &&
1827 (SEQ_LEQ(th
->th_ack
, tp
->snd_una
) ||
1828 SEQ_GT(th
->th_ack
, tp
->snd_max
))) {
1829 rstreason
= BANDLIM_RST_OPENPORT
;
1835 * If the state is SYN_SENT:
1836 * if seg contains an ACK, but not for our SYN, drop the input.
1837 * if seg contains a RST, then drop the connection.
1838 * if seg does not contain SYN, then drop it.
1839 * Otherwise this is an acceptable SYN segment
1840 * initialize tp->rcv_nxt and tp->irs
1841 * if seg contains ack then advance tp->snd_una
1842 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1843 * arrange for segment to be acked (eventually)
1844 * continue processing rest of data/controls, beginning with URG
1847 if ((thflags
& TH_ACK
) &&
1848 (SEQ_LEQ(th
->th_ack
, tp
->iss
) ||
1849 SEQ_GT(th
->th_ack
, tp
->snd_max
))) {
1850 rstreason
= BANDLIM_UNLIMITED
;
1853 if (thflags
& TH_RST
) {
1854 if ((thflags
& TH_ACK
) != 0) {
1855 tp
= tcp_drop(tp
, ECONNREFUSED
);
1856 postevent(so
, 0, EV_RESET
);
1860 if ((thflags
& TH_SYN
) == 0)
1862 tp
->snd_wnd
= th
->th_win
; /* initial send window */
1864 tp
->irs
= th
->th_seq
;
1866 if (thflags
& TH_ACK
) {
1867 tcpstat
.tcps_connects
++;
1869 if ((thflags
& (TH_ECE
| TH_CWR
)) == (TH_ECE
)) {
1870 /* ECN-setup SYN-ACK */
1871 tp
->ecn_flags
|= TE_SETUPRECEIVED
;
1874 /* non-ECN-setup SYN-ACK */
1875 tp
->ecn_flags
&= ~TE_SENDIPECT
;
1878 #if CONFIG_MACF_NET && CONFIG_MACF_SOCKET
1879 /* XXXMAC: recursive lock: SOCK_LOCK(so); */
1880 mac_socketpeer_label_associate_mbuf(m
, so
);
1881 /* XXXMAC: SOCK_UNLOCK(so); */
1883 /* Do window scaling on this connection? */
1884 if ((tp
->t_flags
& (TF_RCVD_SCALE
|TF_REQ_SCALE
)) ==
1885 (TF_RCVD_SCALE
|TF_REQ_SCALE
)) {
1886 tp
->snd_scale
= tp
->requested_s_scale
;
1887 tp
->rcv_scale
= tp
->request_r_scale
;
1889 tp
->rcv_adv
+= tp
->rcv_wnd
;
1890 tp
->snd_una
++; /* SYN is acked */
1892 * If there's data, delay ACK; if there's also a FIN
1893 * ACKNOW will be turned on later.
1895 if (DELAY_ACK(tp
) && tlen
!= 0) {
1896 tp
->t_flags
|= TF_DELACK
;
1900 tp
->t_flags
|= TF_ACKNOW
;
1901 tp
->t_unacksegs
= 0;
1904 * Received <SYN,ACK> in SYN_SENT[*] state.
1906 * SYN_SENT --> ESTABLISHED
1907 * SYN_SENT* --> FIN_WAIT_1
1909 tp
->t_starttime
= 0;
1910 if (tp
->t_flags
& TF_NEEDFIN
) {
1911 tp
->t_state
= TCPS_FIN_WAIT_1
;
1912 tp
->t_flags
&= ~TF_NEEDFIN
;
1915 tp
->t_state
= TCPS_ESTABLISHED
;
1916 tp
->t_timer
[TCPT_KEEP
] = TCP_KEEPIDLE(tp
);
1918 /* soisconnected may lead to socket_unlock in case of upcalls,
1919 * make sure this is done when everything is setup.
1924 * Received initial SYN in SYN-SENT[*] state => simul-
1925 * taneous open. If segment contains CC option and there is
1926 * a cached CC, apply TAO test; if it succeeds, connection is
1927 * half-synchronized. Otherwise, do 3-way handshake:
1928 * SYN-SENT -> SYN-RECEIVED
1929 * SYN-SENT* -> SYN-RECEIVED*
1931 tp
->t_flags
|= TF_ACKNOW
;
1932 tp
->t_timer
[TCPT_REXMT
] = 0;
1933 tp
->t_state
= TCPS_SYN_RECEIVED
;
1939 * Advance th->th_seq to correspond to first data byte.
1940 * If data, trim to stay within window,
1941 * dropping FIN if necessary.
1944 if (tlen
> tp
->rcv_wnd
) {
1945 todrop
= tlen
- tp
->rcv_wnd
;
1949 tcpstat
.tcps_rcvpackafterwin
++;
1950 tcpstat
.tcps_rcvbyteafterwin
+= todrop
;
1952 tp
->snd_wl1
= th
->th_seq
- 1;
1953 tp
->rcv_up
= th
->th_seq
;
1955 * Client side of transaction: already sent SYN and data.
1956 * If the remote host used T/TCP to validate the SYN,
1957 * our data will be ACK'd; if so, enter normal data segment
1958 * processing in the middle of step 5, ack processing.
1959 * Otherwise, goto step 6.
1961 if (thflags
& TH_ACK
)
1965 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1966 * do normal processing.
1968 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
1972 case TCPS_TIME_WAIT
:
1973 break; /* continue normal processing */
1975 /* Received a SYN while connection is already established.
1976 * This is a "half open connection and other anomalies" described
1977 * in RFC793 page 34, send an ACK so the remote reset the connection
1978 * or recovers by adjusting its sequence numberering
1980 case TCPS_ESTABLISHED
:
1981 if (thflags
& TH_SYN
)
1987 * States other than LISTEN or SYN_SENT.
1988 * First check the RST flag and sequence number since reset segments
1989 * are exempt from the timestamp and connection count tests. This
1990 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1991 * below which allowed reset segments in half the sequence space
1992 * to fall though and be processed (which gives forged reset
1993 * segments with a random sequence number a 50 percent chance of
1994 * killing a connection).
1995 * Then check timestamp, if present.
1996 * Then check the connection count, if present.
1997 * Then check that at least some bytes of segment are within
1998 * receive window. If segment begins before rcv_nxt,
1999 * drop leading data (and SYN); if nothing left, just ack.
2002 * If the RST bit is set, check the sequence number to see
2003 * if this is a valid reset segment.
2005 * In all states except SYN-SENT, all reset (RST) segments
2006 * are validated by checking their SEQ-fields. A reset is
2007 * valid if its sequence number is in the window.
2008 * Note: this does not take into account delayed ACKs, so
2009 * we should test against last_ack_sent instead of rcv_nxt.
2010 * The sequence number in the reset segment is normally an
2011 * echo of our outgoing acknowlegement numbers, but some hosts
2012 * send a reset with the sequence number at the rightmost edge
2013 * of our receive window, and we have to handle this case.
2014 * Note 2: Paul Watson's paper "Slipping in the Window" has shown
2015 * that brute force RST attacks are possible. To combat this,
2016 * we use a much stricter check while in the ESTABLISHED state,
2017 * only accepting RSTs where the sequence number is equal to
2018 * last_ack_sent. In all other states (the states in which a
2019 * RST is more likely), the more permissive check is used.
2020 * If we have multiple segments in flight, the intial reset
2021 * segment sequence numbers will be to the left of last_ack_sent,
2022 * but they will eventually catch up.
2023 * In any case, it never made sense to trim reset segments to
2024 * fit the receive window since RFC 1122 says:
2025 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
2027 * A TCP SHOULD allow a received RST segment to include data.
2030 * It has been suggested that a RST segment could contain
2031 * ASCII text that encoded and explained the cause of the
2032 * RST. No standard has yet been established for such
2035 * If the reset segment passes the sequence number test examine
2037 * SYN_RECEIVED STATE:
2038 * If passive open, return to LISTEN state.
2039 * If active open, inform user that connection was refused.
2040 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
2041 * Inform user that connection was reset, and close tcb.
2042 * CLOSING, LAST_ACK STATES:
2045 * Drop the segment - see Stevens, vol. 2, p. 964 and
2048 * Radar 4803931: Allows for the case where we ACKed the FIN but
2049 * there is already a RST in flight from the peer.
2050 * In that case, accept the RST for non-established
2051 * state if it's one off from last_ack_sent.
2054 if (thflags
& TH_RST
) {
2055 if ((SEQ_GEQ(th
->th_seq
, tp
->last_ack_sent
) &&
2056 SEQ_LT(th
->th_seq
, tp
->last_ack_sent
+ tp
->rcv_wnd
)) ||
2057 (tp
->rcv_wnd
== 0 &&
2058 ((tp
->last_ack_sent
== th
->th_seq
) || ((tp
->last_ack_sent
-1) == th
->th_seq
)))) {
2059 switch (tp
->t_state
) {
2061 case TCPS_SYN_RECEIVED
:
2062 so
->so_error
= ECONNREFUSED
;
2065 case TCPS_ESTABLISHED
:
2066 if (tp
->last_ack_sent
!= th
->th_seq
) {
2067 tcpstat
.tcps_badrst
++;
2070 case TCPS_FIN_WAIT_1
:
2071 case TCPS_CLOSE_WAIT
:
2075 case TCPS_FIN_WAIT_2
:
2076 so
->so_error
= ECONNRESET
;
2078 postevent(so
, 0, EV_RESET
);
2079 tp
->t_state
= TCPS_CLOSED
;
2080 tcpstat
.tcps_drops
++;
2089 case TCPS_TIME_WAIT
:
2097 lck_mtx_assert(((struct inpcb
*)so
->so_pcb
)->inpcb_mtx
, LCK_MTX_ASSERT_OWNED
);
2101 * RFC 1323 PAWS: If we have a timestamp reply on this segment
2102 * and it's less than ts_recent, drop it.
2104 if ((to
.to_flags
& TOF_TS
) != 0 && tp
->ts_recent
&&
2105 TSTMP_LT(to
.to_tsval
, tp
->ts_recent
)) {
2107 /* Check to see if ts_recent is over 24 days old. */
2108 if ((int)(tcp_now
- tp
->ts_recent_age
) > TCP_PAWS_IDLE
) {
2110 * Invalidate ts_recent. If this segment updates
2111 * ts_recent, the age will be reset later and ts_recent
2112 * will get a valid value. If it does not, setting
2113 * ts_recent to zero will at least satisfy the
2114 * requirement that zero be placed in the timestamp
2115 * echo reply when ts_recent isn't valid. The
2116 * age isn't reset until we get a valid ts_recent
2117 * because we don't want out-of-order segments to be
2118 * dropped when ts_recent is old.
2122 tcpstat
.tcps_rcvduppack
++;
2123 tcpstat
.tcps_rcvdupbyte
+= tlen
;
2124 tcpstat
.tcps_pawsdrop
++;
2132 * In the SYN-RECEIVED state, validate that the packet belongs to
2133 * this connection before trimming the data to fit the receive
2134 * window. Check the sequence number versus IRS since we know
2135 * the sequence numbers haven't wrapped. This is a partial fix
2136 * for the "LAND" DoS attack.
2138 if (tp
->t_state
== TCPS_SYN_RECEIVED
&& SEQ_LT(th
->th_seq
, tp
->irs
)) {
2139 rstreason
= BANDLIM_RST_OPENPORT
;
2143 todrop
= tp
->rcv_nxt
- th
->th_seq
;
2145 if (thflags
& TH_SYN
) {
2155 * Following if statement from Stevens, vol. 2, p. 960.
2158 || (todrop
== tlen
&& (thflags
& TH_FIN
) == 0)) {
2160 * Any valid FIN must be to the left of the window.
2161 * At this point the FIN must be a duplicate or out
2162 * of sequence; drop it.
2167 * Send an ACK to resynchronize and drop any data.
2168 * But keep on processing for RST or ACK.
2170 tp
->t_flags
|= TF_ACKNOW
;
2171 tp
->t_unacksegs
= 0;
2173 tcpstat
.tcps_rcvduppack
++;
2174 tcpstat
.tcps_rcvdupbyte
+= todrop
;
2176 tcpstat
.tcps_rcvpartduppack
++;
2177 tcpstat
.tcps_rcvpartdupbyte
+= todrop
;
2179 drop_hdrlen
+= todrop
; /* drop from the top afterwards */
2180 th
->th_seq
+= todrop
;
2182 if (th
->th_urp
> todrop
)
2183 th
->th_urp
-= todrop
;
2191 * If new data are received on a connection after the
2192 * user processes are gone, then RST the other end.
2194 if ((so
->so_state
& SS_NOFDREF
) &&
2195 tp
->t_state
> TCPS_CLOSE_WAIT
&& tlen
) {
2197 tcpstat
.tcps_rcvafterclose
++;
2198 rstreason
= BANDLIM_UNLIMITED
;
2203 * If segment ends after window, drop trailing data
2204 * (and PUSH and FIN); if nothing left, just ACK.
2206 todrop
= (th
->th_seq
+tlen
) - (tp
->rcv_nxt
+tp
->rcv_wnd
);
2208 tcpstat
.tcps_rcvpackafterwin
++;
2209 if (todrop
>= tlen
) {
2210 tcpstat
.tcps_rcvbyteafterwin
+= tlen
;
2212 * If a new connection request is received
2213 * while in TIME_WAIT, drop the old connection
2214 * and start over if the sequence numbers
2215 * are above the previous ones.
2217 if (thflags
& TH_SYN
&&
2218 tp
->t_state
== TCPS_TIME_WAIT
&&
2219 SEQ_GT(th
->th_seq
, tp
->rcv_nxt
)) {
2220 iss
= tcp_new_isn(tp
);
2222 tcp_unlock(so
, 1, 0);
2226 * If window is closed can only take segments at
2227 * window edge, and have to drop data and PUSH from
2228 * incoming segments. Continue processing, but
2229 * remember to ack. Otherwise, drop segment
2232 if (tp
->rcv_wnd
== 0 && th
->th_seq
== tp
->rcv_nxt
) {
2233 tp
->t_flags
|= TF_ACKNOW
;
2234 tp
->t_unacksegs
= 0;
2235 tcpstat
.tcps_rcvwinprobe
++;
2239 tcpstat
.tcps_rcvbyteafterwin
+= todrop
;
2242 thflags
&= ~(TH_PUSH
|TH_FIN
);
2246 * If last ACK falls within this segment's sequence numbers,
2247 * record its timestamp.
2249 * 1) That the test incorporates suggestions from the latest
2250 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
2251 * 2) That updating only on newer timestamps interferes with
2252 * our earlier PAWS tests, so this check should be solely
2253 * predicated on the sequence space of this segment.
2254 * 3) That we modify the segment boundary check to be
2255 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
2256 * instead of RFC1323's
2257 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
2258 * This modified check allows us to overcome RFC1323's
2259 * limitations as described in Stevens TCP/IP Illustrated
2260 * Vol. 2 p.869. In such cases, we can still calculate the
2261 * RTT correctly when RCV.NXT == Last.ACK.Sent.
2263 if ((to
.to_flags
& TOF_TS
) != 0 &&
2264 SEQ_LEQ(th
->th_seq
, tp
->last_ack_sent
) &&
2265 SEQ_LEQ(tp
->last_ack_sent
, th
->th_seq
+ tlen
+
2266 ((thflags
& (TH_SYN
|TH_FIN
)) != 0))) {
2267 tp
->ts_recent_age
= tcp_now
;
2268 tp
->ts_recent
= to
.to_tsval
;
2272 * If a SYN is in the window, then this is an
2273 * error and we send an RST and drop the connection.
2275 if (thflags
& TH_SYN
) {
2276 tp
= tcp_drop(tp
, ECONNRESET
);
2277 rstreason
= BANDLIM_UNLIMITED
;
2278 postevent(so
, 0, EV_RESET
);
2283 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
2284 * flag is on (half-synchronized state), then queue data for
2285 * later processing; else drop segment and return.
2287 if ((thflags
& TH_ACK
) == 0) {
2288 if (tp
->t_state
== TCPS_SYN_RECEIVED
||
2289 (tp
->t_flags
& TF_NEEDSYN
))
2291 else if (tp
->t_flags
& TF_ACKNOW
)
2300 switch (tp
->t_state
) {
2303 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
2304 * ESTABLISHED state and continue processing.
2305 * The ACK was checked above.
2307 case TCPS_SYN_RECEIVED
:
2309 tcpstat
.tcps_connects
++;
2311 /* Do window scaling? */
2312 if ((tp
->t_flags
& (TF_RCVD_SCALE
|TF_REQ_SCALE
)) ==
2313 (TF_RCVD_SCALE
|TF_REQ_SCALE
)) {
2314 tp
->snd_scale
= tp
->requested_s_scale
;
2315 tp
->rcv_scale
= tp
->request_r_scale
;
2319 * SYN-RECEIVED -> ESTABLISHED
2320 * SYN-RECEIVED* -> FIN-WAIT-1
2322 tp
->t_starttime
= 0;
2323 if (tp
->t_flags
& TF_NEEDFIN
) {
2324 tp
->t_state
= TCPS_FIN_WAIT_1
;
2325 tp
->t_flags
&= ~TF_NEEDFIN
;
2327 tp
->t_state
= TCPS_ESTABLISHED
;
2328 tp
->t_timer
[TCPT_KEEP
] = TCP_KEEPIDLE(tp
);
2331 * If segment contains data or ACK, will call tcp_reass()
2332 * later; if not, do so now to pass queued data to user.
2334 if (tlen
== 0 && (thflags
& TH_FIN
) == 0)
2335 (void) tcp_reass(tp
, (struct tcphdr
*)0, &tlen
,
2337 tp
->snd_wl1
= th
->th_seq
- 1;
2341 /* soisconnected may lead to socket_unlock in case of upcalls,
2342 * make sure this is done when everything is setup.
2347 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2348 * ACKs. If the ack is in the range
2349 * tp->snd_una < th->th_ack <= tp->snd_max
2350 * then advance tp->snd_una to th->th_ack and drop
2351 * data from the retransmission queue. If this ACK reflects
2352 * more up to date window information we update our window information.
2354 case TCPS_ESTABLISHED
:
2355 case TCPS_FIN_WAIT_1
:
2356 case TCPS_FIN_WAIT_2
:
2357 case TCPS_CLOSE_WAIT
:
2360 case TCPS_TIME_WAIT
:
2361 if (SEQ_GT(th
->th_ack
, tp
->snd_max
)) {
2362 tcpstat
.tcps_rcvacktoomuch
++;
2365 if (tp
->sack_enable
&&
2366 (to
.to_nsacks
> 0 || !TAILQ_EMPTY(&tp
->snd_holes
)))
2367 tcp_sack_doack(tp
, &to
, th
->th_ack
);
2368 if (SEQ_LEQ(th
->th_ack
, tp
->snd_una
)) {
2369 if (tlen
== 0 && tiwin
== tp
->snd_wnd
) {
2370 tcpstat
.tcps_rcvdupack
++;
2372 * If we have outstanding data (other than
2373 * a window probe), this is a completely
2374 * duplicate ack (ie, window info didn't
2375 * change), the ack is the biggest we've
2376 * seen and we've seen exactly our rexmt
2377 * threshhold of them, assume a packet
2378 * has been dropped and retransmit it.
2379 * Kludge snd_nxt & the congestion
2380 * window so we send only this one
2383 * We know we're losing at the current
2384 * window size so do congestion avoidance
2385 * (set ssthresh to half the current window
2386 * and pull our congestion window back to
2387 * the new ssthresh).
2389 * Dup acks mean that packets have left the
2390 * network (they're now cached at the receiver)
2391 * so bump cwnd by the amount in the receiver
2392 * to keep a constant cwnd packets in the
2395 if (tp
->t_timer
[TCPT_REXMT
] == 0 ||
2396 th
->th_ack
!= tp
->snd_una
)
2398 else if (++tp
->t_dupacks
> tcprexmtthresh
||
2399 ((tcp_do_newreno
|| tp
->sack_enable
) &&
2400 IN_FASTRECOVERY(tp
))) {
2401 if (tp
->sack_enable
&& IN_FASTRECOVERY(tp
)) {
2405 * Compute the amount of data in flight first.
2406 * We can inject new data into the pipe iff
2407 * we have less than 1/2 the original window's
2408 * worth of data in flight.
2410 awnd
= (tp
->snd_nxt
- tp
->snd_fack
) +
2411 tp
->sackhint
.sack_bytes_rexmit
;
2412 if (awnd
< tp
->snd_ssthresh
) {
2413 tp
->snd_cwnd
+= tp
->t_maxseg
;
2414 if (tp
->snd_cwnd
> tp
->snd_ssthresh
)
2415 tp
->snd_cwnd
= tp
->snd_ssthresh
;
2418 tp
->snd_cwnd
+= tp
->t_maxseg
;
2419 tp
->t_unacksegs
= 0;
2420 (void) tcp_output(tp
);
2422 } else if (tp
->t_dupacks
== tcprexmtthresh
) {
2423 tcp_seq onxt
= tp
->snd_nxt
;
2427 * If we're doing sack, check to
2428 * see if we're already in sack
2429 * recovery. If we're not doing sack,
2430 * check to see if we're in newreno
2433 if (tp
->sack_enable
) {
2434 if (IN_FASTRECOVERY(tp
)) {
2438 } else if (tcp_do_newreno
) {
2439 if (SEQ_LEQ(th
->th_ack
,
2445 win
= min(tp
->snd_wnd
, tp
->snd_cwnd
) /
2449 tp
->snd_ssthresh
= win
* tp
->t_maxseg
;
2450 ENTER_FASTRECOVERY(tp
);
2451 tp
->snd_recover
= tp
->snd_max
;
2452 tp
->t_timer
[TCPT_REXMT
] = 0;
2454 tp
->ecn_flags
|= TE_SENDCWR
;
2455 if (tp
->sack_enable
) {
2456 tcpstat
.tcps_sack_recovery_episode
++;
2457 tp
->sack_newdata
= tp
->snd_nxt
;
2458 tp
->snd_cwnd
= tp
->t_maxseg
;
2459 tp
->t_unacksegs
= 0;
2460 (void) tcp_output(tp
);
2463 tp
->snd_nxt
= th
->th_ack
;
2464 tp
->snd_cwnd
= tp
->t_maxseg
;
2465 tp
->t_unacksegs
= 0;
2466 (void) tcp_output(tp
);
2467 tp
->snd_cwnd
= tp
->snd_ssthresh
+
2468 tp
->t_maxseg
* tp
->t_dupacks
;
2469 if (SEQ_GT(onxt
, tp
->snd_nxt
))
2478 * If the congestion window was inflated to account
2479 * for the other side's cached packets, retract it.
2481 if (!IN_FASTRECOVERY(tp
)) {
2483 * We were not in fast recovery. Reset the duplicate ack
2489 * If the congestion window was inflated to account
2490 * for the other side's cached packets, retract it.
2493 if (tcp_do_newreno
|| tp
->sack_enable
) {
2494 if (SEQ_LT(th
->th_ack
, tp
->snd_recover
)) {
2495 if (tp
->sack_enable
)
2496 tcp_sack_partialack(tp
, th
);
2498 tcp_newreno_partial_ack(tp
, th
);
2501 if (tcp_do_newreno
) {
2502 int32_t ss
= tp
->snd_max
- th
->th_ack
;
2505 * Complete ack. Inflate the congestion window to
2506 * ssthresh and exit fast recovery.
2508 * Window inflation should have left us with approx.
2509 * snd_ssthresh outstanding data. But in case we
2510 * would be inclined to send a burst, better to do
2511 * it via the slow start mechanism.
2513 if (ss
< tp
->snd_ssthresh
)
2514 tp
->snd_cwnd
= ss
+ tp
->t_maxseg
;
2516 tp
->snd_cwnd
= tp
->snd_ssthresh
;
2520 * Clamp the congestion window to the crossover point
2521 * and exit fast recovery.
2523 if (tp
->snd_cwnd
> tp
->snd_ssthresh
)
2524 tp
->snd_cwnd
= tp
->snd_ssthresh
;
2527 EXIT_FASTRECOVERY(tp
);
2529 tp
->t_bytes_acked
= 0;
2534 * Clamp the congestion window to the crossover point
2535 * and exit fast recovery in non-newreno and non-SACK case.
2537 if (tp
->snd_cwnd
> tp
->snd_ssthresh
)
2538 tp
->snd_cwnd
= tp
->snd_ssthresh
;
2539 EXIT_FASTRECOVERY(tp
);
2541 tp
->t_bytes_acked
= 0;
2547 * If we reach this point, ACK is not a duplicate,
2548 * i.e., it ACKs something we sent.
2550 if (tp
->t_flags
& TF_NEEDSYN
) {
2552 * T/TCP: Connection was half-synchronized, and our
2553 * SYN has been ACK'd (so connection is now fully
2554 * synchronized). Go to non-starred state,
2555 * increment snd_una for ACK of SYN, and check if
2556 * we can do window scaling.
2558 tp
->t_flags
&= ~TF_NEEDSYN
;
2560 /* Do window scaling? */
2561 if ((tp
->t_flags
& (TF_RCVD_SCALE
|TF_REQ_SCALE
)) ==
2562 (TF_RCVD_SCALE
|TF_REQ_SCALE
)) {
2563 tp
->snd_scale
= tp
->requested_s_scale
;
2564 tp
->rcv_scale
= tp
->request_r_scale
;
2569 acked
= th
->th_ack
- tp
->snd_una
;
2570 tcpstat
.tcps_rcvackpack
++;
2571 tcpstat
.tcps_rcvackbyte
+= acked
;
2574 * If we just performed our first retransmit, and the ACK
2575 * arrives within our recovery window, then it was a mistake
2576 * to do the retransmit in the first place. Recover our
2577 * original cwnd and ssthresh, and proceed to transmit where
2580 if (tp
->t_rxtshift
== 1 && tcp_now
< tp
->t_badrxtwin
) {
2581 ++tcpstat
.tcps_sndrexmitbad
;
2582 tp
->snd_cwnd
= tp
->snd_cwnd_prev
;
2583 tp
->snd_ssthresh
= tp
->snd_ssthresh_prev
;
2584 tp
->snd_recover
= tp
->snd_recover_prev
;
2585 if (tp
->t_flags
& TF_WASFRECOVERY
)
2586 ENTER_FASTRECOVERY(tp
);
2587 tp
->snd_nxt
= tp
->snd_max
;
2588 tp
->t_badrxtwin
= 0; /* XXX probably not required */
2592 * If we have a timestamp reply, update smoothed
2593 * round trip time. If no timestamp is present but
2594 * transmit timer is running and timed sequence
2595 * number was acked, update smoothed round trip time.
2596 * Since we now have an rtt measurement, cancel the
2597 * timer backoff (cf., Phil Karn's retransmit alg.).
2598 * Recompute the initial retransmit timer.
2599 * Also makes sure we have a valid time stamp in hand
2601 * Some boxes send broken timestamp replies
2602 * during the SYN+ACK phase, ignore
2603 * timestamps of 0 or we could calculate a
2604 * huge RTT and blow up the retransmit timer.
2606 if (((to
.to_flags
& TOF_TS
) != 0) && (to
.to_tsecr
!= 0)) {
2607 if (!tp
->t_rttlow
|| tp
->t_rttlow
> tcp_now
- to
.to_tsecr
)
2608 tp
->t_rttlow
= tcp_now
- to
.to_tsecr
;
2609 tcp_xmit_timer(tp
, tcp_now
- to
.to_tsecr
);
2610 } else if (tp
->t_rtttime
&& SEQ_GT(th
->th_ack
, tp
->t_rtseq
)) {
2611 if (!tp
->t_rttlow
|| tp
->t_rttlow
> tcp_now
- tp
->t_rtttime
)
2612 tp
->t_rttlow
= tcp_now
- tp
->t_rtttime
;
2613 tcp_xmit_timer(tp
, tp
->t_rtttime
);
2617 * If all outstanding data is acked, stop retransmit
2618 * timer and remember to restart (more output or persist).
2619 * If there is more data to be acked, restart retransmit
2620 * timer, using current (possibly backed-off) value.
2622 if (th
->th_ack
== tp
->snd_max
) {
2623 tp
->t_timer
[TCPT_REXMT
] = 0;
2625 } else if (tp
->t_timer
[TCPT_PERSIST
] == 0)
2626 tp
->t_timer
[TCPT_REXMT
] = tp
->t_rxtcur
;
2629 * If no data (only SYN) was ACK'd,
2630 * skip rest of ACK processing.
2636 * When new data is acked, open the congestion window.
2638 if ((thflags
& TH_ECE
) != 0 &&
2639 (tp
->ecn_flags
& TE_SETUPSENT
) != 0) {
2641 * Reduce the congestion window if we haven't done so.
2643 if (!(tp
->sack_enable
&& IN_FASTRECOVERY(tp
)) &&
2644 !(tcp_do_newreno
&& SEQ_LEQ(th
->th_ack
, tp
->snd_recover
))) {
2645 tcp_reduce_congestion_window(tp
);
2647 } else if ((!tcp_do_newreno
&& !tp
->sack_enable
) ||
2648 !IN_FASTRECOVERY(tp
)) {
2650 * RFC 3465 - Appropriate Byte Counting.
2652 * If the window is currently less than ssthresh,
2653 * open the window by the number of bytes ACKed by
2654 * the last ACK, however clamp the window increase
2655 * to an upper limit "L".
2657 * In congestion avoidance phase, open the window by
2658 * one segment each time "bytes_acked" grows to be
2659 * greater than or equal to the congestion window.
2662 register u_int cw
= tp
->snd_cwnd
;
2663 register u_int incr
= tp
->t_maxseg
;
2665 if (tcp_do_rfc3465
) {
2667 if (cw
>= tp
->snd_ssthresh
) {
2668 tp
->t_bytes_acked
+= acked
;
2669 if (tp
->t_bytes_acked
>= cw
) {
2670 /* Time to increase the window. */
2671 tp
->t_bytes_acked
-= cw
;
2673 /* No need to increase yet. */
2678 * If the user explicitly enables RFC3465
2679 * use 2*SMSS for the "L" param. Otherwise
2680 * use the more conservative 1*SMSS.
2682 * (See RFC 3465 2.3 Choosing the Limit)
2686 abc_lim
= (tcp_do_rfc3465_lim2
&&
2687 tp
->snd_nxt
== tp
->snd_max
) ? incr
* 2 : incr
;
2689 incr
= lmin(acked
, abc_lim
);
2694 * If the window gives us less than ssthresh packets
2695 * in flight, open exponentially (segsz per packet).
2696 * Otherwise open linearly: segsz per window
2697 * (segsz^2 / cwnd per packet).
2700 if (cw
>= tp
->snd_ssthresh
) {
2701 incr
= max((incr
* incr
/ cw
), 1);
2706 tp
->snd_cwnd
= min(cw
+incr
, TCP_MAXWIN
<<tp
->snd_scale
);
2708 if (acked
> so
->so_snd
.sb_cc
) {
2709 tp
->snd_wnd
-= so
->so_snd
.sb_cc
;
2710 sbdrop(&so
->so_snd
, (int)so
->so_snd
.sb_cc
);
2713 sbdrop(&so
->so_snd
, acked
);
2714 tp
->snd_wnd
-= acked
;
2717 /* detect una wraparound */
2718 if ((tcp_do_newreno
|| tp
->sack_enable
) &&
2719 !IN_FASTRECOVERY(tp
) &&
2720 SEQ_GT(tp
->snd_una
, tp
->snd_recover
) &&
2721 SEQ_LEQ(th
->th_ack
, tp
->snd_recover
))
2722 tp
->snd_recover
= th
->th_ack
- 1;
2723 if ((tcp_do_newreno
|| tp
->sack_enable
) &&
2724 IN_FASTRECOVERY(tp
) &&
2725 SEQ_GEQ(th
->th_ack
, tp
->snd_recover
))
2726 EXIT_FASTRECOVERY(tp
);
2727 tp
->snd_una
= th
->th_ack
;
2728 if (tp
->sack_enable
) {
2729 if (SEQ_GT(tp
->snd_una
, tp
->snd_recover
))
2730 tp
->snd_recover
= tp
->snd_una
;
2732 if (SEQ_LT(tp
->snd_nxt
, tp
->snd_una
))
2733 tp
->snd_nxt
= tp
->snd_una
;
2736 * sowwakeup must happen after snd_una, et al. are updated so that
2737 * the sequence numbers are in sync with so_snd
2741 switch (tp
->t_state
) {
2744 * In FIN_WAIT_1 STATE in addition to the processing
2745 * for the ESTABLISHED state if our FIN is now acknowledged
2746 * then enter FIN_WAIT_2.
2748 case TCPS_FIN_WAIT_1
:
2749 if (ourfinisacked
) {
2751 * If we can't receive any more
2752 * data, then closing user can proceed.
2753 * Starting the timer is contrary to the
2754 * specification, but if we don't get a FIN
2755 * we'll hang forever.
2757 if (so
->so_state
& SS_CANTRCVMORE
) {
2758 tp
->t_timer
[TCPT_2MSL
] = tcp_maxidle
;
2759 add_to_time_wait(tp
);
2760 soisdisconnected(so
);
2762 tp
->t_state
= TCPS_FIN_WAIT_2
;
2763 /* fall through and make sure we also recognize data ACKed with the FIN */
2765 tp
->t_flags
|= TF_ACKNOW
;
2769 * In CLOSING STATE in addition to the processing for
2770 * the ESTABLISHED state if the ACK acknowledges our FIN
2771 * then enter the TIME-WAIT state, otherwise ignore
2775 if (ourfinisacked
) {
2776 tp
->t_state
= TCPS_TIME_WAIT
;
2777 tcp_canceltimers(tp
);
2778 /* Shorten TIME_WAIT [RFC-1644, p.28] */
2779 if (tp
->cc_recv
!= 0 &&
2780 tp
->t_starttime
< (u_int32_t
)tcp_msl
)
2781 tp
->t_timer
[TCPT_2MSL
] =
2782 tp
->t_rxtcur
* TCPTV_TWTRUNC
;
2784 tp
->t_timer
[TCPT_2MSL
] = 2 * tcp_msl
;
2785 add_to_time_wait(tp
);
2786 soisdisconnected(so
);
2788 tp
->t_flags
|= TF_ACKNOW
;
2792 * In LAST_ACK, we may still be waiting for data to drain
2793 * and/or to be acked, as well as for the ack of our FIN.
2794 * If our FIN is now acknowledged, delete the TCB,
2795 * enter the closed state and return.
2798 if (ourfinisacked
) {
2805 * In TIME_WAIT state the only thing that should arrive
2806 * is a retransmission of the remote FIN. Acknowledge
2807 * it and restart the finack timer.
2809 case TCPS_TIME_WAIT
:
2810 tp
->t_timer
[TCPT_2MSL
] = 2 * tcp_msl
;
2811 add_to_time_wait(tp
);
2818 * Update window information.
2819 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2821 if ((thflags
& TH_ACK
) &&
2822 (SEQ_LT(tp
->snd_wl1
, th
->th_seq
) ||
2823 (tp
->snd_wl1
== th
->th_seq
&& (SEQ_LT(tp
->snd_wl2
, th
->th_ack
) ||
2824 (tp
->snd_wl2
== th
->th_ack
&& tiwin
> tp
->snd_wnd
))))) {
2825 /* keep track of pure window updates */
2827 tp
->snd_wl2
== th
->th_ack
&& tiwin
> tp
->snd_wnd
)
2828 tcpstat
.tcps_rcvwinupd
++;
2829 tp
->snd_wnd
= tiwin
;
2830 tp
->snd_wl1
= th
->th_seq
;
2831 tp
->snd_wl2
= th
->th_ack
;
2832 if (tp
->snd_wnd
> tp
->max_sndwnd
)
2833 tp
->max_sndwnd
= tp
->snd_wnd
;
2838 * Process segments with URG.
2840 if ((thflags
& TH_URG
) && th
->th_urp
&&
2841 TCPS_HAVERCVDFIN(tp
->t_state
) == 0) {
2843 * This is a kludge, but if we receive and accept
2844 * random urgent pointers, we'll crash in
2845 * soreceive. It's hard to imagine someone
2846 * actually wanting to send this much urgent data.
2848 if (th
->th_urp
+ so
->so_rcv
.sb_cc
> sb_max
) {
2849 th
->th_urp
= 0; /* XXX */
2850 thflags
&= ~TH_URG
; /* XXX */
2851 goto dodata
; /* XXX */
2854 * If this segment advances the known urgent pointer,
2855 * then mark the data stream. This should not happen
2856 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2857 * a FIN has been received from the remote side.
2858 * In these states we ignore the URG.
2860 * According to RFC961 (Assigned Protocols),
2861 * the urgent pointer points to the last octet
2862 * of urgent data. We continue, however,
2863 * to consider it to indicate the first octet
2864 * of data past the urgent section as the original
2865 * spec states (in one of two places).
2867 if (SEQ_GT(th
->th_seq
+th
->th_urp
, tp
->rcv_up
)) {
2868 tp
->rcv_up
= th
->th_seq
+ th
->th_urp
;
2869 so
->so_oobmark
= so
->so_rcv
.sb_cc
+
2870 (tp
->rcv_up
- tp
->rcv_nxt
) - 1;
2871 if (so
->so_oobmark
== 0) {
2872 so
->so_state
|= SS_RCVATMARK
;
2873 postevent(so
, 0, EV_OOB
);
2876 tp
->t_oobflags
&= ~(TCPOOB_HAVEDATA
| TCPOOB_HADDATA
);
2879 * Remove out of band data so doesn't get presented to user.
2880 * This can happen independent of advancing the URG pointer,
2881 * but if two URG's are pending at once, some out-of-band
2882 * data may creep in... ick.
2884 if (th
->th_urp
<= (u_int32_t
)tlen
2886 && (so
->so_options
& SO_OOBINLINE
) == 0
2889 tcp_pulloutofband(so
, th
, m
,
2890 drop_hdrlen
); /* hdr drop is delayed */
2893 * If no out of band data is expected,
2894 * pull receive urgent pointer along
2895 * with the receive window.
2897 if (SEQ_GT(tp
->rcv_nxt
, tp
->rcv_up
))
2898 tp
->rcv_up
= tp
->rcv_nxt
;
2902 * Process the segment text, merging it into the TCP sequencing queue,
2903 * and arranging for acknowledgment of receipt if necessary.
2904 * This process logically involves adjusting tp->rcv_wnd as data
2905 * is presented to the user (this happens in tcp_usrreq.c,
2906 * case PRU_RCVD). If a FIN has already been received on this
2907 * connection then we just ignore the text.
2909 if ((tlen
|| (thflags
& TH_FIN
)) &&
2910 TCPS_HAVERCVDFIN(tp
->t_state
) == 0) {
2911 tcp_seq save_start
= th
->th_seq
;
2912 tcp_seq save_end
= th
->th_seq
+ tlen
;
2913 m_adj(m
, drop_hdrlen
); /* delayed header drop */
2915 * Insert segment which includes th into TCP reassembly queue
2916 * with control block tp. Set thflags to whether reassembly now
2917 * includes a segment with FIN. This handles the common case
2918 * inline (segment is the next to be received on an established
2919 * connection, and the queue is empty), avoiding linkage into
2920 * and removal from the queue and repetition of various
2922 * Set DELACK for segments received in order, but ack
2923 * immediately when segments are out of order (so
2924 * fast retransmit can work).
2926 if (th
->th_seq
== tp
->rcv_nxt
&&
2927 LIST_EMPTY(&tp
->t_segq
) &&
2928 TCPS_HAVEESTABLISHED(tp
->t_state
)) {
2929 if (DELAY_ACK(tp
) && ((tp
->t_flags
& TF_ACKNOW
) == 0)) {
2930 tp
->t_flags
|= TF_DELACK
;
2934 tp
->t_unacksegs
= 0;
2935 tp
->t_flags
|= TF_ACKNOW
;
2937 tp
->rcv_nxt
+= tlen
;
2938 thflags
= th
->th_flags
& TH_FIN
;
2939 tcpstat
.tcps_rcvpack
++;
2940 tcpstat
.tcps_rcvbyte
+= tlen
;
2942 if (sbappendstream(&so
->so_rcv
, m
))
2945 thflags
= tcp_reass(tp
, th
, &tlen
, m
);
2946 tp
->t_flags
|= TF_ACKNOW
;
2947 tp
->t_unacksegs
= 0;
2950 if (tlen
> 0 && tp
->sack_enable
)
2951 tcp_update_sack_list(tp
, save_start
, save_end
);
2953 if (tp
->t_flags
& TF_DELACK
)
2957 KERNEL_DEBUG(DBG_LAYER_END
, ((th
->th_dport
<< 16) | th
->th_sport
),
2958 (((ip6
->ip6_src
.s6_addr16
[0]) << 16) | (ip6
->ip6_dst
.s6_addr16
[0])),
2959 th
->th_seq
, th
->th_ack
, th
->th_win
);
2964 KERNEL_DEBUG(DBG_LAYER_END
, ((th
->th_dport
<< 16) | th
->th_sport
),
2965 (((ip
->ip_src
.s_addr
& 0xffff) << 16) | (ip
->ip_dst
.s_addr
& 0xffff)),
2966 th
->th_seq
, th
->th_ack
, th
->th_win
);
2971 * Note the amount of data that peer has sent into
2972 * our window, in order to estimate the sender's
2975 len
= (u_int
)(so
->so_rcv
.sb_hiwat
- (tp
->rcv_adv
- tp
->rcv_nxt
));
2976 if (len
> so
->so_rcv
.sb_maxused
)
2977 so
->so_rcv
.sb_maxused
= len
;
2984 * If FIN is received ACK the FIN and let the user know
2985 * that the connection is closing.
2987 if (thflags
& TH_FIN
) {
2988 if (TCPS_HAVERCVDFIN(tp
->t_state
) == 0) {
2990 postevent(so
, 0, EV_FIN
);
2992 * If connection is half-synchronized
2993 * (ie NEEDSYN flag on) then delay ACK,
2994 * If connection is half-synchronized
2995 * (ie NEEDSYN flag on) then delay ACK,
2996 * so it may be piggybacked when SYN is sent.
2997 * Otherwise, since we received a FIN then no
2998 * more input can be expected, send ACK now.
3000 if (DELAY_ACK(tp
) && (tp
->t_flags
& TF_NEEDSYN
)) {
3001 tp
->t_flags
|= TF_DELACK
;
3005 tp
->t_flags
|= TF_ACKNOW
;
3006 tp
->t_unacksegs
= 0;
3010 switch (tp
->t_state
) {
3013 * In SYN_RECEIVED and ESTABLISHED STATES
3014 * enter the CLOSE_WAIT state.
3016 case TCPS_SYN_RECEIVED
:
3017 tp
->t_starttime
= 0;
3018 case TCPS_ESTABLISHED
:
3019 tp
->t_state
= TCPS_CLOSE_WAIT
;
3023 * If still in FIN_WAIT_1 STATE FIN has not been acked so
3024 * enter the CLOSING state.
3026 case TCPS_FIN_WAIT_1
:
3027 tp
->t_state
= TCPS_CLOSING
;
3031 * In FIN_WAIT_2 state enter the TIME_WAIT state,
3032 * starting the time-wait timer, turning off the other
3035 case TCPS_FIN_WAIT_2
:
3036 tp
->t_state
= TCPS_TIME_WAIT
;
3037 tcp_canceltimers(tp
);
3038 /* Shorten TIME_WAIT [RFC-1644, p.28] */
3039 if (tp
->cc_recv
!= 0 &&
3040 tp
->t_starttime
< (u_int32_t
)tcp_msl
) {
3041 tp
->t_timer
[TCPT_2MSL
] =
3042 tp
->t_rxtcur
* TCPTV_TWTRUNC
;
3043 /* For transaction client, force ACK now. */
3044 tp
->t_flags
|= TF_ACKNOW
;
3045 tp
->t_unacksegs
= 0;
3048 tp
->t_timer
[TCPT_2MSL
] = 2 * tcp_msl
;
3050 add_to_time_wait(tp
);
3051 soisdisconnected(so
);
3055 * In TIME_WAIT state restart the 2 MSL time_wait timer.
3057 case TCPS_TIME_WAIT
:
3058 tp
->t_timer
[TCPT_2MSL
] = 2 * tcp_msl
;
3059 add_to_time_wait(tp
);
3064 if (so
->so_options
& SO_DEBUG
)
3065 tcp_trace(TA_INPUT
, ostate
, tp
, (void *)tcp_saveipgen
,
3070 * Return any desired output.
3072 if (needoutput
|| (tp
->t_flags
& TF_ACKNOW
)) {
3073 tp
->t_unacksegs
= 0;
3074 (void) tcp_output(tp
);
3076 tcp_unlock(so
, 1, 0);
3077 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
3082 * Generate an ACK dropping incoming segment if it occupies
3083 * sequence space, where the ACK reflects our state.
3085 * We can now skip the test for the RST flag since all
3086 * paths to this code happen after packets containing
3087 * RST have been dropped.
3089 * In the SYN-RECEIVED state, don't send an ACK unless the
3090 * segment we received passes the SYN-RECEIVED ACK test.
3091 * If it fails send a RST. This breaks the loop in the
3092 * "LAND" DoS attack, and also prevents an ACK storm
3093 * between two listening ports that have been sent forged
3094 * SYN segments, each with the source address of the other.
3096 if (tp
->t_state
== TCPS_SYN_RECEIVED
&& (thflags
& TH_ACK
) &&
3097 (SEQ_GT(tp
->snd_una
, th
->th_ack
) ||
3098 SEQ_GT(th
->th_ack
, tp
->snd_max
)) ) {
3099 rstreason
= BANDLIM_RST_OPENPORT
;
3103 if (so
->so_options
& SO_DEBUG
)
3104 tcp_trace(TA_DROP
, ostate
, tp
, (void *)tcp_saveipgen
,
3108 tp
->t_flags
|= TF_ACKNOW
;
3109 tp
->t_unacksegs
= 0;
3110 (void) tcp_output(tp
);
3111 tcp_unlock(so
, 1, 0);
3112 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
3114 dropwithresetnosock
:
3118 * Generate a RST, dropping incoming segment.
3119 * Make ACK acceptable to originator of segment.
3120 * Don't bother to respond if destination was broadcast/multicast.
3122 if ((thflags
& TH_RST
) || m
->m_flags
& (M_BCAST
|M_MCAST
))
3126 if (IN6_IS_ADDR_MULTICAST(&ip6
->ip6_dst
) ||
3127 IN6_IS_ADDR_MULTICAST(&ip6
->ip6_src
))
3131 if (IN_MULTICAST(ntohl(ip
->ip_dst
.s_addr
)) ||
3132 IN_MULTICAST(ntohl(ip
->ip_src
.s_addr
)) ||
3133 ip
->ip_src
.s_addr
== htonl(INADDR_BROADCAST
) ||
3134 in_broadcast(ip
->ip_dst
, m
->m_pkthdr
.rcvif
))
3136 /* IPv6 anycast check is done at tcp6_input() */
3139 * Perform bandwidth limiting.
3142 if (badport_bandlim(rstreason
) < 0)
3147 if (tp
== 0 || (tp
->t_inpcb
->inp_socket
->so_options
& SO_DEBUG
))
3148 tcp_trace(TA_DROP
, ostate
, tp
, (void *)tcp_saveipgen
,
3151 if (thflags
& TH_ACK
)
3152 /* mtod() below is safe as long as hdr dropping is delayed */
3153 tcp_respond(tp
, mtod(m
, void *), th
, m
, (tcp_seq
)0, th
->th_ack
,
3156 if (thflags
& TH_SYN
)
3158 /* mtod() below is safe as long as hdr dropping is delayed */
3159 tcp_respond(tp
, mtod(m
, void *), th
, m
, th
->th_seq
+tlen
,
3160 (tcp_seq
)0, TH_RST
|TH_ACK
, ifscope
);
3162 /* destroy temporarily created socket */
3165 tcp_unlock(so
, 1, 0);
3168 if ((inp
!= NULL
) && (nosock
== 0))
3169 tcp_unlock(so
, 1, 0);
3170 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
3176 * Drop space held by incoming segment and return.
3179 if (tp
== 0 || (tp
->t_inpcb
->inp_socket
->so_options
& SO_DEBUG
))
3180 tcp_trace(TA_DROP
, ostate
, tp
, (void *)tcp_saveipgen
,
3184 /* destroy temporarily created socket */
3187 tcp_unlock(so
, 1, 0);
3191 tcp_unlock(so
, 1, 0);
3192 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
3197 tcp_dooptions(tp
, cp
, cnt
, th
, to
, input_ifscope
)
3199 * Parse TCP options and place in tcpopt.
3206 unsigned int input_ifscope
;
3211 for (; cnt
> 0; cnt
-= optlen
, cp
+= optlen
) {
3213 if (opt
== TCPOPT_EOL
)
3215 if (opt
== TCPOPT_NOP
)
3221 if (optlen
< 2 || optlen
> cnt
)
3230 if (optlen
!= TCPOLEN_MAXSEG
)
3232 if (!(th
->th_flags
& TH_SYN
))
3234 bcopy((char *) cp
+ 2, (char *) &mss
, sizeof(mss
));
3236 #if BYTE_ORDER != BIG_ENDIAN
3243 if (optlen
!= TCPOLEN_WINDOW
)
3245 if (!(th
->th_flags
& TH_SYN
))
3247 tp
->t_flags
|= TF_RCVD_SCALE
;
3248 tp
->requested_s_scale
= min(cp
[2], TCP_MAX_WINSHIFT
);
3251 case TCPOPT_TIMESTAMP
:
3252 if (optlen
!= TCPOLEN_TIMESTAMP
)
3254 to
->to_flags
|= TOF_TS
;
3255 bcopy((char *)cp
+ 2,
3256 (char *)&to
->to_tsval
, sizeof(to
->to_tsval
));
3258 #if BYTE_ORDER != BIG_ENDIAN
3259 NTOHL(to
->to_tsval
);
3262 bcopy((char *)cp
+ 6,
3263 (char *)&to
->to_tsecr
, sizeof(to
->to_tsecr
));
3265 #if BYTE_ORDER != BIG_ENDIAN
3266 NTOHL(to
->to_tsecr
);
3270 * A timestamp received in a SYN makes
3271 * it ok to send timestamp requests and replies.
3273 if (th
->th_flags
& TH_SYN
) {
3274 tp
->t_flags
|= TF_RCVD_TSTMP
;
3275 tp
->ts_recent
= to
->to_tsval
;
3276 tp
->ts_recent_age
= tcp_now
;
3279 case TCPOPT_SACK_PERMITTED
:
3281 optlen
!= TCPOLEN_SACK_PERMITTED
)
3283 if (th
->th_flags
& TH_SYN
)
3284 to
->to_flags
|= TOF_SACK
;
3287 if (optlen
<= 2 || (optlen
- 2) % TCPOLEN_SACK
!= 0)
3289 to
->to_nsacks
= (optlen
- 2) / TCPOLEN_SACK
;
3290 to
->to_sacks
= cp
+ 2;
3291 tcpstat
.tcps_sack_rcv_blocks
++;
3296 if (th
->th_flags
& TH_SYN
)
3297 tcp_mss(tp
, mss
, input_ifscope
); /* sets t_maxseg */
3301 * Pull out of band byte out of a segment so
3302 * it doesn't appear in the user's data queue.
3303 * It is still reflected in the segment length for
3304 * sequencing purposes.
3307 tcp_pulloutofband(so
, th
, m
, off
)
3310 register struct mbuf
*m
;
3311 int off
; /* delayed to be droped hdrlen */
3313 int cnt
= off
+ th
->th_urp
- 1;
3316 if (m
->m_len
> cnt
) {
3317 char *cp
= mtod(m
, caddr_t
) + cnt
;
3318 struct tcpcb
*tp
= sototcpcb(so
);
3321 tp
->t_oobflags
|= TCPOOB_HAVEDATA
;
3322 bcopy(cp
+1, cp
, (unsigned)(m
->m_len
- cnt
- 1));
3324 if (m
->m_flags
& M_PKTHDR
)
3333 panic("tcp_pulloutofband");
3337 * Collect new round-trip time estimate
3338 * and update averages and current timeout.
3341 tcp_xmit_timer(tp
, rtt
)
3342 register struct tcpcb
*tp
;
3347 tcpstat
.tcps_rttupdated
++;
3349 if (tp
->t_srtt
!= 0) {
3351 * srtt is stored as fixed point with 5 bits after the
3352 * binary point (i.e., scaled by 8). The following magic
3353 * is equivalent to the smoothing algorithm in rfc793 with
3354 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
3355 * point). Adjust rtt to origin 0.
3357 delta
= ((rtt
- 1) << TCP_DELTA_SHIFT
)
3358 - (tp
->t_srtt
>> (TCP_RTT_SHIFT
- TCP_DELTA_SHIFT
));
3360 if ((tp
->t_srtt
+= delta
) <= 0)
3364 * We accumulate a smoothed rtt variance (actually, a
3365 * smoothed mean difference), then set the retransmit
3366 * timer to smoothed rtt + 4 times the smoothed variance.
3367 * rttvar is stored as fixed point with 4 bits after the
3368 * binary point (scaled by 16). The following is
3369 * equivalent to rfc793 smoothing with an alpha of .75
3370 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
3371 * rfc793's wired-in beta.
3375 delta
-= tp
->t_rttvar
>> (TCP_RTTVAR_SHIFT
- TCP_DELTA_SHIFT
);
3376 if ((tp
->t_rttvar
+= delta
) <= 0)
3378 if (tp
->t_rttbest
> tp
->t_srtt
+ tp
->t_rttvar
)
3379 tp
->t_rttbest
= tp
->t_srtt
+ tp
->t_rttvar
;
3382 * No rtt measurement yet - use the unsmoothed rtt.
3383 * Set the variance to half the rtt (so our first
3384 * retransmit happens at 3*rtt).
3386 tp
->t_srtt
= rtt
<< TCP_RTT_SHIFT
;
3387 tp
->t_rttvar
= rtt
<< (TCP_RTTVAR_SHIFT
- 1);
3388 tp
->t_rttbest
= tp
->t_srtt
+ tp
->t_rttvar
;
3394 * the retransmit should happen at rtt + 4 * rttvar.
3395 * Because of the way we do the smoothing, srtt and rttvar
3396 * will each average +1/2 tick of bias. When we compute
3397 * the retransmit timer, we want 1/2 tick of rounding and
3398 * 1 extra tick because of +-1/2 tick uncertainty in the
3399 * firing of the timer. The bias will give us exactly the
3400 * 1.5 tick we need. But, because the bias is
3401 * statistical, we have to test that we don't drop below
3402 * the minimum feasible timer (which is 2 ticks).
3404 TCPT_RANGESET(tp
->t_rxtcur
, TCP_REXMTVAL(tp
),
3405 max(tp
->t_rttmin
, rtt
+ 2), TCPTV_REXMTMAX
);
3408 * We received an ack for a packet that wasn't retransmitted;
3409 * it is probably safe to discard any error indications we've
3410 * received recently. This isn't quite right, but close enough
3411 * for now (a route might have failed after we sent a segment,
3412 * and the return path might not be symmetrical).
3414 tp
->t_softerror
= 0;
3417 static inline unsigned int
3418 tcp_maxmtu(struct rtentry
*rt
)
3420 unsigned int maxmtu
;
3422 RT_LOCK_ASSERT_HELD(rt
);
3423 if (rt
->rt_rmx
.rmx_mtu
== 0)
3424 maxmtu
= rt
->rt_ifp
->if_mtu
;
3426 maxmtu
= MIN(rt
->rt_rmx
.rmx_mtu
, rt
->rt_ifp
->if_mtu
);
3432 static inline unsigned int
3433 tcp_maxmtu6(struct rtentry
*rt
)
3435 unsigned int maxmtu
;
3437 RT_LOCK_ASSERT_HELD(rt
);
3438 lck_rw_lock_shared(nd_if_rwlock
);
3439 if (rt
->rt_rmx
.rmx_mtu
== 0)
3440 maxmtu
= IN6_LINKMTU(rt
->rt_ifp
);
3442 maxmtu
= MIN(rt
->rt_rmx
.rmx_mtu
, IN6_LINKMTU(rt
->rt_ifp
));
3443 lck_rw_done(nd_if_rwlock
);
3450 * Determine a reasonable value for maxseg size.
3451 * If the route is known, check route for mtu.
3452 * If none, use an mss that can be handled on the outgoing
3453 * interface without forcing IP to fragment; if bigger than
3454 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
3455 * to utilize large mbufs. If no route is found, route has no mtu,
3456 * or the destination isn't local, use a default, hopefully conservative
3457 * size (usually 512 or the default IP max size, but no more than the mtu
3458 * of the interface), as we can't discover anything about intervening
3459 * gateways or networks. We also initialize the congestion/slow start
3460 * window to be a single segment if the destination isn't local.
3461 * While looking at the routing entry, we also initialize other path-dependent
3462 * parameters from pre-set or cached values in the routing entry.
3464 * Also take into account the space needed for options that we
3465 * send regularly. Make maxseg shorter by that amount to assure
3466 * that we can send maxseg amount of data even when the options
3467 * are present. Store the upper limit of the length of options plus
3470 * NOTE that this routine is only called when we process an incoming
3471 * segment, for outgoing segments only tcp_mssopt is called.
3475 tcp_mss(tp
, offer
, input_ifscope
)
3478 unsigned int input_ifscope
;
3480 register struct rtentry
*rt
;
3482 register int rtt
, mss
;
3486 struct rmxp_tao
*taop
;
3487 int origoffer
= offer
;
3488 u_int32_t sb_max_corrected
;
3497 isipv6
= ((inp
->inp_vflag
& INP_IPV6
) != 0) ? 1 : 0;
3498 min_protoh
= isipv6
? sizeof (struct ip6_hdr
) + sizeof (struct tcphdr
)
3499 : sizeof (struct tcpiphdr
);
3501 #define min_protoh (sizeof (struct tcpiphdr))
3506 rt
= tcp_rtlookup6(inp
);
3508 (IN6_IS_ADDR_LOOPBACK(&inp
->in6p_faddr
) ||
3509 IN6_IS_ADDR_LINKLOCAL(&inp
->in6p_faddr
) ||
3510 rt
->rt_gateway
->sa_family
== AF_LINK
))
3516 rt
= tcp_rtlookup(inp
, input_ifscope
);
3518 (rt
->rt_gateway
->sa_family
== AF_LINK
||
3519 rt
->rt_ifp
->if_flags
& IFF_LOOPBACK
))
3523 tp
->t_maxopd
= tp
->t_maxseg
=
3525 isipv6
? tcp_v6mssdflt
:
3532 * Slower link window correction:
3533 * If a value is specificied for slowlink_wsize use it for PPP links
3534 * believed to be on a serial modem (speed <128Kbps). Excludes 9600bps as
3535 * it is the default value adversized by pseudo-devices over ppp.
3537 if (ifp
->if_type
== IFT_PPP
&& slowlink_wsize
> 0 &&
3538 ifp
->if_baudrate
> 9600 && ifp
->if_baudrate
<= 128000) {
3539 tp
->t_flags
|= TF_SLOWLINK
;
3541 so
= inp
->inp_socket
;
3543 taop
= rmx_taop(rt
->rt_rmx
);
3545 * Offer == -1 means that we didn't receive SYN yet,
3546 * use cached value in that case;
3549 offer
= taop
->tao_mssopt
;
3551 * Offer == 0 means that there was no MSS on the SYN segment,
3552 * in this case we use tcp_mssdflt.
3557 isipv6
? tcp_v6mssdflt
:
3562 * Prevent DoS attack with too small MSS. Round up
3563 * to at least minmss.
3565 offer
= max(offer
, tcp_minmss
);
3567 * Sanity check: make sure that maxopd will be large
3568 * enough to allow some data on segments even is the
3569 * all the option space is used (40bytes). Otherwise
3570 * funny things may happen in tcp_output.
3572 offer
= max(offer
, 64);
3574 taop
->tao_mssopt
= offer
;
3577 * While we're here, check if there's an initial rtt
3578 * or rttvar. Convert from the route-table units
3579 * to scaled multiples of the slow timeout timer.
3581 if (tp
->t_srtt
== 0 && (rtt
= rt
->rt_rmx
.rmx_rtt
)) {
3583 * XXX the lock bit for RTT indicates that the value
3584 * is also a minimum value; this is subject to time.
3586 if (rt
->rt_rmx
.rmx_locks
& RTV_RTT
)
3587 tp
->t_rttmin
= rtt
/ (RTM_RTTUNIT
/ TCP_RETRANSHZ
);
3589 tp
->t_rttmin
= isnetlocal
? tcp_TCPTV_MIN
: TCP_RETRANSHZ
;
3590 tp
->t_srtt
= rtt
/ (RTM_RTTUNIT
/ (TCP_RETRANSHZ
* TCP_RTT_SCALE
));
3591 tcpstat
.tcps_usedrtt
++;
3592 if (rt
->rt_rmx
.rmx_rttvar
) {
3593 tp
->t_rttvar
= rt
->rt_rmx
.rmx_rttvar
/
3594 (RTM_RTTUNIT
/ (TCP_RETRANSHZ
* TCP_RTTVAR_SCALE
));
3595 tcpstat
.tcps_usedrttvar
++;
3597 /* default variation is +- 1 rtt */
3599 tp
->t_srtt
* TCP_RTTVAR_SCALE
/ TCP_RTT_SCALE
;
3601 TCPT_RANGESET(tp
->t_rxtcur
,
3602 ((tp
->t_srtt
>> 2) + tp
->t_rttvar
) >> 1,
3603 tp
->t_rttmin
, TCPTV_REXMTMAX
);
3606 tp
->t_rttmin
= isnetlocal
? tcp_TCPTV_MIN
: TCP_RETRANSHZ
;
3609 mss
= (isipv6
? tcp_maxmtu6(rt
) : tcp_maxmtu(rt
));
3611 mss
= tcp_maxmtu(rt
);
3615 if (rt
->rt_rmx
.rmx_mtu
== 0) {
3619 mss
= min(mss
, tcp_v6mssdflt
);
3623 mss
= min(mss
, tcp_mssdflt
);
3626 mss
= min(mss
, offer
);
3628 * maxopd stores the maximum length of data AND options
3629 * in a segment; maxseg is the amount of data in a normal
3630 * segment. We need to store this value (maxopd) apart
3631 * from maxseg, because now every segment carries options
3632 * and thus we normally have somewhat less data in segments.
3637 * origoffer==-1 indicates, that no segments were received yet.
3638 * In this case we just guess.
3640 if ((tp
->t_flags
& (TF_REQ_TSTMP
|TF_NOOPT
)) == TF_REQ_TSTMP
&&
3642 (tp
->t_flags
& TF_RCVD_TSTMP
) == TF_RCVD_TSTMP
))
3643 mss
-= TCPOLEN_TSTAMP_APPA
;
3647 * Calculate corrected value for sb_max; ensure to upgrade the
3648 * numerator for large sb_max values else it will overflow.
3650 sb_max_corrected
= (sb_max
* (u_int64_t
)MCLBYTES
) / (MSIZE
+ MCLBYTES
);
3653 * If there's a pipesize (ie loopback), change the socket
3654 * buffer to that size only if it's bigger than the current
3655 * sockbuf size. Make the socket buffers an integral
3656 * number of mss units; if the mss is larger than
3657 * the socket buffer, decrease the mss.
3660 bufsize
= rt
->rt_rmx
.rmx_sendpipe
;
3661 if (bufsize
< so
->so_snd
.sb_hiwat
)
3663 bufsize
= so
->so_snd
.sb_hiwat
;
3667 bufsize
= (((bufsize
+ (u_int64_t
)mss
- 1) / (u_int64_t
)mss
) * (u_int64_t
)mss
);
3668 if (bufsize
> sb_max_corrected
)
3669 bufsize
= sb_max_corrected
;
3670 (void)sbreserve(&so
->so_snd
, bufsize
);
3675 bufsize
= rt
->rt_rmx
.rmx_recvpipe
;
3676 if (bufsize
< so
->so_rcv
.sb_hiwat
)
3678 bufsize
= so
->so_rcv
.sb_hiwat
;
3679 if (bufsize
> mss
) {
3680 bufsize
= (((bufsize
+ (u_int64_t
)mss
- 1) / (u_int64_t
)mss
) * (u_int64_t
)mss
);
3681 if (bufsize
> sb_max_corrected
)
3682 bufsize
= sb_max_corrected
;
3683 (void)sbreserve(&so
->so_rcv
, bufsize
);
3687 * Set the slow-start flight size depending on whether this
3688 * is a local network or not.
3691 tp
->snd_cwnd
= mss
* ss_fltsz_local
;
3693 tp
->snd_cwnd
= mss
* ss_fltsz
;
3695 if (rt
->rt_rmx
.rmx_ssthresh
) {
3697 * There's some sort of gateway or interface
3698 * buffer limit on the path. Use this to set
3699 * the slow start threshhold, but set the
3700 * threshold to no less than 2*mss.
3702 tp
->snd_ssthresh
= max(2 * mss
, rt
->rt_rmx
.rmx_ssthresh
);
3703 tcpstat
.tcps_usedssthresh
++;
3705 tp
->snd_ssthresh
= TCP_MAXWIN
<< TCP_MAX_WINSHIFT
;
3708 /* Route locked during lookup above */
3713 * Determine the MSS option to send on an outgoing SYN.
3727 isipv6
= ((tp
->t_inpcb
->inp_vflag
& INP_IPV6
) != 0) ? 1 : 0;
3728 min_protoh
= isipv6
? sizeof (struct ip6_hdr
) + sizeof (struct tcphdr
)
3729 : sizeof (struct tcpiphdr
);
3731 #define min_protoh (sizeof (struct tcpiphdr))
3736 rt
= tcp_rtlookup6(tp
->t_inpcb
);
3739 rt
= tcp_rtlookup(tp
->t_inpcb
, IFSCOPE_NONE
);
3743 isipv6
? tcp_v6mssdflt
:
3748 * Slower link window correction:
3749 * If a value is specificied for slowlink_wsize use it for PPP links
3750 * believed to be on a serial modem (speed <128Kbps). Excludes 9600bps as
3751 * it is the default value adversized by pseudo-devices over ppp.
3753 if (rt
->rt_ifp
->if_type
== IFT_PPP
&& slowlink_wsize
> 0 &&
3754 rt
->rt_ifp
->if_baudrate
> 9600 && rt
->rt_ifp
->if_baudrate
<= 128000) {
3755 tp
->t_flags
|= TF_SLOWLINK
;
3759 mss
= (isipv6
? tcp_maxmtu6(rt
) : tcp_maxmtu(rt
));
3761 mss
= tcp_maxmtu(rt
);
3763 /* Route locked during lookup above */
3765 return (mss
- min_protoh
);
3769 * On a partial ack arrives, force the retransmission of the
3770 * next unacknowledged segment. Do not clear tp->t_dupacks.
3771 * By setting snd_nxt to ti_ack, this forces retransmission timer to
3775 tcp_newreno_partial_ack(tp
, th
)
3779 tcp_seq onxt
= tp
->snd_nxt
;
3780 u_int32_t ocwnd
= tp
->snd_cwnd
;
3781 tp
->t_timer
[TCPT_REXMT
] = 0;
3783 tp
->snd_nxt
= th
->th_ack
;
3785 * Set snd_cwnd to one segment beyond acknowledged offset
3786 * (tp->snd_una has not yet been updated when this function
3789 tp
->snd_cwnd
= tp
->t_maxseg
+ (th
->th_ack
- tp
->snd_una
);
3790 tp
->t_flags
|= TF_ACKNOW
;
3791 tp
->t_unacksegs
= 0;
3792 (void) tcp_output(tp
);
3793 tp
->snd_cwnd
= ocwnd
;
3794 if (SEQ_GT(onxt
, tp
->snd_nxt
))
3797 * Partial window deflation. Relies on fact that tp->snd_una
3800 if (tp
->snd_cwnd
> th
->th_ack
- tp
->snd_una
)
3801 tp
->snd_cwnd
-= th
->th_ack
- tp
->snd_una
;
3804 tp
->snd_cwnd
+= tp
->t_maxseg
;
3809 * Drop a random TCP connection that hasn't been serviced yet and
3810 * is eligible for discard. There is a one in qlen chance that
3811 * we will return a null, saying that there are no dropable
3812 * requests. In this case, the protocol specific code should drop
3813 * the new request. This insures fairness.
3815 * The listening TCP socket "head" must be locked
3818 tcp_dropdropablreq(struct socket
*head
)
3820 struct socket
*so
, *sonext
;
3821 unsigned int i
, j
, qlen
;
3823 static struct timeval old_runtime
;
3824 static unsigned int cur_cnt
, old_cnt
;
3826 struct inpcb
*inp
= NULL
;
3829 if ((head
->so_options
& SO_ACCEPTCONN
) == 0)
3832 so
= TAILQ_FIRST(&head
->so_incomp
);
3837 if ((i
= (tv
.tv_sec
- old_runtime
.tv_sec
)) != 0) {
3839 old_cnt
= cur_cnt
/ i
;
3844 qlen
= head
->so_incqlen
;
3845 if (++cur_cnt
> qlen
|| old_cnt
> qlen
) {
3846 rnd
= (314159 * rnd
+ 66329) & 0xffff;
3847 j
= ((qlen
+ 1) * rnd
) >> 16;
3850 so
= TAILQ_NEXT(so
, so_list
);
3852 /* Find a connection that is not already closing (or being served) */
3854 inp
= (struct inpcb
*)so
->so_pcb
;
3856 sonext
= TAILQ_NEXT(so
, so_list
);
3858 if (in_pcb_checkstate(inp
, WNT_ACQUIRE
, 0) != WNT_STOPUSING
) {
3859 /* Avoid the issue of a socket being accepted by one input thread
3860 * and being dropped by another input thread.
3861 * If we can't get a hold on this mutex, then grab the next socket in line.
3863 if (lck_mtx_try_lock(inp
->inpcb_mtx
)) {
3865 if ((so
->so_usecount
== 2) && so
->so_state
& SS_INCOMP
)
3867 else {/* don't use if beeing accepted or used in any other way */
3868 in_pcb_checkstate(inp
, WNT_RELEASE
, 1);
3869 tcp_unlock(so
, 1, 0);
3873 /* do not try to lock the inp in in_pcb_checkstate
3874 * because the lock is already held in some other thread.
3875 * Only drop the inp_wntcnt reference.
3877 in_pcb_checkstate(inp
, WNT_RELEASE
, 1);
3886 TAILQ_REMOVE(&head
->so_incomp
, so
, so_list
);
3887 tcp_unlock(head
, 0, 0);
3889 /* Makes sure socket is still in the right state to be discarded */
3891 if (in_pcb_checkstate(inp
, WNT_RELEASE
, 1) == WNT_STOPUSING
) {
3892 tcp_unlock(so
, 1, 0);
3893 tcp_lock(head
, 0, 0);
3897 if (so
->so_usecount
!= 2 || !(so
->so_state
& SS_INCOMP
)) {
3898 /* do not discard: that socket is beeing accepted */
3899 tcp_unlock(so
, 1, 0);
3900 tcp_lock(head
, 0, 0);
3907 * We do not want to lose track of the PCB right away in case we receive
3908 * more segments from the peer
3911 so
->so_flags
|= SOF_OVERFLOW
;
3912 tp
->t_state
= TCPS_TIME_WAIT
;
3913 (void) tcp_close(tp
);
3914 tp
->t_unacksegs
= 0;
3915 tcpstat
.tcps_drops
++;
3916 tcp_canceltimers(tp
);
3917 add_to_time_wait(tp
);
3919 tcp_unlock(so
, 1, 0);
3920 tcp_lock(head
, 0, 0);
3927 tcp_getstat SYSCTL_HANDLER_ARGS
3929 #pragma unused(oidp, arg1, arg2)
3933 if (req
->oldptr
== 0) {
3934 req
->oldlen
= (size_t)sizeof(struct tcpstat
);
3937 error
= SYSCTL_OUT(req
, &tcpstat
, MIN(sizeof (tcpstat
), req
->oldlen
));
3943 SYSCTL_PROC(_net_inet_tcp
, TCPCTL_STATS
, stats
, CTLFLAG_RD
, 0, 0,
3944 tcp_getstat
, "S,tcpstat", "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
3947 sysctl_rexmtthresh SYSCTL_HANDLER_ARGS
3949 #pragma unused(arg1, arg2)
3951 int error
, val
= tcprexmtthresh
;
3953 error
= sysctl_handle_int(oidp
, &val
, 0, req
);
3954 if (error
|| !req
->newptr
)
3958 * Constrain the number of duplicate ACKs
3959 * to consider for TCP fast retransmit
3963 if (val
< 2 || val
> 3)
3966 tcprexmtthresh
= val
;
3971 SYSCTL_PROC(_net_inet_tcp
, OID_AUTO
, rexmt_thresh
, CTLTYPE_INT
|CTLFLAG_RW
,
3972 &tcprexmtthresh
, 0, &sysctl_rexmtthresh
, "I", "Duplicate ACK Threshold for Fast Retransmit");