2 * Copyright (c) 2000-2007 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
*);
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
;
556 /* Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain. */
557 fwd_tag
= m_tag_locate(m
, KERNEL_MODULE_TAG_ID
, KERNEL_TAG_TYPE_IPFORWARD
, NULL
);
558 if (fwd_tag
!= NULL
) {
559 struct ip_fwd_tag
*ipfwd_tag
= (struct ip_fwd_tag
*)(fwd_tag
+1);
561 next_hop
= ipfwd_tag
->next_hop
;
562 m_tag_delete(m
, fwd_tag
);
566 struct ip6_hdr
*ip6
= NULL
;
569 int rstreason
; /* For badport_bandlim accounting purposes */
570 struct proc
*proc0
=current_proc();
572 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_START
,0,0,0,0,0);
575 isipv6
= (mtod(m
, struct ip
*)->ip_v
== 6) ? 1 : 0;
577 bzero((char *)&to
, sizeof(to
));
579 tcpstat
.tcps_rcvtotal
++;
585 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
586 ip6
= mtod(m
, struct ip6_hdr
*);
587 tlen
= sizeof(*ip6
) + ntohs(ip6
->ip6_plen
) - off0
;
588 if (in6_cksum(m
, IPPROTO_TCP
, off0
, tlen
)) {
589 tcpstat
.tcps_rcvbadsum
++;
592 th
= (struct tcphdr
*)((caddr_t
)ip6
+ off0
);
594 KERNEL_DEBUG(DBG_LAYER_BEG
, ((th
->th_dport
<< 16) | th
->th_sport
),
595 (((ip6
->ip6_src
.s6_addr16
[0]) << 16) | (ip6
->ip6_dst
.s6_addr16
[0])),
596 th
->th_seq
, th
->th_ack
, th
->th_win
);
598 * Be proactive about unspecified IPv6 address in source.
599 * As we use all-zero to indicate unbounded/unconnected pcb,
600 * unspecified IPv6 address can be used to confuse us.
602 * Note that packets with unspecified IPv6 destination is
603 * already dropped in ip6_input.
605 if (IN6_IS_ADDR_UNSPECIFIED(&ip6
->ip6_src
)) {
613 * Get IP and TCP header together in first mbuf.
614 * Note: IP leaves IP header in first mbuf.
616 if (off0
> sizeof (struct ip
)) {
617 ip_stripoptions(m
, (struct mbuf
*)0);
618 off0
= sizeof(struct ip
);
619 if (m
->m_pkthdr
.csum_flags
& CSUM_TCP_SUM16
)
620 m
->m_pkthdr
.csum_flags
= 0; /* invalidate hwcksuming */
623 if (m
->m_len
< sizeof (struct tcpiphdr
)) {
624 if ((m
= m_pullup(m
, sizeof (struct tcpiphdr
))) == 0) {
625 tcpstat
.tcps_rcvshort
++;
629 ip
= mtod(m
, struct ip
*);
630 ipov
= (struct ipovly
*)ip
;
631 th
= (struct tcphdr
*)((caddr_t
)ip
+ off0
);
634 KERNEL_DEBUG(DBG_LAYER_BEG
, ((th
->th_dport
<< 16) | th
->th_sport
),
635 (((ip
->ip_src
.s_addr
& 0xffff) << 16) | (ip
->ip_dst
.s_addr
& 0xffff)),
636 th
->th_seq
, th
->th_ack
, th
->th_win
);
638 if (m
->m_pkthdr
.csum_flags
& CSUM_DATA_VALID
) {
639 if (m
->m_pkthdr
.csum_flags
& CSUM_TCP_SUM16
) {
642 *(uint32_t*)&b
[0] = *(uint32_t*)&ipov
->ih_x1
[0];
643 *(uint32_t*)&b
[4] = *(uint32_t*)&ipov
->ih_x1
[4];
644 *(uint8_t*)&b
[8] = *(uint8_t*)&ipov
->ih_x1
[8];
646 bzero(ipov
->ih_x1
, sizeof(ipov
->ih_x1
));
647 ipov
->ih_len
= (u_short
)tlen
;
649 pseudo
= in_cksum(m
, sizeof (struct ip
));
651 *(uint32_t*)&ipov
->ih_x1
[0] = *(uint32_t*)&b
[0];
652 *(uint32_t*)&ipov
->ih_x1
[4] = *(uint32_t*)&b
[4];
653 *(uint8_t*)&ipov
->ih_x1
[8] = *(uint8_t*)&b
[8];
655 th
->th_sum
= in_addword(pseudo
, (m
->m_pkthdr
.csum_data
& 0xFFFF));
657 if (m
->m_pkthdr
.csum_flags
& CSUM_PSEUDO_HDR
)
658 th
->th_sum
= m
->m_pkthdr
.csum_data
;
660 th
->th_sum
= in_pseudo(ip
->ip_src
.s_addr
,
661 ip
->ip_dst
.s_addr
, htonl(m
->m_pkthdr
.csum_data
+
662 ip
->ip_len
+ IPPROTO_TCP
));
664 th
->th_sum
^= 0xffff;
668 * Checksum extended TCP header and data.
670 *(uint32_t*)&b
[0] = *(uint32_t*)&ipov
->ih_x1
[0];
671 *(uint32_t*)&b
[4] = *(uint32_t*)&ipov
->ih_x1
[4];
672 *(uint8_t*)&b
[8] = *(uint8_t*)&ipov
->ih_x1
[8];
674 len
= sizeof (struct ip
) + tlen
;
675 bzero(ipov
->ih_x1
, sizeof(ipov
->ih_x1
));
676 ipov
->ih_len
= (u_short
)tlen
;
678 th
->th_sum
= in_cksum(m
, len
);
680 *(uint32_t*)&ipov
->ih_x1
[0] = *(uint32_t*)&b
[0];
681 *(uint32_t*)&ipov
->ih_x1
[4] = *(uint32_t*)&b
[4];
682 *(uint8_t*)&ipov
->ih_x1
[8] = *(uint8_t*)&b
[8];
684 tcp_in_cksum_stats(len
);
687 tcpstat
.tcps_rcvbadsum
++;
691 /* Re-initialization for later version check */
692 ip
->ip_v
= IPVERSION
;
694 ip_ecn
= (ip
->ip_tos
& IPTOS_ECN_MASK
);
698 * Check that TCP offset makes sense,
699 * pull out TCP options and adjust length. XXX
701 off
= th
->th_off
<< 2;
702 if (off
< sizeof (struct tcphdr
) || off
> tlen
) {
703 tcpstat
.tcps_rcvbadoff
++;
706 tlen
-= off
; /* tlen is used instead of ti->ti_len */
707 if (off
> sizeof (struct tcphdr
)) {
710 IP6_EXTHDR_CHECK(m
, off0
, off
, return);
711 ip6
= mtod(m
, struct ip6_hdr
*);
712 th
= (struct tcphdr
*)((caddr_t
)ip6
+ off0
);
716 if (m
->m_len
< sizeof(struct ip
) + off
) {
717 if ((m
= m_pullup(m
, sizeof (struct ip
) + off
)) == 0) {
718 tcpstat
.tcps_rcvshort
++;
721 ip
= mtod(m
, struct ip
*);
722 ipov
= (struct ipovly
*)ip
;
723 th
= (struct tcphdr
*)((caddr_t
)ip
+ off0
);
726 optlen
= off
- sizeof (struct tcphdr
);
727 optp
= (u_char
*)(th
+ 1);
729 * Do quick retrieval of timestamp options ("options
730 * prediction?"). If timestamp is the only option and it's
731 * formatted as recommended in RFC 1323 appendix A, we
732 * quickly get the values now and not bother calling
733 * tcp_dooptions(), etc.
735 if ((optlen
== TCPOLEN_TSTAMP_APPA
||
736 (optlen
> TCPOLEN_TSTAMP_APPA
&&
737 optp
[TCPOLEN_TSTAMP_APPA
] == TCPOPT_EOL
)) &&
738 *(u_int32_t
*)optp
== htonl(TCPOPT_TSTAMP_HDR
) &&
739 (th
->th_flags
& TH_SYN
) == 0) {
740 to
.to_flags
|= TOF_TS
;
741 to
.to_tsval
= ntohl(*(u_int32_t
*)(optp
+ 4));
742 to
.to_tsecr
= ntohl(*(u_int32_t
*)(optp
+ 8));
743 optp
= NULL
; /* we've parsed the options */
746 thflags
= th
->th_flags
;
750 * If the drop_synfin option is enabled, drop all packets with
751 * both the SYN and FIN bits set. This prevents e.g. nmap from
752 * identifying the TCP/IP stack.
754 * This is a violation of the TCP specification.
756 if (drop_synfin
&& (thflags
& (TH_SYN
|TH_FIN
)) == (TH_SYN
|TH_FIN
))
761 * Convert TCP protocol specific fields to host format.
769 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options,
770 * until after ip6_savecontrol() is called and before other functions
771 * which don't want those proto headers.
772 * Because ip6_savecontrol() is going to parse the mbuf to
773 * search for data to be passed up to user-land, it wants mbuf
774 * parameters to be unchanged.
776 drop_hdrlen
= off0
+ off
;
779 * Locate pcb for segment.
782 #if IPFIREWALL_FORWARD
785 && isipv6
== 0 /* IPv6 support is not yet */
789 * Diverted. Pretend to be the destination.
790 * already got one like this?
792 inp
= in_pcblookup_hash(&tcbinfo
, ip
->ip_src
, th
->th_sport
,
793 ip
->ip_dst
, th
->th_dport
, 0, m
->m_pkthdr
.rcvif
);
796 * No, then it's new. Try find the ambushing socket
798 if (!next_hop
->sin_port
) {
799 inp
= in_pcblookup_hash(&tcbinfo
, ip
->ip_src
,
800 th
->th_sport
, next_hop
->sin_addr
,
801 th
->th_dport
, 1, m
->m_pkthdr
.rcvif
);
803 inp
= in_pcblookup_hash(&tcbinfo
,
804 ip
->ip_src
, th
->th_sport
,
806 ntohs(next_hop
->sin_port
), 1,
811 #endif /* IPFIREWALL_FORWARD */
815 inp
= in6_pcblookup_hash(&tcbinfo
, &ip6
->ip6_src
, th
->th_sport
,
816 &ip6
->ip6_dst
, th
->th_dport
, 1,
820 inp
= in_pcblookup_hash(&tcbinfo
, ip
->ip_src
, th
->th_sport
,
821 ip
->ip_dst
, th
->th_dport
, 1, m
->m_pkthdr
.rcvif
);
825 if (ipsec_bypass
== 0) {
828 if (inp
!= NULL
&& ipsec6_in_reject_so(m
, inp
->inp_socket
)) {
829 IPSEC_STAT_INCREMENT(ipsec6stat
.in_polvio
);
834 if (inp
!= NULL
&& ipsec4_in_reject_so(m
, inp
->inp_socket
)) {
835 IPSEC_STAT_INCREMENT(ipsecstat
.in_polvio
);
842 * If the state is CLOSED (i.e., TCB does not exist) then
843 * all data in the incoming segment is discarded.
844 * If the TCB exists but is in CLOSED state, it is embryonic,
845 * but should either do a listen or a connect soon.
850 char dbuf
[MAX_IPv6_STR_LEN
], sbuf
[MAX_IPv6_STR_LEN
];
852 char dbuf
[MAX_IPv4_STR_LEN
], sbuf
[MAX_IPv4_STR_LEN
];
857 inet_ntop(AF_INET6
, &ip6
->ip6_dst
, dbuf
, sizeof(dbuf
));
858 inet_ntop(AF_INET6
, &ip6
->ip6_src
, sbuf
, sizeof(sbuf
));
862 inet_ntop(AF_INET
, &ip
->ip_dst
, dbuf
, sizeof(dbuf
));
863 inet_ntop(AF_INET
, &ip
->ip_src
, sbuf
, sizeof(sbuf
));
865 switch (log_in_vain
) {
869 "Connection attempt to TCP %s:%d from %s:%d\n",
870 dbuf
, ntohs(th
->th_dport
),
872 ntohs(th
->th_sport
));
876 "Connection attempt to TCP %s:%d from %s:%d flags:0x%x\n",
877 dbuf
, ntohs(th
->th_dport
), sbuf
,
878 ntohs(th
->th_sport
), thflags
);
881 if ((thflags
& TH_SYN
) &&
882 !(m
->m_flags
& (M_BCAST
| M_MCAST
)) &&
884 ((isipv6
&& !IN6_ARE_ADDR_EQUAL(&ip6
->ip6_dst
, &ip6
->ip6_src
)) ||
885 (!isipv6
&& ip
->ip_dst
.s_addr
!= ip
->ip_src
.s_addr
))
887 ip
->ip_dst
.s_addr
!= ip
->ip_src
.s_addr
890 log_in_vain_log((LOG_INFO
,
891 "Stealth Mode connection attempt to TCP %s:%d from %s:%d\n",
892 dbuf
, ntohs(th
->th_dport
),
894 ntohs(th
->th_sport
)));
901 if (m
->m_pkthdr
.rcvif
&& m
->m_pkthdr
.rcvif
->if_type
!= IFT_LOOP
)
904 if (thflags
& TH_SYN
)
913 rstreason
= BANDLIM_RST_CLOSEDPORT
;
914 goto dropwithresetnosock
;
916 so
= inp
->inp_socket
;
918 if (in_pcb_checkstate(inp
, WNT_RELEASE
, 1) == WNT_STOPUSING
)
919 inp
= NULL
; // pretend we didn't find it
921 printf("tcp_input: no more socket for inp=%x\n", inp
);
928 * Bogus state when listening port owned by SharedIP with loopback as the
929 * only configured interface: BlueBox does not filters loopback
931 if (so
== &tcbinfo
.nat_dummy_socket
)
936 if (in_pcb_checkstate(inp
, WNT_RELEASE
, 1) == WNT_STOPUSING
) {
937 tcp_unlock(so
, 1, 2);
938 inp
= NULL
; // pretend we didn't find it
944 rstreason
= BANDLIM_RST_CLOSEDPORT
;
947 if (tp
->t_state
== TCPS_CLOSED
)
950 /* Unscale the window into a 32-bit value. */
951 if ((thflags
& TH_SYN
) == 0)
952 tiwin
= th
->th_win
<< tp
->snd_scale
;
957 if (mac_inpcb_check_deliver(inp
, m
, AF_INET
, SOCK_STREAM
))
961 if (so
->so_options
& (SO_DEBUG
|SO_ACCEPTCONN
)) {
963 if (so
->so_options
& SO_DEBUG
) {
964 ostate
= tp
->t_state
;
967 bcopy((char *)ip6
, (char *)tcp_saveipgen
,
971 bcopy((char *)ip
, (char *)tcp_saveipgen
, sizeof(*ip
));
975 if (so
->so_options
& SO_ACCEPTCONN
) {
976 register struct tcpcb
*tp0
= tp
;
979 struct sockaddr_storage from
;
981 struct inpcb
*oinp
= sotoinpcb(so
);
983 int ogencnt
= so
->so_gencnt
;
987 * Current IPsec implementation makes incorrect IPsec
988 * cache if this check is done here.
989 * So delay this until duplicated socket is created.
991 if ((thflags
& (TH_RST
|TH_ACK
|TH_SYN
)) != TH_SYN
) {
993 * Note: dropwithreset makes sure we don't
994 * send a RST in response to a RST.
996 if (thflags
& TH_ACK
) {
997 tcpstat
.tcps_badsyn
++;
998 rstreason
= BANDLIM_RST_OPENPORT
;
1004 KERNEL_DEBUG(DBG_FNC_TCP_NEWCONN
| DBG_FUNC_START
,0,0,0,0,0);
1008 * If deprecated address is forbidden,
1009 * we do not accept SYN to deprecated interface
1010 * address to prevent any new inbound connection from
1011 * getting established.
1012 * When we do not accept SYN, we send a TCP RST,
1013 * with deprecated source address (instead of dropping
1014 * it). We compromise it as it is much better for peer
1015 * to send a RST, and RST will be the final packet
1018 * If we do not forbid deprecated addresses, we accept
1019 * the SYN packet. RFC2462 does not suggest dropping
1021 * If we decipher RFC2462 5.5.4, it says like this:
1022 * 1. use of deprecated addr with existing
1023 * communication is okay - "SHOULD continue to be
1025 * 2. use of it with new communication:
1026 * (2a) "SHOULD NOT be used if alternate address
1027 * with sufficient scope is available"
1028 * (2b) nothing mentioned otherwise.
1029 * Here we fall into (2b) case as we have no choice in
1030 * our source address selection - we must obey the peer.
1032 * The wording in RFC2462 is confusing, and there are
1033 * multiple description text for deprecated address
1034 * handling - worse, they are not exactly the same.
1035 * I believe 5.5.4 is the best one, so we follow 5.5.4.
1037 if (isipv6
&& !ip6_use_deprecated
) {
1038 struct in6_ifaddr
*ia6
;
1040 if ((ia6
= ip6_getdstifaddr(m
)) &&
1041 (ia6
->ia6_flags
& IN6_IFF_DEPRECATED
)) {
1043 rstreason
= BANDLIM_RST_OPENPORT
;
1051 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*)&from
;
1053 sin6
->sin6_len
= sizeof(*sin6
);
1054 sin6
->sin6_family
= AF_INET6
;
1055 sin6
->sin6_port
= th
->th_sport
;
1056 sin6
->sin6_flowinfo
= 0;
1057 sin6
->sin6_addr
= ip6
->ip6_src
;
1058 sin6
->sin6_scope_id
= 0;
1063 struct sockaddr_in
*sin
= (struct sockaddr_in
*)&from
;
1065 sin
->sin_len
= sizeof(*sin
);
1066 sin
->sin_family
= AF_INET
;
1067 sin
->sin_port
= th
->th_sport
;
1068 sin
->sin_addr
= ip
->ip_src
;
1070 so2
= sonewconn(so
, 0, (struct sockaddr
*)&from
);
1072 so2
= sonewconn(so
, 0, NULL
);
1075 tcpstat
.tcps_listendrop
++;
1076 if (tcp_dropdropablreq(so
)) {
1078 so2
= sonewconn(so
, 0, (struct sockaddr
*)&from
);
1080 so2
= sonewconn(so
, 0, NULL
);
1086 * Make sure listening socket did not get closed during socket allocation,
1087 * not only this is incorrect but it is know to cause panic
1089 if (so
->so_gencnt
!= ogencnt
)
1093 tcp_unlock(so
, 0, 0); /* Unlock but keep a reference on listener for now */
1098 * This is ugly, but ....
1100 * Mark socket as temporary until we're
1101 * committed to keeping it. The code at
1102 * ``drop'' and ``dropwithreset'' check the
1103 * flag dropsocket to see if the temporary
1104 * socket created here should be discarded.
1105 * We mark the socket as discardable until
1106 * we're committed to it below in TCPS_LISTEN.
1109 inp
= (struct inpcb
*)so
->so_pcb
;
1112 inp
->in6p_laddr
= ip6
->ip6_dst
;
1114 inp
->inp_vflag
&= ~INP_IPV6
;
1115 inp
->inp_vflag
|= INP_IPV4
;
1117 inp
->inp_laddr
= ip
->ip_dst
;
1121 inp
->inp_lport
= th
->th_dport
;
1122 if (in_pcbinshash(inp
, 0) != 0) {
1124 * Undo the assignments above if we failed to
1125 * put the PCB on the hash lists.
1129 inp
->in6p_laddr
= in6addr_any
;
1132 inp
->inp_laddr
.s_addr
= INADDR_ANY
;
1134 tcp_lock(oso
, 0, 0); /* release ref on parent */
1135 tcp_unlock(oso
, 1, 0);
1140 * To avoid creating incorrectly cached IPsec
1141 * association, this is need to be done here.
1143 * Subject: (KAME-snap 748)
1144 * From: Wayne Knowles <w.knowles@niwa.cri.nz>
1145 * ftp://ftp.kame.net/pub/mail-list/snap-users/748
1147 if ((thflags
& (TH_RST
|TH_ACK
|TH_SYN
)) != TH_SYN
) {
1149 * Note: dropwithreset makes sure we don't
1150 * send a RST in response to a RST.
1152 tcp_lock(oso
, 0, 0); /* release ref on parent */
1153 tcp_unlock(oso
, 1, 0);
1154 if (thflags
& TH_ACK
) {
1155 tcpstat
.tcps_badsyn
++;
1156 rstreason
= BANDLIM_RST_OPENPORT
;
1165 * Inherit socket options from the listening
1167 * Note that in6p_inputopts are not (even
1168 * should not be) copied, since it stores
1169 * previously received options and is used to
1170 * detect if each new option is different than
1171 * the previous one and hence should be passed
1173 * If we copied in6p_inputopts, a user would
1174 * not be able to receive options just after
1175 * calling the accept system call.
1178 oinp
->inp_flags
& INP_CONTROLOPTS
;
1179 if (oinp
->in6p_outputopts
)
1180 inp
->in6p_outputopts
=
1181 ip6_copypktopts(oinp
->in6p_outputopts
,
1185 inp
->inp_options
= ip_srcroute();
1186 tcp_lock(oso
, 0, 0);
1188 /* copy old policy into new socket's */
1189 if (sotoinpcb(oso
)->inp_sp
)
1192 /* Is it a security hole here to silently fail to copy the policy? */
1193 if (inp
->inp_sp
!= NULL
)
1194 error
= ipsec_init_policy(so
, &inp
->inp_sp
);
1195 if (error
!= 0 || ipsec_copy_policy(sotoinpcb(oso
)->inp_sp
, inp
->inp_sp
))
1196 printf("tcp_input: could not copy policy\n");
1199 tcp_unlock(oso
, 1, 0); /* now drop the reference on the listener */
1200 tp
= intotcpcb(inp
);
1201 tp
->t_state
= TCPS_LISTEN
;
1202 tp
->t_flags
|= tp0
->t_flags
& (TF_NOPUSH
|TF_NOOPT
|TF_NODELAY
);
1203 tp
->t_inpcb
->inp_ip_ttl
= tp0
->t_inpcb
->inp_ip_ttl
;
1204 /* Compute proper scaling value from buffer space */
1205 if (inp
->inp_pcbinfo
->ipi_count
< tcp_sockthreshold
) {
1206 tp
->request_r_scale
= max(tcp_win_scale
, tp
->request_r_scale
);
1207 so
->so_rcv
.sb_hiwat
= lmin(TCP_MAXWIN
<< tp
->request_r_scale
, (sb_max
/ (MSIZE
+MCLBYTES
)) * MCLBYTES
);
1210 while (tp
->request_r_scale
< TCP_MAX_WINSHIFT
&&
1211 TCP_MAXWIN
<< tp
->request_r_scale
<
1212 so
->so_rcv
.sb_hiwat
)
1213 tp
->request_r_scale
++;
1216 KERNEL_DEBUG(DBG_FNC_TCP_NEWCONN
| DBG_FUNC_END
,0,0,0,0,0);
1221 lck_mtx_assert(((struct inpcb
*)so
->so_pcb
)->inpcb_mtx
, LCK_MTX_ASSERT_OWNED
);
1225 * This is the second part of the MSS DoS prevention code (after
1226 * minmss on the sending side) and it deals with too many too small
1227 * tcp packets in a too short timeframe (1 second).
1229 * For every full second we count the number of received packets
1230 * and bytes. If we get a lot of packets per second for this connection
1231 * (tcp_minmssoverload) we take a closer look at it and compute the
1232 * average packet size for the past second. If that is less than
1233 * tcp_minmss we get too many packets with very small payload which
1234 * is not good and burdens our system (and every packet generates
1235 * a wakeup to the process connected to our socket). We can reasonable
1236 * expect this to be small packet DoS attack to exhaust our CPU
1239 * Care has to be taken for the minimum packet overload value. This
1240 * value defines the minimum number of packets per second before we
1241 * start to worry. This must not be too low to avoid killing for
1242 * example interactive connections with many small packets like
1245 * Setting either tcp_minmssoverload or tcp_minmss to "0" disables
1248 * Account for packet if payload packet, skip over ACK, etc.
1250 * The packet per second count is done all the time and is also used
1251 * by "DELAY_ACK" to detect streaming situations.
1254 if (tp
->t_state
== TCPS_ESTABLISHED
&& tlen
> 0) {
1255 if (tp
->rcv_reset
> tcp_now
) {
1257 tp
->rcv_byps
+= tlen
+ off
;
1258 if (tp
->rcv_byps
> tp
->rcv_maxbyps
)
1259 tp
->rcv_maxbyps
= tp
->rcv_byps
;
1261 * Setting either tcp_minmssoverload or tcp_minmss to "0" disables
1264 if (tcp_minmss
&& tcp_minmssoverload
&& tp
->rcv_pps
> tcp_minmssoverload
) {
1265 if ((tp
->rcv_byps
/ tp
->rcv_pps
) < tcp_minmss
) {
1266 char ipstrbuf
[MAX_IPv6_STR_LEN
];
1267 printf("too many small tcp packets from "
1268 "%s:%u, av. %lubyte/packet, "
1269 "dropping connection\n",
1272 inet_ntop(AF_INET6
, &inp
->in6p_faddr
, ipstrbuf
,
1275 inet_ntop(AF_INET
, &inp
->inp_faddr
, ipstrbuf
,
1278 tp
->rcv_byps
/ tp
->rcv_pps
);
1279 tp
= tcp_drop(tp
, ECONNRESET
);
1280 /* tcpstat.tcps_minmssdrops++; */
1285 tp
->rcv_reset
= tcp_now
+ TCP_RETRANSHZ
;
1287 tp
->rcv_byps
= tlen
+ off
;
1292 if (so
->so_traffic_mgt_flags
& TRAFFIC_MGT_SO_BACKGROUND
) {
1293 tcpstat
.tcps_bg_rcvtotal
++;
1295 /* Take snapshots of pkts recv;
1296 * tcpcb should have been initialized to 0 when allocated,
1297 * so if 0 then this is the first time we're doing this
1299 if (!tp
->tot_recv_snapshot
) {
1300 tp
->tot_recv_snapshot
= tcpstat
.tcps_rcvtotal
;
1302 if (!tp
->bg_recv_snapshot
) {
1303 tp
->bg_recv_snapshot
= tcpstat
.tcps_bg_rcvtotal
;
1306 #endif /* TRAFFIC_MGT */
1309 Explicit Congestion Notification - Flag that we need to send ECT if
1310 + The IP Congestion experienced flag was set.
1311 + Socket is in established state
1312 + We negotiated ECN in the TCP setup
1313 + This isn't a pure ack (tlen > 0)
1314 + The data is in the valid window
1316 TE_SENDECE will be cleared when we receive a packet with TH_CWR set.
1318 if (ip_ecn
== IPTOS_ECN_CE
&& tp
->t_state
== TCPS_ESTABLISHED
&&
1319 (tp
->ecn_flags
& (TE_SETUPSENT
| TE_SETUPRECEIVED
)) ==
1320 (TE_SETUPSENT
| TE_SETUPRECEIVED
) && tlen
> 0 &&
1321 SEQ_GEQ(th
->th_seq
, tp
->last_ack_sent
) &&
1322 SEQ_LT(th
->th_seq
, tp
->last_ack_sent
+ tp
->rcv_wnd
)) {
1323 tp
->ecn_flags
|= TE_SENDECE
;
1327 Clear TE_SENDECE if TH_CWR is set. This is harmless, so we don't
1328 bother doing extensive checks for state and whatnot.
1330 if ((thflags
& TH_CWR
) == TH_CWR
) {
1331 tp
->ecn_flags
&= ~TE_SENDECE
;
1335 * Segment received on connection.
1336 * Reset idle time and keep-alive timer.
1339 if (TCPS_HAVEESTABLISHED(tp
->t_state
))
1340 tp
->t_timer
[TCPT_KEEP
] = TCP_KEEPIDLE(tp
);
1343 * Process options if not in LISTEN state,
1344 * else do it below (after getting remote address).
1346 if (tp
->t_state
!= TCPS_LISTEN
&& optp
)
1347 tcp_dooptions(tp
, optp
, optlen
, th
, &to
);
1349 if (tp
->t_state
== TCPS_SYN_SENT
&& (thflags
& TH_SYN
)) {
1350 if (to
.to_flags
& TOF_SCALE
) {
1351 tp
->t_flags
|= TF_RCVD_SCALE
;
1352 tp
->requested_s_scale
= to
.to_requested_s_scale
;
1353 tp
->snd_wnd
= th
->th_win
<< tp
->snd_scale
;
1354 tiwin
= tp
->snd_wnd
;
1356 if (to
.to_flags
& TOF_TS
) {
1357 tp
->t_flags
|= TF_RCVD_TSTMP
;
1358 tp
->ts_recent
= to
.to_tsval
;
1359 tp
->ts_recent_age
= tcp_now
;
1361 if (to
.to_flags
& TOF_MSS
)
1362 tcp_mss(tp
, to
.to_mss
);
1363 if (tp
->sack_enable
) {
1364 if (!(to
.to_flags
& TOF_SACK
))
1365 tp
->sack_enable
= 0;
1367 tp
->t_flags
|= TF_SACK_PERMIT
;
1372 * Header prediction: check for the two common cases
1373 * of a uni-directional data xfer. If the packet has
1374 * no control flags, is in-sequence, the window didn't
1375 * change and we're not retransmitting, it's a
1376 * candidate. If the length is zero and the ack moved
1377 * forward, we're the sender side of the xfer. Just
1378 * free the data acked & wake any higher level process
1379 * that was blocked waiting for space. If the length
1380 * is non-zero and the ack didn't move, we're the
1381 * receiver side. If we're getting packets in-order
1382 * (the reassembly queue is empty), add the data to
1383 * the socket buffer and note that we need a delayed ack.
1384 * Make sure that the hidden state-flags are also off.
1385 * Since we check for TCPS_ESTABLISHED above, it can only
1388 if (tp
->t_state
== TCPS_ESTABLISHED
&&
1389 (thflags
& (TH_SYN
|TH_FIN
|TH_RST
|TH_URG
|TH_ACK
|TH_ECE
)) == TH_ACK
&&
1390 ((tp
->t_flags
& (TF_NEEDSYN
|TF_NEEDFIN
)) == 0) &&
1391 ((to
.to_flags
& TOF_TS
) == 0 ||
1392 TSTMP_GEQ(to
.to_tsval
, tp
->ts_recent
)) &&
1393 th
->th_seq
== tp
->rcv_nxt
&&
1394 tiwin
&& tiwin
== tp
->snd_wnd
&&
1395 tp
->snd_nxt
== tp
->snd_max
) {
1398 * If last ACK falls within this segment's sequence numbers,
1399 * record the timestamp.
1400 * NOTE that the test is modified according to the latest
1401 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1403 if ((to
.to_flags
& TOF_TS
) != 0 &&
1404 SEQ_LEQ(th
->th_seq
, tp
->last_ack_sent
)) {
1405 tp
->ts_recent_age
= tcp_now
;
1406 tp
->ts_recent
= to
.to_tsval
;
1410 if (SEQ_GT(th
->th_ack
, tp
->snd_una
) &&
1411 SEQ_LEQ(th
->th_ack
, tp
->snd_max
) &&
1412 tp
->snd_cwnd
>= tp
->snd_ssthresh
&&
1413 ((!tcp_do_newreno
&& !tp
->sack_enable
&&
1414 tp
->t_dupacks
< tcprexmtthresh
) ||
1415 ((tcp_do_newreno
|| tp
->sack_enable
) &&
1416 !IN_FASTRECOVERY(tp
) && to
.to_nsacks
== 0 &&
1417 TAILQ_EMPTY(&tp
->snd_holes
)))) {
1419 * this is a pure ack for outstanding data.
1421 ++tcpstat
.tcps_predack
;
1423 * "bad retransmit" recovery
1425 if (tp
->t_rxtshift
== 1 &&
1426 tcp_now
< tp
->t_badrxtwin
) {
1427 ++tcpstat
.tcps_sndrexmitbad
;
1428 tp
->snd_cwnd
= tp
->snd_cwnd_prev
;
1430 tp
->snd_ssthresh_prev
;
1431 tp
->snd_recover
= tp
->snd_recover_prev
;
1432 if (tp
->t_flags
& TF_WASFRECOVERY
)
1433 ENTER_FASTRECOVERY(tp
);
1434 tp
->snd_nxt
= tp
->snd_max
;
1435 tp
->t_badrxtwin
= 0;
1438 * Recalculate the transmit timer / rtt.
1440 * Some boxes send broken timestamp replies
1441 * during the SYN+ACK phase, ignore
1442 * timestamps of 0 or we could calculate a
1443 * huge RTT and blow up the retransmit timer.
1445 if (((to
.to_flags
& TOF_TS
) != 0) && (to
.to_tsecr
!= 0)) { /* Makes sure we already have a TS */
1446 if (!tp
->t_rttlow
||
1447 tp
->t_rttlow
> tcp_now
- to
.to_tsecr
)
1448 tp
->t_rttlow
= tcp_now
- to
.to_tsecr
;
1450 tcp_now
- to
.to_tsecr
);
1451 } else if (tp
->t_rtttime
&&
1452 SEQ_GT(th
->th_ack
, tp
->t_rtseq
)) {
1453 if (!tp
->t_rttlow
||
1454 tp
->t_rttlow
> tcp_now
- tp
->t_rtttime
)
1455 tp
->t_rttlow
= tcp_now
- tp
->t_rtttime
;
1456 tcp_xmit_timer(tp
, tp
->t_rtttime
);
1458 acked
= th
->th_ack
- tp
->snd_una
;
1459 tcpstat
.tcps_rcvackpack
++;
1460 tcpstat
.tcps_rcvackbyte
+= acked
;
1462 * Grow the congestion window, if the
1463 * connection is cwnd bound.
1465 sbdrop(&so
->so_snd
, acked
);
1466 if (SEQ_GT(tp
->snd_una
, tp
->snd_recover
) &&
1467 SEQ_LEQ(th
->th_ack
, tp
->snd_recover
))
1468 tp
->snd_recover
= th
->th_ack
- 1;
1469 tp
->snd_una
= th
->th_ack
;
1471 * pull snd_wl2 up to prevent seq wrap relative
1474 tp
->snd_wl2
= th
->th_ack
;
1477 ND6_HINT(tp
); /* some progress has been done */
1480 * If all outstanding data are acked, stop
1481 * retransmit timer, otherwise restart timer
1482 * using current (possibly backed-off) value.
1483 * If process is waiting for space,
1484 * wakeup/selwakeup/signal. If data
1485 * are ready to send, let tcp_output
1486 * decide between more output or persist.
1488 if (tp
->snd_una
== tp
->snd_max
)
1489 tp
->t_timer
[TCPT_REXMT
] = 0;
1490 else if (tp
->t_timer
[TCPT_PERSIST
] == 0)
1491 tp
->t_timer
[TCPT_REXMT
] = tp
->t_rxtcur
;
1493 sowwakeup(so
); /* has to be done with socket lock held */
1494 if ((so
->so_snd
.sb_cc
) || (tp
->t_flags
& TF_ACKNOW
)) {
1495 tp
->t_unacksegs
= 0;
1496 (void) tcp_output(tp
);
1498 tcp_unlock(so
, 1, 0);
1499 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
1502 } else if (th
->th_ack
== tp
->snd_una
&&
1503 LIST_EMPTY(&tp
->t_segq
) &&
1504 tlen
<= tcp_sbspace(tp
)) {
1506 * this is a pure, in-sequence data packet
1507 * with nothing on the reassembly queue and
1508 * we have enough buffer space to take it.
1510 /* Clean receiver SACK report if present */
1511 if (tp
->sack_enable
&& tp
->rcv_numsacks
)
1512 tcp_clean_sackreport(tp
);
1513 ++tcpstat
.tcps_preddat
;
1514 tp
->rcv_nxt
+= tlen
;
1516 * Pull snd_wl1 up to prevent seq wrap relative to
1519 tp
->snd_wl1
= th
->th_seq
;
1521 * Pull rcv_up up to prevent seq wrap relative to
1524 tp
->rcv_up
= tp
->rcv_nxt
;
1525 tcpstat
.tcps_rcvpack
++;
1526 tcpstat
.tcps_rcvbyte
+= tlen
;
1527 ND6_HINT(tp
); /* some progress has been done */
1529 * Add data to socket buffer.
1531 m_adj(m
, drop_hdrlen
); /* delayed header drop */
1532 if (sbappendstream(&so
->so_rcv
, m
))
1536 KERNEL_DEBUG(DBG_LAYER_END
, ((th
->th_dport
<< 16) | th
->th_sport
),
1537 (((ip6
->ip6_src
.s6_addr16
[0]) << 16) | (ip6
->ip6_dst
.s6_addr16
[0])),
1538 th
->th_seq
, th
->th_ack
, th
->th_win
);
1543 KERNEL_DEBUG(DBG_LAYER_END
, ((th
->th_dport
<< 16) | th
->th_sport
),
1544 (((ip
->ip_src
.s_addr
& 0xffff) << 16) | (ip
->ip_dst
.s_addr
& 0xffff)),
1545 th
->th_seq
, th
->th_ack
, th
->th_win
);
1547 if (DELAY_ACK(tp
)) {
1548 tp
->t_flags
|= TF_DELACK
;
1551 tp
->t_unacksegs
= 0;
1552 tp
->t_flags
|= TF_ACKNOW
;
1555 tcp_unlock(so
, 1, 0);
1556 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
1562 * Calculate amount of space in receive window,
1563 * and then do TCP input processing.
1564 * Receive window is amount of space in rcv queue,
1565 * but not less than advertised window.
1568 lck_mtx_assert(((struct inpcb
*)so
->so_pcb
)->inpcb_mtx
, LCK_MTX_ASSERT_OWNED
);
1572 win
= tcp_sbspace(tp
);
1576 else { /* clip rcv window to 4K for modems */
1577 if (tp
->t_flags
& TF_SLOWLINK
&& slowlink_wsize
> 0)
1578 win
= min(win
, slowlink_wsize
);
1580 tp
->rcv_wnd
= imax(win
, (int)(tp
->rcv_adv
- tp
->rcv_nxt
));
1583 switch (tp
->t_state
) {
1586 * If the state is LISTEN then ignore segment if it contains an RST.
1587 * If the segment contains an ACK then it is bad and send a RST.
1588 * If it does not contain a SYN then it is not interesting; drop it.
1589 * If it is from this socket, drop it, it must be forged.
1590 * Don't bother responding if the destination was a broadcast.
1591 * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial
1592 * tp->iss, and send a segment:
1593 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
1594 * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
1595 * Fill in remote peer address fields if not previously specified.
1596 * Enter SYN_RECEIVED state, and process any other fields of this
1597 * segment in this state.
1600 register struct sockaddr_in
*sin
;
1602 register struct sockaddr_in6
*sin6
;
1606 lck_mtx_assert(((struct inpcb
*)so
->so_pcb
)->inpcb_mtx
, LCK_MTX_ASSERT_OWNED
);
1608 if (thflags
& TH_RST
)
1610 if (thflags
& TH_ACK
) {
1611 rstreason
= BANDLIM_RST_OPENPORT
;
1614 if ((thflags
& TH_SYN
) == 0)
1616 if (th
->th_dport
== th
->th_sport
) {
1619 if (IN6_ARE_ADDR_EQUAL(&ip6
->ip6_dst
,
1624 if (ip
->ip_dst
.s_addr
== ip
->ip_src
.s_addr
)
1628 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
1629 * in_broadcast() should never return true on a received
1630 * packet with M_BCAST not set.
1632 * Packets with a multicast source address should also
1635 if (m
->m_flags
& (M_BCAST
|M_MCAST
))
1639 if (IN6_IS_ADDR_MULTICAST(&ip6
->ip6_dst
) ||
1640 IN6_IS_ADDR_MULTICAST(&ip6
->ip6_src
))
1644 if (IN_MULTICAST(ntohl(ip
->ip_dst
.s_addr
)) ||
1645 IN_MULTICAST(ntohl(ip
->ip_src
.s_addr
)) ||
1646 ip
->ip_src
.s_addr
== htonl(INADDR_BROADCAST
) ||
1647 in_broadcast(ip
->ip_dst
, m
->m_pkthdr
.rcvif
))
1651 MALLOC(sin6
, struct sockaddr_in6
*, sizeof *sin6
,
1652 M_SONAME
, M_NOWAIT
);
1655 bzero(sin6
, sizeof(*sin6
));
1656 sin6
->sin6_family
= AF_INET6
;
1657 sin6
->sin6_len
= sizeof(*sin6
);
1658 sin6
->sin6_addr
= ip6
->ip6_src
;
1659 sin6
->sin6_port
= th
->th_sport
;
1660 laddr6
= inp
->in6p_laddr
;
1661 if (IN6_IS_ADDR_UNSPECIFIED(&inp
->in6p_laddr
))
1662 inp
->in6p_laddr
= ip6
->ip6_dst
;
1663 if (in6_pcbconnect(inp
, (struct sockaddr
*)sin6
,
1665 inp
->in6p_laddr
= laddr6
;
1666 FREE(sin6
, M_SONAME
);
1669 FREE(sin6
, M_SONAME
);
1674 lck_mtx_assert(((struct inpcb
*)so
->so_pcb
)->inpcb_mtx
, LCK_MTX_ASSERT_OWNED
);
1676 MALLOC(sin
, struct sockaddr_in
*, sizeof *sin
, M_SONAME
,
1680 sin
->sin_family
= AF_INET
;
1681 sin
->sin_len
= sizeof(*sin
);
1682 sin
->sin_addr
= ip
->ip_src
;
1683 sin
->sin_port
= th
->th_sport
;
1684 bzero((caddr_t
)sin
->sin_zero
, sizeof(sin
->sin_zero
));
1685 laddr
= inp
->inp_laddr
;
1686 if (inp
->inp_laddr
.s_addr
== INADDR_ANY
)
1687 inp
->inp_laddr
= ip
->ip_dst
;
1688 if (in_pcbconnect(inp
, (struct sockaddr
*)sin
, proc0
)) {
1689 inp
->inp_laddr
= laddr
;
1690 FREE(sin
, M_SONAME
);
1693 FREE(sin
, M_SONAME
);
1696 tcp_dooptions(tp
, optp
, optlen
, th
, &to
);
1698 if (tp
->sack_enable
) {
1699 if (!(to
.to_flags
& TOF_SACK
))
1700 tp
->sack_enable
= 0;
1702 tp
->t_flags
|= TF_SACK_PERMIT
;
1708 tp
->iss
= tcp_new_isn(tp
);
1710 tp
->irs
= th
->th_seq
;
1711 tcp_sendseqinit(tp
);
1713 tp
->snd_recover
= tp
->snd_una
;
1715 * Initialization of the tcpcb for transaction;
1716 * set SND.WND = SEG.WND,
1717 * initialize CCsend and CCrecv.
1719 tp
->snd_wnd
= tiwin
; /* initial send-window */
1720 tp
->t_flags
|= TF_ACKNOW
;
1721 tp
->t_unacksegs
= 0;
1722 tp
->t_state
= TCPS_SYN_RECEIVED
;
1723 tp
->t_timer
[TCPT_KEEP
] = tcp_keepinit
;
1724 dropsocket
= 0; /* committed to socket */
1725 tcpstat
.tcps_accepts
++;
1726 if ((thflags
& (TH_ECE
| TH_CWR
)) == (TH_ECE
| TH_CWR
)) {
1728 tp
->ecn_flags
|= (TE_SETUPRECEIVED
| TE_SENDIPECT
);
1734 * If the state is SYN_RECEIVED:
1735 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1737 case TCPS_SYN_RECEIVED
:
1738 if ((thflags
& TH_ACK
) &&
1739 (SEQ_LEQ(th
->th_ack
, tp
->snd_una
) ||
1740 SEQ_GT(th
->th_ack
, tp
->snd_max
))) {
1741 rstreason
= BANDLIM_RST_OPENPORT
;
1747 * If the state is SYN_SENT:
1748 * if seg contains an ACK, but not for our SYN, drop the input.
1749 * if seg contains a RST, then drop the connection.
1750 * if seg does not contain SYN, then drop it.
1751 * Otherwise this is an acceptable SYN segment
1752 * initialize tp->rcv_nxt and tp->irs
1753 * if seg contains ack then advance tp->snd_una
1754 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1755 * arrange for segment to be acked (eventually)
1756 * continue processing rest of data/controls, beginning with URG
1759 if ((thflags
& TH_ACK
) &&
1760 (SEQ_LEQ(th
->th_ack
, tp
->iss
) ||
1761 SEQ_GT(th
->th_ack
, tp
->snd_max
))) {
1762 rstreason
= BANDLIM_UNLIMITED
;
1765 if (thflags
& TH_RST
) {
1766 if ((thflags
& TH_ACK
) != 0) {
1767 tp
= tcp_drop(tp
, ECONNREFUSED
);
1768 postevent(so
, 0, EV_RESET
);
1772 if ((thflags
& TH_SYN
) == 0)
1774 tp
->snd_wnd
= th
->th_win
; /* initial send window */
1776 tp
->irs
= th
->th_seq
;
1778 if (thflags
& TH_ACK
) {
1779 tcpstat
.tcps_connects
++;
1781 if ((thflags
& (TH_ECE
| TH_CWR
)) == (TH_ECE
)) {
1782 /* ECN-setup SYN-ACK */
1783 tp
->ecn_flags
|= TE_SETUPRECEIVED
;
1786 /* non-ECN-setup SYN-ACK */
1787 tp
->ecn_flags
&= ~TE_SENDIPECT
;
1790 #if CONFIG_MACF_NET && CONFIG_MACF_SOCKET
1791 /* XXXMAC: recursive lock: SOCK_LOCK(so); */
1792 mac_socketpeer_label_associate_mbuf(m
, so
);
1793 /* XXXMAC: SOCK_UNLOCK(so); */
1795 /* Do window scaling on this connection? */
1796 if ((tp
->t_flags
& (TF_RCVD_SCALE
|TF_REQ_SCALE
)) ==
1797 (TF_RCVD_SCALE
|TF_REQ_SCALE
)) {
1798 tp
->snd_scale
= tp
->requested_s_scale
;
1799 tp
->rcv_scale
= tp
->request_r_scale
;
1801 tp
->rcv_adv
+= tp
->rcv_wnd
;
1802 tp
->snd_una
++; /* SYN is acked */
1804 * If there's data, delay ACK; if there's also a FIN
1805 * ACKNOW will be turned on later.
1807 if (DELAY_ACK(tp
) && tlen
!= 0) {
1808 tp
->t_flags
|= TF_DELACK
;
1812 tp
->t_flags
|= TF_ACKNOW
;
1813 tp
->t_unacksegs
= 0;
1816 * Received <SYN,ACK> in SYN_SENT[*] state.
1818 * SYN_SENT --> ESTABLISHED
1819 * SYN_SENT* --> FIN_WAIT_1
1821 tp
->t_starttime
= 0;
1822 if (tp
->t_flags
& TF_NEEDFIN
) {
1823 tp
->t_state
= TCPS_FIN_WAIT_1
;
1824 tp
->t_flags
&= ~TF_NEEDFIN
;
1827 tp
->t_state
= TCPS_ESTABLISHED
;
1828 tp
->t_timer
[TCPT_KEEP
] = TCP_KEEPIDLE(tp
);
1830 /* soisconnected may lead to socket_unlock in case of upcalls,
1831 * make sure this is done when everything is setup.
1836 * Received initial SYN in SYN-SENT[*] state => simul-
1837 * taneous open. If segment contains CC option and there is
1838 * a cached CC, apply TAO test; if it succeeds, connection is
1839 * half-synchronized. Otherwise, do 3-way handshake:
1840 * SYN-SENT -> SYN-RECEIVED
1841 * SYN-SENT* -> SYN-RECEIVED*
1843 tp
->t_flags
|= TF_ACKNOW
;
1844 tp
->t_timer
[TCPT_REXMT
] = 0;
1845 tp
->t_state
= TCPS_SYN_RECEIVED
;
1851 * Advance th->th_seq to correspond to first data byte.
1852 * If data, trim to stay within window,
1853 * dropping FIN if necessary.
1856 if (tlen
> tp
->rcv_wnd
) {
1857 todrop
= tlen
- tp
->rcv_wnd
;
1861 tcpstat
.tcps_rcvpackafterwin
++;
1862 tcpstat
.tcps_rcvbyteafterwin
+= todrop
;
1864 tp
->snd_wl1
= th
->th_seq
- 1;
1865 tp
->rcv_up
= th
->th_seq
;
1867 * Client side of transaction: already sent SYN and data.
1868 * If the remote host used T/TCP to validate the SYN,
1869 * our data will be ACK'd; if so, enter normal data segment
1870 * processing in the middle of step 5, ack processing.
1871 * Otherwise, goto step 6.
1873 if (thflags
& TH_ACK
)
1877 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1878 * do normal processing.
1880 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
1884 case TCPS_TIME_WAIT
:
1885 break; /* continue normal processing */
1887 /* Received a SYN while connection is already established.
1888 * This is a "half open connection and other anomalies" described
1889 * in RFC793 page 34, send an ACK so the remote reset the connection
1890 * or recovers by adjusting its sequence numberering
1892 case TCPS_ESTABLISHED
:
1893 if (thflags
& TH_SYN
)
1899 * States other than LISTEN or SYN_SENT.
1900 * First check the RST flag and sequence number since reset segments
1901 * are exempt from the timestamp and connection count tests. This
1902 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1903 * below which allowed reset segments in half the sequence space
1904 * to fall though and be processed (which gives forged reset
1905 * segments with a random sequence number a 50 percent chance of
1906 * killing a connection).
1907 * Then check timestamp, if present.
1908 * Then check the connection count, if present.
1909 * Then check that at least some bytes of segment are within
1910 * receive window. If segment begins before rcv_nxt,
1911 * drop leading data (and SYN); if nothing left, just ack.
1914 * If the RST bit is set, check the sequence number to see
1915 * if this is a valid reset segment.
1917 * In all states except SYN-SENT, all reset (RST) segments
1918 * are validated by checking their SEQ-fields. A reset is
1919 * valid if its sequence number is in the window.
1920 * Note: this does not take into account delayed ACKs, so
1921 * we should test against last_ack_sent instead of rcv_nxt.
1922 * The sequence number in the reset segment is normally an
1923 * echo of our outgoing acknowlegement numbers, but some hosts
1924 * send a reset with the sequence number at the rightmost edge
1925 * of our receive window, and we have to handle this case.
1926 * Note 2: Paul Watson's paper "Slipping in the Window" has shown
1927 * that brute force RST attacks are possible. To combat this,
1928 * we use a much stricter check while in the ESTABLISHED state,
1929 * only accepting RSTs where the sequence number is equal to
1930 * last_ack_sent. In all other states (the states in which a
1931 * RST is more likely), the more permissive check is used.
1932 * If we have multiple segments in flight, the intial reset
1933 * segment sequence numbers will be to the left of last_ack_sent,
1934 * but they will eventually catch up.
1935 * In any case, it never made sense to trim reset segments to
1936 * fit the receive window since RFC 1122 says:
1937 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1939 * A TCP SHOULD allow a received RST segment to include data.
1942 * It has been suggested that a RST segment could contain
1943 * ASCII text that encoded and explained the cause of the
1944 * RST. No standard has yet been established for such
1947 * If the reset segment passes the sequence number test examine
1949 * SYN_RECEIVED STATE:
1950 * If passive open, return to LISTEN state.
1951 * If active open, inform user that connection was refused.
1952 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1953 * Inform user that connection was reset, and close tcb.
1954 * CLOSING, LAST_ACK STATES:
1957 * Drop the segment - see Stevens, vol. 2, p. 964 and
1960 * Radar 4803931: Allows for the case where we ACKed the FIN but
1961 * there is already a RST in flight from the peer.
1962 * In that case, accept the RST for non-established
1963 * state if it's one off from last_ack_sent.
1966 if (thflags
& TH_RST
) {
1967 if ((SEQ_GEQ(th
->th_seq
, tp
->last_ack_sent
) &&
1968 SEQ_LT(th
->th_seq
, tp
->last_ack_sent
+ tp
->rcv_wnd
)) ||
1969 (tp
->rcv_wnd
== 0 &&
1970 ((tp
->last_ack_sent
== th
->th_seq
) || ((tp
->last_ack_sent
-1) == th
->th_seq
)))) {
1971 switch (tp
->t_state
) {
1973 case TCPS_SYN_RECEIVED
:
1974 so
->so_error
= ECONNREFUSED
;
1977 case TCPS_ESTABLISHED
:
1978 if (tp
->last_ack_sent
!= th
->th_seq
) {
1979 tcpstat
.tcps_badrst
++;
1982 case TCPS_FIN_WAIT_1
:
1983 case TCPS_CLOSE_WAIT
:
1987 case TCPS_FIN_WAIT_2
:
1988 so
->so_error
= ECONNRESET
;
1990 postevent(so
, 0, EV_RESET
);
1991 tp
->t_state
= TCPS_CLOSED
;
1992 tcpstat
.tcps_drops
++;
2001 case TCPS_TIME_WAIT
:
2009 lck_mtx_assert(((struct inpcb
*)so
->so_pcb
)->inpcb_mtx
, LCK_MTX_ASSERT_OWNED
);
2013 * RFC 1323 PAWS: If we have a timestamp reply on this segment
2014 * and it's less than ts_recent, drop it.
2016 if ((to
.to_flags
& TOF_TS
) != 0 && tp
->ts_recent
&&
2017 TSTMP_LT(to
.to_tsval
, tp
->ts_recent
)) {
2019 /* Check to see if ts_recent is over 24 days old. */
2020 if ((int)(tcp_now
- tp
->ts_recent_age
) > TCP_PAWS_IDLE
) {
2022 * Invalidate ts_recent. If this segment updates
2023 * ts_recent, the age will be reset later and ts_recent
2024 * will get a valid value. If it does not, setting
2025 * ts_recent to zero will at least satisfy the
2026 * requirement that zero be placed in the timestamp
2027 * echo reply when ts_recent isn't valid. The
2028 * age isn't reset until we get a valid ts_recent
2029 * because we don't want out-of-order segments to be
2030 * dropped when ts_recent is old.
2034 tcpstat
.tcps_rcvduppack
++;
2035 tcpstat
.tcps_rcvdupbyte
+= tlen
;
2036 tcpstat
.tcps_pawsdrop
++;
2044 * In the SYN-RECEIVED state, validate that the packet belongs to
2045 * this connection before trimming the data to fit the receive
2046 * window. Check the sequence number versus IRS since we know
2047 * the sequence numbers haven't wrapped. This is a partial fix
2048 * for the "LAND" DoS attack.
2050 if (tp
->t_state
== TCPS_SYN_RECEIVED
&& SEQ_LT(th
->th_seq
, tp
->irs
)) {
2051 rstreason
= BANDLIM_RST_OPENPORT
;
2055 todrop
= tp
->rcv_nxt
- th
->th_seq
;
2057 if (thflags
& TH_SYN
) {
2067 * Following if statement from Stevens, vol. 2, p. 960.
2070 || (todrop
== tlen
&& (thflags
& TH_FIN
) == 0)) {
2072 * Any valid FIN must be to the left of the window.
2073 * At this point the FIN must be a duplicate or out
2074 * of sequence; drop it.
2079 * Send an ACK to resynchronize and drop any data.
2080 * But keep on processing for RST or ACK.
2082 tp
->t_flags
|= TF_ACKNOW
;
2083 tp
->t_unacksegs
= 0;
2085 tcpstat
.tcps_rcvduppack
++;
2086 tcpstat
.tcps_rcvdupbyte
+= todrop
;
2088 tcpstat
.tcps_rcvpartduppack
++;
2089 tcpstat
.tcps_rcvpartdupbyte
+= todrop
;
2091 drop_hdrlen
+= todrop
; /* drop from the top afterwards */
2092 th
->th_seq
+= todrop
;
2094 if (th
->th_urp
> todrop
)
2095 th
->th_urp
-= todrop
;
2103 * If new data are received on a connection after the
2104 * user processes are gone, then RST the other end.
2106 if ((so
->so_state
& SS_NOFDREF
) &&
2107 tp
->t_state
> TCPS_CLOSE_WAIT
&& tlen
) {
2109 tcpstat
.tcps_rcvafterclose
++;
2110 rstreason
= BANDLIM_UNLIMITED
;
2115 * If segment ends after window, drop trailing data
2116 * (and PUSH and FIN); if nothing left, just ACK.
2118 todrop
= (th
->th_seq
+tlen
) - (tp
->rcv_nxt
+tp
->rcv_wnd
);
2120 tcpstat
.tcps_rcvpackafterwin
++;
2121 if (todrop
>= tlen
) {
2122 tcpstat
.tcps_rcvbyteafterwin
+= tlen
;
2124 * If a new connection request is received
2125 * while in TIME_WAIT, drop the old connection
2126 * and start over if the sequence numbers
2127 * are above the previous ones.
2129 if (thflags
& TH_SYN
&&
2130 tp
->t_state
== TCPS_TIME_WAIT
&&
2131 SEQ_GT(th
->th_seq
, tp
->rcv_nxt
)) {
2132 iss
= tcp_new_isn(tp
);
2134 tcp_unlock(so
, 1, 0);
2138 * If window is closed can only take segments at
2139 * window edge, and have to drop data and PUSH from
2140 * incoming segments. Continue processing, but
2141 * remember to ack. Otherwise, drop segment
2144 if (tp
->rcv_wnd
== 0 && th
->th_seq
== tp
->rcv_nxt
) {
2145 tp
->t_flags
|= TF_ACKNOW
;
2146 tp
->t_unacksegs
= 0;
2147 tcpstat
.tcps_rcvwinprobe
++;
2151 tcpstat
.tcps_rcvbyteafterwin
+= todrop
;
2154 thflags
&= ~(TH_PUSH
|TH_FIN
);
2158 * If last ACK falls within this segment's sequence numbers,
2159 * record its timestamp.
2161 * 1) That the test incorporates suggestions from the latest
2162 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
2163 * 2) That updating only on newer timestamps interferes with
2164 * our earlier PAWS tests, so this check should be solely
2165 * predicated on the sequence space of this segment.
2166 * 3) That we modify the segment boundary check to be
2167 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
2168 * instead of RFC1323's
2169 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
2170 * This modified check allows us to overcome RFC1323's
2171 * limitations as described in Stevens TCP/IP Illustrated
2172 * Vol. 2 p.869. In such cases, we can still calculate the
2173 * RTT correctly when RCV.NXT == Last.ACK.Sent.
2175 if ((to
.to_flags
& TOF_TS
) != 0 &&
2176 SEQ_LEQ(th
->th_seq
, tp
->last_ack_sent
) &&
2177 SEQ_LEQ(tp
->last_ack_sent
, th
->th_seq
+ tlen
+
2178 ((thflags
& (TH_SYN
|TH_FIN
)) != 0))) {
2179 tp
->ts_recent_age
= tcp_now
;
2180 tp
->ts_recent
= to
.to_tsval
;
2184 * If a SYN is in the window, then this is an
2185 * error and we send an RST and drop the connection.
2187 if (thflags
& TH_SYN
) {
2188 tp
= tcp_drop(tp
, ECONNRESET
);
2189 rstreason
= BANDLIM_UNLIMITED
;
2190 postevent(so
, 0, EV_RESET
);
2195 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
2196 * flag is on (half-synchronized state), then queue data for
2197 * later processing; else drop segment and return.
2199 if ((thflags
& TH_ACK
) == 0) {
2200 if (tp
->t_state
== TCPS_SYN_RECEIVED
||
2201 (tp
->t_flags
& TF_NEEDSYN
))
2203 else if (tp
->t_flags
& TF_ACKNOW
)
2212 switch (tp
->t_state
) {
2215 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
2216 * ESTABLISHED state and continue processing.
2217 * The ACK was checked above.
2219 case TCPS_SYN_RECEIVED
:
2221 tcpstat
.tcps_connects
++;
2223 /* Do window scaling? */
2224 if ((tp
->t_flags
& (TF_RCVD_SCALE
|TF_REQ_SCALE
)) ==
2225 (TF_RCVD_SCALE
|TF_REQ_SCALE
)) {
2226 tp
->snd_scale
= tp
->requested_s_scale
;
2227 tp
->rcv_scale
= tp
->request_r_scale
;
2231 * SYN-RECEIVED -> ESTABLISHED
2232 * SYN-RECEIVED* -> FIN-WAIT-1
2234 tp
->t_starttime
= 0;
2235 if (tp
->t_flags
& TF_NEEDFIN
) {
2236 tp
->t_state
= TCPS_FIN_WAIT_1
;
2237 tp
->t_flags
&= ~TF_NEEDFIN
;
2239 tp
->t_state
= TCPS_ESTABLISHED
;
2240 tp
->t_timer
[TCPT_KEEP
] = TCP_KEEPIDLE(tp
);
2243 * If segment contains data or ACK, will call tcp_reass()
2244 * later; if not, do so now to pass queued data to user.
2246 if (tlen
== 0 && (thflags
& TH_FIN
) == 0)
2247 (void) tcp_reass(tp
, (struct tcphdr
*)0, &tlen
,
2249 tp
->snd_wl1
= th
->th_seq
- 1;
2253 /* soisconnected may lead to socket_unlock in case of upcalls,
2254 * make sure this is done when everything is setup.
2259 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2260 * ACKs. If the ack is in the range
2261 * tp->snd_una < th->th_ack <= tp->snd_max
2262 * then advance tp->snd_una to th->th_ack and drop
2263 * data from the retransmission queue. If this ACK reflects
2264 * more up to date window information we update our window information.
2266 case TCPS_ESTABLISHED
:
2267 case TCPS_FIN_WAIT_1
:
2268 case TCPS_FIN_WAIT_2
:
2269 case TCPS_CLOSE_WAIT
:
2272 case TCPS_TIME_WAIT
:
2273 if (SEQ_GT(th
->th_ack
, tp
->snd_max
)) {
2274 tcpstat
.tcps_rcvacktoomuch
++;
2277 if (tp
->sack_enable
&&
2278 (to
.to_nsacks
> 0 || !TAILQ_EMPTY(&tp
->snd_holes
)))
2279 tcp_sack_doack(tp
, &to
, th
->th_ack
);
2280 if (SEQ_LEQ(th
->th_ack
, tp
->snd_una
)) {
2281 if (tlen
== 0 && tiwin
== tp
->snd_wnd
) {
2282 tcpstat
.tcps_rcvdupack
++;
2284 * If we have outstanding data (other than
2285 * a window probe), this is a completely
2286 * duplicate ack (ie, window info didn't
2287 * change), the ack is the biggest we've
2288 * seen and we've seen exactly our rexmt
2289 * threshhold of them, assume a packet
2290 * has been dropped and retransmit it.
2291 * Kludge snd_nxt & the congestion
2292 * window so we send only this one
2295 * We know we're losing at the current
2296 * window size so do congestion avoidance
2297 * (set ssthresh to half the current window
2298 * and pull our congestion window back to
2299 * the new ssthresh).
2301 * Dup acks mean that packets have left the
2302 * network (they're now cached at the receiver)
2303 * so bump cwnd by the amount in the receiver
2304 * to keep a constant cwnd packets in the
2307 if (tp
->t_timer
[TCPT_REXMT
] == 0 ||
2308 th
->th_ack
!= tp
->snd_una
)
2310 else if (++tp
->t_dupacks
> tcprexmtthresh
||
2311 ((tcp_do_newreno
|| tp
->sack_enable
) &&
2312 IN_FASTRECOVERY(tp
))) {
2313 if (tp
->sack_enable
&& IN_FASTRECOVERY(tp
)) {
2317 * Compute the amount of data in flight first.
2318 * We can inject new data into the pipe iff
2319 * we have less than 1/2 the original window's
2320 * worth of data in flight.
2322 awnd
= (tp
->snd_nxt
- tp
->snd_fack
) +
2323 tp
->sackhint
.sack_bytes_rexmit
;
2324 if (awnd
< tp
->snd_ssthresh
) {
2325 tp
->snd_cwnd
+= tp
->t_maxseg
;
2326 if (tp
->snd_cwnd
> tp
->snd_ssthresh
)
2327 tp
->snd_cwnd
= tp
->snd_ssthresh
;
2330 tp
->snd_cwnd
+= tp
->t_maxseg
;
2331 tp
->t_unacksegs
= 0;
2332 (void) tcp_output(tp
);
2334 } else if (tp
->t_dupacks
== tcprexmtthresh
) {
2335 tcp_seq onxt
= tp
->snd_nxt
;
2339 * If we're doing sack, check to
2340 * see if we're already in sack
2341 * recovery. If we're not doing sack,
2342 * check to see if we're in newreno
2345 if (tp
->sack_enable
) {
2346 if (IN_FASTRECOVERY(tp
)) {
2350 } else if (tcp_do_newreno
) {
2351 if (SEQ_LEQ(th
->th_ack
,
2357 win
= min(tp
->snd_wnd
, tp
->snd_cwnd
) /
2361 tp
->snd_ssthresh
= win
* tp
->t_maxseg
;
2362 ENTER_FASTRECOVERY(tp
);
2363 tp
->snd_recover
= tp
->snd_max
;
2364 tp
->t_timer
[TCPT_REXMT
] = 0;
2366 tp
->ecn_flags
|= TE_SENDCWR
;
2367 if (tp
->sack_enable
) {
2368 tcpstat
.tcps_sack_recovery_episode
++;
2369 tp
->sack_newdata
= tp
->snd_nxt
;
2370 tp
->snd_cwnd
= tp
->t_maxseg
;
2371 tp
->t_unacksegs
= 0;
2372 (void) tcp_output(tp
);
2375 tp
->snd_nxt
= th
->th_ack
;
2376 tp
->snd_cwnd
= tp
->t_maxseg
;
2377 tp
->t_unacksegs
= 0;
2378 (void) tcp_output(tp
);
2379 tp
->snd_cwnd
= tp
->snd_ssthresh
+
2380 tp
->t_maxseg
* tp
->t_dupacks
;
2381 if (SEQ_GT(onxt
, tp
->snd_nxt
))
2390 * If the congestion window was inflated to account
2391 * for the other side's cached packets, retract it.
2393 if (tcp_do_newreno
|| tp
->sack_enable
) {
2394 if (IN_FASTRECOVERY(tp
)) {
2395 if (SEQ_LT(th
->th_ack
, tp
->snd_recover
)) {
2396 if (tp
->sack_enable
)
2397 tcp_sack_partialack(tp
, th
);
2399 tcp_newreno_partial_ack(tp
, th
);
2402 * Out of fast recovery.
2403 * Window inflation should have left us
2404 * with approximately snd_ssthresh
2406 * But in case we would be inclined to
2407 * send a burst, better to do it via
2408 * the slow start mechanism.
2410 if (SEQ_GT(th
->th_ack
+
2413 tp
->snd_cwnd
= tp
->snd_max
-
2417 tp
->snd_cwnd
= tp
->snd_ssthresh
;
2421 if (tp
->t_dupacks
>= tcprexmtthresh
&&
2422 tp
->snd_cwnd
> tp
->snd_ssthresh
)
2423 tp
->snd_cwnd
= tp
->snd_ssthresh
;
2426 tp
->t_bytes_acked
= 0;
2428 * If we reach this point, ACK is not a duplicate,
2429 * i.e., it ACKs something we sent.
2431 if (tp
->t_flags
& TF_NEEDSYN
) {
2433 * T/TCP: Connection was half-synchronized, and our
2434 * SYN has been ACK'd (so connection is now fully
2435 * synchronized). Go to non-starred state,
2436 * increment snd_una for ACK of SYN, and check if
2437 * we can do window scaling.
2439 tp
->t_flags
&= ~TF_NEEDSYN
;
2441 /* Do window scaling? */
2442 if ((tp
->t_flags
& (TF_RCVD_SCALE
|TF_REQ_SCALE
)) ==
2443 (TF_RCVD_SCALE
|TF_REQ_SCALE
)) {
2444 tp
->snd_scale
= tp
->requested_s_scale
;
2445 tp
->rcv_scale
= tp
->request_r_scale
;
2450 acked
= th
->th_ack
- tp
->snd_una
;
2451 tcpstat
.tcps_rcvackpack
++;
2452 tcpstat
.tcps_rcvackbyte
+= acked
;
2455 * If we just performed our first retransmit, and the ACK
2456 * arrives within our recovery window, then it was a mistake
2457 * to do the retransmit in the first place. Recover our
2458 * original cwnd and ssthresh, and proceed to transmit where
2461 if (tp
->t_rxtshift
== 1 && tcp_now
< tp
->t_badrxtwin
) {
2462 ++tcpstat
.tcps_sndrexmitbad
;
2463 tp
->snd_cwnd
= tp
->snd_cwnd_prev
;
2464 tp
->snd_ssthresh
= tp
->snd_ssthresh_prev
;
2465 tp
->snd_recover
= tp
->snd_recover_prev
;
2466 if (tp
->t_flags
& TF_WASFRECOVERY
)
2467 ENTER_FASTRECOVERY(tp
);
2468 tp
->snd_nxt
= tp
->snd_max
;
2469 tp
->t_badrxtwin
= 0; /* XXX probably not required */
2473 * If we have a timestamp reply, update smoothed
2474 * round trip time. If no timestamp is present but
2475 * transmit timer is running and timed sequence
2476 * number was acked, update smoothed round trip time.
2477 * Since we now have an rtt measurement, cancel the
2478 * timer backoff (cf., Phil Karn's retransmit alg.).
2479 * Recompute the initial retransmit timer.
2480 * Also makes sure we have a valid time stamp in hand
2482 * Some boxes send broken timestamp replies
2483 * during the SYN+ACK phase, ignore
2484 * timestamps of 0 or we could calculate a
2485 * huge RTT and blow up the retransmit timer.
2487 if (((to
.to_flags
& TOF_TS
) != 0) && (to
.to_tsecr
!= 0)) {
2488 if (!tp
->t_rttlow
|| tp
->t_rttlow
> tcp_now
- to
.to_tsecr
)
2489 tp
->t_rttlow
= tcp_now
- to
.to_tsecr
;
2490 tcp_xmit_timer(tp
, tcp_now
- to
.to_tsecr
);
2491 } else if (tp
->t_rtttime
&& SEQ_GT(th
->th_ack
, tp
->t_rtseq
)) {
2492 if (!tp
->t_rttlow
|| tp
->t_rttlow
> tcp_now
- tp
->t_rtttime
)
2493 tp
->t_rttlow
= tcp_now
- tp
->t_rtttime
;
2494 tcp_xmit_timer(tp
, tp
->t_rtttime
);
2498 * If all outstanding data is acked, stop retransmit
2499 * timer and remember to restart (more output or persist).
2500 * If there is more data to be acked, restart retransmit
2501 * timer, using current (possibly backed-off) value.
2503 if (th
->th_ack
== tp
->snd_max
) {
2504 tp
->t_timer
[TCPT_REXMT
] = 0;
2506 } else if (tp
->t_timer
[TCPT_PERSIST
] == 0)
2507 tp
->t_timer
[TCPT_REXMT
] = tp
->t_rxtcur
;
2510 * If no data (only SYN) was ACK'd,
2511 * skip rest of ACK processing.
2517 * When new data is acked, open the congestion window.
2519 if ((thflags
& TH_ECE
) != 0 &&
2520 (tp
->ecn_flags
& TE_SETUPSENT
) != 0) {
2522 * Reduce the congestion window if we haven't done so.
2524 if (!(tp
->sack_enable
&& IN_FASTRECOVERY(tp
)) &&
2525 !(tcp_do_newreno
&& SEQ_LEQ(th
->th_ack
, tp
->snd_recover
))) {
2526 tcp_reduce_congestion_window(tp
);
2528 } else if ((!tcp_do_newreno
&& !tp
->sack_enable
) ||
2529 !IN_FASTRECOVERY(tp
)) {
2531 * RFC 3465 - Appropriate Byte Counting.
2533 * If the window is currently less than ssthresh,
2534 * open the window by the number of bytes ACKed by
2535 * the last ACK, however clamp the window increase
2536 * to an upper limit "L".
2538 * In congestion avoidance phase, open the window by
2539 * one segment each time "bytes_acked" grows to be
2540 * greater than or equal to the congestion window.
2543 register u_int cw
= tp
->snd_cwnd
;
2544 register u_int incr
= tp
->t_maxseg
;
2546 if ((acked
> incr
) && tcp_do_rfc3465
) {
2547 if (cw
>= tp
->snd_ssthresh
) {
2548 tp
->t_bytes_acked
+= acked
;
2549 if (tp
->t_bytes_acked
>= cw
) {
2550 /* Time to increase the window. */
2551 tp
->t_bytes_acked
-= cw
;
2553 /* No need to increase yet. */
2558 * If the user explicitly enables RFC3465
2559 * use 2*SMSS for the "L" param. Otherwise
2560 * use the more conservative 1*SMSS.
2562 * (See RFC 3465 2.3 Choosing the Limit)
2566 abc_lim
= (tcp_do_rfc3465
== 0) ?
2568 incr
= lmin(acked
, abc_lim
);
2573 * If the window gives us less than ssthresh packets
2574 * in flight, open exponentially (segsz per packet).
2575 * Otherwise open linearly: segsz per window
2576 * (segsz^2 / cwnd per packet).
2579 if (cw
>= tp
->snd_ssthresh
) {
2580 incr
= incr
* incr
/ cw
;
2585 tp
->snd_cwnd
= min(cw
+incr
, TCP_MAXWIN
<<tp
->snd_scale
);
2587 if (acked
> so
->so_snd
.sb_cc
) {
2588 tp
->snd_wnd
-= so
->so_snd
.sb_cc
;
2589 sbdrop(&so
->so_snd
, (int)so
->so_snd
.sb_cc
);
2592 sbdrop(&so
->so_snd
, acked
);
2593 tp
->snd_wnd
-= acked
;
2596 /* detect una wraparound */
2597 if ((tcp_do_newreno
|| tp
->sack_enable
) &&
2598 !IN_FASTRECOVERY(tp
) &&
2599 SEQ_GT(tp
->snd_una
, tp
->snd_recover
) &&
2600 SEQ_LEQ(th
->th_ack
, tp
->snd_recover
))
2601 tp
->snd_recover
= th
->th_ack
- 1;
2602 if ((tcp_do_newreno
|| tp
->sack_enable
) &&
2603 IN_FASTRECOVERY(tp
) &&
2604 SEQ_GEQ(th
->th_ack
, tp
->snd_recover
))
2605 EXIT_FASTRECOVERY(tp
);
2606 tp
->snd_una
= th
->th_ack
;
2607 if (tp
->sack_enable
) {
2608 if (SEQ_GT(tp
->snd_una
, tp
->snd_recover
))
2609 tp
->snd_recover
= tp
->snd_una
;
2611 if (SEQ_LT(tp
->snd_nxt
, tp
->snd_una
))
2612 tp
->snd_nxt
= tp
->snd_una
;
2615 * sowwakeup must happen after snd_una, et al. are updated so that
2616 * the sequence numbers are in sync with so_snd
2620 switch (tp
->t_state
) {
2623 * In FIN_WAIT_1 STATE in addition to the processing
2624 * for the ESTABLISHED state if our FIN is now acknowledged
2625 * then enter FIN_WAIT_2.
2627 case TCPS_FIN_WAIT_1
:
2628 if (ourfinisacked
) {
2630 * If we can't receive any more
2631 * data, then closing user can proceed.
2632 * Starting the timer is contrary to the
2633 * specification, but if we don't get a FIN
2634 * we'll hang forever.
2636 if (so
->so_state
& SS_CANTRCVMORE
) {
2637 tp
->t_timer
[TCPT_2MSL
] = tcp_maxidle
;
2638 add_to_time_wait(tp
);
2639 soisdisconnected(so
);
2641 tp
->t_state
= TCPS_FIN_WAIT_2
;
2647 * In CLOSING STATE in addition to the processing for
2648 * the ESTABLISHED state if the ACK acknowledges our FIN
2649 * then enter the TIME-WAIT state, otherwise ignore
2653 if (ourfinisacked
) {
2654 tp
->t_state
= TCPS_TIME_WAIT
;
2655 tcp_canceltimers(tp
);
2656 /* Shorten TIME_WAIT [RFC-1644, p.28] */
2657 if (tp
->cc_recv
!= 0 &&
2658 tp
->t_starttime
< (u_long
)tcp_msl
)
2659 tp
->t_timer
[TCPT_2MSL
] =
2660 tp
->t_rxtcur
* TCPTV_TWTRUNC
;
2662 tp
->t_timer
[TCPT_2MSL
] = 2 * tcp_msl
;
2663 add_to_time_wait(tp
);
2664 soisdisconnected(so
);
2669 * In LAST_ACK, we may still be waiting for data to drain
2670 * and/or to be acked, as well as for the ack of our FIN.
2671 * If our FIN is now acknowledged, delete the TCB,
2672 * enter the closed state and return.
2675 if (ourfinisacked
) {
2682 * In TIME_WAIT state the only thing that should arrive
2683 * is a retransmission of the remote FIN. Acknowledge
2684 * it and restart the finack timer.
2686 case TCPS_TIME_WAIT
:
2687 tp
->t_timer
[TCPT_2MSL
] = 2 * tcp_msl
;
2688 add_to_time_wait(tp
);
2695 * Update window information.
2696 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2698 if ((thflags
& TH_ACK
) &&
2699 (SEQ_LT(tp
->snd_wl1
, th
->th_seq
) ||
2700 (tp
->snd_wl1
== th
->th_seq
&& (SEQ_LT(tp
->snd_wl2
, th
->th_ack
) ||
2701 (tp
->snd_wl2
== th
->th_ack
&& tiwin
> tp
->snd_wnd
))))) {
2702 /* keep track of pure window updates */
2704 tp
->snd_wl2
== th
->th_ack
&& tiwin
> tp
->snd_wnd
)
2705 tcpstat
.tcps_rcvwinupd
++;
2706 tp
->snd_wnd
= tiwin
;
2707 tp
->snd_wl1
= th
->th_seq
;
2708 tp
->snd_wl2
= th
->th_ack
;
2709 if (tp
->snd_wnd
> tp
->max_sndwnd
)
2710 tp
->max_sndwnd
= tp
->snd_wnd
;
2715 * Process segments with URG.
2717 if ((thflags
& TH_URG
) && th
->th_urp
&&
2718 TCPS_HAVERCVDFIN(tp
->t_state
) == 0) {
2720 * This is a kludge, but if we receive and accept
2721 * random urgent pointers, we'll crash in
2722 * soreceive. It's hard to imagine someone
2723 * actually wanting to send this much urgent data.
2725 if (th
->th_urp
+ so
->so_rcv
.sb_cc
> sb_max
) {
2726 th
->th_urp
= 0; /* XXX */
2727 thflags
&= ~TH_URG
; /* XXX */
2728 goto dodata
; /* XXX */
2731 * If this segment advances the known urgent pointer,
2732 * then mark the data stream. This should not happen
2733 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2734 * a FIN has been received from the remote side.
2735 * In these states we ignore the URG.
2737 * According to RFC961 (Assigned Protocols),
2738 * the urgent pointer points to the last octet
2739 * of urgent data. We continue, however,
2740 * to consider it to indicate the first octet
2741 * of data past the urgent section as the original
2742 * spec states (in one of two places).
2744 if (SEQ_GT(th
->th_seq
+th
->th_urp
, tp
->rcv_up
)) {
2745 tp
->rcv_up
= th
->th_seq
+ th
->th_urp
;
2746 so
->so_oobmark
= so
->so_rcv
.sb_cc
+
2747 (tp
->rcv_up
- tp
->rcv_nxt
) - 1;
2748 if (so
->so_oobmark
== 0) {
2749 so
->so_state
|= SS_RCVATMARK
;
2750 postevent(so
, 0, EV_OOB
);
2753 tp
->t_oobflags
&= ~(TCPOOB_HAVEDATA
| TCPOOB_HADDATA
);
2756 * Remove out of band data so doesn't get presented to user.
2757 * This can happen independent of advancing the URG pointer,
2758 * but if two URG's are pending at once, some out-of-band
2759 * data may creep in... ick.
2761 if (th
->th_urp
<= (u_long
)tlen
2763 && (so
->so_options
& SO_OOBINLINE
) == 0
2766 tcp_pulloutofband(so
, th
, m
,
2767 drop_hdrlen
); /* hdr drop is delayed */
2770 * If no out of band data is expected,
2771 * pull receive urgent pointer along
2772 * with the receive window.
2774 if (SEQ_GT(tp
->rcv_nxt
, tp
->rcv_up
))
2775 tp
->rcv_up
= tp
->rcv_nxt
;
2779 * Process the segment text, merging it into the TCP sequencing queue,
2780 * and arranging for acknowledgment of receipt if necessary.
2781 * This process logically involves adjusting tp->rcv_wnd as data
2782 * is presented to the user (this happens in tcp_usrreq.c,
2783 * case PRU_RCVD). If a FIN has already been received on this
2784 * connection then we just ignore the text.
2786 if ((tlen
|| (thflags
&TH_FIN
)) &&
2787 TCPS_HAVERCVDFIN(tp
->t_state
) == 0) {
2788 tcp_seq save_start
= th
->th_seq
;
2789 tcp_seq save_end
= th
->th_seq
+ tlen
;
2790 m_adj(m
, drop_hdrlen
); /* delayed header drop */
2792 * Insert segment which includes th into TCP reassembly queue
2793 * with control block tp. Set thflags to whether reassembly now
2794 * includes a segment with FIN. This handles the common case
2795 * inline (segment is the next to be received on an established
2796 * connection, and the queue is empty), avoiding linkage into
2797 * and removal from the queue and repetition of various
2799 * Set DELACK for segments received in order, but ack
2800 * immediately when segments are out of order (so
2801 * fast retransmit can work).
2803 if (th
->th_seq
== tp
->rcv_nxt
&&
2804 LIST_EMPTY(&tp
->t_segq
) &&
2805 TCPS_HAVEESTABLISHED(tp
->t_state
)) {
2806 if (DELAY_ACK(tp
) && ((tp
->t_flags
& TF_ACKNOW
) == 0)) {
2807 tp
->t_flags
|= TF_DELACK
;
2811 tp
->t_unacksegs
= 0;
2812 tp
->t_flags
|= TF_ACKNOW
;
2814 tp
->rcv_nxt
+= tlen
;
2815 thflags
= th
->th_flags
& TH_FIN
;
2816 tcpstat
.tcps_rcvpack
++;
2817 tcpstat
.tcps_rcvbyte
+= tlen
;
2819 if (sbappendstream(&so
->so_rcv
, m
))
2822 thflags
= tcp_reass(tp
, th
, &tlen
, m
);
2823 tp
->t_flags
|= TF_ACKNOW
;
2824 tp
->t_unacksegs
= 0;
2827 if (tlen
> 0 && tp
->sack_enable
)
2828 tcp_update_sack_list(tp
, save_start
, save_end
);
2830 if (tp
->t_flags
& TF_DELACK
)
2834 KERNEL_DEBUG(DBG_LAYER_END
, ((th
->th_dport
<< 16) | th
->th_sport
),
2835 (((ip6
->ip6_src
.s6_addr16
[0]) << 16) | (ip6
->ip6_dst
.s6_addr16
[0])),
2836 th
->th_seq
, th
->th_ack
, th
->th_win
);
2841 KERNEL_DEBUG(DBG_LAYER_END
, ((th
->th_dport
<< 16) | th
->th_sport
),
2842 (((ip
->ip_src
.s_addr
& 0xffff) << 16) | (ip
->ip_dst
.s_addr
& 0xffff)),
2843 th
->th_seq
, th
->th_ack
, th
->th_win
);
2848 * Note the amount of data that peer has sent into
2849 * our window, in order to estimate the sender's
2852 len
= (u_int
)(so
->so_rcv
.sb_hiwat
- (tp
->rcv_adv
- tp
->rcv_nxt
));
2853 if (len
> so
->so_rcv
.sb_maxused
)
2854 so
->so_rcv
.sb_maxused
= len
;
2861 * If FIN is received ACK the FIN and let the user know
2862 * that the connection is closing.
2864 if (thflags
& TH_FIN
) {
2865 if (TCPS_HAVERCVDFIN(tp
->t_state
) == 0) {
2867 postevent(so
, 0, EV_FIN
);
2869 * If connection is half-synchronized
2870 * (ie NEEDSYN flag on) then delay ACK,
2871 * If connection is half-synchronized
2872 * (ie NEEDSYN flag on) then delay ACK,
2873 * so it may be piggybacked when SYN is sent.
2874 * Otherwise, since we received a FIN then no
2875 * more input can be expected, send ACK now.
2877 if (DELAY_ACK(tp
) && (tp
->t_flags
& TF_NEEDSYN
)) {
2878 tp
->t_flags
|= TF_DELACK
;
2882 tp
->t_flags
|= TF_ACKNOW
;
2883 tp
->t_unacksegs
= 0;
2887 switch (tp
->t_state
) {
2890 * In SYN_RECEIVED and ESTABLISHED STATES
2891 * enter the CLOSE_WAIT state.
2893 case TCPS_SYN_RECEIVED
:
2894 tp
->t_starttime
= 0;
2895 case TCPS_ESTABLISHED
:
2896 tp
->t_state
= TCPS_CLOSE_WAIT
;
2900 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2901 * enter the CLOSING state.
2903 case TCPS_FIN_WAIT_1
:
2904 tp
->t_state
= TCPS_CLOSING
;
2908 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2909 * starting the time-wait timer, turning off the other
2912 case TCPS_FIN_WAIT_2
:
2913 tp
->t_state
= TCPS_TIME_WAIT
;
2914 tcp_canceltimers(tp
);
2915 /* Shorten TIME_WAIT [RFC-1644, p.28] */
2916 if (tp
->cc_recv
!= 0 &&
2917 tp
->t_starttime
< (u_long
)tcp_msl
) {
2918 tp
->t_timer
[TCPT_2MSL
] =
2919 tp
->t_rxtcur
* TCPTV_TWTRUNC
;
2920 /* For transaction client, force ACK now. */
2921 tp
->t_flags
|= TF_ACKNOW
;
2922 tp
->t_unacksegs
= 0;
2925 tp
->t_timer
[TCPT_2MSL
] = 2 * tcp_msl
;
2927 add_to_time_wait(tp
);
2928 soisdisconnected(so
);
2932 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2934 case TCPS_TIME_WAIT
:
2935 tp
->t_timer
[TCPT_2MSL
] = 2 * tcp_msl
;
2936 add_to_time_wait(tp
);
2941 if (so
->so_options
& SO_DEBUG
)
2942 tcp_trace(TA_INPUT
, ostate
, tp
, (void *)tcp_saveipgen
,
2947 * Return any desired output.
2949 if (needoutput
|| (tp
->t_flags
& TF_ACKNOW
)) {
2950 tp
->t_unacksegs
= 0;
2951 (void) tcp_output(tp
);
2953 tcp_unlock(so
, 1, 0);
2954 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
2959 * Generate an ACK dropping incoming segment if it occupies
2960 * sequence space, where the ACK reflects our state.
2962 * We can now skip the test for the RST flag since all
2963 * paths to this code happen after packets containing
2964 * RST have been dropped.
2966 * In the SYN-RECEIVED state, don't send an ACK unless the
2967 * segment we received passes the SYN-RECEIVED ACK test.
2968 * If it fails send a RST. This breaks the loop in the
2969 * "LAND" DoS attack, and also prevents an ACK storm
2970 * between two listening ports that have been sent forged
2971 * SYN segments, each with the source address of the other.
2973 if (tp
->t_state
== TCPS_SYN_RECEIVED
&& (thflags
& TH_ACK
) &&
2974 (SEQ_GT(tp
->snd_una
, th
->th_ack
) ||
2975 SEQ_GT(th
->th_ack
, tp
->snd_max
)) ) {
2976 rstreason
= BANDLIM_RST_OPENPORT
;
2980 if (so
->so_options
& SO_DEBUG
)
2981 tcp_trace(TA_DROP
, ostate
, tp
, (void *)tcp_saveipgen
,
2985 tp
->t_flags
|= TF_ACKNOW
;
2986 tp
->t_unacksegs
= 0;
2987 (void) tcp_output(tp
);
2988 tcp_unlock(so
, 1, 0);
2989 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
2991 dropwithresetnosock
:
2995 * Generate a RST, dropping incoming segment.
2996 * Make ACK acceptable to originator of segment.
2997 * Don't bother to respond if destination was broadcast/multicast.
2999 if ((thflags
& TH_RST
) || m
->m_flags
& (M_BCAST
|M_MCAST
))
3003 if (IN6_IS_ADDR_MULTICAST(&ip6
->ip6_dst
) ||
3004 IN6_IS_ADDR_MULTICAST(&ip6
->ip6_src
))
3008 if (IN_MULTICAST(ntohl(ip
->ip_dst
.s_addr
)) ||
3009 IN_MULTICAST(ntohl(ip
->ip_src
.s_addr
)) ||
3010 ip
->ip_src
.s_addr
== htonl(INADDR_BROADCAST
) ||
3011 in_broadcast(ip
->ip_dst
, m
->m_pkthdr
.rcvif
))
3013 /* IPv6 anycast check is done at tcp6_input() */
3016 * Perform bandwidth limiting.
3019 if (badport_bandlim(rstreason
) < 0)
3024 if (tp
== 0 || (tp
->t_inpcb
->inp_socket
->so_options
& SO_DEBUG
))
3025 tcp_trace(TA_DROP
, ostate
, tp
, (void *)tcp_saveipgen
,
3028 if (thflags
& TH_ACK
)
3029 /* mtod() below is safe as long as hdr dropping is delayed */
3030 tcp_respond(tp
, mtod(m
, void *), th
, m
, (tcp_seq
)0, th
->th_ack
,
3031 TH_RST
, m
->m_pkthdr
.rcvif
);
3033 if (thflags
& TH_SYN
)
3035 /* mtod() below is safe as long as hdr dropping is delayed */
3036 tcp_respond(tp
, mtod(m
, void *), th
, m
, th
->th_seq
+tlen
,
3037 (tcp_seq
)0, TH_RST
|TH_ACK
, m
->m_pkthdr
.rcvif
);
3039 /* destroy temporarily created socket */
3042 tcp_unlock(so
, 1, 0);
3045 if ((inp
!= NULL
) && (nosock
== 0))
3046 tcp_unlock(so
, 1, 0);
3047 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
3053 * Drop space held by incoming segment and return.
3056 if (tp
== 0 || (tp
->t_inpcb
->inp_socket
->so_options
& SO_DEBUG
))
3057 tcp_trace(TA_DROP
, ostate
, tp
, (void *)tcp_saveipgen
,
3061 /* destroy temporarily created socket */
3064 tcp_unlock(so
, 1, 0);
3068 tcp_unlock(so
, 1, 0);
3069 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
3074 tcp_dooptions(tp
, cp
, cnt
, th
, to
)
3076 * Parse TCP options and place in tcpopt.
3087 for (; cnt
> 0; cnt
-= optlen
, cp
+= optlen
) {
3089 if (opt
== TCPOPT_EOL
)
3091 if (opt
== TCPOPT_NOP
)
3097 if (optlen
< 2 || optlen
> cnt
)
3106 if (optlen
!= TCPOLEN_MAXSEG
)
3108 if (!(th
->th_flags
& TH_SYN
))
3110 bcopy((char *) cp
+ 2, (char *) &mss
, sizeof(mss
));
3115 if (optlen
!= TCPOLEN_WINDOW
)
3117 if (!(th
->th_flags
& TH_SYN
))
3119 tp
->t_flags
|= TF_RCVD_SCALE
;
3120 tp
->requested_s_scale
= min(cp
[2], TCP_MAX_WINSHIFT
);
3123 case TCPOPT_TIMESTAMP
:
3124 if (optlen
!= TCPOLEN_TIMESTAMP
)
3126 to
->to_flags
|= TOF_TS
;
3127 bcopy((char *)cp
+ 2,
3128 (char *)&to
->to_tsval
, sizeof(to
->to_tsval
));
3129 NTOHL(to
->to_tsval
);
3130 bcopy((char *)cp
+ 6,
3131 (char *)&to
->to_tsecr
, sizeof(to
->to_tsecr
));
3132 NTOHL(to
->to_tsecr
);
3135 * A timestamp received in a SYN makes
3136 * it ok to send timestamp requests and replies.
3138 if (th
->th_flags
& TH_SYN
) {
3139 tp
->t_flags
|= TF_RCVD_TSTMP
;
3140 tp
->ts_recent
= to
->to_tsval
;
3141 tp
->ts_recent_age
= tcp_now
;
3144 case TCPOPT_SACK_PERMITTED
:
3146 optlen
!= TCPOLEN_SACK_PERMITTED
)
3148 if (th
->th_flags
& TH_SYN
)
3149 to
->to_flags
|= TOF_SACK
;
3152 if (optlen
<= 2 || (optlen
- 2) % TCPOLEN_SACK
!= 0)
3154 to
->to_nsacks
= (optlen
- 2) / TCPOLEN_SACK
;
3155 to
->to_sacks
= cp
+ 2;
3156 tcpstat
.tcps_sack_rcv_blocks
++;
3161 if (th
->th_flags
& TH_SYN
)
3162 tcp_mss(tp
, mss
); /* sets t_maxseg */
3166 * Pull out of band byte out of a segment so
3167 * it doesn't appear in the user's data queue.
3168 * It is still reflected in the segment length for
3169 * sequencing purposes.
3172 tcp_pulloutofband(so
, th
, m
, off
)
3175 register struct mbuf
*m
;
3176 int off
; /* delayed to be droped hdrlen */
3178 int cnt
= off
+ th
->th_urp
- 1;
3181 if (m
->m_len
> cnt
) {
3182 char *cp
= mtod(m
, caddr_t
) + cnt
;
3183 struct tcpcb
*tp
= sototcpcb(so
);
3186 tp
->t_oobflags
|= TCPOOB_HAVEDATA
;
3187 bcopy(cp
+1, cp
, (unsigned)(m
->m_len
- cnt
- 1));
3189 if (m
->m_flags
& M_PKTHDR
)
3198 panic("tcp_pulloutofband");
3202 * Collect new round-trip time estimate
3203 * and update averages and current timeout.
3206 tcp_xmit_timer(tp
, rtt
)
3207 register struct tcpcb
*tp
;
3212 tcpstat
.tcps_rttupdated
++;
3214 if (tp
->t_srtt
!= 0) {
3216 * srtt is stored as fixed point with 5 bits after the
3217 * binary point (i.e., scaled by 8). The following magic
3218 * is equivalent to the smoothing algorithm in rfc793 with
3219 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
3220 * point). Adjust rtt to origin 0.
3222 delta
= ((rtt
- 1) << TCP_DELTA_SHIFT
)
3223 - (tp
->t_srtt
>> (TCP_RTT_SHIFT
- TCP_DELTA_SHIFT
));
3225 if ((tp
->t_srtt
+= delta
) <= 0)
3229 * We accumulate a smoothed rtt variance (actually, a
3230 * smoothed mean difference), then set the retransmit
3231 * timer to smoothed rtt + 4 times the smoothed variance.
3232 * rttvar is stored as fixed point with 4 bits after the
3233 * binary point (scaled by 16). The following is
3234 * equivalent to rfc793 smoothing with an alpha of .75
3235 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
3236 * rfc793's wired-in beta.
3240 delta
-= tp
->t_rttvar
>> (TCP_RTTVAR_SHIFT
- TCP_DELTA_SHIFT
);
3241 if ((tp
->t_rttvar
+= delta
) <= 0)
3243 if (tp
->t_rttbest
> tp
->t_srtt
+ tp
->t_rttvar
)
3244 tp
->t_rttbest
= tp
->t_srtt
+ tp
->t_rttvar
;
3247 * No rtt measurement yet - use the unsmoothed rtt.
3248 * Set the variance to half the rtt (so our first
3249 * retransmit happens at 3*rtt).
3251 tp
->t_srtt
= rtt
<< TCP_RTT_SHIFT
;
3252 tp
->t_rttvar
= rtt
<< (TCP_RTTVAR_SHIFT
- 1);
3253 tp
->t_rttbest
= tp
->t_srtt
+ tp
->t_rttvar
;
3259 * the retransmit should happen at rtt + 4 * rttvar.
3260 * Because of the way we do the smoothing, srtt and rttvar
3261 * will each average +1/2 tick of bias. When we compute
3262 * the retransmit timer, we want 1/2 tick of rounding and
3263 * 1 extra tick because of +-1/2 tick uncertainty in the
3264 * firing of the timer. The bias will give us exactly the
3265 * 1.5 tick we need. But, because the bias is
3266 * statistical, we have to test that we don't drop below
3267 * the minimum feasible timer (which is 2 ticks).
3269 TCPT_RANGESET(tp
->t_rxtcur
, TCP_REXMTVAL(tp
),
3270 max(tp
->t_rttmin
, rtt
+ 2), TCPTV_REXMTMAX
);
3273 * We received an ack for a packet that wasn't retransmitted;
3274 * it is probably safe to discard any error indications we've
3275 * received recently. This isn't quite right, but close enough
3276 * for now (a route might have failed after we sent a segment,
3277 * and the return path might not be symmetrical).
3279 tp
->t_softerror
= 0;
3282 static inline unsigned int
3283 tcp_maxmtu(struct rtentry
*rt
)
3285 unsigned int maxmtu
;
3287 if (rt
->rt_rmx
.rmx_mtu
== 0)
3288 maxmtu
= rt
->rt_ifp
->if_mtu
;
3290 maxmtu
= MIN(rt
->rt_rmx
.rmx_mtu
, rt
->rt_ifp
->if_mtu
);
3296 static inline unsigned int
3297 tcp_maxmtu6(struct rtentry
*rt
)
3299 unsigned int maxmtu
;
3301 if (rt
->rt_rmx
.rmx_mtu
== 0)
3302 maxmtu
= IN6_LINKMTU(rt
->rt_ifp
);
3304 maxmtu
= MIN(rt
->rt_rmx
.rmx_mtu
, IN6_LINKMTU(rt
->rt_ifp
));
3311 * Determine a reasonable value for maxseg size.
3312 * If the route is known, check route for mtu.
3313 * If none, use an mss that can be handled on the outgoing
3314 * interface without forcing IP to fragment; if bigger than
3315 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
3316 * to utilize large mbufs. If no route is found, route has no mtu,
3317 * or the destination isn't local, use a default, hopefully conservative
3318 * size (usually 512 or the default IP max size, but no more than the mtu
3319 * of the interface), as we can't discover anything about intervening
3320 * gateways or networks. We also initialize the congestion/slow start
3321 * window to be a single segment if the destination isn't local.
3322 * While looking at the routing entry, we also initialize other path-dependent
3323 * parameters from pre-set or cached values in the routing entry.
3325 * Also take into account the space needed for options that we
3326 * send regularly. Make maxseg shorter by that amount to assure
3327 * that we can send maxseg amount of data even when the options
3328 * are present. Store the upper limit of the length of options plus
3331 * NOTE that this routine is only called when we process an incoming
3332 * segment, for outgoing segments only tcp_mssopt is called.
3340 register struct rtentry
*rt
;
3342 register int rtt
, mss
;
3346 struct rmxp_tao
*taop
;
3347 int origoffer
= offer
;
3348 u_long sb_max_corrected
;
3357 isipv6
= ((inp
->inp_vflag
& INP_IPV6
) != 0) ? 1 : 0;
3358 min_protoh
= isipv6
? sizeof (struct ip6_hdr
) + sizeof (struct tcphdr
)
3359 : sizeof (struct tcpiphdr
);
3361 #define min_protoh (sizeof (struct tcpiphdr))
3363 lck_mtx_lock(rt_mtx
);
3366 rt
= tcp_rtlookup6(inp
);
3367 if (rt
&& (IN6_IS_ADDR_LOOPBACK(&inp
->in6p_faddr
) || IN6_IS_ADDR_LINKLOCAL(&inp
->in6p_faddr
) || rt
->rt_gateway
->sa_family
== AF_LINK
))
3373 rt
= tcp_rtlookup(inp
);
3374 if (rt
&& (rt
->rt_gateway
->sa_family
== AF_LINK
||
3375 rt
->rt_ifp
->if_flags
& IFF_LOOPBACK
))
3379 tp
->t_maxopd
= tp
->t_maxseg
=
3381 isipv6
? tcp_v6mssdflt
:
3384 lck_mtx_unlock(rt_mtx
);
3389 * Slower link window correction:
3390 * If a value is specificied for slowlink_wsize use it for PPP links
3391 * believed to be on a serial modem (speed <128Kbps). Excludes 9600bps as
3392 * it is the default value adversized by pseudo-devices over ppp.
3394 if (ifp
->if_type
== IFT_PPP
&& slowlink_wsize
> 0 &&
3395 ifp
->if_baudrate
> 9600 && ifp
->if_baudrate
<= 128000) {
3396 tp
->t_flags
|= TF_SLOWLINK
;
3398 so
= inp
->inp_socket
;
3400 taop
= rmx_taop(rt
->rt_rmx
);
3402 * Offer == -1 means that we didn't receive SYN yet,
3403 * use cached value in that case;
3406 offer
= taop
->tao_mssopt
;
3408 * Offer == 0 means that there was no MSS on the SYN segment,
3409 * in this case we use tcp_mssdflt.
3414 isipv6
? tcp_v6mssdflt
:
3419 * Prevent DoS attack with too small MSS. Round up
3420 * to at least minmss.
3422 offer
= max(offer
, tcp_minmss
);
3424 * Sanity check: make sure that maxopd will be large
3425 * enough to allow some data on segments even is the
3426 * all the option space is used (40bytes). Otherwise
3427 * funny things may happen in tcp_output.
3429 offer
= max(offer
, 64);
3431 taop
->tao_mssopt
= offer
;
3434 * While we're here, check if there's an initial rtt
3435 * or rttvar. Convert from the route-table units
3436 * to scaled multiples of the slow timeout timer.
3438 if (tp
->t_srtt
== 0 && (rtt
= rt
->rt_rmx
.rmx_rtt
)) {
3440 * XXX the lock bit for RTT indicates that the value
3441 * is also a minimum value; this is subject to time.
3443 if (rt
->rt_rmx
.rmx_locks
& RTV_RTT
)
3444 tp
->t_rttmin
= rtt
/ (RTM_RTTUNIT
/ TCP_RETRANSHZ
);
3446 tp
->t_rttmin
= isnetlocal
? tcp_TCPTV_MIN
: TCP_RETRANSHZ
;
3447 tp
->t_srtt
= rtt
/ (RTM_RTTUNIT
/ (TCP_RETRANSHZ
* TCP_RTT_SCALE
));
3448 tcpstat
.tcps_usedrtt
++;
3449 if (rt
->rt_rmx
.rmx_rttvar
) {
3450 tp
->t_rttvar
= rt
->rt_rmx
.rmx_rttvar
/
3451 (RTM_RTTUNIT
/ (TCP_RETRANSHZ
* TCP_RTTVAR_SCALE
));
3452 tcpstat
.tcps_usedrttvar
++;
3454 /* default variation is +- 1 rtt */
3456 tp
->t_srtt
* TCP_RTTVAR_SCALE
/ TCP_RTT_SCALE
;
3458 TCPT_RANGESET(tp
->t_rxtcur
,
3459 ((tp
->t_srtt
>> 2) + tp
->t_rttvar
) >> 1,
3460 tp
->t_rttmin
, TCPTV_REXMTMAX
);
3463 tp
->t_rttmin
= isnetlocal
? tcp_TCPTV_MIN
: TCP_RETRANSHZ
;
3466 mss
= (isipv6
? tcp_maxmtu6(rt
) : tcp_maxmtu(rt
));
3468 mss
= tcp_maxmtu(rt
);
3472 if (rt
->rt_rmx
.rmx_mtu
== 0) {
3476 mss
= min(mss
, tcp_v6mssdflt
);
3480 mss
= min(mss
, tcp_mssdflt
);
3483 mss
= min(mss
, offer
);
3485 * maxopd stores the maximum length of data AND options
3486 * in a segment; maxseg is the amount of data in a normal
3487 * segment. We need to store this value (maxopd) apart
3488 * from maxseg, because now every segment carries options
3489 * and thus we normally have somewhat less data in segments.
3494 * origoffer==-1 indicates, that no segments were received yet.
3495 * In this case we just guess.
3497 if ((tp
->t_flags
& (TF_REQ_TSTMP
|TF_NOOPT
)) == TF_REQ_TSTMP
&&
3499 (tp
->t_flags
& TF_RCVD_TSTMP
) == TF_RCVD_TSTMP
))
3500 mss
-= TCPOLEN_TSTAMP_APPA
;
3504 * Calculate corrected value for sb_max; ensure to upgrade the
3505 * numerator for large sb_max values else it will overflow.
3507 sb_max_corrected
= (sb_max
* (u_int64_t
)MCLBYTES
) / (MSIZE
+ MCLBYTES
);
3510 * If there's a pipesize (ie loopback), change the socket
3511 * buffer to that size only if it's bigger than the current
3512 * sockbuf size. Make the socket buffers an integral
3513 * number of mss units; if the mss is larger than
3514 * the socket buffer, decrease the mss.
3517 bufsize
= rt
->rt_rmx
.rmx_sendpipe
;
3518 if (bufsize
< so
->so_snd
.sb_hiwat
)
3520 bufsize
= so
->so_snd
.sb_hiwat
;
3524 bufsize
= (((bufsize
+ (u_int64_t
)mss
- 1) / (u_int64_t
)mss
) * (u_int64_t
)mss
);
3525 if (bufsize
> sb_max_corrected
)
3526 bufsize
= sb_max_corrected
;
3527 (void)sbreserve(&so
->so_snd
, bufsize
);
3532 bufsize
= rt
->rt_rmx
.rmx_recvpipe
;
3533 if (bufsize
< so
->so_rcv
.sb_hiwat
)
3535 bufsize
= so
->so_rcv
.sb_hiwat
;
3536 if (bufsize
> mss
) {
3537 bufsize
= (((bufsize
+ (u_int64_t
)mss
- 1) / (u_int64_t
)mss
) * (u_int64_t
)mss
);
3538 if (bufsize
> sb_max_corrected
)
3539 bufsize
= sb_max_corrected
;
3540 (void)sbreserve(&so
->so_rcv
, bufsize
);
3544 * Set the slow-start flight size depending on whether this
3545 * is a local network or not.
3548 tp
->snd_cwnd
= mss
* ss_fltsz_local
;
3550 tp
->snd_cwnd
= mss
* ss_fltsz
;
3552 if (rt
->rt_rmx
.rmx_ssthresh
) {
3554 * There's some sort of gateway or interface
3555 * buffer limit on the path. Use this to set
3556 * the slow start threshhold, but set the
3557 * threshold to no less than 2*mss.
3559 tp
->snd_ssthresh
= max(2 * mss
, rt
->rt_rmx
.rmx_ssthresh
);
3560 tcpstat
.tcps_usedssthresh
++;
3562 lck_mtx_unlock(rt_mtx
);
3566 * Determine the MSS option to send on an outgoing SYN.
3580 isipv6
= ((tp
->t_inpcb
->inp_vflag
& INP_IPV6
) != 0) ? 1 : 0;
3581 min_protoh
= isipv6
? sizeof (struct ip6_hdr
) + sizeof (struct tcphdr
)
3582 : sizeof (struct tcpiphdr
);
3584 #define min_protoh (sizeof (struct tcpiphdr))
3586 lck_mtx_lock(rt_mtx
);
3589 rt
= tcp_rtlookup6(tp
->t_inpcb
);
3592 rt
= tcp_rtlookup(tp
->t_inpcb
);
3594 lck_mtx_unlock(rt_mtx
);
3597 isipv6
? tcp_v6mssdflt
:
3602 * Slower link window correction:
3603 * If a value is specificied for slowlink_wsize use it for PPP links
3604 * believed to be on a serial modem (speed <128Kbps). Excludes 9600bps as
3605 * it is the default value adversized by pseudo-devices over ppp.
3607 if (rt
->rt_ifp
->if_type
== IFT_PPP
&& slowlink_wsize
> 0 &&
3608 rt
->rt_ifp
->if_baudrate
> 9600 && rt
->rt_ifp
->if_baudrate
<= 128000) {
3609 tp
->t_flags
|= TF_SLOWLINK
;
3613 mss
= (isipv6
? tcp_maxmtu6(rt
) : tcp_maxmtu(rt
));
3615 mss
= tcp_maxmtu(rt
);
3617 lck_mtx_unlock(rt_mtx
);
3618 return (mss
- min_protoh
);
3622 * On a partial ack arrives, force the retransmission of the
3623 * next unacknowledged segment. Do not clear tp->t_dupacks.
3624 * By setting snd_nxt to ti_ack, this forces retransmission timer to
3628 tcp_newreno_partial_ack(tp
, th
)
3632 tcp_seq onxt
= tp
->snd_nxt
;
3633 u_long ocwnd
= tp
->snd_cwnd
;
3634 tp
->t_timer
[TCPT_REXMT
] = 0;
3636 tp
->snd_nxt
= th
->th_ack
;
3638 * Set snd_cwnd to one segment beyond acknowledged offset
3639 * (tp->snd_una has not yet been updated when this function
3642 tp
->snd_cwnd
= tp
->t_maxseg
+ (th
->th_ack
- tp
->snd_una
);
3643 tp
->t_flags
|= TF_ACKNOW
;
3644 tp
->t_unacksegs
= 0;
3645 (void) tcp_output(tp
);
3646 tp
->snd_cwnd
= ocwnd
;
3647 if (SEQ_GT(onxt
, tp
->snd_nxt
))
3650 * Partial window deflation. Relies on fact that tp->snd_una
3653 if (tp
->snd_cwnd
> th
->th_ack
- tp
->snd_una
)
3654 tp
->snd_cwnd
-= th
->th_ack
- tp
->snd_una
;
3657 tp
->snd_cwnd
+= tp
->t_maxseg
;
3662 * Drop a random TCP connection that hasn't been serviced yet and
3663 * is eligible for discard. There is a one in qlen chance that
3664 * we will return a null, saying that there are no dropable
3665 * requests. In this case, the protocol specific code should drop
3666 * the new request. This insures fairness.
3668 * The listening TCP socket "head" must be locked
3671 tcp_dropdropablreq(struct socket
*head
)
3673 struct socket
*so
, *sonext
;
3674 unsigned int i
, j
, qlen
;
3676 static struct timeval old_runtime
;
3677 static unsigned int cur_cnt
, old_cnt
;
3679 struct inpcb
*inp
= NULL
;
3682 if ((head
->so_options
& SO_ACCEPTCONN
) == 0)
3685 so
= TAILQ_FIRST(&head
->so_incomp
);
3690 if ((i
= (tv
.tv_sec
- old_runtime
.tv_sec
)) != 0) {
3692 old_cnt
= cur_cnt
/ i
;
3697 qlen
= head
->so_incqlen
;
3698 if (++cur_cnt
> qlen
|| old_cnt
> qlen
) {
3699 rnd
= (314159 * rnd
+ 66329) & 0xffff;
3700 j
= ((qlen
+ 1) * rnd
) >> 16;
3703 so
= TAILQ_NEXT(so
, so_list
);
3705 /* Find a connection that is not already closing (or being served) */
3707 inp
= (struct inpcb
*)so
->so_pcb
;
3709 sonext
= TAILQ_NEXT(so
, so_list
);
3711 if (in_pcb_checkstate(inp
, WNT_ACQUIRE
, 0) != WNT_STOPUSING
) {
3712 /* Avoid the issue of a socket being accepted by one input thread
3713 * and being dropped by another input thread.
3714 * If we can't get a hold on this mutex, then grab the next socket in line.
3716 if (lck_mtx_try_lock(inp
->inpcb_mtx
)) {
3718 if ((so
->so_usecount
== 2) && so
->so_state
& SS_INCOMP
)
3720 else {/* don't use if beeing accepted or used in any other way */
3721 in_pcb_checkstate(inp
, WNT_RELEASE
, 1);
3722 tcp_unlock(so
, 1, 0);
3732 TAILQ_REMOVE(&head
->so_incomp
, so
, so_list
);
3733 tcp_unlock(head
, 0, 0);
3735 /* Makes sure socket is still in the right state to be discarded */
3737 if (in_pcb_checkstate(inp
, WNT_RELEASE
, 1) == WNT_STOPUSING
) {
3738 tcp_unlock(so
, 1, 0);
3739 tcp_lock(head
, 0, 0);
3743 if (so
->so_usecount
!= 2 || !(so
->so_state
& SS_INCOMP
)) {
3744 /* do not discard: that socket is beeing accepted */
3745 tcp_unlock(so
, 1, 0);
3746 tcp_lock(head
, 0, 0);
3753 * We do not want to lose track of the PCB right away in case we receive
3754 * more segments from the peer
3757 so
->so_flags
|= SOF_OVERFLOW
;
3758 tp
->t_state
= TCPS_TIME_WAIT
;
3759 (void) tcp_close(tp
);
3760 tp
->t_unacksegs
= 0;
3761 tcpstat
.tcps_drops
++;
3762 tcp_canceltimers(tp
);
3763 add_to_time_wait(tp
);
3765 tcp_unlock(so
, 1, 0);
3766 tcp_lock(head
, 0, 0);
3773 tcp_getstat SYSCTL_HANDLER_ARGS
3775 #pragma unused(oidp, arg1, arg2)
3779 if (req
->oldptr
== 0) {
3780 req
->oldlen
= (size_t)sizeof(struct tcpstat
);
3783 error
= SYSCTL_OUT(req
, &tcpstat
, MIN(sizeof (tcpstat
), req
->oldlen
));
3789 SYSCTL_PROC(_net_inet_tcp
, TCPCTL_STATS
, stats
, CTLFLAG_RD
, 0, 0,
3790 tcp_getstat
, "S,tcpstat", "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
3793 sysctl_rexmtthresh SYSCTL_HANDLER_ARGS
3795 #pragma unused(arg1, arg2)
3797 int error
, val
= tcprexmtthresh
;
3799 error
= sysctl_handle_int(oidp
, &val
, 0, req
);
3800 if (error
|| !req
->newptr
)
3804 * Constrain the number of duplicate ACKs
3805 * to consider for TCP fast retransmit
3809 if (val
< 2 || val
> 3)
3812 tcprexmtthresh
= val
;
3817 SYSCTL_PROC(_net_inet_tcp
, OID_AUTO
, rexmt_thresh
, CTLTYPE_INT
|CTLFLAG_RW
,
3818 &tcprexmtthresh
, 0, &sysctl_rexmtthresh
, "I", "Duplicate ACK Threshold for Fast Retransmit");