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() */
85 #include <net/if_types.h>
86 #include <net/route.h>
88 #include <netinet/in.h>
89 #include <netinet/in_systm.h>
90 #include <netinet/ip.h>
91 #include <netinet/ip_icmp.h> /* for ICMP_BANDLIM */
92 #include <netinet/in_var.h>
93 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
94 #include <netinet/in_pcb.h>
95 #include <netinet/ip_var.h>
97 #include <netinet/ip6.h>
98 #include <netinet/icmp6.h>
99 #include <netinet6/nd6.h>
100 #include <netinet6/ip6_var.h>
101 #include <netinet6/in6_pcb.h>
103 #include <netinet/tcp.h>
104 #include <netinet/tcp_fsm.h>
105 #include <netinet/tcp_seq.h>
106 #include <netinet/tcp_timer.h>
107 #include <netinet/tcp_var.h>
109 #include <netinet6/tcp6_var.h>
111 #include <netinet/tcpip.h>
113 #include <netinet/tcp_debug.h>
114 u_char tcp_saveipgen
[40]; /* the size must be of max ip header, now IPv6 */
115 struct tcphdr tcp_savetcp
;
116 #endif /* TCPDEBUG */
119 #include <netinet6/ipsec.h>
121 #include <netinet6/ipsec6.h>
123 #include <netkey/key.h>
126 #if CONFIG_MACF_NET || CONFIG_MACF_SOCKET
127 #include <security/mac_framework.h>
128 #endif /* CONFIG_MACF_NET || CONFIG_MACF_SOCKET */
130 #include <sys/kdebug.h>
133 MALLOC_DEFINE(M_TSEGQ
, "tseg_qent", "TCP segment queue entry");
136 #define DBG_LAYER_BEG NETDBG_CODE(DBG_NETTCP, 0)
137 #define DBG_LAYER_END NETDBG_CODE(DBG_NETTCP, 2)
138 #define DBG_FNC_TCP_INPUT NETDBG_CODE(DBG_NETTCP, (3 << 8))
139 #define DBG_FNC_TCP_NEWCONN NETDBG_CODE(DBG_NETTCP, (7 << 8))
141 static int tcprexmtthresh
= 2;
145 extern int ipsec_bypass
;
148 struct tcpstat tcpstat
;
150 static int log_in_vain
= 0;
151 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, log_in_vain
, CTLFLAG_RW
,
152 &log_in_vain
, 0, "Log all incoming TCP connections");
154 static int blackhole
= 0;
155 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, blackhole
, CTLFLAG_RW
,
156 &blackhole
, 0, "Do not send RST when dropping refused connections");
158 int tcp_delack_enabled
= 3;
159 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, delayed_ack
, CTLFLAG_RW
,
160 &tcp_delack_enabled
, 0,
161 "Delay ACK to try and piggyback it onto a data packet");
163 int tcp_lq_overflow
= 1;
164 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, tcp_lq_overflow
, CTLFLAG_RW
,
166 "Listen Queue Overflow");
169 static int drop_synfin
= 1;
170 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, drop_synfin
, CTLFLAG_RW
,
171 &drop_synfin
, 0, "Drop TCP packets with SYN+FIN set");
174 SYSCTL_NODE(_net_inet_tcp
, OID_AUTO
, reass
, CTLFLAG_RW
|CTLFLAG_LOCKED
, 0,
175 "TCP Segment Reassembly Queue");
177 __private_extern__
int tcp_reass_maxseg
= 0;
178 SYSCTL_INT(_net_inet_tcp_reass
, OID_AUTO
, maxsegments
, CTLFLAG_RW
,
179 &tcp_reass_maxseg
, 0,
180 "Global maximum number of TCP Segments in Reassembly Queue");
182 __private_extern__
int tcp_reass_qsize
= 0;
183 SYSCTL_INT(_net_inet_tcp_reass
, OID_AUTO
, cursegments
, CTLFLAG_RD
,
185 "Global number of TCP Segments currently in Reassembly Queue");
187 static int tcp_reass_overflows
= 0;
188 SYSCTL_INT(_net_inet_tcp_reass
, OID_AUTO
, overflows
, CTLFLAG_RD
,
189 &tcp_reass_overflows
, 0,
190 "Global number of TCP Segment Reassembly Queue Overflows");
193 __private_extern__
int slowlink_wsize
= 8192;
194 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, slowlink_wsize
, CTLFLAG_RW
,
195 &slowlink_wsize
, 0, "Maximum advertised window size for slowlink");
197 static int maxseg_unacked
= 8;
198 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, maxseg_unacked
, CTLFLAG_RW
,
199 &maxseg_unacked
, 0, "Maximum number of outstanding segments left unacked");
201 static int tcp_do_rfc3465
= 1;
202 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, rfc3465
, CTLFLAG_RW
,
203 &tcp_do_rfc3465
, 0, "");
204 extern int tcp_TCPTV_MIN
;
208 struct inpcbhead tcb
;
209 #define tcb6 tcb /* for KAME src sync over BSD*'s */
210 struct inpcbinfo tcbinfo
;
212 static void tcp_dooptions(struct tcpcb
*,
213 u_char
*, int, struct tcphdr
*, struct tcpopt
*, unsigned int);
214 static void tcp_pulloutofband(struct socket
*,
215 struct tcphdr
*, struct mbuf
*, int);
216 static int tcp_reass(struct tcpcb
*, struct tcphdr
*, int *,
218 static void tcp_xmit_timer(struct tcpcb
*, int);
219 static inline unsigned int tcp_maxmtu(struct rtentry
*);
221 static inline unsigned int tcp_maxmtu6(struct rtentry
*);
224 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
226 #define ND6_HINT(tp) \
228 if ((tp) && (tp)->t_inpcb && \
229 ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0 && \
230 (tp)->t_inpcb->in6p_route.ro_rt) \
231 nd6_nud_hint((tp)->t_inpcb->in6p_route.ro_rt, NULL, 0); \
237 extern u_long
*delack_bitmask
;
239 extern void add_to_time_wait(struct tcpcb
*);
240 extern void postevent(struct socket
*, struct sockbuf
*, int);
242 extern void ipfwsyslog( int level
, const char *format
,...);
243 extern int ChkAddressOK( __uint32_t dstaddr
, __uint32_t srcaddr
);
244 extern int fw_verbose
;
245 __private_extern__
int tcp_sockthreshold
;
246 __private_extern__
int tcp_win_scale
;
249 #define log_in_vain_log( a ) { \
250 if ( (log_in_vain == 3 ) && (fw_verbose == 2)) { /* Apple logging, log to ipfw.log */ \
256 #define log_in_vain_log( a ) { log a; }
261 * Indicate whether this ack should be delayed.
262 * We can delay the ack if:
263 * - delayed acks are enabled (set to 1) and
264 * - our last ack wasn't a 0-sized window. We never want to delay
265 * the ack that opens up a 0-sized window.
266 * - delayed acks are enabled (set to 2, "more compatible") and
267 * - our last ack wasn't a 0-sized window.
268 * - if the peer hasn't sent us a TH_PUSH data packet (this solves 3649245)
269 * - the peer hasn't sent us a TH_PUSH data packet, if he did, take this as a clue that we
270 * need to ACK with no delay. This helps higher level protocols who won't send
271 * us more data even if the window is open because their last "segment" hasn't been ACKed
272 * - delayed acks are enabled (set to 3, "streaming detection") and
273 * - if we receive more than "maxseg_unacked" full packets per second on this socket
274 * - if we don't have more than "maxseg_unacked" delayed so far
275 * - if those criteria aren't met, acts like "2". Allowing faster acking while browsing for example.
278 #define DELAY_ACK(tp) \
279 (((tcp_delack_enabled == 1) && ((tp->t_flags & TF_RXWIN0SENT) == 0)) || \
280 (((tcp_delack_enabled == 2) && (tp->t_flags & TF_RXWIN0SENT) == 0) && \
281 ((thflags & TH_PUSH) == 0) && ((tp->t_flags & TF_DELACK) == 0)) || \
282 (((tcp_delack_enabled == 3) && (tp->t_flags & TF_RXWIN0SENT) == 0) && \
283 (tp->t_rcvtime == 0) && ((thflags & TH_PUSH) == 0) && \
284 (((tp->t_unacksegs == 0)) || \
285 ((tp->rcv_byps > (maxseg_unacked * tp->t_maxseg)) && (tp->t_unacksegs < maxseg_unacked)))))
287 static int tcp_dropdropablreq(struct socket
*head
);
288 static void tcp_newreno_partial_ack(struct tcpcb
*tp
, struct tcphdr
*th
);
292 tcp_reass(tp
, th
, tlenp
, m
)
293 register struct tcpcb
*tp
;
294 register struct tcphdr
*th
;
299 struct tseg_qent
*p
= NULL
;
300 struct tseg_qent
*nq
;
301 struct tseg_qent
*te
= NULL
;
302 struct socket
*so
= tp
->t_inpcb
->inp_socket
;
307 * Call with th==0 after become established to
308 * force pre-ESTABLISHED data up to user socket.
314 * Limit the number of segments in the reassembly queue to prevent
315 * holding on to too many segments (and thus running out of mbufs).
316 * Make sure to let the missing segment through which caused this
317 * queue. Always keep one global queue entry spare to be able to
318 * process the missing segment.
320 if (th
->th_seq
!= tp
->rcv_nxt
&&
321 tcp_reass_qsize
+ 1 >= tcp_reass_maxseg
) {
322 tcp_reass_overflows
++;
323 tcpstat
.tcps_rcvmemdrop
++;
329 /* Allocate a new queue entry. If we can't, just drop the pkt. XXX */
330 MALLOC(te
, struct tseg_qent
*, sizeof (struct tseg_qent
), M_TSEGQ
,
333 tcpstat
.tcps_rcvmemdrop
++;
340 * Find a segment which begins after this one does.
342 LIST_FOREACH(q
, &tp
->t_segq
, tqe_q
) {
343 if (SEQ_GT(q
->tqe_th
->th_seq
, th
->th_seq
))
349 * If there is a preceding segment, it may provide some of
350 * our data already. If so, drop the data from the incoming
351 * segment. If it provides all of our data, drop us.
355 /* conversion to int (in i) handles seq wraparound */
356 i
= p
->tqe_th
->th_seq
+ p
->tqe_len
- th
->th_seq
;
359 tcpstat
.tcps_rcvduppack
++;
360 tcpstat
.tcps_rcvdupbyte
+= *tlenp
;
365 * Try to present any queued data
366 * at the left window edge to the user.
367 * This is needed after the 3-WHS
370 goto present
; /* ??? */
377 tcpstat
.tcps_rcvoopack
++;
378 tcpstat
.tcps_rcvoobyte
+= *tlenp
;
381 * While we overlap succeeding segments trim them or,
382 * if they are completely covered, dequeue them.
385 register int i
= (th
->th_seq
+ *tlenp
) - q
->tqe_th
->th_seq
;
388 if (i
< q
->tqe_len
) {
389 q
->tqe_th
->th_seq
+= i
;
395 nq
= LIST_NEXT(q
, tqe_q
);
396 LIST_REMOVE(q
, tqe_q
);
403 /* Insert the new segment queue entry into place. */
406 te
->tqe_len
= *tlenp
;
409 LIST_INSERT_HEAD(&tp
->t_segq
, te
, tqe_q
);
411 LIST_INSERT_AFTER(p
, te
, tqe_q
);
416 * Present data to user, advancing rcv_nxt through
417 * completed sequence space.
419 if (!TCPS_HAVEESTABLISHED(tp
->t_state
))
421 q
= LIST_FIRST(&tp
->t_segq
);
422 if (!q
|| q
->tqe_th
->th_seq
!= tp
->rcv_nxt
)
425 tp
->rcv_nxt
+= q
->tqe_len
;
426 flags
= q
->tqe_th
->th_flags
& TH_FIN
;
427 nq
= LIST_NEXT(q
, tqe_q
);
428 LIST_REMOVE(q
, tqe_q
);
429 if (so
->so_state
& SS_CANTRCVMORE
)
432 if (sbappendstream(&so
->so_rcv
, q
->tqe_m
))
438 } while (q
&& q
->tqe_th
->th_seq
== tp
->rcv_nxt
);
442 if ((tp
->t_inpcb
->inp_vflag
& INP_IPV6
) != 0) {
444 KERNEL_DEBUG(DBG_LAYER_BEG
,
445 ((tp
->t_inpcb
->inp_fport
<< 16) | tp
->t_inpcb
->inp_lport
),
446 (((tp
->t_inpcb
->in6p_laddr
.s6_addr16
[0] & 0xffff) << 16) |
447 (tp
->t_inpcb
->in6p_faddr
.s6_addr16
[0] & 0xffff)),
453 KERNEL_DEBUG(DBG_LAYER_BEG
,
454 ((tp
->t_inpcb
->inp_fport
<< 16) | tp
->t_inpcb
->inp_lport
),
455 (((tp
->t_inpcb
->inp_laddr
.s_addr
& 0xffff) << 16) |
456 (tp
->t_inpcb
->inp_faddr
.s_addr
& 0xffff)),
460 sorwakeup(so
); /* done with socket lock held */
466 * Reduce congestion window.
469 tcp_reduce_congestion_window(
474 win
= min(tp
->snd_wnd
, tp
->snd_cwnd
) /
478 tp
->snd_ssthresh
= win
* tp
->t_maxseg
;
479 ENTER_FASTRECOVERY(tp
);
480 tp
->snd_recover
= tp
->snd_max
;
481 tp
->t_timer
[TCPT_REXMT
] = 0;
483 tp
->ecn_flags
|= TE_SENDCWR
;
484 tp
->snd_cwnd
= tp
->snd_ssthresh
+
485 tp
->t_maxseg
* tcprexmtthresh
;
490 * TCP input routine, follows pages 65-76 of the
491 * protocol specification dated September, 1981 very closely.
499 register struct mbuf
*m
= *mp
;
500 struct in6_ifaddr
*ia6
;
502 IP6_EXTHDR_CHECK(m
, *offp
, sizeof(struct tcphdr
), return IPPROTO_DONE
);
505 * draft-itojun-ipv6-tcp-to-anycast
506 * better place to put this in?
508 ia6
= ip6_getdstifaddr(m
);
509 if (ia6
&& (ia6
->ia6_flags
& IN6_IFF_ANYCAST
)) {
512 ip6
= mtod(m
, struct ip6_hdr
*);
513 icmp6_error(m
, ICMP6_DST_UNREACH
, ICMP6_DST_UNREACH_ADDR
,
514 (caddr_t
)&ip6
->ip6_dst
- (caddr_t
)ip6
);
528 register struct tcphdr
*th
;
529 register struct ip
*ip
= NULL
;
530 register struct ipovly
*ipov
;
531 register struct inpcb
*inp
;
536 register struct tcpcb
*tp
= 0;
537 register int thflags
;
538 struct socket
*so
= 0;
539 int todrop
, acked
, ourfinisacked
, needoutput
= 0;
540 struct in_addr laddr
;
542 struct in6_addr laddr6
;
548 struct tcpopt to
; /* options in this segment */
549 struct sockaddr_in
*next_hop
= NULL
;
553 struct m_tag
*fwd_tag
;
554 u_char ip_ecn
= IPTOS_ECN_NOTECT
;
555 unsigned int ifscope
;
558 * Record the interface where this segment arrived on; this does not
559 * affect normal data output (for non-detached TCP) as it provides a
560 * hint about which route and interface to use for sending in the
561 * absence of a PCB, when scoped routing (and thus source interface
562 * selection) are enabled.
564 if ((m
->m_flags
& M_PKTHDR
) && m
->m_pkthdr
.rcvif
!= NULL
)
565 ifscope
= m
->m_pkthdr
.rcvif
->if_index
;
567 ifscope
= IFSCOPE_NONE
;
569 /* Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain. */
570 fwd_tag
= m_tag_locate(m
, KERNEL_MODULE_TAG_ID
, KERNEL_TAG_TYPE_IPFORWARD
, NULL
);
571 if (fwd_tag
!= NULL
) {
572 struct ip_fwd_tag
*ipfwd_tag
= (struct ip_fwd_tag
*)(fwd_tag
+1);
574 next_hop
= ipfwd_tag
->next_hop
;
575 m_tag_delete(m
, fwd_tag
);
579 struct ip6_hdr
*ip6
= NULL
;
582 int rstreason
; /* For badport_bandlim accounting purposes */
583 struct proc
*proc0
=current_proc();
585 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_START
,0,0,0,0,0);
588 isipv6
= (mtod(m
, struct ip
*)->ip_v
== 6) ? 1 : 0;
590 bzero((char *)&to
, sizeof(to
));
592 tcpstat
.tcps_rcvtotal
++;
598 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
599 ip6
= mtod(m
, struct ip6_hdr
*);
600 tlen
= sizeof(*ip6
) + ntohs(ip6
->ip6_plen
) - off0
;
601 if (in6_cksum(m
, IPPROTO_TCP
, off0
, tlen
)) {
602 tcpstat
.tcps_rcvbadsum
++;
605 th
= (struct tcphdr
*)((caddr_t
)ip6
+ off0
);
607 KERNEL_DEBUG(DBG_LAYER_BEG
, ((th
->th_dport
<< 16) | th
->th_sport
),
608 (((ip6
->ip6_src
.s6_addr16
[0]) << 16) | (ip6
->ip6_dst
.s6_addr16
[0])),
609 th
->th_seq
, th
->th_ack
, th
->th_win
);
611 * Be proactive about unspecified IPv6 address in source.
612 * As we use all-zero to indicate unbounded/unconnected pcb,
613 * unspecified IPv6 address can be used to confuse us.
615 * Note that packets with unspecified IPv6 destination is
616 * already dropped in ip6_input.
618 if (IN6_IS_ADDR_UNSPECIFIED(&ip6
->ip6_src
)) {
626 * Get IP and TCP header together in first mbuf.
627 * Note: IP leaves IP header in first mbuf.
629 if (off0
> sizeof (struct ip
)) {
630 ip_stripoptions(m
, (struct mbuf
*)0);
631 off0
= sizeof(struct ip
);
632 if (m
->m_pkthdr
.csum_flags
& CSUM_TCP_SUM16
)
633 m
->m_pkthdr
.csum_flags
= 0; /* invalidate hwcksuming */
636 if (m
->m_len
< sizeof (struct tcpiphdr
)) {
637 if ((m
= m_pullup(m
, sizeof (struct tcpiphdr
))) == 0) {
638 tcpstat
.tcps_rcvshort
++;
642 ip
= mtod(m
, struct ip
*);
643 ipov
= (struct ipovly
*)ip
;
644 th
= (struct tcphdr
*)((caddr_t
)ip
+ off0
);
647 KERNEL_DEBUG(DBG_LAYER_BEG
, ((th
->th_dport
<< 16) | th
->th_sport
),
648 (((ip
->ip_src
.s_addr
& 0xffff) << 16) | (ip
->ip_dst
.s_addr
& 0xffff)),
649 th
->th_seq
, th
->th_ack
, th
->th_win
);
651 if (m
->m_pkthdr
.csum_flags
& CSUM_DATA_VALID
) {
652 if (m
->m_pkthdr
.csum_flags
& CSUM_TCP_SUM16
) {
655 *(uint32_t*)&b
[0] = *(uint32_t*)&ipov
->ih_x1
[0];
656 *(uint32_t*)&b
[4] = *(uint32_t*)&ipov
->ih_x1
[4];
657 *(uint8_t*)&b
[8] = *(uint8_t*)&ipov
->ih_x1
[8];
659 bzero(ipov
->ih_x1
, sizeof(ipov
->ih_x1
));
660 ipov
->ih_len
= (u_short
)tlen
;
662 pseudo
= in_cksum(m
, sizeof (struct ip
));
664 *(uint32_t*)&ipov
->ih_x1
[0] = *(uint32_t*)&b
[0];
665 *(uint32_t*)&ipov
->ih_x1
[4] = *(uint32_t*)&b
[4];
666 *(uint8_t*)&ipov
->ih_x1
[8] = *(uint8_t*)&b
[8];
668 th
->th_sum
= in_addword(pseudo
, (m
->m_pkthdr
.csum_data
& 0xFFFF));
670 if (m
->m_pkthdr
.csum_flags
& CSUM_PSEUDO_HDR
)
671 th
->th_sum
= m
->m_pkthdr
.csum_data
;
673 th
->th_sum
= in_pseudo(ip
->ip_src
.s_addr
,
674 ip
->ip_dst
.s_addr
, htonl(m
->m_pkthdr
.csum_data
+
675 ip
->ip_len
+ IPPROTO_TCP
));
677 th
->th_sum
^= 0xffff;
681 * Checksum extended TCP header and data.
683 *(uint32_t*)&b
[0] = *(uint32_t*)&ipov
->ih_x1
[0];
684 *(uint32_t*)&b
[4] = *(uint32_t*)&ipov
->ih_x1
[4];
685 *(uint8_t*)&b
[8] = *(uint8_t*)&ipov
->ih_x1
[8];
687 len
= sizeof (struct ip
) + tlen
;
688 bzero(ipov
->ih_x1
, sizeof(ipov
->ih_x1
));
689 ipov
->ih_len
= (u_short
)tlen
;
691 th
->th_sum
= in_cksum(m
, len
);
693 *(uint32_t*)&ipov
->ih_x1
[0] = *(uint32_t*)&b
[0];
694 *(uint32_t*)&ipov
->ih_x1
[4] = *(uint32_t*)&b
[4];
695 *(uint8_t*)&ipov
->ih_x1
[8] = *(uint8_t*)&b
[8];
697 tcp_in_cksum_stats(len
);
700 tcpstat
.tcps_rcvbadsum
++;
704 /* Re-initialization for later version check */
705 ip
->ip_v
= IPVERSION
;
707 ip_ecn
= (ip
->ip_tos
& IPTOS_ECN_MASK
);
711 * Check that TCP offset makes sense,
712 * pull out TCP options and adjust length. XXX
714 off
= th
->th_off
<< 2;
715 if (off
< sizeof (struct tcphdr
) || off
> tlen
) {
716 tcpstat
.tcps_rcvbadoff
++;
719 tlen
-= off
; /* tlen is used instead of ti->ti_len */
720 if (off
> sizeof (struct tcphdr
)) {
723 IP6_EXTHDR_CHECK(m
, off0
, off
, return);
724 ip6
= mtod(m
, struct ip6_hdr
*);
725 th
= (struct tcphdr
*)((caddr_t
)ip6
+ off0
);
729 if (m
->m_len
< sizeof(struct ip
) + off
) {
730 if ((m
= m_pullup(m
, sizeof (struct ip
) + off
)) == 0) {
731 tcpstat
.tcps_rcvshort
++;
734 ip
= mtod(m
, struct ip
*);
735 ipov
= (struct ipovly
*)ip
;
736 th
= (struct tcphdr
*)((caddr_t
)ip
+ off0
);
739 optlen
= off
- sizeof (struct tcphdr
);
740 optp
= (u_char
*)(th
+ 1);
742 * Do quick retrieval of timestamp options ("options
743 * prediction?"). If timestamp is the only option and it's
744 * formatted as recommended in RFC 1323 appendix A, we
745 * quickly get the values now and not bother calling
746 * tcp_dooptions(), etc.
748 if ((optlen
== TCPOLEN_TSTAMP_APPA
||
749 (optlen
> TCPOLEN_TSTAMP_APPA
&&
750 optp
[TCPOLEN_TSTAMP_APPA
] == TCPOPT_EOL
)) &&
751 *(u_int32_t
*)optp
== htonl(TCPOPT_TSTAMP_HDR
) &&
752 (th
->th_flags
& TH_SYN
) == 0) {
753 to
.to_flags
|= TOF_TS
;
754 to
.to_tsval
= ntohl(*(u_int32_t
*)(optp
+ 4));
755 to
.to_tsecr
= ntohl(*(u_int32_t
*)(optp
+ 8));
756 optp
= NULL
; /* we've parsed the options */
759 thflags
= th
->th_flags
;
763 * If the drop_synfin option is enabled, drop all packets with
764 * both the SYN and FIN bits set. This prevents e.g. nmap from
765 * identifying the TCP/IP stack.
767 * This is a violation of the TCP specification.
769 if (drop_synfin
&& (thflags
& (TH_SYN
|TH_FIN
)) == (TH_SYN
|TH_FIN
))
774 * Convert TCP protocol specific fields to host format.
782 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options,
783 * until after ip6_savecontrol() is called and before other functions
784 * which don't want those proto headers.
785 * Because ip6_savecontrol() is going to parse the mbuf to
786 * search for data to be passed up to user-land, it wants mbuf
787 * parameters to be unchanged.
789 drop_hdrlen
= off0
+ off
;
792 * Locate pcb for segment.
795 #if IPFIREWALL_FORWARD
798 && isipv6
== 0 /* IPv6 support is not yet */
802 * Diverted. Pretend to be the destination.
803 * already got one like this?
805 inp
= in_pcblookup_hash(&tcbinfo
, ip
->ip_src
, th
->th_sport
,
806 ip
->ip_dst
, th
->th_dport
, 0, m
->m_pkthdr
.rcvif
);
809 * No, then it's new. Try find the ambushing socket
811 if (!next_hop
->sin_port
) {
812 inp
= in_pcblookup_hash(&tcbinfo
, ip
->ip_src
,
813 th
->th_sport
, next_hop
->sin_addr
,
814 th
->th_dport
, 1, m
->m_pkthdr
.rcvif
);
816 inp
= in_pcblookup_hash(&tcbinfo
,
817 ip
->ip_src
, th
->th_sport
,
819 ntohs(next_hop
->sin_port
), 1,
824 #endif /* IPFIREWALL_FORWARD */
828 inp
= in6_pcblookup_hash(&tcbinfo
, &ip6
->ip6_src
, th
->th_sport
,
829 &ip6
->ip6_dst
, th
->th_dport
, 1,
833 inp
= in_pcblookup_hash(&tcbinfo
, ip
->ip_src
, th
->th_sport
,
834 ip
->ip_dst
, th
->th_dport
, 1, m
->m_pkthdr
.rcvif
);
838 * Use the interface scope information from the PCB for outbound
839 * segments. If the PCB isn't present and if scoped routing is
840 * enabled, tcp_respond will use the scope of the interface where
841 * the segment arrived on.
843 if (inp
!= NULL
&& (inp
->inp_flags
& INP_BOUND_IF
))
844 ifscope
= inp
->inp_boundif
;
846 if (ipsec_bypass
== 0) {
849 if (inp
!= NULL
&& ipsec6_in_reject_so(m
, inp
->inp_socket
)) {
850 IPSEC_STAT_INCREMENT(ipsec6stat
.in_polvio
);
855 if (inp
!= NULL
&& ipsec4_in_reject_so(m
, inp
->inp_socket
)) {
856 IPSEC_STAT_INCREMENT(ipsecstat
.in_polvio
);
863 * If the state is CLOSED (i.e., TCB does not exist) then
864 * all data in the incoming segment is discarded.
865 * If the TCB exists but is in CLOSED state, it is embryonic,
866 * but should either do a listen or a connect soon.
871 char dbuf
[MAX_IPv6_STR_LEN
], sbuf
[MAX_IPv6_STR_LEN
];
873 char dbuf
[MAX_IPv4_STR_LEN
], sbuf
[MAX_IPv4_STR_LEN
];
878 inet_ntop(AF_INET6
, &ip6
->ip6_dst
, dbuf
, sizeof(dbuf
));
879 inet_ntop(AF_INET6
, &ip6
->ip6_src
, sbuf
, sizeof(sbuf
));
883 inet_ntop(AF_INET
, &ip
->ip_dst
, dbuf
, sizeof(dbuf
));
884 inet_ntop(AF_INET
, &ip
->ip_src
, sbuf
, sizeof(sbuf
));
886 switch (log_in_vain
) {
890 "Connection attempt to TCP %s:%d from %s:%d\n",
891 dbuf
, ntohs(th
->th_dport
),
893 ntohs(th
->th_sport
));
897 "Connection attempt to TCP %s:%d from %s:%d flags:0x%x\n",
898 dbuf
, ntohs(th
->th_dport
), sbuf
,
899 ntohs(th
->th_sport
), thflags
);
902 if ((thflags
& TH_SYN
) &&
903 !(m
->m_flags
& (M_BCAST
| M_MCAST
)) &&
905 ((isipv6
&& !IN6_ARE_ADDR_EQUAL(&ip6
->ip6_dst
, &ip6
->ip6_src
)) ||
906 (!isipv6
&& ip
->ip_dst
.s_addr
!= ip
->ip_src
.s_addr
))
908 ip
->ip_dst
.s_addr
!= ip
->ip_src
.s_addr
911 log_in_vain_log((LOG_INFO
,
912 "Stealth Mode connection attempt to TCP %s:%d from %s:%d\n",
913 dbuf
, ntohs(th
->th_dport
),
915 ntohs(th
->th_sport
)));
922 if (m
->m_pkthdr
.rcvif
&& m
->m_pkthdr
.rcvif
->if_type
!= IFT_LOOP
)
925 if (thflags
& TH_SYN
)
934 rstreason
= BANDLIM_RST_CLOSEDPORT
;
935 goto dropwithresetnosock
;
937 so
= inp
->inp_socket
;
939 if (in_pcb_checkstate(inp
, WNT_RELEASE
, 1) == WNT_STOPUSING
)
940 inp
= NULL
; // pretend we didn't find it
942 printf("tcp_input: no more socket for inp=%x\n", inp
);
949 * Bogus state when listening port owned by SharedIP with loopback as the
950 * only configured interface: BlueBox does not filters loopback
952 if (so
== &tcbinfo
.nat_dummy_socket
)
957 if (in_pcb_checkstate(inp
, WNT_RELEASE
, 1) == WNT_STOPUSING
) {
958 tcp_unlock(so
, 1, 2);
959 inp
= NULL
; // pretend we didn't find it
965 rstreason
= BANDLIM_RST_CLOSEDPORT
;
968 if (tp
->t_state
== TCPS_CLOSED
)
971 /* Unscale the window into a 32-bit value. */
972 if ((thflags
& TH_SYN
) == 0)
973 tiwin
= th
->th_win
<< tp
->snd_scale
;
978 if (mac_inpcb_check_deliver(inp
, m
, AF_INET
, SOCK_STREAM
))
982 if (so
->so_options
& (SO_DEBUG
|SO_ACCEPTCONN
)) {
984 if (so
->so_options
& SO_DEBUG
) {
985 ostate
= tp
->t_state
;
988 bcopy((char *)ip6
, (char *)tcp_saveipgen
,
992 bcopy((char *)ip
, (char *)tcp_saveipgen
, sizeof(*ip
));
996 if (so
->so_options
& SO_ACCEPTCONN
) {
997 register struct tcpcb
*tp0
= tp
;
1000 struct sockaddr_storage from
;
1002 struct inpcb
*oinp
= sotoinpcb(so
);
1004 int ogencnt
= so
->so_gencnt
;
1005 unsigned int head_ifscope
;
1007 /* Get listener's bound-to-interface, if any */
1008 head_ifscope
= (inp
->inp_flags
& INP_BOUND_IF
) ?
1009 inp
->inp_boundif
: IFSCOPE_NONE
;
1013 * Current IPsec implementation makes incorrect IPsec
1014 * cache if this check is done here.
1015 * So delay this until duplicated socket is created.
1017 if ((thflags
& (TH_RST
|TH_ACK
|TH_SYN
)) != TH_SYN
) {
1019 * Note: dropwithreset makes sure we don't
1020 * send a RST in response to a RST.
1022 if (thflags
& TH_ACK
) {
1023 tcpstat
.tcps_badsyn
++;
1024 rstreason
= BANDLIM_RST_OPENPORT
;
1030 KERNEL_DEBUG(DBG_FNC_TCP_NEWCONN
| DBG_FUNC_START
,0,0,0,0,0);
1034 * If deprecated address is forbidden,
1035 * we do not accept SYN to deprecated interface
1036 * address to prevent any new inbound connection from
1037 * getting established.
1038 * When we do not accept SYN, we send a TCP RST,
1039 * with deprecated source address (instead of dropping
1040 * it). We compromise it as it is much better for peer
1041 * to send a RST, and RST will be the final packet
1044 * If we do not forbid deprecated addresses, we accept
1045 * the SYN packet. RFC2462 does not suggest dropping
1047 * If we decipher RFC2462 5.5.4, it says like this:
1048 * 1. use of deprecated addr with existing
1049 * communication is okay - "SHOULD continue to be
1051 * 2. use of it with new communication:
1052 * (2a) "SHOULD NOT be used if alternate address
1053 * with sufficient scope is available"
1054 * (2b) nothing mentioned otherwise.
1055 * Here we fall into (2b) case as we have no choice in
1056 * our source address selection - we must obey the peer.
1058 * The wording in RFC2462 is confusing, and there are
1059 * multiple description text for deprecated address
1060 * handling - worse, they are not exactly the same.
1061 * I believe 5.5.4 is the best one, so we follow 5.5.4.
1063 if (isipv6
&& !ip6_use_deprecated
) {
1064 struct in6_ifaddr
*ia6
;
1066 if ((ia6
= ip6_getdstifaddr(m
)) &&
1067 (ia6
->ia6_flags
& IN6_IFF_DEPRECATED
)) {
1069 rstreason
= BANDLIM_RST_OPENPORT
;
1077 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*)&from
;
1079 sin6
->sin6_len
= sizeof(*sin6
);
1080 sin6
->sin6_family
= AF_INET6
;
1081 sin6
->sin6_port
= th
->th_sport
;
1082 sin6
->sin6_flowinfo
= 0;
1083 sin6
->sin6_addr
= ip6
->ip6_src
;
1084 sin6
->sin6_scope_id
= 0;
1089 struct sockaddr_in
*sin
= (struct sockaddr_in
*)&from
;
1091 sin
->sin_len
= sizeof(*sin
);
1092 sin
->sin_family
= AF_INET
;
1093 sin
->sin_port
= th
->th_sport
;
1094 sin
->sin_addr
= ip
->ip_src
;
1096 so2
= sonewconn(so
, 0, (struct sockaddr
*)&from
);
1098 so2
= sonewconn(so
, 0, NULL
);
1101 tcpstat
.tcps_listendrop
++;
1102 if (tcp_dropdropablreq(so
)) {
1104 so2
= sonewconn(so
, 0, (struct sockaddr
*)&from
);
1106 so2
= sonewconn(so
, 0, NULL
);
1112 * Make sure listening socket did not get closed during socket allocation,
1113 * not only this is incorrect but it is know to cause panic
1115 if (so
->so_gencnt
!= ogencnt
)
1119 tcp_unlock(so
, 0, 0); /* Unlock but keep a reference on listener for now */
1124 * This is ugly, but ....
1126 * Mark socket as temporary until we're
1127 * committed to keeping it. The code at
1128 * ``drop'' and ``dropwithreset'' check the
1129 * flag dropsocket to see if the temporary
1130 * socket created here should be discarded.
1131 * We mark the socket as discardable until
1132 * we're committed to it below in TCPS_LISTEN.
1135 inp
= (struct inpcb
*)so
->so_pcb
;
1138 * Inherit INP_BOUND_IF from listener; testing if
1139 * head_ifscope is non-zero is sufficient, since it
1140 * can only be set to a non-zero value earlier if
1141 * the listener has such a flag set.
1144 if (head_ifscope
!= IFSCOPE_NONE
&& !isipv6
) {
1146 if (head_ifscope
!= IFSCOPE_NONE
) {
1148 inp
->inp_flags
|= INP_BOUND_IF
;
1149 inp
->inp_boundif
= head_ifscope
;
1153 inp
->in6p_laddr
= ip6
->ip6_dst
;
1155 inp
->inp_vflag
&= ~INP_IPV6
;
1156 inp
->inp_vflag
|= INP_IPV4
;
1158 inp
->inp_laddr
= ip
->ip_dst
;
1162 inp
->inp_lport
= th
->th_dport
;
1163 if (in_pcbinshash(inp
, 0) != 0) {
1165 * Undo the assignments above if we failed to
1166 * put the PCB on the hash lists.
1170 inp
->in6p_laddr
= in6addr_any
;
1173 inp
->inp_laddr
.s_addr
= INADDR_ANY
;
1175 tcp_lock(oso
, 0, 0); /* release ref on parent */
1176 tcp_unlock(oso
, 1, 0);
1181 * To avoid creating incorrectly cached IPsec
1182 * association, this is need to be done here.
1184 * Subject: (KAME-snap 748)
1185 * From: Wayne Knowles <w.knowles@niwa.cri.nz>
1186 * ftp://ftp.kame.net/pub/mail-list/snap-users/748
1188 if ((thflags
& (TH_RST
|TH_ACK
|TH_SYN
)) != TH_SYN
) {
1190 * Note: dropwithreset makes sure we don't
1191 * send a RST in response to a RST.
1193 tcp_lock(oso
, 0, 0); /* release ref on parent */
1194 tcp_unlock(oso
, 1, 0);
1195 if (thflags
& TH_ACK
) {
1196 tcpstat
.tcps_badsyn
++;
1197 rstreason
= BANDLIM_RST_OPENPORT
;
1206 * Inherit socket options from the listening
1208 * Note that in6p_inputopts are not (even
1209 * should not be) copied, since it stores
1210 * previously received options and is used to
1211 * detect if each new option is different than
1212 * the previous one and hence should be passed
1214 * If we copied in6p_inputopts, a user would
1215 * not be able to receive options just after
1216 * calling the accept system call.
1219 oinp
->inp_flags
& INP_CONTROLOPTS
;
1220 if (oinp
->in6p_outputopts
)
1221 inp
->in6p_outputopts
=
1222 ip6_copypktopts(oinp
->in6p_outputopts
,
1226 inp
->inp_options
= ip_srcroute();
1227 tcp_lock(oso
, 0, 0);
1229 /* copy old policy into new socket's */
1230 if (sotoinpcb(oso
)->inp_sp
)
1233 /* Is it a security hole here to silently fail to copy the policy? */
1234 if (inp
->inp_sp
!= NULL
)
1235 error
= ipsec_init_policy(so
, &inp
->inp_sp
);
1236 if (error
!= 0 || ipsec_copy_policy(sotoinpcb(oso
)->inp_sp
, inp
->inp_sp
))
1237 printf("tcp_input: could not copy policy\n");
1240 tcp_unlock(oso
, 1, 0); /* now drop the reference on the listener */
1241 tp
= intotcpcb(inp
);
1242 tp
->t_state
= TCPS_LISTEN
;
1243 tp
->t_flags
|= tp0
->t_flags
& (TF_NOPUSH
|TF_NOOPT
|TF_NODELAY
);
1244 tp
->t_inpcb
->inp_ip_ttl
= tp0
->t_inpcb
->inp_ip_ttl
;
1245 /* Compute proper scaling value from buffer space */
1246 if (inp
->inp_pcbinfo
->ipi_count
< tcp_sockthreshold
) {
1247 tp
->request_r_scale
= max(tcp_win_scale
, tp
->request_r_scale
);
1248 so
->so_rcv
.sb_hiwat
= lmin(TCP_MAXWIN
<< tp
->request_r_scale
, (sb_max
/ (MSIZE
+MCLBYTES
)) * MCLBYTES
);
1251 while (tp
->request_r_scale
< TCP_MAX_WINSHIFT
&&
1252 TCP_MAXWIN
<< tp
->request_r_scale
<
1253 so
->so_rcv
.sb_hiwat
)
1254 tp
->request_r_scale
++;
1257 KERNEL_DEBUG(DBG_FNC_TCP_NEWCONN
| DBG_FUNC_END
,0,0,0,0,0);
1262 lck_mtx_assert(((struct inpcb
*)so
->so_pcb
)->inpcb_mtx
, LCK_MTX_ASSERT_OWNED
);
1266 * This is the second part of the MSS DoS prevention code (after
1267 * minmss on the sending side) and it deals with too many too small
1268 * tcp packets in a too short timeframe (1 second).
1270 * For every full second we count the number of received packets
1271 * and bytes. If we get a lot of packets per second for this connection
1272 * (tcp_minmssoverload) we take a closer look at it and compute the
1273 * average packet size for the past second. If that is less than
1274 * tcp_minmss we get too many packets with very small payload which
1275 * is not good and burdens our system (and every packet generates
1276 * a wakeup to the process connected to our socket). We can reasonable
1277 * expect this to be small packet DoS attack to exhaust our CPU
1280 * Care has to be taken for the minimum packet overload value. This
1281 * value defines the minimum number of packets per second before we
1282 * start to worry. This must not be too low to avoid killing for
1283 * example interactive connections with many small packets like
1286 * Setting either tcp_minmssoverload or tcp_minmss to "0" disables
1289 * Account for packet if payload packet, skip over ACK, etc.
1291 * The packet per second count is done all the time and is also used
1292 * by "DELAY_ACK" to detect streaming situations.
1295 if (tp
->t_state
== TCPS_ESTABLISHED
&& tlen
> 0) {
1296 if (tp
->rcv_reset
> tcp_now
) {
1298 tp
->rcv_byps
+= tlen
+ off
;
1299 if (tp
->rcv_byps
> tp
->rcv_maxbyps
)
1300 tp
->rcv_maxbyps
= tp
->rcv_byps
;
1302 * Setting either tcp_minmssoverload or tcp_minmss to "0" disables
1305 if (tcp_minmss
&& tcp_minmssoverload
&& tp
->rcv_pps
> tcp_minmssoverload
) {
1306 if ((tp
->rcv_byps
/ tp
->rcv_pps
) < tcp_minmss
) {
1307 char ipstrbuf
[MAX_IPv6_STR_LEN
];
1308 printf("too many small tcp packets from "
1309 "%s:%u, av. %lubyte/packet, "
1310 "dropping connection\n",
1313 inet_ntop(AF_INET6
, &inp
->in6p_faddr
, ipstrbuf
,
1316 inet_ntop(AF_INET
, &inp
->inp_faddr
, ipstrbuf
,
1319 tp
->rcv_byps
/ tp
->rcv_pps
);
1320 tp
= tcp_drop(tp
, ECONNRESET
);
1321 /* tcpstat.tcps_minmssdrops++; */
1326 tp
->rcv_reset
= tcp_now
+ TCP_RETRANSHZ
;
1328 tp
->rcv_byps
= tlen
+ off
;
1333 if (so
->so_traffic_mgt_flags
& TRAFFIC_MGT_SO_BACKGROUND
) {
1334 tcpstat
.tcps_bg_rcvtotal
++;
1336 /* Take snapshots of pkts recv;
1337 * tcpcb should have been initialized to 0 when allocated,
1338 * so if 0 then this is the first time we're doing this
1340 if (!tp
->tot_recv_snapshot
) {
1341 tp
->tot_recv_snapshot
= tcpstat
.tcps_rcvtotal
;
1343 if (!tp
->bg_recv_snapshot
) {
1344 tp
->bg_recv_snapshot
= tcpstat
.tcps_bg_rcvtotal
;
1347 #endif /* TRAFFIC_MGT */
1350 Explicit Congestion Notification - Flag that we need to send ECT if
1351 + The IP Congestion experienced flag was set.
1352 + Socket is in established state
1353 + We negotiated ECN in the TCP setup
1354 + This isn't a pure ack (tlen > 0)
1355 + The data is in the valid window
1357 TE_SENDECE will be cleared when we receive a packet with TH_CWR set.
1359 if (ip_ecn
== IPTOS_ECN_CE
&& tp
->t_state
== TCPS_ESTABLISHED
&&
1360 (tp
->ecn_flags
& (TE_SETUPSENT
| TE_SETUPRECEIVED
)) ==
1361 (TE_SETUPSENT
| TE_SETUPRECEIVED
) && tlen
> 0 &&
1362 SEQ_GEQ(th
->th_seq
, tp
->last_ack_sent
) &&
1363 SEQ_LT(th
->th_seq
, tp
->last_ack_sent
+ tp
->rcv_wnd
)) {
1364 tp
->ecn_flags
|= TE_SENDECE
;
1368 Clear TE_SENDECE if TH_CWR is set. This is harmless, so we don't
1369 bother doing extensive checks for state and whatnot.
1371 if ((thflags
& TH_CWR
) == TH_CWR
) {
1372 tp
->ecn_flags
&= ~TE_SENDECE
;
1376 * Segment received on connection.
1377 * Reset idle time and keep-alive timer.
1380 if (TCPS_HAVEESTABLISHED(tp
->t_state
))
1381 tp
->t_timer
[TCPT_KEEP
] = TCP_KEEPIDLE(tp
);
1384 * Process options if not in LISTEN state,
1385 * else do it below (after getting remote address).
1387 if (tp
->t_state
!= TCPS_LISTEN
&& optp
)
1388 tcp_dooptions(tp
, optp
, optlen
, th
, &to
, ifscope
);
1390 if (tp
->t_state
== TCPS_SYN_SENT
&& (thflags
& TH_SYN
)) {
1391 if (to
.to_flags
& TOF_SCALE
) {
1392 tp
->t_flags
|= TF_RCVD_SCALE
;
1393 tp
->requested_s_scale
= to
.to_requested_s_scale
;
1394 tp
->snd_wnd
= th
->th_win
<< tp
->snd_scale
;
1395 tiwin
= tp
->snd_wnd
;
1397 if (to
.to_flags
& TOF_TS
) {
1398 tp
->t_flags
|= TF_RCVD_TSTMP
;
1399 tp
->ts_recent
= to
.to_tsval
;
1400 tp
->ts_recent_age
= tcp_now
;
1402 if (to
.to_flags
& TOF_MSS
)
1403 tcp_mss(tp
, to
.to_mss
, ifscope
);
1404 if (tp
->sack_enable
) {
1405 if (!(to
.to_flags
& TOF_SACK
))
1406 tp
->sack_enable
= 0;
1408 tp
->t_flags
|= TF_SACK_PERMIT
;
1413 * Header prediction: check for the two common cases
1414 * of a uni-directional data xfer. If the packet has
1415 * no control flags, is in-sequence, the window didn't
1416 * change and we're not retransmitting, it's a
1417 * candidate. If the length is zero and the ack moved
1418 * forward, we're the sender side of the xfer. Just
1419 * free the data acked & wake any higher level process
1420 * that was blocked waiting for space. If the length
1421 * is non-zero and the ack didn't move, we're the
1422 * receiver side. If we're getting packets in-order
1423 * (the reassembly queue is empty), add the data to
1424 * the socket buffer and note that we need a delayed ack.
1425 * Make sure that the hidden state-flags are also off.
1426 * Since we check for TCPS_ESTABLISHED above, it can only
1429 if (tp
->t_state
== TCPS_ESTABLISHED
&&
1430 (thflags
& (TH_SYN
|TH_FIN
|TH_RST
|TH_URG
|TH_ACK
|TH_ECE
)) == TH_ACK
&&
1431 ((tp
->t_flags
& (TF_NEEDSYN
|TF_NEEDFIN
)) == 0) &&
1432 ((to
.to_flags
& TOF_TS
) == 0 ||
1433 TSTMP_GEQ(to
.to_tsval
, tp
->ts_recent
)) &&
1434 th
->th_seq
== tp
->rcv_nxt
&&
1435 tiwin
&& tiwin
== tp
->snd_wnd
&&
1436 tp
->snd_nxt
== tp
->snd_max
) {
1439 * If last ACK falls within this segment's sequence numbers,
1440 * record the timestamp.
1441 * NOTE that the test is modified according to the latest
1442 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1444 if ((to
.to_flags
& TOF_TS
) != 0 &&
1445 SEQ_LEQ(th
->th_seq
, tp
->last_ack_sent
)) {
1446 tp
->ts_recent_age
= tcp_now
;
1447 tp
->ts_recent
= to
.to_tsval
;
1450 /* Force acknowledgment if we received a FIN */
1452 if (thflags
& TH_FIN
)
1453 tp
->t_flags
|= TF_ACKNOW
;
1456 if (SEQ_GT(th
->th_ack
, tp
->snd_una
) &&
1457 SEQ_LEQ(th
->th_ack
, tp
->snd_max
) &&
1458 tp
->snd_cwnd
>= tp
->snd_ssthresh
&&
1459 ((!tcp_do_newreno
&& !tp
->sack_enable
&&
1460 tp
->t_dupacks
< tcprexmtthresh
) ||
1461 ((tcp_do_newreno
|| tp
->sack_enable
) &&
1462 !IN_FASTRECOVERY(tp
) && to
.to_nsacks
== 0 &&
1463 TAILQ_EMPTY(&tp
->snd_holes
)))) {
1465 * this is a pure ack for outstanding data.
1467 ++tcpstat
.tcps_predack
;
1469 * "bad retransmit" recovery
1471 if (tp
->t_rxtshift
== 1 &&
1472 tcp_now
< tp
->t_badrxtwin
) {
1473 ++tcpstat
.tcps_sndrexmitbad
;
1474 tp
->snd_cwnd
= tp
->snd_cwnd_prev
;
1476 tp
->snd_ssthresh_prev
;
1477 tp
->snd_recover
= tp
->snd_recover_prev
;
1478 if (tp
->t_flags
& TF_WASFRECOVERY
)
1479 ENTER_FASTRECOVERY(tp
);
1480 tp
->snd_nxt
= tp
->snd_max
;
1481 tp
->t_badrxtwin
= 0;
1484 * Recalculate the transmit timer / rtt.
1486 * Some boxes send broken timestamp replies
1487 * during the SYN+ACK phase, ignore
1488 * timestamps of 0 or we could calculate a
1489 * huge RTT and blow up the retransmit timer.
1491 if (((to
.to_flags
& TOF_TS
) != 0) && (to
.to_tsecr
!= 0)) { /* Makes sure we already have a TS */
1492 if (!tp
->t_rttlow
||
1493 tp
->t_rttlow
> tcp_now
- to
.to_tsecr
)
1494 tp
->t_rttlow
= tcp_now
- to
.to_tsecr
;
1496 tcp_now
- to
.to_tsecr
);
1497 } else if (tp
->t_rtttime
&&
1498 SEQ_GT(th
->th_ack
, tp
->t_rtseq
)) {
1499 if (!tp
->t_rttlow
||
1500 tp
->t_rttlow
> tcp_now
- tp
->t_rtttime
)
1501 tp
->t_rttlow
= tcp_now
- tp
->t_rtttime
;
1502 tcp_xmit_timer(tp
, tp
->t_rtttime
);
1504 acked
= th
->th_ack
- tp
->snd_una
;
1505 tcpstat
.tcps_rcvackpack
++;
1506 tcpstat
.tcps_rcvackbyte
+= acked
;
1508 * Grow the congestion window, if the
1509 * connection is cwnd bound.
1511 if (tp
->snd_cwnd
< tp
->snd_wnd
) {
1512 tp
->t_bytes_acked
+= acked
;
1513 if (tp
->t_bytes_acked
> tp
->snd_cwnd
) {
1514 tp
->t_bytes_acked
-= tp
->snd_cwnd
;
1515 tp
->snd_cwnd
+= tp
->t_maxseg
;
1518 sbdrop(&so
->so_snd
, acked
);
1519 if (SEQ_GT(tp
->snd_una
, tp
->snd_recover
) &&
1520 SEQ_LEQ(th
->th_ack
, tp
->snd_recover
))
1521 tp
->snd_recover
= th
->th_ack
- 1;
1522 tp
->snd_una
= th
->th_ack
;
1524 * pull snd_wl2 up to prevent seq wrap relative
1527 tp
->snd_wl2
= th
->th_ack
;
1530 ND6_HINT(tp
); /* some progress has been done */
1533 * If all outstanding data are acked, stop
1534 * retransmit timer, otherwise restart timer
1535 * using current (possibly backed-off) value.
1536 * If process is waiting for space,
1537 * wakeup/selwakeup/signal. If data
1538 * are ready to send, let tcp_output
1539 * decide between more output or persist.
1541 if (tp
->snd_una
== tp
->snd_max
)
1542 tp
->t_timer
[TCPT_REXMT
] = 0;
1543 else if (tp
->t_timer
[TCPT_PERSIST
] == 0)
1544 tp
->t_timer
[TCPT_REXMT
] = tp
->t_rxtcur
;
1546 sowwakeup(so
); /* has to be done with socket lock held */
1547 if ((so
->so_snd
.sb_cc
) || (tp
->t_flags
& TF_ACKNOW
)) {
1548 tp
->t_unacksegs
= 0;
1549 (void) tcp_output(tp
);
1551 tcp_unlock(so
, 1, 0);
1552 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
1555 } else if (th
->th_ack
== tp
->snd_una
&&
1556 LIST_EMPTY(&tp
->t_segq
) &&
1557 tlen
<= tcp_sbspace(tp
)) {
1559 * this is a pure, in-sequence data packet
1560 * with nothing on the reassembly queue and
1561 * we have enough buffer space to take it.
1563 /* Clean receiver SACK report if present */
1564 if (tp
->sack_enable
&& tp
->rcv_numsacks
)
1565 tcp_clean_sackreport(tp
);
1566 ++tcpstat
.tcps_preddat
;
1567 tp
->rcv_nxt
+= tlen
;
1569 * Pull snd_wl1 up to prevent seq wrap relative to
1572 tp
->snd_wl1
= th
->th_seq
;
1574 * Pull rcv_up up to prevent seq wrap relative to
1577 tp
->rcv_up
= tp
->rcv_nxt
;
1578 tcpstat
.tcps_rcvpack
++;
1579 tcpstat
.tcps_rcvbyte
+= tlen
;
1580 ND6_HINT(tp
); /* some progress has been done */
1582 * Add data to socket buffer.
1584 m_adj(m
, drop_hdrlen
); /* delayed header drop */
1585 if (sbappendstream(&so
->so_rcv
, m
))
1589 KERNEL_DEBUG(DBG_LAYER_END
, ((th
->th_dport
<< 16) | th
->th_sport
),
1590 (((ip6
->ip6_src
.s6_addr16
[0]) << 16) | (ip6
->ip6_dst
.s6_addr16
[0])),
1591 th
->th_seq
, th
->th_ack
, th
->th_win
);
1596 KERNEL_DEBUG(DBG_LAYER_END
, ((th
->th_dport
<< 16) | th
->th_sport
),
1597 (((ip
->ip_src
.s_addr
& 0xffff) << 16) | (ip
->ip_dst
.s_addr
& 0xffff)),
1598 th
->th_seq
, th
->th_ack
, th
->th_win
);
1600 if (DELAY_ACK(tp
)) {
1601 tp
->t_flags
|= TF_DELACK
;
1604 tp
->t_unacksegs
= 0;
1605 tp
->t_flags
|= TF_ACKNOW
;
1608 tcp_unlock(so
, 1, 0);
1609 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
1615 * Calculate amount of space in receive window,
1616 * and then do TCP input processing.
1617 * Receive window is amount of space in rcv queue,
1618 * but not less than advertised window.
1621 lck_mtx_assert(((struct inpcb
*)so
->so_pcb
)->inpcb_mtx
, LCK_MTX_ASSERT_OWNED
);
1625 win
= tcp_sbspace(tp
);
1629 else { /* clip rcv window to 4K for modems */
1630 if (tp
->t_flags
& TF_SLOWLINK
&& slowlink_wsize
> 0)
1631 win
= min(win
, slowlink_wsize
);
1633 tp
->rcv_wnd
= imax(win
, (int)(tp
->rcv_adv
- tp
->rcv_nxt
));
1636 switch (tp
->t_state
) {
1639 * If the state is LISTEN then ignore segment if it contains an RST.
1640 * If the segment contains an ACK then it is bad and send a RST.
1641 * If it does not contain a SYN then it is not interesting; drop it.
1642 * If it is from this socket, drop it, it must be forged.
1643 * Don't bother responding if the destination was a broadcast.
1644 * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial
1645 * tp->iss, and send a segment:
1646 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
1647 * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
1648 * Fill in remote peer address fields if not previously specified.
1649 * Enter SYN_RECEIVED state, and process any other fields of this
1650 * segment in this state.
1653 register struct sockaddr_in
*sin
;
1655 register struct sockaddr_in6
*sin6
;
1659 lck_mtx_assert(((struct inpcb
*)so
->so_pcb
)->inpcb_mtx
, LCK_MTX_ASSERT_OWNED
);
1661 if (thflags
& TH_RST
)
1663 if (thflags
& TH_ACK
) {
1664 rstreason
= BANDLIM_RST_OPENPORT
;
1667 if ((thflags
& TH_SYN
) == 0)
1669 if (th
->th_dport
== th
->th_sport
) {
1672 if (IN6_ARE_ADDR_EQUAL(&ip6
->ip6_dst
,
1677 if (ip
->ip_dst
.s_addr
== ip
->ip_src
.s_addr
)
1681 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
1682 * in_broadcast() should never return true on a received
1683 * packet with M_BCAST not set.
1685 * Packets with a multicast source address should also
1688 if (m
->m_flags
& (M_BCAST
|M_MCAST
))
1692 if (IN6_IS_ADDR_MULTICAST(&ip6
->ip6_dst
) ||
1693 IN6_IS_ADDR_MULTICAST(&ip6
->ip6_src
))
1697 if (IN_MULTICAST(ntohl(ip
->ip_dst
.s_addr
)) ||
1698 IN_MULTICAST(ntohl(ip
->ip_src
.s_addr
)) ||
1699 ip
->ip_src
.s_addr
== htonl(INADDR_BROADCAST
) ||
1700 in_broadcast(ip
->ip_dst
, m
->m_pkthdr
.rcvif
))
1704 MALLOC(sin6
, struct sockaddr_in6
*, sizeof *sin6
,
1705 M_SONAME
, M_NOWAIT
);
1708 bzero(sin6
, sizeof(*sin6
));
1709 sin6
->sin6_family
= AF_INET6
;
1710 sin6
->sin6_len
= sizeof(*sin6
);
1711 sin6
->sin6_addr
= ip6
->ip6_src
;
1712 sin6
->sin6_port
= th
->th_sport
;
1713 laddr6
= inp
->in6p_laddr
;
1714 if (IN6_IS_ADDR_UNSPECIFIED(&inp
->in6p_laddr
))
1715 inp
->in6p_laddr
= ip6
->ip6_dst
;
1716 if (in6_pcbconnect(inp
, (struct sockaddr
*)sin6
,
1718 inp
->in6p_laddr
= laddr6
;
1719 FREE(sin6
, M_SONAME
);
1722 FREE(sin6
, M_SONAME
);
1727 lck_mtx_assert(((struct inpcb
*)so
->so_pcb
)->inpcb_mtx
, LCK_MTX_ASSERT_OWNED
);
1729 MALLOC(sin
, struct sockaddr_in
*, sizeof *sin
, M_SONAME
,
1733 sin
->sin_family
= AF_INET
;
1734 sin
->sin_len
= sizeof(*sin
);
1735 sin
->sin_addr
= ip
->ip_src
;
1736 sin
->sin_port
= th
->th_sport
;
1737 bzero((caddr_t
)sin
->sin_zero
, sizeof(sin
->sin_zero
));
1738 laddr
= inp
->inp_laddr
;
1739 if (inp
->inp_laddr
.s_addr
== INADDR_ANY
)
1740 inp
->inp_laddr
= ip
->ip_dst
;
1741 if (in_pcbconnect(inp
, (struct sockaddr
*)sin
, proc0
)) {
1742 inp
->inp_laddr
= laddr
;
1743 FREE(sin
, M_SONAME
);
1746 FREE(sin
, M_SONAME
);
1749 tcp_dooptions(tp
, optp
, optlen
, th
, &to
, ifscope
);
1751 if (tp
->sack_enable
) {
1752 if (!(to
.to_flags
& TOF_SACK
))
1753 tp
->sack_enable
= 0;
1755 tp
->t_flags
|= TF_SACK_PERMIT
;
1761 tp
->iss
= tcp_new_isn(tp
);
1763 tp
->irs
= th
->th_seq
;
1764 tcp_sendseqinit(tp
);
1766 tp
->snd_recover
= tp
->snd_una
;
1768 * Initialization of the tcpcb for transaction;
1769 * set SND.WND = SEG.WND,
1770 * initialize CCsend and CCrecv.
1772 tp
->snd_wnd
= tiwin
; /* initial send-window */
1773 tp
->t_flags
|= TF_ACKNOW
;
1774 tp
->t_unacksegs
= 0;
1775 tp
->t_state
= TCPS_SYN_RECEIVED
;
1776 tp
->t_timer
[TCPT_KEEP
] = tcp_keepinit
;
1777 dropsocket
= 0; /* committed to socket */
1778 tcpstat
.tcps_accepts
++;
1779 if ((thflags
& (TH_ECE
| TH_CWR
)) == (TH_ECE
| TH_CWR
)) {
1781 tp
->ecn_flags
|= (TE_SETUPRECEIVED
| TE_SENDIPECT
);
1783 #ifdef IFEF_NOWINDOWSCALE
1784 if (m
->m_pkthdr
.rcvif
!= NULL
&&
1785 (m
->m_pkthdr
.rcvif
->if_eflags
& IFEF_NOWINDOWSCALE
) != 0)
1787 // Timestamps are not enabled on this interface
1788 tp
->t_flags
&= ~(TF_REQ_SCALE
);
1795 * If the state is SYN_RECEIVED:
1796 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1798 case TCPS_SYN_RECEIVED
:
1799 if ((thflags
& TH_ACK
) &&
1800 (SEQ_LEQ(th
->th_ack
, tp
->snd_una
) ||
1801 SEQ_GT(th
->th_ack
, tp
->snd_max
))) {
1802 rstreason
= BANDLIM_RST_OPENPORT
;
1808 * If the state is SYN_SENT:
1809 * if seg contains an ACK, but not for our SYN, drop the input.
1810 * if seg contains a RST, then drop the connection.
1811 * if seg does not contain SYN, then drop it.
1812 * Otherwise this is an acceptable SYN segment
1813 * initialize tp->rcv_nxt and tp->irs
1814 * if seg contains ack then advance tp->snd_una
1815 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1816 * arrange for segment to be acked (eventually)
1817 * continue processing rest of data/controls, beginning with URG
1820 if ((thflags
& TH_ACK
) &&
1821 (SEQ_LEQ(th
->th_ack
, tp
->iss
) ||
1822 SEQ_GT(th
->th_ack
, tp
->snd_max
))) {
1823 rstreason
= BANDLIM_UNLIMITED
;
1826 if (thflags
& TH_RST
) {
1827 if ((thflags
& TH_ACK
) != 0) {
1828 tp
= tcp_drop(tp
, ECONNREFUSED
);
1829 postevent(so
, 0, EV_RESET
);
1833 if ((thflags
& TH_SYN
) == 0)
1835 tp
->snd_wnd
= th
->th_win
; /* initial send window */
1837 tp
->irs
= th
->th_seq
;
1839 if (thflags
& TH_ACK
) {
1840 tcpstat
.tcps_connects
++;
1842 if ((thflags
& (TH_ECE
| TH_CWR
)) == (TH_ECE
)) {
1843 /* ECN-setup SYN-ACK */
1844 tp
->ecn_flags
|= TE_SETUPRECEIVED
;
1847 /* non-ECN-setup SYN-ACK */
1848 tp
->ecn_flags
&= ~TE_SENDIPECT
;
1851 #if CONFIG_MACF_NET && CONFIG_MACF_SOCKET
1852 /* XXXMAC: recursive lock: SOCK_LOCK(so); */
1853 mac_socketpeer_label_associate_mbuf(m
, so
);
1854 /* XXXMAC: SOCK_UNLOCK(so); */
1856 /* Do window scaling on this connection? */
1857 if ((tp
->t_flags
& (TF_RCVD_SCALE
|TF_REQ_SCALE
)) ==
1858 (TF_RCVD_SCALE
|TF_REQ_SCALE
)) {
1859 tp
->snd_scale
= tp
->requested_s_scale
;
1860 tp
->rcv_scale
= tp
->request_r_scale
;
1862 tp
->rcv_adv
+= tp
->rcv_wnd
;
1863 tp
->snd_una
++; /* SYN is acked */
1865 * If there's data, delay ACK; if there's also a FIN
1866 * ACKNOW will be turned on later.
1868 if (DELAY_ACK(tp
) && tlen
!= 0) {
1869 tp
->t_flags
|= TF_DELACK
;
1873 tp
->t_flags
|= TF_ACKNOW
;
1874 tp
->t_unacksegs
= 0;
1877 * Received <SYN,ACK> in SYN_SENT[*] state.
1879 * SYN_SENT --> ESTABLISHED
1880 * SYN_SENT* --> FIN_WAIT_1
1882 tp
->t_starttime
= 0;
1883 if (tp
->t_flags
& TF_NEEDFIN
) {
1884 tp
->t_state
= TCPS_FIN_WAIT_1
;
1885 tp
->t_flags
&= ~TF_NEEDFIN
;
1888 tp
->t_state
= TCPS_ESTABLISHED
;
1889 tp
->t_timer
[TCPT_KEEP
] = TCP_KEEPIDLE(tp
);
1891 /* soisconnected may lead to socket_unlock in case of upcalls,
1892 * make sure this is done when everything is setup.
1897 * Received initial SYN in SYN-SENT[*] state => simul-
1898 * taneous open. If segment contains CC option and there is
1899 * a cached CC, apply TAO test; if it succeeds, connection is
1900 * half-synchronized. Otherwise, do 3-way handshake:
1901 * SYN-SENT -> SYN-RECEIVED
1902 * SYN-SENT* -> SYN-RECEIVED*
1904 tp
->t_flags
|= TF_ACKNOW
;
1905 tp
->t_timer
[TCPT_REXMT
] = 0;
1906 tp
->t_state
= TCPS_SYN_RECEIVED
;
1912 * Advance th->th_seq to correspond to first data byte.
1913 * If data, trim to stay within window,
1914 * dropping FIN if necessary.
1917 if (tlen
> tp
->rcv_wnd
) {
1918 todrop
= tlen
- tp
->rcv_wnd
;
1922 tcpstat
.tcps_rcvpackafterwin
++;
1923 tcpstat
.tcps_rcvbyteafterwin
+= todrop
;
1925 tp
->snd_wl1
= th
->th_seq
- 1;
1926 tp
->rcv_up
= th
->th_seq
;
1928 * Client side of transaction: already sent SYN and data.
1929 * If the remote host used T/TCP to validate the SYN,
1930 * our data will be ACK'd; if so, enter normal data segment
1931 * processing in the middle of step 5, ack processing.
1932 * Otherwise, goto step 6.
1934 if (thflags
& TH_ACK
)
1938 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1939 * do normal processing.
1941 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
1945 case TCPS_TIME_WAIT
:
1946 break; /* continue normal processing */
1948 /* Received a SYN while connection is already established.
1949 * This is a "half open connection and other anomalies" described
1950 * in RFC793 page 34, send an ACK so the remote reset the connection
1951 * or recovers by adjusting its sequence numberering
1953 case TCPS_ESTABLISHED
:
1954 if (thflags
& TH_SYN
)
1960 * States other than LISTEN or SYN_SENT.
1961 * First check the RST flag and sequence number since reset segments
1962 * are exempt from the timestamp and connection count tests. This
1963 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1964 * below which allowed reset segments in half the sequence space
1965 * to fall though and be processed (which gives forged reset
1966 * segments with a random sequence number a 50 percent chance of
1967 * killing a connection).
1968 * Then check timestamp, if present.
1969 * Then check the connection count, if present.
1970 * Then check that at least some bytes of segment are within
1971 * receive window. If segment begins before rcv_nxt,
1972 * drop leading data (and SYN); if nothing left, just ack.
1975 * If the RST bit is set, check the sequence number to see
1976 * if this is a valid reset segment.
1978 * In all states except SYN-SENT, all reset (RST) segments
1979 * are validated by checking their SEQ-fields. A reset is
1980 * valid if its sequence number is in the window.
1981 * Note: this does not take into account delayed ACKs, so
1982 * we should test against last_ack_sent instead of rcv_nxt.
1983 * The sequence number in the reset segment is normally an
1984 * echo of our outgoing acknowlegement numbers, but some hosts
1985 * send a reset with the sequence number at the rightmost edge
1986 * of our receive window, and we have to handle this case.
1987 * Note 2: Paul Watson's paper "Slipping in the Window" has shown
1988 * that brute force RST attacks are possible. To combat this,
1989 * we use a much stricter check while in the ESTABLISHED state,
1990 * only accepting RSTs where the sequence number is equal to
1991 * last_ack_sent. In all other states (the states in which a
1992 * RST is more likely), the more permissive check is used.
1993 * If we have multiple segments in flight, the intial reset
1994 * segment sequence numbers will be to the left of last_ack_sent,
1995 * but they will eventually catch up.
1996 * In any case, it never made sense to trim reset segments to
1997 * fit the receive window since RFC 1122 says:
1998 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
2000 * A TCP SHOULD allow a received RST segment to include data.
2003 * It has been suggested that a RST segment could contain
2004 * ASCII text that encoded and explained the cause of the
2005 * RST. No standard has yet been established for such
2008 * If the reset segment passes the sequence number test examine
2010 * SYN_RECEIVED STATE:
2011 * If passive open, return to LISTEN state.
2012 * If active open, inform user that connection was refused.
2013 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
2014 * Inform user that connection was reset, and close tcb.
2015 * CLOSING, LAST_ACK STATES:
2018 * Drop the segment - see Stevens, vol. 2, p. 964 and
2021 * Radar 4803931: Allows for the case where we ACKed the FIN but
2022 * there is already a RST in flight from the peer.
2023 * In that case, accept the RST for non-established
2024 * state if it's one off from last_ack_sent.
2027 if (thflags
& TH_RST
) {
2028 if ((SEQ_GEQ(th
->th_seq
, tp
->last_ack_sent
) &&
2029 SEQ_LT(th
->th_seq
, tp
->last_ack_sent
+ tp
->rcv_wnd
)) ||
2030 (tp
->rcv_wnd
== 0 &&
2031 ((tp
->last_ack_sent
== th
->th_seq
) || ((tp
->last_ack_sent
-1) == th
->th_seq
)))) {
2032 switch (tp
->t_state
) {
2034 case TCPS_SYN_RECEIVED
:
2035 so
->so_error
= ECONNREFUSED
;
2038 case TCPS_ESTABLISHED
:
2039 if (tp
->last_ack_sent
!= th
->th_seq
) {
2040 tcpstat
.tcps_badrst
++;
2043 case TCPS_FIN_WAIT_1
:
2044 case TCPS_CLOSE_WAIT
:
2048 case TCPS_FIN_WAIT_2
:
2049 so
->so_error
= ECONNRESET
;
2051 postevent(so
, 0, EV_RESET
);
2052 tp
->t_state
= TCPS_CLOSED
;
2053 tcpstat
.tcps_drops
++;
2062 case TCPS_TIME_WAIT
:
2070 lck_mtx_assert(((struct inpcb
*)so
->so_pcb
)->inpcb_mtx
, LCK_MTX_ASSERT_OWNED
);
2074 * RFC 1323 PAWS: If we have a timestamp reply on this segment
2075 * and it's less than ts_recent, drop it.
2077 if ((to
.to_flags
& TOF_TS
) != 0 && tp
->ts_recent
&&
2078 TSTMP_LT(to
.to_tsval
, tp
->ts_recent
)) {
2080 /* Check to see if ts_recent is over 24 days old. */
2081 if ((int)(tcp_now
- tp
->ts_recent_age
) > TCP_PAWS_IDLE
) {
2083 * Invalidate ts_recent. If this segment updates
2084 * ts_recent, the age will be reset later and ts_recent
2085 * will get a valid value. If it does not, setting
2086 * ts_recent to zero will at least satisfy the
2087 * requirement that zero be placed in the timestamp
2088 * echo reply when ts_recent isn't valid. The
2089 * age isn't reset until we get a valid ts_recent
2090 * because we don't want out-of-order segments to be
2091 * dropped when ts_recent is old.
2095 tcpstat
.tcps_rcvduppack
++;
2096 tcpstat
.tcps_rcvdupbyte
+= tlen
;
2097 tcpstat
.tcps_pawsdrop
++;
2105 * In the SYN-RECEIVED state, validate that the packet belongs to
2106 * this connection before trimming the data to fit the receive
2107 * window. Check the sequence number versus IRS since we know
2108 * the sequence numbers haven't wrapped. This is a partial fix
2109 * for the "LAND" DoS attack.
2111 if (tp
->t_state
== TCPS_SYN_RECEIVED
&& SEQ_LT(th
->th_seq
, tp
->irs
)) {
2112 rstreason
= BANDLIM_RST_OPENPORT
;
2116 todrop
= tp
->rcv_nxt
- th
->th_seq
;
2118 if (thflags
& TH_SYN
) {
2128 * Following if statement from Stevens, vol. 2, p. 960.
2131 || (todrop
== tlen
&& (thflags
& TH_FIN
) == 0)) {
2133 * Any valid FIN must be to the left of the window.
2134 * At this point the FIN must be a duplicate or out
2135 * of sequence; drop it.
2140 * Send an ACK to resynchronize and drop any data.
2141 * But keep on processing for RST or ACK.
2143 tp
->t_flags
|= TF_ACKNOW
;
2144 tp
->t_unacksegs
= 0;
2146 tcpstat
.tcps_rcvduppack
++;
2147 tcpstat
.tcps_rcvdupbyte
+= todrop
;
2149 tcpstat
.tcps_rcvpartduppack
++;
2150 tcpstat
.tcps_rcvpartdupbyte
+= todrop
;
2152 drop_hdrlen
+= todrop
; /* drop from the top afterwards */
2153 th
->th_seq
+= todrop
;
2155 if (th
->th_urp
> todrop
)
2156 th
->th_urp
-= todrop
;
2164 * If new data are received on a connection after the
2165 * user processes are gone, then RST the other end.
2167 if ((so
->so_state
& SS_NOFDREF
) &&
2168 tp
->t_state
> TCPS_CLOSE_WAIT
&& tlen
) {
2170 tcpstat
.tcps_rcvafterclose
++;
2171 rstreason
= BANDLIM_UNLIMITED
;
2176 * If segment ends after window, drop trailing data
2177 * (and PUSH and FIN); if nothing left, just ACK.
2179 todrop
= (th
->th_seq
+tlen
) - (tp
->rcv_nxt
+tp
->rcv_wnd
);
2181 tcpstat
.tcps_rcvpackafterwin
++;
2182 if (todrop
>= tlen
) {
2183 tcpstat
.tcps_rcvbyteafterwin
+= tlen
;
2185 * If a new connection request is received
2186 * while in TIME_WAIT, drop the old connection
2187 * and start over if the sequence numbers
2188 * are above the previous ones.
2190 if (thflags
& TH_SYN
&&
2191 tp
->t_state
== TCPS_TIME_WAIT
&&
2192 SEQ_GT(th
->th_seq
, tp
->rcv_nxt
)) {
2193 iss
= tcp_new_isn(tp
);
2195 tcp_unlock(so
, 1, 0);
2199 * If window is closed can only take segments at
2200 * window edge, and have to drop data and PUSH from
2201 * incoming segments. Continue processing, but
2202 * remember to ack. Otherwise, drop segment
2205 if (tp
->rcv_wnd
== 0 && th
->th_seq
== tp
->rcv_nxt
) {
2206 tp
->t_flags
|= TF_ACKNOW
;
2207 tp
->t_unacksegs
= 0;
2208 tcpstat
.tcps_rcvwinprobe
++;
2212 tcpstat
.tcps_rcvbyteafterwin
+= todrop
;
2215 thflags
&= ~(TH_PUSH
|TH_FIN
);
2219 * If last ACK falls within this segment's sequence numbers,
2220 * record its timestamp.
2222 * 1) That the test incorporates suggestions from the latest
2223 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
2224 * 2) That updating only on newer timestamps interferes with
2225 * our earlier PAWS tests, so this check should be solely
2226 * predicated on the sequence space of this segment.
2227 * 3) That we modify the segment boundary check to be
2228 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
2229 * instead of RFC1323's
2230 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
2231 * This modified check allows us to overcome RFC1323's
2232 * limitations as described in Stevens TCP/IP Illustrated
2233 * Vol. 2 p.869. In such cases, we can still calculate the
2234 * RTT correctly when RCV.NXT == Last.ACK.Sent.
2236 if ((to
.to_flags
& TOF_TS
) != 0 &&
2237 SEQ_LEQ(th
->th_seq
, tp
->last_ack_sent
) &&
2238 SEQ_LEQ(tp
->last_ack_sent
, th
->th_seq
+ tlen
+
2239 ((thflags
& (TH_SYN
|TH_FIN
)) != 0))) {
2240 tp
->ts_recent_age
= tcp_now
;
2241 tp
->ts_recent
= to
.to_tsval
;
2245 * If a SYN is in the window, then this is an
2246 * error and we send an RST and drop the connection.
2248 if (thflags
& TH_SYN
) {
2249 tp
= tcp_drop(tp
, ECONNRESET
);
2250 rstreason
= BANDLIM_UNLIMITED
;
2251 postevent(so
, 0, EV_RESET
);
2256 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
2257 * flag is on (half-synchronized state), then queue data for
2258 * later processing; else drop segment and return.
2260 if ((thflags
& TH_ACK
) == 0) {
2261 if (tp
->t_state
== TCPS_SYN_RECEIVED
||
2262 (tp
->t_flags
& TF_NEEDSYN
))
2264 else if (tp
->t_flags
& TF_ACKNOW
)
2273 switch (tp
->t_state
) {
2276 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
2277 * ESTABLISHED state and continue processing.
2278 * The ACK was checked above.
2280 case TCPS_SYN_RECEIVED
:
2282 tcpstat
.tcps_connects
++;
2284 /* Do window scaling? */
2285 if ((tp
->t_flags
& (TF_RCVD_SCALE
|TF_REQ_SCALE
)) ==
2286 (TF_RCVD_SCALE
|TF_REQ_SCALE
)) {
2287 tp
->snd_scale
= tp
->requested_s_scale
;
2288 tp
->rcv_scale
= tp
->request_r_scale
;
2292 * SYN-RECEIVED -> ESTABLISHED
2293 * SYN-RECEIVED* -> FIN-WAIT-1
2295 tp
->t_starttime
= 0;
2296 if (tp
->t_flags
& TF_NEEDFIN
) {
2297 tp
->t_state
= TCPS_FIN_WAIT_1
;
2298 tp
->t_flags
&= ~TF_NEEDFIN
;
2300 tp
->t_state
= TCPS_ESTABLISHED
;
2301 tp
->t_timer
[TCPT_KEEP
] = TCP_KEEPIDLE(tp
);
2304 * If segment contains data or ACK, will call tcp_reass()
2305 * later; if not, do so now to pass queued data to user.
2307 if (tlen
== 0 && (thflags
& TH_FIN
) == 0)
2308 (void) tcp_reass(tp
, (struct tcphdr
*)0, &tlen
,
2310 tp
->snd_wl1
= th
->th_seq
- 1;
2314 /* soisconnected may lead to socket_unlock in case of upcalls,
2315 * make sure this is done when everything is setup.
2320 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2321 * ACKs. If the ack is in the range
2322 * tp->snd_una < th->th_ack <= tp->snd_max
2323 * then advance tp->snd_una to th->th_ack and drop
2324 * data from the retransmission queue. If this ACK reflects
2325 * more up to date window information we update our window information.
2327 case TCPS_ESTABLISHED
:
2328 case TCPS_FIN_WAIT_1
:
2329 case TCPS_FIN_WAIT_2
:
2330 case TCPS_CLOSE_WAIT
:
2333 case TCPS_TIME_WAIT
:
2334 if (SEQ_GT(th
->th_ack
, tp
->snd_max
)) {
2335 tcpstat
.tcps_rcvacktoomuch
++;
2338 if (tp
->sack_enable
&&
2339 (to
.to_nsacks
> 0 || !TAILQ_EMPTY(&tp
->snd_holes
)))
2340 tcp_sack_doack(tp
, &to
, th
->th_ack
);
2341 if (SEQ_LEQ(th
->th_ack
, tp
->snd_una
)) {
2342 if (tlen
== 0 && tiwin
== tp
->snd_wnd
) {
2343 tcpstat
.tcps_rcvdupack
++;
2345 * If we have outstanding data (other than
2346 * a window probe), this is a completely
2347 * duplicate ack (ie, window info didn't
2348 * change), the ack is the biggest we've
2349 * seen and we've seen exactly our rexmt
2350 * threshhold of them, assume a packet
2351 * has been dropped and retransmit it.
2352 * Kludge snd_nxt & the congestion
2353 * window so we send only this one
2356 * We know we're losing at the current
2357 * window size so do congestion avoidance
2358 * (set ssthresh to half the current window
2359 * and pull our congestion window back to
2360 * the new ssthresh).
2362 * Dup acks mean that packets have left the
2363 * network (they're now cached at the receiver)
2364 * so bump cwnd by the amount in the receiver
2365 * to keep a constant cwnd packets in the
2368 if (tp
->t_timer
[TCPT_REXMT
] == 0 ||
2369 th
->th_ack
!= tp
->snd_una
)
2371 else if (++tp
->t_dupacks
> tcprexmtthresh
||
2372 ((tcp_do_newreno
|| tp
->sack_enable
) &&
2373 IN_FASTRECOVERY(tp
))) {
2374 if (tp
->sack_enable
&& IN_FASTRECOVERY(tp
)) {
2378 * Compute the amount of data in flight first.
2379 * We can inject new data into the pipe iff
2380 * we have less than 1/2 the original window's
2381 * worth of data in flight.
2383 awnd
= (tp
->snd_nxt
- tp
->snd_fack
) +
2384 tp
->sackhint
.sack_bytes_rexmit
;
2385 if (awnd
< tp
->snd_ssthresh
) {
2386 tp
->snd_cwnd
+= tp
->t_maxseg
;
2387 if (tp
->snd_cwnd
> tp
->snd_ssthresh
)
2388 tp
->snd_cwnd
= tp
->snd_ssthresh
;
2391 tp
->snd_cwnd
+= tp
->t_maxseg
;
2392 tp
->t_unacksegs
= 0;
2393 (void) tcp_output(tp
);
2395 } else if (tp
->t_dupacks
== tcprexmtthresh
) {
2396 tcp_seq onxt
= tp
->snd_nxt
;
2400 * If we're doing sack, check to
2401 * see if we're already in sack
2402 * recovery. If we're not doing sack,
2403 * check to see if we're in newreno
2406 if (tp
->sack_enable
) {
2407 if (IN_FASTRECOVERY(tp
)) {
2411 } else if (tcp_do_newreno
) {
2412 if (SEQ_LEQ(th
->th_ack
,
2418 win
= min(tp
->snd_wnd
, tp
->snd_cwnd
) /
2422 tp
->snd_ssthresh
= win
* tp
->t_maxseg
;
2423 ENTER_FASTRECOVERY(tp
);
2424 tp
->snd_recover
= tp
->snd_max
;
2425 tp
->t_timer
[TCPT_REXMT
] = 0;
2427 tp
->ecn_flags
|= TE_SENDCWR
;
2428 if (tp
->sack_enable
) {
2429 tcpstat
.tcps_sack_recovery_episode
++;
2430 tp
->sack_newdata
= tp
->snd_nxt
;
2431 tp
->snd_cwnd
= tp
->t_maxseg
;
2432 tp
->t_unacksegs
= 0;
2433 (void) tcp_output(tp
);
2436 tp
->snd_nxt
= th
->th_ack
;
2437 tp
->snd_cwnd
= tp
->t_maxseg
;
2438 tp
->t_unacksegs
= 0;
2439 (void) tcp_output(tp
);
2440 tp
->snd_cwnd
= tp
->snd_ssthresh
+
2441 tp
->t_maxseg
* tp
->t_dupacks
;
2442 if (SEQ_GT(onxt
, tp
->snd_nxt
))
2451 if (!IN_FASTRECOVERY(tp
)) {
2453 * We were not in fast recovery. Reset the duplicate ack
2459 * If the congestion window was inflated to account
2460 * for the other side's cached packets, retract it.
2463 if (tcp_do_newreno
|| tp
->sack_enable
) {
2464 if (SEQ_LT(th
->th_ack
, tp
->snd_recover
)) {
2465 if (tp
->sack_enable
)
2466 tcp_sack_partialack(tp
, th
);
2468 tcp_newreno_partial_ack(tp
, th
);
2471 if (tcp_do_newreno
) {
2472 long ss
= tp
->snd_max
- th
->th_ack
;
2475 * Complete ack. Inflate the congestion window to
2476 * ssthresh and exit fast recovery.
2478 * Window inflation should have left us with approx.
2479 * snd_ssthresh outstanding data. But in case we
2480 * would be inclined to send a burst, better to do
2481 * it via the slow start mechanism.
2483 if (ss
< tp
->snd_ssthresh
)
2484 tp
->snd_cwnd
= ss
+ tp
->t_maxseg
;
2486 tp
->snd_cwnd
= tp
->snd_ssthresh
;
2490 * Clamp the congestion window to the crossover point
2491 * and exit fast recovery.
2493 if (tp
->snd_cwnd
> tp
->snd_ssthresh
)
2494 tp
->snd_cwnd
= tp
->snd_ssthresh
;
2497 EXIT_FASTRECOVERY(tp
);
2499 tp
->t_bytes_acked
= 0;
2504 * Clamp the congestion window to the crossover point
2505 * and exit fast recovery in non-newreno and non-SACK case.
2507 if (tp
->snd_cwnd
> tp
->snd_ssthresh
)
2508 tp
->snd_cwnd
= tp
->snd_ssthresh
;
2509 EXIT_FASTRECOVERY(tp
);
2511 tp
->t_bytes_acked
= 0;
2517 * If we reach this point, ACK is not a duplicate,
2518 * i.e., it ACKs something we sent.
2520 if (tp
->t_flags
& TF_NEEDSYN
) {
2522 * T/TCP: Connection was half-synchronized, and our
2523 * SYN has been ACK'd (so connection is now fully
2524 * synchronized). Go to non-starred state,
2525 * increment snd_una for ACK of SYN, and check if
2526 * we can do window scaling.
2528 tp
->t_flags
&= ~TF_NEEDSYN
;
2530 /* Do window scaling? */
2531 if ((tp
->t_flags
& (TF_RCVD_SCALE
|TF_REQ_SCALE
)) ==
2532 (TF_RCVD_SCALE
|TF_REQ_SCALE
)) {
2533 tp
->snd_scale
= tp
->requested_s_scale
;
2534 tp
->rcv_scale
= tp
->request_r_scale
;
2539 acked
= th
->th_ack
- tp
->snd_una
;
2540 tcpstat
.tcps_rcvackpack
++;
2541 tcpstat
.tcps_rcvackbyte
+= acked
;
2544 * If we just performed our first retransmit, and the ACK
2545 * arrives within our recovery window, then it was a mistake
2546 * to do the retransmit in the first place. Recover our
2547 * original cwnd and ssthresh, and proceed to transmit where
2550 if (tp
->t_rxtshift
== 1 && tcp_now
< tp
->t_badrxtwin
) {
2551 ++tcpstat
.tcps_sndrexmitbad
;
2552 tp
->snd_cwnd
= tp
->snd_cwnd_prev
;
2553 tp
->snd_ssthresh
= tp
->snd_ssthresh_prev
;
2554 tp
->snd_recover
= tp
->snd_recover_prev
;
2555 if (tp
->t_flags
& TF_WASFRECOVERY
)
2556 ENTER_FASTRECOVERY(tp
);
2557 tp
->snd_nxt
= tp
->snd_max
;
2558 tp
->t_badrxtwin
= 0; /* XXX probably not required */
2562 * If we have a timestamp reply, update smoothed
2563 * round trip time. If no timestamp is present but
2564 * transmit timer is running and timed sequence
2565 * number was acked, update smoothed round trip time.
2566 * Since we now have an rtt measurement, cancel the
2567 * timer backoff (cf., Phil Karn's retransmit alg.).
2568 * Recompute the initial retransmit timer.
2569 * Also makes sure we have a valid time stamp in hand
2571 * Some boxes send broken timestamp replies
2572 * during the SYN+ACK phase, ignore
2573 * timestamps of 0 or we could calculate a
2574 * huge RTT and blow up the retransmit timer.
2576 if (((to
.to_flags
& TOF_TS
) != 0) && (to
.to_tsecr
!= 0)) {
2577 if (!tp
->t_rttlow
|| tp
->t_rttlow
> tcp_now
- to
.to_tsecr
)
2578 tp
->t_rttlow
= tcp_now
- to
.to_tsecr
;
2579 tcp_xmit_timer(tp
, tcp_now
- to
.to_tsecr
);
2580 } else if (tp
->t_rtttime
&& SEQ_GT(th
->th_ack
, tp
->t_rtseq
)) {
2581 if (!tp
->t_rttlow
|| tp
->t_rttlow
> tcp_now
- tp
->t_rtttime
)
2582 tp
->t_rttlow
= tcp_now
- tp
->t_rtttime
;
2583 tcp_xmit_timer(tp
, tp
->t_rtttime
);
2587 * If all outstanding data is acked, stop retransmit
2588 * timer and remember to restart (more output or persist).
2589 * If there is more data to be acked, restart retransmit
2590 * timer, using current (possibly backed-off) value.
2592 if (th
->th_ack
== tp
->snd_max
) {
2593 tp
->t_timer
[TCPT_REXMT
] = 0;
2595 } else if (tp
->t_timer
[TCPT_PERSIST
] == 0)
2596 tp
->t_timer
[TCPT_REXMT
] = tp
->t_rxtcur
;
2599 * If no data (only SYN) was ACK'd,
2600 * skip rest of ACK processing.
2606 * When new data is acked, open the congestion window.
2608 if ((thflags
& TH_ECE
) != 0 &&
2609 (tp
->ecn_flags
& TE_SETUPSENT
) != 0) {
2611 * Reduce the congestion window if we haven't done so.
2613 if (!(tp
->sack_enable
&& IN_FASTRECOVERY(tp
)) &&
2614 !(tcp_do_newreno
&& SEQ_LEQ(th
->th_ack
, tp
->snd_recover
))) {
2615 tcp_reduce_congestion_window(tp
);
2617 } else if ((!tcp_do_newreno
&& !tp
->sack_enable
) ||
2618 !IN_FASTRECOVERY(tp
)) {
2620 * RFC 3465 - Appropriate Byte Counting.
2622 * If the window is currently less than ssthresh,
2623 * open the window by the number of bytes ACKed by
2624 * the last ACK, however clamp the window increase
2625 * to an upper limit "L".
2627 * In congestion avoidance phase, open the window by
2628 * one segment each time "bytes_acked" grows to be
2629 * greater than or equal to the congestion window.
2632 register u_int cw
= tp
->snd_cwnd
;
2633 register u_int incr
= tp
->t_maxseg
;
2635 if (cw
>= tp
->snd_ssthresh
) {
2636 tp
->t_bytes_acked
+= acked
;
2637 if (tp
->t_bytes_acked
>= cw
) {
2638 /* Time to increase the window. */
2639 tp
->t_bytes_acked
-= cw
;
2641 /* No need to increase yet. */
2646 * If the user explicitly enables RFC3465
2647 * use 2*SMSS for the "L" param. Otherwise
2648 * use the more conservative 1*SMSS.
2650 * (See RFC 3465 2.3 Choosing the Limit)
2654 abc_lim
= (tcp_do_rfc3465
== 0) ?
2656 incr
= min(acked
, abc_lim
);
2659 tp
->snd_cwnd
= min(cw
+incr
, TCP_MAXWIN
<<tp
->snd_scale
);
2661 if (acked
> so
->so_snd
.sb_cc
) {
2662 tp
->snd_wnd
-= so
->so_snd
.sb_cc
;
2663 sbdrop(&so
->so_snd
, (int)so
->so_snd
.sb_cc
);
2666 sbdrop(&so
->so_snd
, acked
);
2667 tp
->snd_wnd
-= acked
;
2670 /* detect una wraparound */
2671 if ((tcp_do_newreno
|| tp
->sack_enable
) &&
2672 !IN_FASTRECOVERY(tp
) &&
2673 SEQ_GT(tp
->snd_una
, tp
->snd_recover
) &&
2674 SEQ_LEQ(th
->th_ack
, tp
->snd_recover
))
2675 tp
->snd_recover
= th
->th_ack
- 1;
2676 if ((tcp_do_newreno
|| tp
->sack_enable
) &&
2677 IN_FASTRECOVERY(tp
) &&
2678 SEQ_GEQ(th
->th_ack
, tp
->snd_recover
))
2679 EXIT_FASTRECOVERY(tp
);
2680 tp
->snd_una
= th
->th_ack
;
2681 if (tp
->sack_enable
) {
2682 if (SEQ_GT(tp
->snd_una
, tp
->snd_recover
))
2683 tp
->snd_recover
= tp
->snd_una
;
2685 if (SEQ_LT(tp
->snd_nxt
, tp
->snd_una
))
2686 tp
->snd_nxt
= tp
->snd_una
;
2689 * sowwakeup must happen after snd_una, et al. are updated so that
2690 * the sequence numbers are in sync with so_snd
2694 switch (tp
->t_state
) {
2697 * In FIN_WAIT_1 STATE in addition to the processing
2698 * for the ESTABLISHED state if our FIN is now acknowledged
2699 * then enter FIN_WAIT_2.
2701 case TCPS_FIN_WAIT_1
:
2702 if (ourfinisacked
) {
2704 * If we can't receive any more
2705 * data, then closing user can proceed.
2706 * Starting the timer is contrary to the
2707 * specification, but if we don't get a FIN
2708 * we'll hang forever.
2710 if (so
->so_state
& SS_CANTRCVMORE
) {
2711 tp
->t_timer
[TCPT_2MSL
] = tcp_maxidle
;
2712 add_to_time_wait(tp
);
2713 soisdisconnected(so
);
2715 tp
->t_state
= TCPS_FIN_WAIT_2
;
2716 /* fall through and make sure we also recognize data ACKed with the FIN */
2718 tp
->t_flags
|= TF_ACKNOW
;
2722 * In CLOSING STATE in addition to the processing for
2723 * the ESTABLISHED state if the ACK acknowledges our FIN
2724 * then enter the TIME-WAIT state, otherwise ignore
2728 if (ourfinisacked
) {
2729 tp
->t_state
= TCPS_TIME_WAIT
;
2730 tcp_canceltimers(tp
);
2731 /* Shorten TIME_WAIT [RFC-1644, p.28] */
2732 if (tp
->cc_recv
!= 0 &&
2733 tp
->t_starttime
< (u_long
)tcp_msl
)
2734 tp
->t_timer
[TCPT_2MSL
] =
2735 tp
->t_rxtcur
* TCPTV_TWTRUNC
;
2737 tp
->t_timer
[TCPT_2MSL
] = 2 * tcp_msl
;
2738 add_to_time_wait(tp
);
2739 soisdisconnected(so
);
2741 tp
->t_flags
|= TF_ACKNOW
;
2745 * In LAST_ACK, we may still be waiting for data to drain
2746 * and/or to be acked, as well as for the ack of our FIN.
2747 * If our FIN is now acknowledged, delete the TCB,
2748 * enter the closed state and return.
2751 if (ourfinisacked
) {
2758 * In TIME_WAIT state the only thing that should arrive
2759 * is a retransmission of the remote FIN. Acknowledge
2760 * it and restart the finack timer.
2762 case TCPS_TIME_WAIT
:
2763 tp
->t_timer
[TCPT_2MSL
] = 2 * tcp_msl
;
2764 add_to_time_wait(tp
);
2771 * Update window information.
2772 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2774 if ((thflags
& TH_ACK
) &&
2775 (SEQ_LT(tp
->snd_wl1
, th
->th_seq
) ||
2776 (tp
->snd_wl1
== th
->th_seq
&& (SEQ_LT(tp
->snd_wl2
, th
->th_ack
) ||
2777 (tp
->snd_wl2
== th
->th_ack
&& tiwin
> tp
->snd_wnd
))))) {
2778 /* keep track of pure window updates */
2780 tp
->snd_wl2
== th
->th_ack
&& tiwin
> tp
->snd_wnd
)
2781 tcpstat
.tcps_rcvwinupd
++;
2782 tp
->snd_wnd
= tiwin
;
2783 tp
->snd_wl1
= th
->th_seq
;
2784 tp
->snd_wl2
= th
->th_ack
;
2785 if (tp
->snd_wnd
> tp
->max_sndwnd
)
2786 tp
->max_sndwnd
= tp
->snd_wnd
;
2791 * Process segments with URG.
2793 if ((thflags
& TH_URG
) && th
->th_urp
&&
2794 TCPS_HAVERCVDFIN(tp
->t_state
) == 0) {
2796 * This is a kludge, but if we receive and accept
2797 * random urgent pointers, we'll crash in
2798 * soreceive. It's hard to imagine someone
2799 * actually wanting to send this much urgent data.
2801 if (th
->th_urp
+ so
->so_rcv
.sb_cc
> sb_max
) {
2802 th
->th_urp
= 0; /* XXX */
2803 thflags
&= ~TH_URG
; /* XXX */
2804 goto dodata
; /* XXX */
2807 * If this segment advances the known urgent pointer,
2808 * then mark the data stream. This should not happen
2809 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2810 * a FIN has been received from the remote side.
2811 * In these states we ignore the URG.
2813 * According to RFC961 (Assigned Protocols),
2814 * the urgent pointer points to the last octet
2815 * of urgent data. We continue, however,
2816 * to consider it to indicate the first octet
2817 * of data past the urgent section as the original
2818 * spec states (in one of two places).
2820 if (SEQ_GT(th
->th_seq
+th
->th_urp
, tp
->rcv_up
)) {
2821 tp
->rcv_up
= th
->th_seq
+ th
->th_urp
;
2822 so
->so_oobmark
= so
->so_rcv
.sb_cc
+
2823 (tp
->rcv_up
- tp
->rcv_nxt
) - 1;
2824 if (so
->so_oobmark
== 0) {
2825 so
->so_state
|= SS_RCVATMARK
;
2826 postevent(so
, 0, EV_OOB
);
2829 tp
->t_oobflags
&= ~(TCPOOB_HAVEDATA
| TCPOOB_HADDATA
);
2832 * Remove out of band data so doesn't get presented to user.
2833 * This can happen independent of advancing the URG pointer,
2834 * but if two URG's are pending at once, some out-of-band
2835 * data may creep in... ick.
2837 if (th
->th_urp
<= (u_long
)tlen
2839 && (so
->so_options
& SO_OOBINLINE
) == 0
2842 tcp_pulloutofband(so
, th
, m
,
2843 drop_hdrlen
); /* hdr drop is delayed */
2846 * If no out of band data is expected,
2847 * pull receive urgent pointer along
2848 * with the receive window.
2850 if (SEQ_GT(tp
->rcv_nxt
, tp
->rcv_up
))
2851 tp
->rcv_up
= tp
->rcv_nxt
;
2855 * Process the segment text, merging it into the TCP sequencing queue,
2856 * and arranging for acknowledgment of receipt if necessary.
2857 * This process logically involves adjusting tp->rcv_wnd as data
2858 * is presented to the user (this happens in tcp_usrreq.c,
2859 * case PRU_RCVD). If a FIN has already been received on this
2860 * connection then we just ignore the text.
2862 if ((tlen
|| (thflags
& TH_FIN
)) &&
2863 TCPS_HAVERCVDFIN(tp
->t_state
) == 0) {
2864 tcp_seq save_start
= th
->th_seq
;
2865 tcp_seq save_end
= th
->th_seq
+ tlen
;
2866 m_adj(m
, drop_hdrlen
); /* delayed header drop */
2868 * Insert segment which includes th into TCP reassembly queue
2869 * with control block tp. Set thflags to whether reassembly now
2870 * includes a segment with FIN. This handles the common case
2871 * inline (segment is the next to be received on an established
2872 * connection, and the queue is empty), avoiding linkage into
2873 * and removal from the queue and repetition of various
2875 * Set DELACK for segments received in order, but ack
2876 * immediately when segments are out of order (so
2877 * fast retransmit can work).
2879 if (th
->th_seq
== tp
->rcv_nxt
&&
2880 LIST_EMPTY(&tp
->t_segq
) &&
2881 TCPS_HAVEESTABLISHED(tp
->t_state
)) {
2882 if (DELAY_ACK(tp
) && ((tp
->t_flags
& TF_ACKNOW
) == 0)) {
2883 tp
->t_flags
|= TF_DELACK
;
2887 tp
->t_unacksegs
= 0;
2888 tp
->t_flags
|= TF_ACKNOW
;
2890 tp
->rcv_nxt
+= tlen
;
2891 thflags
= th
->th_flags
& TH_FIN
;
2892 tcpstat
.tcps_rcvpack
++;
2893 tcpstat
.tcps_rcvbyte
+= tlen
;
2895 if (sbappendstream(&so
->so_rcv
, m
))
2898 thflags
= tcp_reass(tp
, th
, &tlen
, m
);
2899 tp
->t_flags
|= TF_ACKNOW
;
2900 tp
->t_unacksegs
= 0;
2903 if (tlen
> 0 && tp
->sack_enable
)
2904 tcp_update_sack_list(tp
, save_start
, save_end
);
2906 if (tp
->t_flags
& TF_DELACK
)
2910 KERNEL_DEBUG(DBG_LAYER_END
, ((th
->th_dport
<< 16) | th
->th_sport
),
2911 (((ip6
->ip6_src
.s6_addr16
[0]) << 16) | (ip6
->ip6_dst
.s6_addr16
[0])),
2912 th
->th_seq
, th
->th_ack
, th
->th_win
);
2917 KERNEL_DEBUG(DBG_LAYER_END
, ((th
->th_dport
<< 16) | th
->th_sport
),
2918 (((ip
->ip_src
.s_addr
& 0xffff) << 16) | (ip
->ip_dst
.s_addr
& 0xffff)),
2919 th
->th_seq
, th
->th_ack
, th
->th_win
);
2924 * Note the amount of data that peer has sent into
2925 * our window, in order to estimate the sender's
2928 len
= (u_int
)(so
->so_rcv
.sb_hiwat
- (tp
->rcv_adv
- tp
->rcv_nxt
));
2929 if (len
> so
->so_rcv
.sb_maxused
)
2930 so
->so_rcv
.sb_maxused
= len
;
2937 * If FIN is received ACK the FIN and let the user know
2938 * that the connection is closing.
2940 if (thflags
& TH_FIN
) {
2941 if (TCPS_HAVERCVDFIN(tp
->t_state
) == 0) {
2943 postevent(so
, 0, EV_FIN
);
2945 * If connection is half-synchronized
2946 * (ie NEEDSYN flag on) then delay ACK,
2947 * If connection is half-synchronized
2948 * (ie NEEDSYN flag on) then delay ACK,
2949 * so it may be piggybacked when SYN is sent.
2950 * Otherwise, since we received a FIN then no
2951 * more input can be expected, send ACK now.
2953 if (DELAY_ACK(tp
) && (tp
->t_flags
& TF_NEEDSYN
)) {
2954 tp
->t_flags
|= TF_DELACK
;
2958 tp
->t_flags
|= TF_ACKNOW
;
2959 tp
->t_unacksegs
= 0;
2963 switch (tp
->t_state
) {
2966 * In SYN_RECEIVED and ESTABLISHED STATES
2967 * enter the CLOSE_WAIT state.
2969 case TCPS_SYN_RECEIVED
:
2970 tp
->t_starttime
= 0;
2971 case TCPS_ESTABLISHED
:
2972 tp
->t_state
= TCPS_CLOSE_WAIT
;
2976 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2977 * enter the CLOSING state.
2979 case TCPS_FIN_WAIT_1
:
2980 tp
->t_state
= TCPS_CLOSING
;
2984 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2985 * starting the time-wait timer, turning off the other
2988 case TCPS_FIN_WAIT_2
:
2989 tp
->t_state
= TCPS_TIME_WAIT
;
2990 tcp_canceltimers(tp
);
2991 /* Shorten TIME_WAIT [RFC-1644, p.28] */
2992 if (tp
->cc_recv
!= 0 &&
2993 tp
->t_starttime
< (u_long
)tcp_msl
) {
2994 tp
->t_timer
[TCPT_2MSL
] =
2995 tp
->t_rxtcur
* TCPTV_TWTRUNC
;
2996 /* For transaction client, force ACK now. */
2997 tp
->t_flags
|= TF_ACKNOW
;
2998 tp
->t_unacksegs
= 0;
3001 tp
->t_timer
[TCPT_2MSL
] = 2 * tcp_msl
;
3003 add_to_time_wait(tp
);
3004 soisdisconnected(so
);
3008 * In TIME_WAIT state restart the 2 MSL time_wait timer.
3010 case TCPS_TIME_WAIT
:
3011 tp
->t_timer
[TCPT_2MSL
] = 2 * tcp_msl
;
3012 add_to_time_wait(tp
);
3017 if (so
->so_options
& SO_DEBUG
)
3018 tcp_trace(TA_INPUT
, ostate
, tp
, (void *)tcp_saveipgen
,
3023 * Return any desired output.
3025 if (needoutput
|| (tp
->t_flags
& TF_ACKNOW
)) {
3026 tp
->t_unacksegs
= 0;
3027 (void) tcp_output(tp
);
3029 tcp_unlock(so
, 1, 0);
3030 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
3035 * Generate an ACK dropping incoming segment if it occupies
3036 * sequence space, where the ACK reflects our state.
3038 * We can now skip the test for the RST flag since all
3039 * paths to this code happen after packets containing
3040 * RST have been dropped.
3042 * In the SYN-RECEIVED state, don't send an ACK unless the
3043 * segment we received passes the SYN-RECEIVED ACK test.
3044 * If it fails send a RST. This breaks the loop in the
3045 * "LAND" DoS attack, and also prevents an ACK storm
3046 * between two listening ports that have been sent forged
3047 * SYN segments, each with the source address of the other.
3049 if (tp
->t_state
== TCPS_SYN_RECEIVED
&& (thflags
& TH_ACK
) &&
3050 (SEQ_GT(tp
->snd_una
, th
->th_ack
) ||
3051 SEQ_GT(th
->th_ack
, tp
->snd_max
)) ) {
3052 rstreason
= BANDLIM_RST_OPENPORT
;
3056 if (so
->so_options
& SO_DEBUG
)
3057 tcp_trace(TA_DROP
, ostate
, tp
, (void *)tcp_saveipgen
,
3061 tp
->t_flags
|= TF_ACKNOW
;
3062 tp
->t_unacksegs
= 0;
3063 (void) tcp_output(tp
);
3064 tcp_unlock(so
, 1, 0);
3065 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
3067 dropwithresetnosock
:
3071 * Generate a RST, dropping incoming segment.
3072 * Make ACK acceptable to originator of segment.
3073 * Don't bother to respond if destination was broadcast/multicast.
3075 if ((thflags
& TH_RST
) || m
->m_flags
& (M_BCAST
|M_MCAST
))
3079 if (IN6_IS_ADDR_MULTICAST(&ip6
->ip6_dst
) ||
3080 IN6_IS_ADDR_MULTICAST(&ip6
->ip6_src
))
3084 if (IN_MULTICAST(ntohl(ip
->ip_dst
.s_addr
)) ||
3085 IN_MULTICAST(ntohl(ip
->ip_src
.s_addr
)) ||
3086 ip
->ip_src
.s_addr
== htonl(INADDR_BROADCAST
) ||
3087 in_broadcast(ip
->ip_dst
, m
->m_pkthdr
.rcvif
))
3089 /* IPv6 anycast check is done at tcp6_input() */
3092 * Perform bandwidth limiting.
3095 if (badport_bandlim(rstreason
) < 0)
3100 if (tp
== 0 || (tp
->t_inpcb
->inp_socket
->so_options
& SO_DEBUG
))
3101 tcp_trace(TA_DROP
, ostate
, tp
, (void *)tcp_saveipgen
,
3104 if (thflags
& TH_ACK
)
3105 /* mtod() below is safe as long as hdr dropping is delayed */
3106 tcp_respond(tp
, mtod(m
, void *), th
, m
, (tcp_seq
)0, th
->th_ack
,
3109 if (thflags
& TH_SYN
)
3111 /* mtod() below is safe as long as hdr dropping is delayed */
3112 tcp_respond(tp
, mtod(m
, void *), th
, m
, th
->th_seq
+tlen
,
3113 (tcp_seq
)0, TH_RST
|TH_ACK
, ifscope
);
3115 /* destroy temporarily created socket */
3118 tcp_unlock(so
, 1, 0);
3121 if ((inp
!= NULL
) && (nosock
== 0))
3122 tcp_unlock(so
, 1, 0);
3123 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
3129 * Drop space held by incoming segment and return.
3132 if (tp
== 0 || (tp
->t_inpcb
->inp_socket
->so_options
& SO_DEBUG
))
3133 tcp_trace(TA_DROP
, ostate
, tp
, (void *)tcp_saveipgen
,
3137 /* destroy temporarily created socket */
3140 tcp_unlock(so
, 1, 0);
3144 tcp_unlock(so
, 1, 0);
3145 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
3150 tcp_dooptions(tp
, cp
, cnt
, th
, to
, input_ifscope
)
3152 * Parse TCP options and place in tcpopt.
3159 unsigned int input_ifscope
;
3164 for (; cnt
> 0; cnt
-= optlen
, cp
+= optlen
) {
3166 if (opt
== TCPOPT_EOL
)
3168 if (opt
== TCPOPT_NOP
)
3174 if (optlen
< 2 || optlen
> cnt
)
3183 if (optlen
!= TCPOLEN_MAXSEG
)
3185 if (!(th
->th_flags
& TH_SYN
))
3187 bcopy((char *) cp
+ 2, (char *) &mss
, sizeof(mss
));
3192 if (optlen
!= TCPOLEN_WINDOW
)
3194 if (!(th
->th_flags
& TH_SYN
))
3196 tp
->t_flags
|= TF_RCVD_SCALE
;
3197 tp
->requested_s_scale
= min(cp
[2], TCP_MAX_WINSHIFT
);
3200 case TCPOPT_TIMESTAMP
:
3201 if (optlen
!= TCPOLEN_TIMESTAMP
)
3203 to
->to_flags
|= TOF_TS
;
3204 bcopy((char *)cp
+ 2,
3205 (char *)&to
->to_tsval
, sizeof(to
->to_tsval
));
3206 NTOHL(to
->to_tsval
);
3207 bcopy((char *)cp
+ 6,
3208 (char *)&to
->to_tsecr
, sizeof(to
->to_tsecr
));
3209 NTOHL(to
->to_tsecr
);
3212 * A timestamp received in a SYN makes
3213 * it ok to send timestamp requests and replies.
3215 if (th
->th_flags
& TH_SYN
) {
3216 tp
->t_flags
|= TF_RCVD_TSTMP
;
3217 tp
->ts_recent
= to
->to_tsval
;
3218 tp
->ts_recent_age
= tcp_now
;
3221 case TCPOPT_SACK_PERMITTED
:
3223 optlen
!= TCPOLEN_SACK_PERMITTED
)
3225 if (th
->th_flags
& TH_SYN
)
3226 to
->to_flags
|= TOF_SACK
;
3229 if (optlen
<= 2 || (optlen
- 2) % TCPOLEN_SACK
!= 0)
3231 to
->to_nsacks
= (optlen
- 2) / TCPOLEN_SACK
;
3232 to
->to_sacks
= cp
+ 2;
3233 tcpstat
.tcps_sack_rcv_blocks
++;
3238 if (th
->th_flags
& TH_SYN
)
3239 tcp_mss(tp
, mss
, input_ifscope
); /* sets t_maxseg */
3243 * Pull out of band byte out of a segment so
3244 * it doesn't appear in the user's data queue.
3245 * It is still reflected in the segment length for
3246 * sequencing purposes.
3249 tcp_pulloutofband(so
, th
, m
, off
)
3252 register struct mbuf
*m
;
3253 int off
; /* delayed to be droped hdrlen */
3255 int cnt
= off
+ th
->th_urp
- 1;
3258 if (m
->m_len
> cnt
) {
3259 char *cp
= mtod(m
, caddr_t
) + cnt
;
3260 struct tcpcb
*tp
= sototcpcb(so
);
3263 tp
->t_oobflags
|= TCPOOB_HAVEDATA
;
3264 bcopy(cp
+1, cp
, (unsigned)(m
->m_len
- cnt
- 1));
3266 if (m
->m_flags
& M_PKTHDR
)
3275 panic("tcp_pulloutofband");
3279 * Collect new round-trip time estimate
3280 * and update averages and current timeout.
3283 tcp_xmit_timer(tp
, rtt
)
3284 register struct tcpcb
*tp
;
3289 tcpstat
.tcps_rttupdated
++;
3291 if (tp
->t_srtt
!= 0) {
3293 * srtt is stored as fixed point with 5 bits after the
3294 * binary point (i.e., scaled by 8). The following magic
3295 * is equivalent to the smoothing algorithm in rfc793 with
3296 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
3297 * point). Adjust rtt to origin 0.
3299 delta
= ((rtt
- 1) << TCP_DELTA_SHIFT
)
3300 - (tp
->t_srtt
>> (TCP_RTT_SHIFT
- TCP_DELTA_SHIFT
));
3302 if ((tp
->t_srtt
+= delta
) <= 0)
3306 * We accumulate a smoothed rtt variance (actually, a
3307 * smoothed mean difference), then set the retransmit
3308 * timer to smoothed rtt + 4 times the smoothed variance.
3309 * rttvar is stored as fixed point with 4 bits after the
3310 * binary point (scaled by 16). The following is
3311 * equivalent to rfc793 smoothing with an alpha of .75
3312 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
3313 * rfc793's wired-in beta.
3317 delta
-= tp
->t_rttvar
>> (TCP_RTTVAR_SHIFT
- TCP_DELTA_SHIFT
);
3318 if ((tp
->t_rttvar
+= delta
) <= 0)
3320 if (tp
->t_rttbest
> tp
->t_srtt
+ tp
->t_rttvar
)
3321 tp
->t_rttbest
= tp
->t_srtt
+ tp
->t_rttvar
;
3324 * No rtt measurement yet - use the unsmoothed rtt.
3325 * Set the variance to half the rtt (so our first
3326 * retransmit happens at 3*rtt).
3328 tp
->t_srtt
= rtt
<< TCP_RTT_SHIFT
;
3329 tp
->t_rttvar
= rtt
<< (TCP_RTTVAR_SHIFT
- 1);
3330 tp
->t_rttbest
= tp
->t_srtt
+ tp
->t_rttvar
;
3336 * the retransmit should happen at rtt + 4 * rttvar.
3337 * Because of the way we do the smoothing, srtt and rttvar
3338 * will each average +1/2 tick of bias. When we compute
3339 * the retransmit timer, we want 1/2 tick of rounding and
3340 * 1 extra tick because of +-1/2 tick uncertainty in the
3341 * firing of the timer. The bias will give us exactly the
3342 * 1.5 tick we need. But, because the bias is
3343 * statistical, we have to test that we don't drop below
3344 * the minimum feasible timer (which is 2 ticks).
3346 TCPT_RANGESET(tp
->t_rxtcur
, TCP_REXMTVAL(tp
),
3347 max(tp
->t_rttmin
, rtt
+ 2), TCPTV_REXMTMAX
);
3350 * We received an ack for a packet that wasn't retransmitted;
3351 * it is probably safe to discard any error indications we've
3352 * received recently. This isn't quite right, but close enough
3353 * for now (a route might have failed after we sent a segment,
3354 * and the return path might not be symmetrical).
3356 tp
->t_softerror
= 0;
3359 static inline unsigned int
3360 tcp_maxmtu(struct rtentry
*rt
)
3362 unsigned int maxmtu
;
3364 if (rt
->rt_rmx
.rmx_mtu
== 0)
3365 maxmtu
= rt
->rt_ifp
->if_mtu
;
3367 maxmtu
= MIN(rt
->rt_rmx
.rmx_mtu
, rt
->rt_ifp
->if_mtu
);
3373 static inline unsigned int
3374 tcp_maxmtu6(struct rtentry
*rt
)
3376 unsigned int maxmtu
;
3378 if (rt
->rt_rmx
.rmx_mtu
== 0)
3379 maxmtu
= IN6_LINKMTU(rt
->rt_ifp
);
3381 maxmtu
= MIN(rt
->rt_rmx
.rmx_mtu
, IN6_LINKMTU(rt
->rt_ifp
));
3388 * Determine a reasonable value for maxseg size.
3389 * If the route is known, check route for mtu.
3390 * If none, use an mss that can be handled on the outgoing
3391 * interface without forcing IP to fragment; if bigger than
3392 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
3393 * to utilize large mbufs. If no route is found, route has no mtu,
3394 * or the destination isn't local, use a default, hopefully conservative
3395 * size (usually 512 or the default IP max size, but no more than the mtu
3396 * of the interface), as we can't discover anything about intervening
3397 * gateways or networks. We also initialize the congestion/slow start
3398 * window to be a single segment if the destination isn't local.
3399 * While looking at the routing entry, we also initialize other path-dependent
3400 * parameters from pre-set or cached values in the routing entry.
3402 * Also take into account the space needed for options that we
3403 * send regularly. Make maxseg shorter by that amount to assure
3404 * that we can send maxseg amount of data even when the options
3405 * are present. Store the upper limit of the length of options plus
3408 * NOTE that this routine is only called when we process an incoming
3409 * segment, for outgoing segments only tcp_mssopt is called.
3413 tcp_mss(tp
, offer
, input_ifscope
)
3416 unsigned int input_ifscope
;
3418 register struct rtentry
*rt
;
3420 register int rtt
, mss
;
3424 struct rmxp_tao
*taop
;
3425 int origoffer
= offer
;
3426 u_long sb_max_corrected
;
3435 isipv6
= ((inp
->inp_vflag
& INP_IPV6
) != 0) ? 1 : 0;
3436 min_protoh
= isipv6
? sizeof (struct ip6_hdr
) + sizeof (struct tcphdr
)
3437 : sizeof (struct tcpiphdr
);
3439 #define min_protoh (sizeof (struct tcpiphdr))
3441 lck_mtx_lock(rt_mtx
);
3444 rt
= tcp_rtlookup6(inp
);
3445 if (rt
&& (IN6_IS_ADDR_LOOPBACK(&inp
->in6p_faddr
) || IN6_IS_ADDR_LINKLOCAL(&inp
->in6p_faddr
) || rt
->rt_gateway
->sa_family
== AF_LINK
))
3451 rt
= tcp_rtlookup(inp
, input_ifscope
);
3452 if (rt
&& (rt
->rt_gateway
->sa_family
== AF_LINK
||
3453 rt
->rt_ifp
->if_flags
& IFF_LOOPBACK
))
3457 tp
->t_maxopd
= tp
->t_maxseg
=
3459 isipv6
? tcp_v6mssdflt
:
3462 lck_mtx_unlock(rt_mtx
);
3467 * Slower link window correction:
3468 * If a value is specificied for slowlink_wsize use it for PPP links
3469 * believed to be on a serial modem (speed <128Kbps). Excludes 9600bps as
3470 * it is the default value adversized by pseudo-devices over ppp.
3472 if (ifp
->if_type
== IFT_PPP
&& slowlink_wsize
> 0 &&
3473 ifp
->if_baudrate
> 9600 && ifp
->if_baudrate
<= 128000) {
3474 tp
->t_flags
|= TF_SLOWLINK
;
3476 so
= inp
->inp_socket
;
3478 taop
= rmx_taop(rt
->rt_rmx
);
3480 * Offer == -1 means that we didn't receive SYN yet,
3481 * use cached value in that case;
3484 offer
= taop
->tao_mssopt
;
3486 * Offer == 0 means that there was no MSS on the SYN segment,
3487 * in this case we use tcp_mssdflt.
3492 isipv6
? tcp_v6mssdflt
:
3497 * Prevent DoS attack with too small MSS. Round up
3498 * to at least minmss.
3500 offer
= max(offer
, tcp_minmss
);
3502 * Sanity check: make sure that maxopd will be large
3503 * enough to allow some data on segments even is the
3504 * all the option space is used (40bytes). Otherwise
3505 * funny things may happen in tcp_output.
3507 offer
= max(offer
, 64);
3509 taop
->tao_mssopt
= offer
;
3512 * While we're here, check if there's an initial rtt
3513 * or rttvar. Convert from the route-table units
3514 * to scaled multiples of the slow timeout timer.
3516 if (tp
->t_srtt
== 0 && (rtt
= rt
->rt_rmx
.rmx_rtt
)) {
3518 * XXX the lock bit for RTT indicates that the value
3519 * is also a minimum value; this is subject to time.
3521 if (rt
->rt_rmx
.rmx_locks
& RTV_RTT
)
3522 tp
->t_rttmin
= rtt
/ (RTM_RTTUNIT
/ TCP_RETRANSHZ
);
3524 tp
->t_rttmin
= isnetlocal
? tcp_TCPTV_MIN
: TCP_RETRANSHZ
;
3525 tp
->t_srtt
= rtt
/ (RTM_RTTUNIT
/ (TCP_RETRANSHZ
* TCP_RTT_SCALE
));
3526 tcpstat
.tcps_usedrtt
++;
3527 if (rt
->rt_rmx
.rmx_rttvar
) {
3528 tp
->t_rttvar
= rt
->rt_rmx
.rmx_rttvar
/
3529 (RTM_RTTUNIT
/ (TCP_RETRANSHZ
* TCP_RTTVAR_SCALE
));
3530 tcpstat
.tcps_usedrttvar
++;
3532 /* default variation is +- 1 rtt */
3534 tp
->t_srtt
* TCP_RTTVAR_SCALE
/ TCP_RTT_SCALE
;
3536 TCPT_RANGESET(tp
->t_rxtcur
,
3537 ((tp
->t_srtt
>> 2) + tp
->t_rttvar
) >> 1,
3538 tp
->t_rttmin
, TCPTV_REXMTMAX
);
3541 tp
->t_rttmin
= isnetlocal
? tcp_TCPTV_MIN
: TCP_RETRANSHZ
;
3544 mss
= (isipv6
? tcp_maxmtu6(rt
) : tcp_maxmtu(rt
));
3546 mss
= tcp_maxmtu(rt
);
3550 if (rt
->rt_rmx
.rmx_mtu
== 0) {
3554 mss
= min(mss
, tcp_v6mssdflt
);
3558 mss
= min(mss
, tcp_mssdflt
);
3561 mss
= min(mss
, offer
);
3563 * maxopd stores the maximum length of data AND options
3564 * in a segment; maxseg is the amount of data in a normal
3565 * segment. We need to store this value (maxopd) apart
3566 * from maxseg, because now every segment carries options
3567 * and thus we normally have somewhat less data in segments.
3572 * origoffer==-1 indicates, that no segments were received yet.
3573 * In this case we just guess.
3575 if ((tp
->t_flags
& (TF_REQ_TSTMP
|TF_NOOPT
)) == TF_REQ_TSTMP
&&
3577 (tp
->t_flags
& TF_RCVD_TSTMP
) == TF_RCVD_TSTMP
))
3578 mss
-= TCPOLEN_TSTAMP_APPA
;
3582 * Calculate corrected value for sb_max; ensure to upgrade the
3583 * numerator for large sb_max values else it will overflow.
3585 sb_max_corrected
= (sb_max
* (u_int64_t
)MCLBYTES
) / (MSIZE
+ MCLBYTES
);
3588 * If there's a pipesize (ie loopback), change the socket
3589 * buffer to that size only if it's bigger than the current
3590 * sockbuf size. Make the socket buffers an integral
3591 * number of mss units; if the mss is larger than
3592 * the socket buffer, decrease the mss.
3595 bufsize
= rt
->rt_rmx
.rmx_sendpipe
;
3596 if (bufsize
< so
->so_snd
.sb_hiwat
)
3598 bufsize
= so
->so_snd
.sb_hiwat
;
3602 bufsize
= (((bufsize
+ (u_int64_t
)mss
- 1) / (u_int64_t
)mss
) * (u_int64_t
)mss
);
3603 if (bufsize
> sb_max_corrected
)
3604 bufsize
= sb_max_corrected
;
3605 (void)sbreserve(&so
->so_snd
, bufsize
);
3610 bufsize
= rt
->rt_rmx
.rmx_recvpipe
;
3611 if (bufsize
< so
->so_rcv
.sb_hiwat
)
3613 bufsize
= so
->so_rcv
.sb_hiwat
;
3614 if (bufsize
> mss
) {
3615 bufsize
= (((bufsize
+ (u_int64_t
)mss
- 1) / (u_int64_t
)mss
) * (u_int64_t
)mss
);
3616 if (bufsize
> sb_max_corrected
)
3617 bufsize
= sb_max_corrected
;
3618 (void)sbreserve(&so
->so_rcv
, bufsize
);
3622 * Set the slow-start flight size depending on whether this
3623 * is a local network or not.
3626 tp
->snd_cwnd
= mss
* ss_fltsz_local
;
3628 tp
->snd_cwnd
= mss
* ss_fltsz
;
3630 if (rt
->rt_rmx
.rmx_ssthresh
) {
3632 * There's some sort of gateway or interface
3633 * buffer limit on the path. Use this to set
3634 * the slow start threshhold, but set the
3635 * threshold to no less than 2*mss.
3637 tp
->snd_ssthresh
= max(2 * mss
, rt
->rt_rmx
.rmx_ssthresh
);
3638 tcpstat
.tcps_usedssthresh
++;
3641 tp
->snd_ssthresh
= TCP_MAXWIN
<< TCP_MAX_WINSHIFT
;
3643 lck_mtx_unlock(rt_mtx
);
3647 * Determine the MSS option to send on an outgoing SYN.
3661 isipv6
= ((tp
->t_inpcb
->inp_vflag
& INP_IPV6
) != 0) ? 1 : 0;
3662 min_protoh
= isipv6
? sizeof (struct ip6_hdr
) + sizeof (struct tcphdr
)
3663 : sizeof (struct tcpiphdr
);
3665 #define min_protoh (sizeof (struct tcpiphdr))
3667 lck_mtx_lock(rt_mtx
);
3670 rt
= tcp_rtlookup6(tp
->t_inpcb
);
3673 rt
= tcp_rtlookup(tp
->t_inpcb
, IFSCOPE_NONE
);
3675 lck_mtx_unlock(rt_mtx
);
3678 isipv6
? tcp_v6mssdflt
:
3683 * Slower link window correction:
3684 * If a value is specificied for slowlink_wsize use it for PPP links
3685 * believed to be on a serial modem (speed <128Kbps). Excludes 9600bps as
3686 * it is the default value adversized by pseudo-devices over ppp.
3688 if (rt
->rt_ifp
->if_type
== IFT_PPP
&& slowlink_wsize
> 0 &&
3689 rt
->rt_ifp
->if_baudrate
> 9600 && rt
->rt_ifp
->if_baudrate
<= 128000) {
3690 tp
->t_flags
|= TF_SLOWLINK
;
3694 mss
= (isipv6
? tcp_maxmtu6(rt
) : tcp_maxmtu(rt
));
3696 mss
= tcp_maxmtu(rt
);
3698 lck_mtx_unlock(rt_mtx
);
3699 return (mss
- min_protoh
);
3703 * On a partial ack arrives, force the retransmission of the
3704 * next unacknowledged segment. Do not clear tp->t_dupacks.
3705 * By setting snd_nxt to ti_ack, this forces retransmission timer to
3709 tcp_newreno_partial_ack(tp
, th
)
3713 tcp_seq onxt
= tp
->snd_nxt
;
3714 u_long ocwnd
= tp
->snd_cwnd
;
3715 tp
->t_timer
[TCPT_REXMT
] = 0;
3717 tp
->snd_nxt
= th
->th_ack
;
3719 * Set snd_cwnd to one segment beyond acknowledged offset
3720 * (tp->snd_una has not yet been updated when this function
3723 tp
->snd_cwnd
= tp
->t_maxseg
+ (th
->th_ack
- tp
->snd_una
);
3724 tp
->t_flags
|= TF_ACKNOW
;
3725 tp
->t_unacksegs
= 0;
3726 (void) tcp_output(tp
);
3727 tp
->snd_cwnd
= ocwnd
;
3728 if (SEQ_GT(onxt
, tp
->snd_nxt
))
3731 * Partial window deflation. Relies on fact that tp->snd_una
3734 if (tp
->snd_cwnd
> th
->th_ack
- tp
->snd_una
)
3735 tp
->snd_cwnd
-= th
->th_ack
- tp
->snd_una
;
3738 tp
->snd_cwnd
+= tp
->t_maxseg
;
3743 * Drop a random TCP connection that hasn't been serviced yet and
3744 * is eligible for discard. There is a one in qlen chance that
3745 * we will return a null, saying that there are no dropable
3746 * requests. In this case, the protocol specific code should drop
3747 * the new request. This insures fairness.
3749 * The listening TCP socket "head" must be locked
3752 tcp_dropdropablreq(struct socket
*head
)
3754 struct socket
*so
, *sonext
;
3755 unsigned int i
, j
, qlen
;
3757 static struct timeval old_runtime
;
3758 static unsigned int cur_cnt
, old_cnt
;
3760 struct inpcb
*inp
= NULL
;
3763 if ((head
->so_options
& SO_ACCEPTCONN
) == 0)
3766 so
= TAILQ_FIRST(&head
->so_incomp
);
3771 if ((i
= (tv
.tv_sec
- old_runtime
.tv_sec
)) != 0) {
3773 old_cnt
= cur_cnt
/ i
;
3778 qlen
= head
->so_incqlen
;
3779 if (++cur_cnt
> qlen
|| old_cnt
> qlen
) {
3780 rnd
= (314159 * rnd
+ 66329) & 0xffff;
3781 j
= ((qlen
+ 1) * rnd
) >> 16;
3784 so
= TAILQ_NEXT(so
, so_list
);
3786 /* Find a connection that is not already closing (or being served) */
3788 inp
= (struct inpcb
*)so
->so_pcb
;
3790 sonext
= TAILQ_NEXT(so
, so_list
);
3792 if (in_pcb_checkstate(inp
, WNT_ACQUIRE
, 0) != WNT_STOPUSING
) {
3793 /* Avoid the issue of a socket being accepted by one input thread
3794 * and being dropped by another input thread.
3795 * If we can't get a hold on this mutex, then grab the next socket in line.
3797 if (lck_mtx_try_lock(inp
->inpcb_mtx
)) {
3799 if ((so
->so_usecount
== 2) && so
->so_state
& SS_INCOMP
)
3801 else {/* don't use if beeing accepted or used in any other way */
3802 in_pcb_checkstate(inp
, WNT_RELEASE
, 1);
3803 tcp_unlock(so
, 1, 0);
3813 TAILQ_REMOVE(&head
->so_incomp
, so
, so_list
);
3814 tcp_unlock(head
, 0, 0);
3816 /* Makes sure socket is still in the right state to be discarded */
3818 if (in_pcb_checkstate(inp
, WNT_RELEASE
, 1) == WNT_STOPUSING
) {
3819 tcp_unlock(so
, 1, 0);
3820 tcp_lock(head
, 0, 0);
3824 if (so
->so_usecount
!= 2 || !(so
->so_state
& SS_INCOMP
)) {
3825 /* do not discard: that socket is beeing accepted */
3826 tcp_unlock(so
, 1, 0);
3827 tcp_lock(head
, 0, 0);
3834 * We do not want to lose track of the PCB right away in case we receive
3835 * more segments from the peer
3838 so
->so_flags
|= SOF_OVERFLOW
;
3839 tp
->t_state
= TCPS_TIME_WAIT
;
3840 (void) tcp_close(tp
);
3841 tp
->t_unacksegs
= 0;
3842 tcpstat
.tcps_drops
++;
3843 tcp_canceltimers(tp
);
3844 add_to_time_wait(tp
);
3846 tcp_unlock(so
, 1, 0);
3847 tcp_lock(head
, 0, 0);
3854 tcp_getstat SYSCTL_HANDLER_ARGS
3856 #pragma unused(oidp, arg1, arg2)
3860 if (req
->oldptr
== 0) {
3861 req
->oldlen
= (size_t)sizeof(struct tcpstat
);
3864 error
= SYSCTL_OUT(req
, &tcpstat
, MIN(sizeof (tcpstat
), req
->oldlen
));
3870 SYSCTL_PROC(_net_inet_tcp
, TCPCTL_STATS
, stats
, CTLFLAG_RD
, 0, 0,
3871 tcp_getstat
, "S,tcpstat", "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
3874 sysctl_rexmtthresh SYSCTL_HANDLER_ARGS
3876 #pragma unused(arg1, arg2)
3878 int error
, val
= tcprexmtthresh
;
3880 error
= sysctl_handle_int(oidp
, &val
, 0, req
);
3881 if (error
|| !req
->newptr
)
3885 * Constrain the number of duplicate ACKs
3886 * to consider for TCP fast retransmit
3890 if (val
< 2 || val
> 3)
3893 tcprexmtthresh
= val
;
3898 SYSCTL_PROC(_net_inet_tcp
, OID_AUTO
, rexmt_thresh
, CTLTYPE_INT
|CTLFLAG_RW
,
3899 &tcprexmtthresh
, 0, &sysctl_rexmtthresh
, "I", "Duplicate ACK Threshold for Fast Retransmit");