2 * Copyright (c) 2006 Apple Computer, Inc. All Rights Reserved.
4 * @APPLE_LICENSE_OSREFERENCE_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
10 * License may not be used to create, or enable the creation or
11 * redistribution of, unlawful or unlicensed copies of an Apple operating
12 * system, or to circumvent, violate, or enable the circumvention or
13 * violation of, any terms of an Apple operating system software license
16 * Please obtain a copy of the License at
17 * http://www.opensource.apple.com/apsl/ and read it before using this
20 * The Original Code and all software distributed under the License are
21 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
22 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
23 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
24 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
25 * Please see the License for the specific language governing rights and
26 * limitations under the License.
28 * @APPLE_LICENSE_OSREFERENCE_HEADER_END@
31 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
32 * The Regents of the University of California. All rights reserved.
34 * Redistribution and use in source and binary forms, with or without
35 * modification, are permitted provided that the following conditions
37 * 1. Redistributions of source code must retain the above copyright
38 * notice, this list of conditions and the following disclaimer.
39 * 2. Redistributions in binary form must reproduce the above copyright
40 * notice, this list of conditions and the following disclaimer in the
41 * documentation and/or other materials provided with the distribution.
42 * 3. All advertising materials mentioning features or use of this software
43 * must display the following acknowledgement:
44 * This product includes software developed by the University of
45 * California, Berkeley and its contributors.
46 * 4. Neither the name of the University nor the names of its contributors
47 * may be used to endorse or promote products derived from this software
48 * without specific prior written permission.
50 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
62 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
63 * $FreeBSD: src/sys/netinet/tcp_input.c,v 1.107.2.16 2001/08/22 00:59:12 silby Exp $
67 #include <sys/param.h>
68 #include <sys/systm.h>
69 #include <sys/kernel.h>
70 #include <sys/sysctl.h>
71 #include <sys/malloc.h>
73 #include <sys/proc.h> /* for proc0 declaration */
74 #include <sys/protosw.h>
75 #include <sys/socket.h>
76 #include <sys/socketvar.h>
77 #include <sys/syslog.h>
79 #include <kern/cpu_number.h> /* before tcp_seq.h, for tcp_random18() */
82 #include <net/if_types.h>
83 #include <net/route.h>
85 #include <netinet/in.h>
86 #include <netinet/in_systm.h>
87 #include <netinet/ip.h>
88 #include <netinet/ip_icmp.h> /* for ICMP_BANDLIM */
89 #include <netinet/in_var.h>
90 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
91 #include <netinet/in_pcb.h>
92 #include <netinet/ip_var.h>
94 #include <netinet/ip6.h>
95 #include <netinet/icmp6.h>
96 #include <netinet6/nd6.h>
97 #include <netinet6/ip6_var.h>
98 #include <netinet6/in6_pcb.h>
100 #include <netinet/tcp.h>
101 #include <netinet/tcp_fsm.h>
102 #include <netinet/tcp_seq.h>
103 #include <netinet/tcp_timer.h>
104 #include <netinet/tcp_var.h>
106 #include <netinet6/tcp6_var.h>
108 #include <netinet/tcpip.h>
110 #include <netinet/tcp_debug.h>
111 u_char tcp_saveipgen
[40]; /* the size must be of max ip header, now IPv6 */
112 struct tcphdr tcp_savetcp
;
113 #endif /* TCPDEBUG */
116 #include <netinet6/ipsec.h>
118 #include <netinet6/ipsec6.h>
120 #include <netkey/key.h>
123 #include <sys/kdebug.h>
126 MALLOC_DEFINE(M_TSEGQ
, "tseg_qent", "TCP segment queue entry");
129 #define DBG_LAYER_BEG NETDBG_CODE(DBG_NETTCP, 0)
130 #define DBG_LAYER_END NETDBG_CODE(DBG_NETTCP, 2)
131 #define DBG_FNC_TCP_INPUT NETDBG_CODE(DBG_NETTCP, (3 << 8))
132 #define DBG_FNC_TCP_NEWCONN NETDBG_CODE(DBG_NETTCP, (7 << 8))
134 static int tcprexmtthresh
= 3;
136 extern int apple_hwcksum_rx
;
139 extern int ipsec_bypass
;
140 extern lck_mtx_t
*sadb_mutex
;
143 struct tcpstat tcpstat
;
145 static int log_in_vain
= 0;
146 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, log_in_vain
, CTLFLAG_RW
,
147 &log_in_vain
, 0, "Log all incoming TCP connections");
149 static int blackhole
= 0;
150 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, blackhole
, CTLFLAG_RW
,
151 &blackhole
, 0, "Do not send RST when dropping refused connections");
153 int tcp_delack_enabled
= 3;
154 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, delayed_ack
, CTLFLAG_RW
,
155 &tcp_delack_enabled
, 0,
156 "Delay ACK to try and piggyback it onto a data packet");
158 int tcp_lq_overflow
= 1;
159 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, tcp_lq_overflow
, CTLFLAG_RW
,
161 "Listen Queue Overflow");
164 static int drop_synfin
= 1;
165 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, drop_synfin
, CTLFLAG_RW
,
166 &drop_synfin
, 0, "Drop TCP packets with SYN+FIN set");
169 SYSCTL_NODE(_net_inet_tcp
, OID_AUTO
, reass
, CTLFLAG_RW
, 0,
170 "TCP Segment Reassembly Queue");
172 __private_extern__
int tcp_reass_maxseg
= 0;
173 SYSCTL_INT(_net_inet_tcp_reass
, OID_AUTO
, maxsegments
, CTLFLAG_RW
,
174 &tcp_reass_maxseg
, 0,
175 "Global maximum number of TCP Segments in Reassembly Queue");
177 __private_extern__
int tcp_reass_qsize
= 0;
178 SYSCTL_INT(_net_inet_tcp_reass
, OID_AUTO
, cursegments
, CTLFLAG_RD
,
180 "Global number of TCP Segments currently in Reassembly Queue");
182 static int tcp_reass_overflows
= 0;
183 SYSCTL_INT(_net_inet_tcp_reass
, OID_AUTO
, overflows
, CTLFLAG_RD
,
184 &tcp_reass_overflows
, 0,
185 "Global number of TCP Segment Reassembly Queue Overflows");
188 __private_extern__
int slowlink_wsize
= 8192;
189 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, slowlink_wsize
, CTLFLAG_RW
,
190 &slowlink_wsize
, 0, "Maximum advertised window size for slowlink");
194 struct inpcbhead tcb
;
195 #define tcb6 tcb /* for KAME src sync over BSD*'s */
196 struct inpcbinfo tcbinfo
;
198 static void tcp_dooptions(struct tcpcb
*,
199 u_char
*, int, struct tcphdr
*, struct tcpopt
*);
200 static void tcp_pulloutofband(struct socket
*,
201 struct tcphdr
*, struct mbuf
*, int);
202 static int tcp_reass(struct tcpcb
*, struct tcphdr
*, int *,
204 static void tcp_xmit_timer(struct tcpcb
*, int);
206 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
208 #define ND6_HINT(tp) \
210 if ((tp) && (tp)->t_inpcb && \
211 ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0 && \
212 (tp)->t_inpcb->in6p_route.ro_rt) \
213 nd6_nud_hint((tp)->t_inpcb->in6p_route.ro_rt, NULL, 0); \
219 extern u_long
*delack_bitmask
;
221 extern void ipfwsyslog( int level
, char *format
,...);
222 extern int ChkAddressOK( __uint32_t dstaddr
, __uint32_t srcaddr
);
223 extern int fw_verbose
;
225 #define log_in_vain_log( a ) { \
226 if ( (log_in_vain == 3 ) && (fw_verbose == 2)) { /* Apple logging, log to ipfw.log */ \
233 * Indicate whether this ack should be delayed.
234 * We can delay the ack if:
235 * - delayed acks are enabled (set to 1) and
236 * - our last ack wasn't a 0-sized window. We never want to delay
237 * the ack that opens up a 0-sized window.
238 * - delayed acks are enabled (set to 2, "more compatible") and
239 * - our last ack wasn't a 0-sized window.
240 * - if the peer hasn't sent us a TH_PUSH data packet (this solves 3649245)
241 * - the peer hasn't sent us a TH_PUSH data packet, if he did, take this as a clue that we
242 * need to ACK with no delay. This helps higher level protocols who won't send
243 * us more data even if the window is open because their last "segment" hasn't been ACKed
244 * - delayed acks are enabled (set to 3, "streaming detection") and
245 * - if we receive more than 4 full packets per second on this socket, we're streaming acts as "1".
246 * - if we don't meet that criteria, acts like "2". Allowing faster acking while browsing for example.
249 #define DELAY_ACK(tp) \
250 (((tcp_delack_enabled == 1) && ((tp->t_flags & TF_RXWIN0SENT) == 0)) || \
251 (((tcp_delack_enabled == 2) && (tp->t_flags & TF_RXWIN0SENT) == 0) && \
252 ((thflags & TH_PUSH) == 0) && ((tp->t_flags & TF_DELACK) == 0)) || \
253 (((tcp_delack_enabled == 3) && (tp->t_flags & TF_RXWIN0SENT) == 0) && \
254 (((tp->t_rcvtime == 0) && (tp->rcv_byps > (4* tp->t_maxseg))) || (((thflags & TH_PUSH) == 0) && ((tp->t_flags & TF_DELACK) == 0)))))
257 static int tcpdropdropablreq(struct socket
*head
);
258 static void tcp_newreno_partial_ack(struct tcpcb
*tp
, struct tcphdr
*th
);
262 tcp_reass(tp
, th
, tlenp
, m
)
263 register struct tcpcb
*tp
;
264 register struct tcphdr
*th
;
269 struct tseg_qent
*p
= NULL
;
270 struct tseg_qent
*nq
;
271 struct tseg_qent
*te
= NULL
;
272 struct socket
*so
= tp
->t_inpcb
->inp_socket
;
277 * Call with th==0 after become established to
278 * force pre-ESTABLISHED data up to user socket.
284 * Limit the number of segments in the reassembly queue to prevent
285 * holding on to too many segments (and thus running out of mbufs).
286 * Make sure to let the missing segment through which caused this
287 * queue. Always keep one global queue entry spare to be able to
288 * process the missing segment.
290 if (th
->th_seq
!= tp
->rcv_nxt
&&
291 tcp_reass_qsize
+ 1 >= tcp_reass_maxseg
) {
292 tcp_reass_overflows
++;
293 tcpstat
.tcps_rcvmemdrop
++;
298 /* Allocate a new queue entry. If we can't, just drop the pkt. XXX */
299 MALLOC(te
, struct tseg_qent
*, sizeof (struct tseg_qent
), M_TSEGQ
,
302 tcpstat
.tcps_rcvmemdrop
++;
309 * Find a segment which begins after this one does.
311 LIST_FOREACH(q
, &tp
->t_segq
, tqe_q
) {
312 if (SEQ_GT(q
->tqe_th
->th_seq
, th
->th_seq
))
318 * If there is a preceding segment, it may provide some of
319 * our data already. If so, drop the data from the incoming
320 * segment. If it provides all of our data, drop us.
324 /* conversion to int (in i) handles seq wraparound */
325 i
= p
->tqe_th
->th_seq
+ p
->tqe_len
- th
->th_seq
;
328 tcpstat
.tcps_rcvduppack
++;
329 tcpstat
.tcps_rcvdupbyte
+= *tlenp
;
334 * Try to present any queued data
335 * at the left window edge to the user.
336 * This is needed after the 3-WHS
339 goto present
; /* ??? */
346 tcpstat
.tcps_rcvoopack
++;
347 tcpstat
.tcps_rcvoobyte
+= *tlenp
;
350 * While we overlap succeeding segments trim them or,
351 * if they are completely covered, dequeue them.
354 register int i
= (th
->th_seq
+ *tlenp
) - q
->tqe_th
->th_seq
;
357 if (i
< q
->tqe_len
) {
358 q
->tqe_th
->th_seq
+= i
;
364 nq
= LIST_NEXT(q
, tqe_q
);
365 LIST_REMOVE(q
, tqe_q
);
372 /* Insert the new segment queue entry into place. */
375 te
->tqe_len
= *tlenp
;
378 LIST_INSERT_HEAD(&tp
->t_segq
, te
, tqe_q
);
380 LIST_INSERT_AFTER(p
, te
, tqe_q
);
385 * Present data to user, advancing rcv_nxt through
386 * completed sequence space.
388 if (!TCPS_HAVEESTABLISHED(tp
->t_state
))
390 q
= LIST_FIRST(&tp
->t_segq
);
391 if (!q
|| q
->tqe_th
->th_seq
!= tp
->rcv_nxt
)
394 tp
->rcv_nxt
+= q
->tqe_len
;
395 flags
= q
->tqe_th
->th_flags
& TH_FIN
;
396 nq
= LIST_NEXT(q
, tqe_q
);
397 LIST_REMOVE(q
, tqe_q
);
398 if (so
->so_state
& SS_CANTRCVMORE
)
401 if (sbappend(&so
->so_rcv
, q
->tqe_m
))
407 } while (q
&& q
->tqe_th
->th_seq
== tp
->rcv_nxt
);
411 if ((tp
->t_inpcb
->inp_vflag
& INP_IPV6
) != 0) {
413 KERNEL_DEBUG(DBG_LAYER_BEG
,
414 ((tp
->t_inpcb
->inp_fport
<< 16) | tp
->t_inpcb
->inp_lport
),
415 (((tp
->t_inpcb
->in6p_laddr
.s6_addr16
[0] & 0xffff) << 16) |
416 (tp
->t_inpcb
->in6p_faddr
.s6_addr16
[0] & 0xffff)),
422 KERNEL_DEBUG(DBG_LAYER_BEG
,
423 ((tp
->t_inpcb
->inp_fport
<< 16) | tp
->t_inpcb
->inp_lport
),
424 (((tp
->t_inpcb
->inp_laddr
.s_addr
& 0xffff) << 16) |
425 (tp
->t_inpcb
->inp_faddr
.s_addr
& 0xffff)),
429 sorwakeup(so
); /* done with socket lock held */
436 * TCP input routine, follows pages 65-76 of the
437 * protocol specification dated September, 1981 very closely.
445 register struct mbuf
*m
= *mp
;
446 struct in6_ifaddr
*ia6
;
448 IP6_EXTHDR_CHECK(m
, *offp
, sizeof(struct tcphdr
), return IPPROTO_DONE
);
451 * draft-itojun-ipv6-tcp-to-anycast
452 * better place to put this in?
454 ia6
= ip6_getdstifaddr(m
);
455 if (ia6
&& (ia6
->ia6_flags
& IN6_IFF_ANYCAST
)) {
458 ip6
= mtod(m
, struct ip6_hdr
*);
459 icmp6_error(m
, ICMP6_DST_UNREACH
, ICMP6_DST_UNREACH_ADDR
,
460 (caddr_t
)&ip6
->ip6_dst
- (caddr_t
)ip6
);
474 register struct tcphdr
*th
;
475 register struct ip
*ip
= NULL
;
476 register struct ipovly
*ipov
;
477 register struct inpcb
*inp
;
482 register struct tcpcb
*tp
= 0;
483 register int thflags
;
484 struct socket
*so
= 0;
485 int todrop
, acked
, ourfinisacked
, needoutput
= 0;
486 struct in_addr laddr
;
488 struct in6_addr laddr6
;
494 struct tcpopt to
; /* options in this segment */
495 struct rmxp_tao
*taop
; /* pointer to our TAO cache entry */
496 struct rmxp_tao tao_noncached
; /* in case there's no cached entry */
497 struct sockaddr_in
*next_hop
= NULL
;
501 struct m_tag
*fwd_tag
;
503 /* Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain. */
504 fwd_tag
= m_tag_locate(m
, KERNEL_MODULE_TAG_ID
, KERNEL_TAG_TYPE_IPFORWARD
, NULL
);
505 if (fwd_tag
!= NULL
) {
506 struct ip_fwd_tag
*ipfwd_tag
= (struct ip_fwd_tag
*)(fwd_tag
+1);
508 next_hop
= ipfwd_tag
->next_hop
;
509 m_tag_delete(m
, fwd_tag
);
513 struct ip6_hdr
*ip6
= NULL
;
516 int rstreason
; /* For badport_bandlim accounting purposes */
517 struct proc
*proc0
=current_proc();
519 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_START
,0,0,0,0,0);
522 isipv6
= (mtod(m
, struct ip
*)->ip_v
== 6) ? 1 : 0;
524 bzero((char *)&to
, sizeof(to
));
526 tcpstat
.tcps_rcvtotal
++;
532 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
533 ip6
= mtod(m
, struct ip6_hdr
*);
534 tlen
= sizeof(*ip6
) + ntohs(ip6
->ip6_plen
) - off0
;
535 if (in6_cksum(m
, IPPROTO_TCP
, off0
, tlen
)) {
536 tcpstat
.tcps_rcvbadsum
++;
539 th
= (struct tcphdr
*)((caddr_t
)ip6
+ off0
);
541 KERNEL_DEBUG(DBG_LAYER_BEG
, ((th
->th_dport
<< 16) | th
->th_sport
),
542 (((ip6
->ip6_src
.s6_addr16
[0]) << 16) | (ip6
->ip6_dst
.s6_addr16
[0])),
543 th
->th_seq
, th
->th_ack
, th
->th_win
);
545 * Be proactive about unspecified IPv6 address in source.
546 * As we use all-zero to indicate unbounded/unconnected pcb,
547 * unspecified IPv6 address can be used to confuse us.
549 * Note that packets with unspecified IPv6 destination is
550 * already dropped in ip6_input.
552 if (IN6_IS_ADDR_UNSPECIFIED(&ip6
->ip6_src
)) {
560 * Get IP and TCP header together in first mbuf.
561 * Note: IP leaves IP header in first mbuf.
563 if (off0
> sizeof (struct ip
)) {
564 ip_stripoptions(m
, (struct mbuf
*)0);
565 off0
= sizeof(struct ip
);
566 if (m
->m_pkthdr
.csum_flags
& CSUM_TCP_SUM16
)
567 m
->m_pkthdr
.csum_flags
= 0; /* invalidate hwcksuming */
570 if (m
->m_len
< sizeof (struct tcpiphdr
)) {
571 if ((m
= m_pullup(m
, sizeof (struct tcpiphdr
))) == 0) {
572 tcpstat
.tcps_rcvshort
++;
576 ip
= mtod(m
, struct ip
*);
577 ipov
= (struct ipovly
*)ip
;
578 th
= (struct tcphdr
*)((caddr_t
)ip
+ off0
);
581 KERNEL_DEBUG(DBG_LAYER_BEG
, ((th
->th_dport
<< 16) | th
->th_sport
),
582 (((ip
->ip_src
.s_addr
& 0xffff) << 16) | (ip
->ip_dst
.s_addr
& 0xffff)),
583 th
->th_seq
, th
->th_ack
, th
->th_win
);
585 if (m
->m_pkthdr
.csum_flags
& CSUM_DATA_VALID
) {
586 if (apple_hwcksum_rx
&& (m
->m_pkthdr
.csum_flags
& CSUM_TCP_SUM16
)) {
589 *(uint32_t*)&b
[0] = *(uint32_t*)&ipov
->ih_x1
[0];
590 *(uint32_t*)&b
[4] = *(uint32_t*)&ipov
->ih_x1
[4];
591 *(uint8_t*)&b
[8] = *(uint8_t*)&ipov
->ih_x1
[8];
593 bzero(ipov
->ih_x1
, sizeof(ipov
->ih_x1
));
594 ipov
->ih_len
= (u_short
)tlen
;
596 pseudo
= in_cksum(m
, sizeof (struct ip
));
598 *(uint32_t*)&ipov
->ih_x1
[0] = *(uint32_t*)&b
[0];
599 *(uint32_t*)&ipov
->ih_x1
[4] = *(uint32_t*)&b
[4];
600 *(uint8_t*)&ipov
->ih_x1
[8] = *(uint8_t*)&b
[8];
602 th
->th_sum
= in_addword(pseudo
, (m
->m_pkthdr
.csum_data
& 0xFFFF));
604 if (m
->m_pkthdr
.csum_flags
& CSUM_PSEUDO_HDR
)
605 th
->th_sum
= m
->m_pkthdr
.csum_data
;
607 th
->th_sum
= in_pseudo(ip
->ip_src
.s_addr
,
608 ip
->ip_dst
.s_addr
, htonl(m
->m_pkthdr
.csum_data
+
609 ip
->ip_len
+ IPPROTO_TCP
));
611 th
->th_sum
^= 0xffff;
615 * Checksum extended TCP header and data.
617 *(uint32_t*)&b
[0] = *(uint32_t*)&ipov
->ih_x1
[0];
618 *(uint32_t*)&b
[4] = *(uint32_t*)&ipov
->ih_x1
[4];
619 *(uint8_t*)&b
[8] = *(uint8_t*)&ipov
->ih_x1
[8];
621 len
= sizeof (struct ip
) + tlen
;
622 bzero(ipov
->ih_x1
, sizeof(ipov
->ih_x1
));
623 ipov
->ih_len
= (u_short
)tlen
;
625 th
->th_sum
= in_cksum(m
, len
);
627 *(uint32_t*)&ipov
->ih_x1
[0] = *(uint32_t*)&b
[0];
628 *(uint32_t*)&ipov
->ih_x1
[4] = *(uint32_t*)&b
[4];
629 *(uint8_t*)&ipov
->ih_x1
[8] = *(uint8_t*)&b
[8];
632 tcpstat
.tcps_rcvbadsum
++;
636 /* Re-initialization for later version check */
637 ip
->ip_v
= IPVERSION
;
642 * Check that TCP offset makes sense,
643 * pull out TCP options and adjust length. XXX
645 off
= th
->th_off
<< 2;
646 if (off
< sizeof (struct tcphdr
) || off
> tlen
) {
647 tcpstat
.tcps_rcvbadoff
++;
650 tlen
-= off
; /* tlen is used instead of ti->ti_len */
651 if (off
> sizeof (struct tcphdr
)) {
654 IP6_EXTHDR_CHECK(m
, off0
, off
, return);
655 ip6
= mtod(m
, struct ip6_hdr
*);
656 th
= (struct tcphdr
*)((caddr_t
)ip6
+ off0
);
660 if (m
->m_len
< sizeof(struct ip
) + off
) {
661 if ((m
= m_pullup(m
, sizeof (struct ip
) + off
)) == 0) {
662 tcpstat
.tcps_rcvshort
++;
665 ip
= mtod(m
, struct ip
*);
666 ipov
= (struct ipovly
*)ip
;
667 th
= (struct tcphdr
*)((caddr_t
)ip
+ off0
);
670 optlen
= off
- sizeof (struct tcphdr
);
671 optp
= (u_char
*)(th
+ 1);
673 * Do quick retrieval of timestamp options ("options
674 * prediction?"). If timestamp is the only option and it's
675 * formatted as recommended in RFC 1323 appendix A, we
676 * quickly get the values now and not bother calling
677 * tcp_dooptions(), etc.
679 if ((optlen
== TCPOLEN_TSTAMP_APPA
||
680 (optlen
> TCPOLEN_TSTAMP_APPA
&&
681 optp
[TCPOLEN_TSTAMP_APPA
] == TCPOPT_EOL
)) &&
682 *(u_int32_t
*)optp
== htonl(TCPOPT_TSTAMP_HDR
) &&
683 (th
->th_flags
& TH_SYN
) == 0) {
684 to
.to_flags
|= TOF_TS
;
685 to
.to_tsval
= ntohl(*(u_int32_t
*)(optp
+ 4));
686 to
.to_tsecr
= ntohl(*(u_int32_t
*)(optp
+ 8));
687 optp
= NULL
; /* we've parsed the options */
690 thflags
= th
->th_flags
;
694 * If the drop_synfin option is enabled, drop all packets with
695 * both the SYN and FIN bits set. This prevents e.g. nmap from
696 * identifying the TCP/IP stack.
698 * This is a violation of the TCP specification.
700 if (drop_synfin
&& (thflags
& (TH_SYN
|TH_FIN
)) == (TH_SYN
|TH_FIN
))
705 * Convert TCP protocol specific fields to host format.
713 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options,
714 * until after ip6_savecontrol() is called and before other functions
715 * which don't want those proto headers.
716 * Because ip6_savecontrol() is going to parse the mbuf to
717 * search for data to be passed up to user-land, it wants mbuf
718 * parameters to be unchanged.
720 drop_hdrlen
= off0
+ off
;
723 * Locate pcb for segment.
726 #if IPFIREWALL_FORWARD
729 && isipv6
== NULL
/* IPv6 support is not yet */
733 * Diverted. Pretend to be the destination.
734 * already got one like this?
736 inp
= in_pcblookup_hash(&tcbinfo
, ip
->ip_src
, th
->th_sport
,
737 ip
->ip_dst
, th
->th_dport
, 0, m
->m_pkthdr
.rcvif
);
740 * No, then it's new. Try find the ambushing socket
742 if (!next_hop
->sin_port
) {
743 inp
= in_pcblookup_hash(&tcbinfo
, ip
->ip_src
,
744 th
->th_sport
, next_hop
->sin_addr
,
745 th
->th_dport
, 1, m
->m_pkthdr
.rcvif
);
747 inp
= in_pcblookup_hash(&tcbinfo
,
748 ip
->ip_src
, th
->th_sport
,
750 ntohs(next_hop
->sin_port
), 1,
755 #endif /* IPFIREWALL_FORWARD */
759 inp
= in6_pcblookup_hash(&tcbinfo
, &ip6
->ip6_src
, th
->th_sport
,
760 &ip6
->ip6_dst
, th
->th_dport
, 1,
764 inp
= in_pcblookup_hash(&tcbinfo
, ip
->ip_src
, th
->th_sport
,
765 ip
->ip_dst
, th
->th_dport
, 1, m
->m_pkthdr
.rcvif
);
769 if (ipsec_bypass
== 0) {
770 lck_mtx_lock(sadb_mutex
);
773 if (inp
!= NULL
&& ipsec6_in_reject_so(m
, inp
->inp_socket
)) {
774 ipsec6stat
.in_polvio
++;
775 lck_mtx_unlock(sadb_mutex
);
780 if (inp
!= NULL
&& ipsec4_in_reject_so(m
, inp
->inp_socket
)) {
781 ipsecstat
.in_polvio
++;
782 lck_mtx_unlock(sadb_mutex
);
785 lck_mtx_unlock(sadb_mutex
);
790 * If the state is CLOSED (i.e., TCB does not exist) then
791 * all data in the incoming segment is discarded.
792 * If the TCB exists but is in CLOSED state, it is embryonic,
793 * but should either do a listen or a connect soon.
798 char dbuf
[MAX_IPv6_STR_LEN
], sbuf
[MAX_IPv6_STR_LEN
];
800 char dbuf
[MAX_IPv4_STR_LEN
], sbuf
[MAX_IPv4_STR_LEN
];
805 inet_ntop(AF_INET6
, &ip6
->ip6_dst
, dbuf
, sizeof(dbuf
));
806 inet_ntop(AF_INET6
, &ip6
->ip6_src
, sbuf
, sizeof(sbuf
));
810 inet_ntop(AF_INET
, &ip
->ip_dst
, dbuf
, sizeof(dbuf
));
811 inet_ntop(AF_INET
, &ip
->ip_src
, sbuf
, sizeof(sbuf
));
813 switch (log_in_vain
) {
817 "Connection attempt to TCP %s:%d from %s:%d\n",
818 dbuf
, ntohs(th
->th_dport
),
820 ntohs(th
->th_sport
));
824 "Connection attempt to TCP %s:%d from %s:%d flags:0x%x\n",
825 dbuf
, ntohs(th
->th_dport
), sbuf
,
826 ntohs(th
->th_sport
), thflags
);
829 if ((thflags
& TH_SYN
) &&
830 !(m
->m_flags
& (M_BCAST
| M_MCAST
)) &&
832 ((isipv6
&& !IN6_ARE_ADDR_EQUAL(&ip6
->ip6_dst
, &ip6
->ip6_src
)) ||
833 (!isipv6
&& ip
->ip_dst
.s_addr
!= ip
->ip_src
.s_addr
))
835 ip
->ip_dst
.s_addr
!= ip
->ip_src
.s_addr
838 log_in_vain_log((LOG_INFO
,
839 "Stealth Mode connection attempt to TCP %s:%d from %s:%d\n",
840 dbuf
, ntohs(th
->th_dport
),
842 ntohs(th
->th_sport
)));
849 if (m
->m_pkthdr
.rcvif
&& m
->m_pkthdr
.rcvif
->if_type
!= IFT_LOOP
)
852 if (thflags
& TH_SYN
)
861 rstreason
= BANDLIM_RST_CLOSEDPORT
;
862 goto dropwithresetnosock
;
864 so
= inp
->inp_socket
;
866 if (in_pcb_checkstate(inp
, WNT_RELEASE
, 1) == WNT_STOPUSING
)
867 inp
= NULL
; // pretend we didn't find it
869 printf("tcp_input: no more socket for inp=%x\n", inp
);
876 * Bogus state when listening port owned by SharedIP with loopback as the
877 * only configured interface: BlueBox does not filters loopback
879 if (so
== &tcbinfo
.nat_dummy_socket
)
884 if (in_pcb_checkstate(inp
, WNT_RELEASE
, 1) == WNT_STOPUSING
) {
885 tcp_unlock(so
, 1, 2);
886 inp
= NULL
; // pretend we didn't find it
892 rstreason
= BANDLIM_RST_CLOSEDPORT
;
895 if (tp
->t_state
== TCPS_CLOSED
)
898 /* Unscale the window into a 32-bit value. */
899 if ((thflags
& TH_SYN
) == 0)
900 tiwin
= th
->th_win
<< tp
->snd_scale
;
904 if (so
->so_options
& (SO_DEBUG
|SO_ACCEPTCONN
)) {
906 if (so
->so_options
& SO_DEBUG
) {
907 ostate
= tp
->t_state
;
910 bcopy((char *)ip6
, (char *)tcp_saveipgen
,
914 bcopy((char *)ip
, (char *)tcp_saveipgen
, sizeof(*ip
));
918 if (so
->so_options
& SO_ACCEPTCONN
) {
919 register struct tcpcb
*tp0
= tp
;
922 struct sockaddr_storage from
;
924 struct inpcb
*oinp
= sotoinpcb(so
);
926 int ogencnt
= so
->so_gencnt
;
930 * Current IPsec implementation makes incorrect IPsec
931 * cache if this check is done here.
932 * So delay this until duplicated socket is created.
934 if ((thflags
& (TH_RST
|TH_ACK
|TH_SYN
)) != TH_SYN
) {
936 * Note: dropwithreset makes sure we don't
937 * send a RST in response to a RST.
939 if (thflags
& TH_ACK
) {
940 tcpstat
.tcps_badsyn
++;
941 rstreason
= BANDLIM_RST_OPENPORT
;
947 KERNEL_DEBUG(DBG_FNC_TCP_NEWCONN
| DBG_FUNC_START
,0,0,0,0,0);
951 * If deprecated address is forbidden,
952 * we do not accept SYN to deprecated interface
953 * address to prevent any new inbound connection from
954 * getting established.
955 * When we do not accept SYN, we send a TCP RST,
956 * with deprecated source address (instead of dropping
957 * it). We compromise it as it is much better for peer
958 * to send a RST, and RST will be the final packet
961 * If we do not forbid deprecated addresses, we accept
962 * the SYN packet. RFC2462 does not suggest dropping
964 * If we decipher RFC2462 5.5.4, it says like this:
965 * 1. use of deprecated addr with existing
966 * communication is okay - "SHOULD continue to be
968 * 2. use of it with new communication:
969 * (2a) "SHOULD NOT be used if alternate address
970 * with sufficient scope is available"
971 * (2b) nothing mentioned otherwise.
972 * Here we fall into (2b) case as we have no choice in
973 * our source address selection - we must obey the peer.
975 * The wording in RFC2462 is confusing, and there are
976 * multiple description text for deprecated address
977 * handling - worse, they are not exactly the same.
978 * I believe 5.5.4 is the best one, so we follow 5.5.4.
980 if (isipv6
&& !ip6_use_deprecated
) {
981 struct in6_ifaddr
*ia6
;
983 if ((ia6
= ip6_getdstifaddr(m
)) &&
984 (ia6
->ia6_flags
& IN6_IFF_DEPRECATED
)) {
986 rstreason
= BANDLIM_RST_OPENPORT
;
993 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*)&from
;
995 sin6
->sin6_len
= sizeof(*sin6
);
996 sin6
->sin6_family
= AF_INET6
;
997 sin6
->sin6_port
= th
->th_sport
;
998 sin6
->sin6_flowinfo
= 0;
999 sin6
->sin6_addr
= ip6
->ip6_src
;
1000 sin6
->sin6_scope_id
= 0;
1002 struct sockaddr_in
*sin
= (struct sockaddr_in
*)&from
;
1004 sin
->sin_len
= sizeof(*sin
);
1005 sin
->sin_family
= AF_INET
;
1006 sin
->sin_port
= th
->th_sport
;
1007 sin
->sin_addr
= ip
->ip_src
;
1009 so2
= sonewconn(so
, 0, (struct sockaddr
*)&from
);
1011 so2
= sonewconn(so
, 0, NULL
);
1014 tcpstat
.tcps_listendrop
++;
1015 if (tcpdropdropablreq(so
)) {
1017 so2
= sonewconn(so
, 0, (struct sockaddr
*)&from
);
1019 so2
= sonewconn(so
, 0, NULL
);
1025 * Make sure listening socket did not get closed during socket allocation,
1026 * not only this is incorrect but it is know to cause panic
1028 if (so
->so_gencnt
!= ogencnt
)
1032 tcp_unlock(so
, 0, 0); /* Unlock but keep a reference on listener for now */
1037 * This is ugly, but ....
1039 * Mark socket as temporary until we're
1040 * committed to keeping it. The code at
1041 * ``drop'' and ``dropwithreset'' check the
1042 * flag dropsocket to see if the temporary
1043 * socket created here should be discarded.
1044 * We mark the socket as discardable until
1045 * we're committed to it below in TCPS_LISTEN.
1048 inp
= (struct inpcb
*)so
->so_pcb
;
1051 inp
->in6p_laddr
= ip6
->ip6_dst
;
1053 inp
->inp_vflag
&= ~INP_IPV6
;
1054 inp
->inp_vflag
|= INP_IPV4
;
1056 inp
->inp_laddr
= ip
->ip_dst
;
1060 inp
->inp_lport
= th
->th_dport
;
1061 if (in_pcbinshash(inp
, 0) != 0) {
1063 * Undo the assignments above if we failed to
1064 * put the PCB on the hash lists.
1068 inp
->in6p_laddr
= in6addr_any
;
1071 inp
->inp_laddr
.s_addr
= INADDR_ANY
;
1073 tcp_lock(oso
, 0, 0); /* release ref on parent */
1074 tcp_unlock(oso
, 1, 0);
1079 * To avoid creating incorrectly cached IPsec
1080 * association, this is need to be done here.
1082 * Subject: (KAME-snap 748)
1083 * From: Wayne Knowles <w.knowles@niwa.cri.nz>
1084 * ftp://ftp.kame.net/pub/mail-list/snap-users/748
1086 if ((thflags
& (TH_RST
|TH_ACK
|TH_SYN
)) != TH_SYN
) {
1088 * Note: dropwithreset makes sure we don't
1089 * send a RST in response to a RST.
1091 tcp_lock(oso
, 0, 0); /* release ref on parent */
1092 tcp_unlock(oso
, 1, 0);
1093 if (thflags
& TH_ACK
) {
1094 tcpstat
.tcps_badsyn
++;
1095 rstreason
= BANDLIM_RST_OPENPORT
;
1104 * Inherit socket options from the listening
1106 * Note that in6p_inputopts are not (even
1107 * should not be) copied, since it stores
1108 * previously received options and is used to
1109 * detect if each new option is different than
1110 * the previous one and hence should be passed
1112 * If we copied in6p_inputopts, a user would
1113 * not be able to receive options just after
1114 * calling the accept system call.
1117 oinp
->inp_flags
& INP_CONTROLOPTS
;
1118 if (oinp
->in6p_outputopts
)
1119 inp
->in6p_outputopts
=
1120 ip6_copypktopts(oinp
->in6p_outputopts
,
1124 inp
->inp_options
= ip_srcroute();
1125 tcp_lock(oso
, 0, 0);
1127 /* copy old policy into new socket's */
1128 if (sotoinpcb(oso
)->inp_sp
)
1131 lck_mtx_lock(sadb_mutex
);
1132 /* Is it a security hole here to silently fail to copy the policy? */
1133 if (inp
->inp_sp
!= NULL
)
1134 error
= ipsec_init_policy(so
, &inp
->inp_sp
);
1135 if (error
!= 0 || ipsec_copy_policy(sotoinpcb(oso
)->inp_sp
, inp
->inp_sp
))
1136 printf("tcp_input: could not copy policy\n");
1137 lck_mtx_unlock(sadb_mutex
);
1140 tcp_unlock(oso
, 1, 0); /* now drop the reference on the listener */
1141 tp
= intotcpcb(inp
);
1142 tp
->t_state
= TCPS_LISTEN
;
1143 tp
->t_flags
|= tp0
->t_flags
& (TF_NOPUSH
|TF_NOOPT
|TF_NODELAY
);
1144 tp
->t_inpcb
->inp_ip_ttl
= tp0
->t_inpcb
->inp_ip_ttl
;
1145 /* Compute proper scaling value from buffer space */
1146 while (tp
->request_r_scale
< TCP_MAX_WINSHIFT
&&
1147 TCP_MAXWIN
<< tp
->request_r_scale
<
1148 so
->so_rcv
.sb_hiwat
)
1149 tp
->request_r_scale
++;
1151 KERNEL_DEBUG(DBG_FNC_TCP_NEWCONN
| DBG_FUNC_END
,0,0,0,0,0);
1156 lck_mtx_assert(((struct inpcb
*)so
->so_pcb
)->inpcb_mtx
, LCK_MTX_ASSERT_OWNED
);
1160 * This is the second part of the MSS DoS prevention code (after
1161 * minmss on the sending side) and it deals with too many too small
1162 * tcp packets in a too short timeframe (1 second).
1164 * For every full second we count the number of received packets
1165 * and bytes. If we get a lot of packets per second for this connection
1166 * (tcp_minmssoverload) we take a closer look at it and compute the
1167 * average packet size for the past second. If that is less than
1168 * tcp_minmss we get too many packets with very small payload which
1169 * is not good and burdens our system (and every packet generates
1170 * a wakeup to the process connected to our socket). We can reasonable
1171 * expect this to be small packet DoS attack to exhaust our CPU
1174 * Care has to be taken for the minimum packet overload value. This
1175 * value defines the minimum number of packets per second before we
1176 * start to worry. This must not be too low to avoid killing for
1177 * example interactive connections with many small packets like
1181 * Account for packet if payload packet, skip over ACK, etc.
1183 * The packet per second count is done all the time and is also used
1184 * by "DELAY_ACK" to detect streaming situations.
1187 if (tp
->t_state
== TCPS_ESTABLISHED
&& tlen
> 0) {
1188 if (tp
->rcv_reset
> tcp_now
) {
1190 tp
->rcv_byps
+= tlen
+ off
;
1192 * Setting either tcp_minmssoverload or tcp_minmss to "0" disables
1195 if (tcp_minmss
&& tcp_minmssoverload
&& tp
->rcv_pps
> tcp_minmssoverload
) {
1196 if ((tp
->rcv_byps
/ tp
->rcv_pps
) < tcp_minmss
) {
1197 char ipstrbuf
[MAX_IPv6_STR_LEN
];
1198 printf("too many small tcp packets from "
1199 "%s:%u, av. %lubyte/packet, "
1200 "dropping connection\n",
1203 inet_ntop(AF_INET6
, &inp
->in6p_faddr
, ipstrbuf
,
1206 inet_ntop(AF_INET
, &inp
->inp_faddr
, ipstrbuf
,
1209 tp
->rcv_byps
/ tp
->rcv_pps
);
1210 tp
= tcp_drop(tp
, ECONNRESET
);
1211 /* tcpstat.tcps_minmssdrops++; */
1216 tp
->rcv_reset
= tcp_now
+ PR_SLOWHZ
;
1218 tp
->rcv_byps
= tlen
+ off
;
1223 * Segment received on connection.
1224 * Reset idle time and keep-alive timer.
1227 if (TCPS_HAVEESTABLISHED(tp
->t_state
))
1228 tp
->t_timer
[TCPT_KEEP
] = TCP_KEEPIDLE(tp
);
1231 * Process options if not in LISTEN state,
1232 * else do it below (after getting remote address).
1234 if (tp
->t_state
!= TCPS_LISTEN
&& optp
)
1235 tcp_dooptions(tp
, optp
, optlen
, th
, &to
);
1237 if (tp
->t_state
== TCPS_SYN_SENT
&& (thflags
& TH_SYN
)) {
1238 if (to
.to_flags
& TOF_SCALE
) {
1239 tp
->t_flags
|= TF_RCVD_SCALE
;
1240 tp
->requested_s_scale
= to
.to_requested_s_scale
;
1242 if (to
.to_flags
& TOF_TS
) {
1243 tp
->t_flags
|= TF_RCVD_TSTMP
;
1244 tp
->ts_recent
= to
.to_tsval
;
1245 tp
->ts_recent_age
= tcp_now
;
1247 if (to
.to_flags
& TOF_MSS
)
1248 tcp_mss(tp
, to
.to_mss
);
1249 if (tp
->sack_enable
) {
1250 if (!(to
.to_flags
& TOF_SACK
))
1251 tp
->sack_enable
= 0;
1253 tp
->t_flags
|= TF_SACK_PERMIT
;
1258 * Header prediction: check for the two common cases
1259 * of a uni-directional data xfer. If the packet has
1260 * no control flags, is in-sequence, the window didn't
1261 * change and we're not retransmitting, it's a
1262 * candidate. If the length is zero and the ack moved
1263 * forward, we're the sender side of the xfer. Just
1264 * free the data acked & wake any higher level process
1265 * that was blocked waiting for space. If the length
1266 * is non-zero and the ack didn't move, we're the
1267 * receiver side. If we're getting packets in-order
1268 * (the reassembly queue is empty), add the data to
1269 * the socket buffer and note that we need a delayed ack.
1270 * Make sure that the hidden state-flags are also off.
1271 * Since we check for TCPS_ESTABLISHED above, it can only
1274 if (tp
->t_state
== TCPS_ESTABLISHED
&&
1275 (thflags
& (TH_SYN
|TH_FIN
|TH_RST
|TH_URG
|TH_ACK
)) == TH_ACK
&&
1276 ((tp
->t_flags
& (TF_NEEDSYN
|TF_NEEDFIN
)) == 0) &&
1277 ((to
.to_flags
& TOF_TS
) == 0 ||
1278 TSTMP_GEQ(to
.to_tsval
, tp
->ts_recent
)) &&
1279 th
->th_seq
== tp
->rcv_nxt
&&
1280 tiwin
&& tiwin
== tp
->snd_wnd
&&
1281 tp
->snd_nxt
== tp
->snd_max
) {
1284 * If last ACK falls within this segment's sequence numbers,
1285 * record the timestamp.
1286 * NOTE that the test is modified according to the latest
1287 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1289 if ((to
.to_flags
& TOF_TS
) != 0 &&
1290 SEQ_LEQ(th
->th_seq
, tp
->last_ack_sent
)) {
1291 tp
->ts_recent_age
= tcp_now
;
1292 tp
->ts_recent
= to
.to_tsval
;
1296 if (SEQ_GT(th
->th_ack
, tp
->snd_una
) &&
1297 SEQ_LEQ(th
->th_ack
, tp
->snd_max
) &&
1298 tp
->snd_cwnd
>= tp
->snd_wnd
&&
1299 ((!tcp_do_newreno
&& !tp
->sack_enable
&&
1300 tp
->t_dupacks
< tcprexmtthresh
) ||
1301 ((tcp_do_newreno
|| tp
->sack_enable
) &&
1302 !IN_FASTRECOVERY(tp
) && to
.to_nsacks
== 0 &&
1303 TAILQ_EMPTY(&tp
->snd_holes
)))) {
1305 * this is a pure ack for outstanding data.
1307 ++tcpstat
.tcps_predack
;
1309 * "bad retransmit" recovery
1311 if (tp
->t_rxtshift
== 1 &&
1312 tcp_now
< tp
->t_badrxtwin
) {
1313 tp
->snd_cwnd
= tp
->snd_cwnd_prev
;
1315 tp
->snd_ssthresh_prev
;
1316 tp
->snd_recover
= tp
->snd_recover_prev
;
1317 if (tp
->t_flags
& TF_WASFRECOVERY
)
1318 ENTER_FASTRECOVERY(tp
);
1319 tp
->snd_nxt
= tp
->snd_max
;
1320 tp
->t_badrxtwin
= 0;
1322 if (((to
.to_flags
& TOF_TS
) != 0) && (to
.to_tsecr
!= 0)) /* Makes sure we already have a TS */
1324 tcp_now
- to
.to_tsecr
+ 1);
1325 else if (tp
->t_rtttime
&&
1326 SEQ_GT(th
->th_ack
, tp
->t_rtseq
))
1327 tcp_xmit_timer(tp
, tp
->t_rtttime
);
1328 acked
= th
->th_ack
- tp
->snd_una
;
1329 tcpstat
.tcps_rcvackpack
++;
1330 tcpstat
.tcps_rcvackbyte
+= acked
;
1331 sbdrop(&so
->so_snd
, acked
);
1332 if (SEQ_GT(tp
->snd_una
, tp
->snd_recover
) &&
1333 SEQ_LEQ(th
->th_ack
, tp
->snd_recover
))
1334 tp
->snd_recover
= th
->th_ack
- 1;
1335 tp
->snd_una
= th
->th_ack
;
1337 * pull snd_wl2 up to prevent seq wrap relative
1340 tp
->snd_wl2
= th
->th_ack
;
1343 ND6_HINT(tp
); /* some progress has been done */
1346 * If all outstanding data are acked, stop
1347 * retransmit timer, otherwise restart timer
1348 * using current (possibly backed-off) value.
1349 * If process is waiting for space,
1350 * wakeup/selwakeup/signal. If data
1351 * are ready to send, let tcp_output
1352 * decide between more output or persist.
1354 if (tp
->snd_una
== tp
->snd_max
)
1355 tp
->t_timer
[TCPT_REXMT
] = 0;
1356 else if (tp
->t_timer
[TCPT_PERSIST
] == 0)
1357 tp
->t_timer
[TCPT_REXMT
] = tp
->t_rxtcur
;
1359 sowwakeup(so
); /* has to be done with socket lock held */
1360 if ((so
->so_snd
.sb_cc
) || (tp
->t_flags
& TF_ACKNOW
))
1361 (void) tcp_output(tp
);
1362 tcp_unlock(so
, 1, 0);
1363 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
1366 } else if (th
->th_ack
== tp
->snd_una
&&
1367 LIST_EMPTY(&tp
->t_segq
) &&
1368 tlen
<= sbspace(&so
->so_rcv
)) {
1370 * this is a pure, in-sequence data packet
1371 * with nothing on the reassembly queue and
1372 * we have enough buffer space to take it.
1374 /* Clean receiver SACK report if present */
1375 if (tp
->sack_enable
&& tp
->rcv_numsacks
)
1376 tcp_clean_sackreport(tp
);
1377 ++tcpstat
.tcps_preddat
;
1378 tp
->rcv_nxt
+= tlen
;
1380 * Pull snd_wl1 up to prevent seq wrap relative to
1383 tp
->snd_wl1
= th
->th_seq
;
1385 * Pull rcv_up up to prevent seq wrap relative to
1388 tp
->rcv_up
= tp
->rcv_nxt
;
1389 tcpstat
.tcps_rcvpack
++;
1390 tcpstat
.tcps_rcvbyte
+= tlen
;
1391 ND6_HINT(tp
); /* some progress has been done */
1393 * Add data to socket buffer.
1395 m_adj(m
, drop_hdrlen
); /* delayed header drop */
1396 if (sbappend(&so
->so_rcv
, m
))
1400 KERNEL_DEBUG(DBG_LAYER_END
, ((th
->th_dport
<< 16) | th
->th_sport
),
1401 (((ip6
->ip6_src
.s6_addr16
[0]) << 16) | (ip6
->ip6_dst
.s6_addr16
[0])),
1402 th
->th_seq
, th
->th_ack
, th
->th_win
);
1407 KERNEL_DEBUG(DBG_LAYER_END
, ((th
->th_dport
<< 16) | th
->th_sport
),
1408 (((ip
->ip_src
.s_addr
& 0xffff) << 16) | (ip
->ip_dst
.s_addr
& 0xffff)),
1409 th
->th_seq
, th
->th_ack
, th
->th_win
);
1411 if (DELAY_ACK(tp
)) {
1412 tp
->t_flags
|= TF_DELACK
;
1414 tp
->t_flags
|= TF_ACKNOW
;
1417 tcp_unlock(so
, 1, 0);
1418 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
1424 * Calculate amount of space in receive window,
1425 * and then do TCP input processing.
1426 * Receive window is amount of space in rcv queue,
1427 * but not less than advertised window.
1430 lck_mtx_assert(((struct inpcb
*)so
->so_pcb
)->inpcb_mtx
, LCK_MTX_ASSERT_OWNED
);
1434 win
= sbspace(&so
->so_rcv
);
1437 else { /* clip rcv window to 4K for modems */
1438 if (tp
->t_flags
& TF_SLOWLINK
&& slowlink_wsize
> 0)
1439 win
= min(win
, slowlink_wsize
);
1441 tp
->rcv_wnd
= imax(win
, (int)(tp
->rcv_adv
- tp
->rcv_nxt
));
1444 switch (tp
->t_state
) {
1447 * If the state is LISTEN then ignore segment if it contains an RST.
1448 * If the segment contains an ACK then it is bad and send a RST.
1449 * If it does not contain a SYN then it is not interesting; drop it.
1450 * If it is from this socket, drop it, it must be forged.
1451 * Don't bother responding if the destination was a broadcast.
1452 * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial
1453 * tp->iss, and send a segment:
1454 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
1455 * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
1456 * Fill in remote peer address fields if not previously specified.
1457 * Enter SYN_RECEIVED state, and process any other fields of this
1458 * segment in this state.
1461 register struct sockaddr_in
*sin
;
1463 register struct sockaddr_in6
*sin6
;
1467 lck_mtx_assert(((struct inpcb
*)so
->so_pcb
)->inpcb_mtx
, LCK_MTX_ASSERT_OWNED
);
1469 if (thflags
& TH_RST
)
1471 if (thflags
& TH_ACK
) {
1472 rstreason
= BANDLIM_RST_OPENPORT
;
1475 if ((thflags
& TH_SYN
) == 0)
1477 if (th
->th_dport
== th
->th_sport
) {
1480 if (IN6_ARE_ADDR_EQUAL(&ip6
->ip6_dst
,
1485 if (ip
->ip_dst
.s_addr
== ip
->ip_src
.s_addr
)
1489 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
1490 * in_broadcast() should never return true on a received
1491 * packet with M_BCAST not set.
1493 * Packets with a multicast source address should also
1496 if (m
->m_flags
& (M_BCAST
|M_MCAST
))
1500 if (IN6_IS_ADDR_MULTICAST(&ip6
->ip6_dst
) ||
1501 IN6_IS_ADDR_MULTICAST(&ip6
->ip6_src
))
1505 if (IN_MULTICAST(ntohl(ip
->ip_dst
.s_addr
)) ||
1506 IN_MULTICAST(ntohl(ip
->ip_src
.s_addr
)) ||
1507 ip
->ip_src
.s_addr
== htonl(INADDR_BROADCAST
) ||
1508 in_broadcast(ip
->ip_dst
, m
->m_pkthdr
.rcvif
))
1512 MALLOC(sin6
, struct sockaddr_in6
*, sizeof *sin6
,
1513 M_SONAME
, M_NOWAIT
);
1516 bzero(sin6
, sizeof(*sin6
));
1517 sin6
->sin6_family
= AF_INET6
;
1518 sin6
->sin6_len
= sizeof(*sin6
);
1519 sin6
->sin6_addr
= ip6
->ip6_src
;
1520 sin6
->sin6_port
= th
->th_sport
;
1521 laddr6
= inp
->in6p_laddr
;
1522 if (IN6_IS_ADDR_UNSPECIFIED(&inp
->in6p_laddr
))
1523 inp
->in6p_laddr
= ip6
->ip6_dst
;
1524 if (in6_pcbconnect(inp
, (struct sockaddr
*)sin6
,
1526 inp
->in6p_laddr
= laddr6
;
1527 FREE(sin6
, M_SONAME
);
1530 FREE(sin6
, M_SONAME
);
1535 lck_mtx_assert(((struct inpcb
*)so
->so_pcb
)->inpcb_mtx
, LCK_MTX_ASSERT_OWNED
);
1537 MALLOC(sin
, struct sockaddr_in
*, sizeof *sin
, M_SONAME
,
1541 sin
->sin_family
= AF_INET
;
1542 sin
->sin_len
= sizeof(*sin
);
1543 sin
->sin_addr
= ip
->ip_src
;
1544 sin
->sin_port
= th
->th_sport
;
1545 bzero((caddr_t
)sin
->sin_zero
, sizeof(sin
->sin_zero
));
1546 laddr
= inp
->inp_laddr
;
1547 if (inp
->inp_laddr
.s_addr
== INADDR_ANY
)
1548 inp
->inp_laddr
= ip
->ip_dst
;
1549 if (in_pcbconnect(inp
, (struct sockaddr
*)sin
, proc0
)) {
1550 inp
->inp_laddr
= laddr
;
1551 FREE(sin
, M_SONAME
);
1554 FREE(sin
, M_SONAME
);
1557 tcp_dooptions(tp
, optp
, optlen
, th
, &to
);
1559 if (tp
->sack_enable
) {
1560 if (!(to
.to_flags
& TOF_SACK
))
1561 tp
->sack_enable
= 0;
1563 tp
->t_flags
|= TF_SACK_PERMIT
;
1569 tp
->iss
= tcp_new_isn(tp
);
1571 tp
->irs
= th
->th_seq
;
1572 tcp_sendseqinit(tp
);
1574 tp
->snd_recover
= tp
->snd_una
;
1576 * Initialization of the tcpcb for transaction;
1577 * set SND.WND = SEG.WND,
1578 * initialize CCsend and CCrecv.
1580 tp
->snd_wnd
= tiwin
; /* initial send-window */
1581 tp
->t_flags
|= TF_ACKNOW
;
1582 tp
->t_state
= TCPS_SYN_RECEIVED
;
1583 tp
->t_timer
[TCPT_KEEP
] = tcp_keepinit
;
1584 dropsocket
= 0; /* committed to socket */
1585 tcpstat
.tcps_accepts
++;
1590 * If the state is SYN_RECEIVED:
1591 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1593 case TCPS_SYN_RECEIVED
:
1594 if ((thflags
& TH_ACK
) &&
1595 (SEQ_LEQ(th
->th_ack
, tp
->snd_una
) ||
1596 SEQ_GT(th
->th_ack
, tp
->snd_max
))) {
1597 rstreason
= BANDLIM_RST_OPENPORT
;
1603 * If the state is SYN_SENT:
1604 * if seg contains an ACK, but not for our SYN, drop the input.
1605 * if seg contains a RST, then drop the connection.
1606 * if seg does not contain SYN, then drop it.
1607 * Otherwise this is an acceptable SYN segment
1608 * initialize tp->rcv_nxt and tp->irs
1609 * if seg contains ack then advance tp->snd_una
1610 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1611 * arrange for segment to be acked (eventually)
1612 * continue processing rest of data/controls, beginning with URG
1615 if ((thflags
& TH_ACK
) &&
1616 (SEQ_LEQ(th
->th_ack
, tp
->iss
) ||
1617 SEQ_GT(th
->th_ack
, tp
->snd_max
))) {
1618 rstreason
= BANDLIM_UNLIMITED
;
1621 if (thflags
& TH_RST
) {
1622 if (thflags
& TH_ACK
) {
1623 tp
= tcp_drop(tp
, ECONNREFUSED
);
1624 postevent(so
, 0, EV_RESET
);
1628 if ((thflags
& TH_SYN
) == 0)
1630 tp
->snd_wnd
= th
->th_win
; /* initial send window */
1632 tp
->irs
= th
->th_seq
;
1634 if (thflags
& TH_ACK
) {
1635 tcpstat
.tcps_connects
++;
1637 /* Do window scaling on this connection? */
1638 if ((tp
->t_flags
& (TF_RCVD_SCALE
|TF_REQ_SCALE
)) ==
1639 (TF_RCVD_SCALE
|TF_REQ_SCALE
)) {
1640 tp
->snd_scale
= tp
->requested_s_scale
;
1641 tp
->rcv_scale
= tp
->request_r_scale
;
1643 tp
->rcv_adv
+= tp
->rcv_wnd
;
1644 tp
->snd_una
++; /* SYN is acked */
1646 * If there's data, delay ACK; if there's also a FIN
1647 * ACKNOW will be turned on later.
1649 if (DELAY_ACK(tp
) && tlen
!= 0) {
1650 tp
->t_flags
|= TF_DELACK
;
1653 tp
->t_flags
|= TF_ACKNOW
;
1656 * Received <SYN,ACK> in SYN_SENT[*] state.
1658 * SYN_SENT --> ESTABLISHED
1659 * SYN_SENT* --> FIN_WAIT_1
1661 tp
->t_starttime
= 0;
1662 if (tp
->t_flags
& TF_NEEDFIN
) {
1663 tp
->t_state
= TCPS_FIN_WAIT_1
;
1664 tp
->t_flags
&= ~TF_NEEDFIN
;
1667 tp
->t_state
= TCPS_ESTABLISHED
;
1668 tp
->t_timer
[TCPT_KEEP
] = TCP_KEEPIDLE(tp
);
1672 * Received initial SYN in SYN-SENT[*] state => simul-
1673 * taneous open. If segment contains CC option and there is
1674 * a cached CC, apply TAO test; if it succeeds, connection is
1675 * half-synchronized. Otherwise, do 3-way handshake:
1676 * SYN-SENT -> SYN-RECEIVED
1677 * SYN-SENT* -> SYN-RECEIVED*
1679 tp
->t_flags
|= TF_ACKNOW
;
1680 tp
->t_timer
[TCPT_REXMT
] = 0;
1681 tp
->t_state
= TCPS_SYN_RECEIVED
;
1687 * Advance th->th_seq to correspond to first data byte.
1688 * If data, trim to stay within window,
1689 * dropping FIN if necessary.
1692 if (tlen
> tp
->rcv_wnd
) {
1693 todrop
= tlen
- tp
->rcv_wnd
;
1697 tcpstat
.tcps_rcvpackafterwin
++;
1698 tcpstat
.tcps_rcvbyteafterwin
+= todrop
;
1700 tp
->snd_wl1
= th
->th_seq
- 1;
1701 tp
->rcv_up
= th
->th_seq
;
1703 * Client side of transaction: already sent SYN and data.
1704 * If the remote host used T/TCP to validate the SYN,
1705 * our data will be ACK'd; if so, enter normal data segment
1706 * processing in the middle of step 5, ack processing.
1707 * Otherwise, goto step 6.
1709 if (thflags
& TH_ACK
)
1713 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1714 * do normal processing.
1716 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
1720 case TCPS_TIME_WAIT
:
1721 break; /* continue normal processing */
1723 /* Received a SYN while connection is already established.
1724 * This is a "half open connection and other anomalies" described
1725 * in RFC793 page 34, send an ACK so the remote reset the connection
1726 * or recovers by adjusting its sequence numberering
1728 case TCPS_ESTABLISHED
:
1729 if (thflags
& TH_SYN
)
1735 * States other than LISTEN or SYN_SENT.
1736 * First check the RST flag and sequence number since reset segments
1737 * are exempt from the timestamp and connection count tests. This
1738 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1739 * below which allowed reset segments in half the sequence space
1740 * to fall though and be processed (which gives forged reset
1741 * segments with a random sequence number a 50 percent chance of
1742 * killing a connection).
1743 * Then check timestamp, if present.
1744 * Then check the connection count, if present.
1745 * Then check that at least some bytes of segment are within
1746 * receive window. If segment begins before rcv_nxt,
1747 * drop leading data (and SYN); if nothing left, just ack.
1750 * If the RST bit is set, check the sequence number to see
1751 * if this is a valid reset segment.
1753 * In all states except SYN-SENT, all reset (RST) segments
1754 * are validated by checking their SEQ-fields. A reset is
1755 * valid if its sequence number is in the window.
1756 * Note: this does not take into account delayed ACKs, so
1757 * we should test against last_ack_sent instead of rcv_nxt.
1758 * The sequence number in the reset segment is normally an
1759 * echo of our outgoing acknowlegement numbers, but some hosts
1760 * send a reset with the sequence number at the rightmost edge
1761 * of our receive window, and we have to handle this case.
1762 * Note 2: Paul Watson's paper "Slipping in the Window" has shown
1763 * that brute force RST attacks are possible. To combat this,
1764 * we use a much stricter check while in the ESTABLISHED state,
1765 * only accepting RSTs where the sequence number is equal to
1766 * last_ack_sent. In all other states (the states in which a
1767 * RST is more likely), the more permissive check is used.
1768 * If we have multiple segments in flight, the intial reset
1769 * segment sequence numbers will be to the left of last_ack_sent,
1770 * but they will eventually catch up.
1771 * In any case, it never made sense to trim reset segments to
1772 * fit the receive window since RFC 1122 says:
1773 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1775 * A TCP SHOULD allow a received RST segment to include data.
1778 * It has been suggested that a RST segment could contain
1779 * ASCII text that encoded and explained the cause of the
1780 * RST. No standard has yet been established for such
1783 * If the reset segment passes the sequence number test examine
1785 * SYN_RECEIVED STATE:
1786 * If passive open, return to LISTEN state.
1787 * If active open, inform user that connection was refused.
1788 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1789 * Inform user that connection was reset, and close tcb.
1790 * CLOSING, LAST_ACK STATES:
1793 * Drop the segment - see Stevens, vol. 2, p. 964 and
1796 if (thflags
& TH_RST
) {
1797 if ((SEQ_GEQ(th
->th_seq
, tp
->last_ack_sent
) &&
1798 SEQ_LT(th
->th_seq
, tp
->last_ack_sent
+ tp
->rcv_wnd
)) ||
1799 (tp
->rcv_wnd
== 0 && tp
->last_ack_sent
== th
->th_seq
)) {
1800 switch (tp
->t_state
) {
1802 case TCPS_SYN_RECEIVED
:
1803 so
->so_error
= ECONNREFUSED
;
1806 case TCPS_ESTABLISHED
:
1807 if (tp
->last_ack_sent
!= th
->th_seq
) {
1810 case TCPS_FIN_WAIT_1
:
1811 case TCPS_CLOSE_WAIT
:
1815 case TCPS_FIN_WAIT_2
:
1816 so
->so_error
= ECONNRESET
;
1818 postevent(so
, 0, EV_RESET
);
1819 tp
->t_state
= TCPS_CLOSED
;
1820 tcpstat
.tcps_drops
++;
1829 case TCPS_TIME_WAIT
:
1837 lck_mtx_assert(((struct inpcb
*)so
->so_pcb
)->inpcb_mtx
, LCK_MTX_ASSERT_OWNED
);
1840 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1841 * and it's less than ts_recent, drop it.
1843 if ((to
.to_flags
& TOF_TS
) != 0 && tp
->ts_recent
&&
1844 TSTMP_LT(to
.to_tsval
, tp
->ts_recent
)) {
1846 /* Check to see if ts_recent is over 24 days old. */
1847 if ((int)(tcp_now
- tp
->ts_recent_age
) > TCP_PAWS_IDLE
) {
1849 * Invalidate ts_recent. If this segment updates
1850 * ts_recent, the age will be reset later and ts_recent
1851 * will get a valid value. If it does not, setting
1852 * ts_recent to zero will at least satisfy the
1853 * requirement that zero be placed in the timestamp
1854 * echo reply when ts_recent isn't valid. The
1855 * age isn't reset until we get a valid ts_recent
1856 * because we don't want out-of-order segments to be
1857 * dropped when ts_recent is old.
1861 tcpstat
.tcps_rcvduppack
++;
1862 tcpstat
.tcps_rcvdupbyte
+= tlen
;
1863 tcpstat
.tcps_pawsdrop
++;
1871 * In the SYN-RECEIVED state, validate that the packet belongs to
1872 * this connection before trimming the data to fit the receive
1873 * window. Check the sequence number versus IRS since we know
1874 * the sequence numbers haven't wrapped. This is a partial fix
1875 * for the "LAND" DoS attack.
1877 if (tp
->t_state
== TCPS_SYN_RECEIVED
&& SEQ_LT(th
->th_seq
, tp
->irs
)) {
1878 rstreason
= BANDLIM_RST_OPENPORT
;
1882 todrop
= tp
->rcv_nxt
- th
->th_seq
;
1884 if (thflags
& TH_SYN
) {
1894 * Following if statement from Stevens, vol. 2, p. 960.
1897 || (todrop
== tlen
&& (thflags
& TH_FIN
) == 0)) {
1899 * Any valid FIN must be to the left of the window.
1900 * At this point the FIN must be a duplicate or out
1901 * of sequence; drop it.
1906 * Send an ACK to resynchronize and drop any data.
1907 * But keep on processing for RST or ACK.
1909 tp
->t_flags
|= TF_ACKNOW
;
1911 tcpstat
.tcps_rcvduppack
++;
1912 tcpstat
.tcps_rcvdupbyte
+= todrop
;
1914 tcpstat
.tcps_rcvpartduppack
++;
1915 tcpstat
.tcps_rcvpartdupbyte
+= todrop
;
1917 drop_hdrlen
+= todrop
; /* drop from the top afterwards */
1918 th
->th_seq
+= todrop
;
1920 if (th
->th_urp
> todrop
)
1921 th
->th_urp
-= todrop
;
1929 * If new data are received on a connection after the
1930 * user processes are gone, then RST the other end.
1932 if ((so
->so_state
& SS_NOFDREF
) &&
1933 tp
->t_state
> TCPS_CLOSE_WAIT
&& tlen
) {
1935 tcpstat
.tcps_rcvafterclose
++;
1936 rstreason
= BANDLIM_UNLIMITED
;
1941 * If segment ends after window, drop trailing data
1942 * (and PUSH and FIN); if nothing left, just ACK.
1944 todrop
= (th
->th_seq
+tlen
) - (tp
->rcv_nxt
+tp
->rcv_wnd
);
1946 tcpstat
.tcps_rcvpackafterwin
++;
1947 if (todrop
>= tlen
) {
1948 tcpstat
.tcps_rcvbyteafterwin
+= tlen
;
1950 * If a new connection request is received
1951 * while in TIME_WAIT, drop the old connection
1952 * and start over if the sequence numbers
1953 * are above the previous ones.
1955 if (thflags
& TH_SYN
&&
1956 tp
->t_state
== TCPS_TIME_WAIT
&&
1957 SEQ_GT(th
->th_seq
, tp
->rcv_nxt
)) {
1958 iss
= tcp_new_isn(tp
);
1960 tcp_unlock(so
, 1, 0);
1964 * If window is closed can only take segments at
1965 * window edge, and have to drop data and PUSH from
1966 * incoming segments. Continue processing, but
1967 * remember to ack. Otherwise, drop segment
1970 if (tp
->rcv_wnd
== 0 && th
->th_seq
== tp
->rcv_nxt
) {
1971 tp
->t_flags
|= TF_ACKNOW
;
1972 tcpstat
.tcps_rcvwinprobe
++;
1976 tcpstat
.tcps_rcvbyteafterwin
+= todrop
;
1979 thflags
&= ~(TH_PUSH
|TH_FIN
);
1983 * If last ACK falls within this segment's sequence numbers,
1984 * record its timestamp.
1986 * 1) That the test incorporates suggestions from the latest
1987 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1988 * 2) That updating only on newer timestamps interferes with
1989 * our earlier PAWS tests, so this check should be solely
1990 * predicated on the sequence space of this segment.
1991 * 3) That we modify the segment boundary check to be
1992 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
1993 * instead of RFC1323's
1994 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
1995 * This modified check allows us to overcome RFC1323's
1996 * limitations as described in Stevens TCP/IP Illustrated
1997 * Vol. 2 p.869. In such cases, we can still calculate the
1998 * RTT correctly when RCV.NXT == Last.ACK.Sent.
2000 if ((to
.to_flags
& TOF_TS
) != 0 &&
2001 SEQ_LEQ(th
->th_seq
, tp
->last_ack_sent
) &&
2002 SEQ_LEQ(tp
->last_ack_sent
, th
->th_seq
+ tlen
+
2003 ((thflags
& (TH_SYN
|TH_FIN
)) != 0))) {
2004 tp
->ts_recent_age
= tcp_now
;
2005 tp
->ts_recent
= to
.to_tsval
;
2009 * If a SYN is in the window, then this is an
2010 * error and we send an RST and drop the connection.
2012 if (thflags
& TH_SYN
) {
2013 tp
= tcp_drop(tp
, ECONNRESET
);
2014 rstreason
= BANDLIM_UNLIMITED
;
2015 postevent(so
, 0, EV_RESET
);
2020 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
2021 * flag is on (half-synchronized state), then queue data for
2022 * later processing; else drop segment and return.
2024 if ((thflags
& TH_ACK
) == 0) {
2025 if (tp
->t_state
== TCPS_SYN_RECEIVED
||
2026 (tp
->t_flags
& TF_NEEDSYN
))
2035 switch (tp
->t_state
) {
2038 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
2039 * ESTABLISHED state and continue processing.
2040 * The ACK was checked above.
2042 case TCPS_SYN_RECEIVED
:
2044 tcpstat
.tcps_connects
++;
2047 /* Do window scaling? */
2048 if ((tp
->t_flags
& (TF_RCVD_SCALE
|TF_REQ_SCALE
)) ==
2049 (TF_RCVD_SCALE
|TF_REQ_SCALE
)) {
2050 tp
->snd_scale
= tp
->requested_s_scale
;
2051 tp
->rcv_scale
= tp
->request_r_scale
;
2055 * SYN-RECEIVED -> ESTABLISHED
2056 * SYN-RECEIVED* -> FIN-WAIT-1
2058 tp
->t_starttime
= 0;
2059 if (tp
->t_flags
& TF_NEEDFIN
) {
2060 tp
->t_state
= TCPS_FIN_WAIT_1
;
2061 tp
->t_flags
&= ~TF_NEEDFIN
;
2063 tp
->t_state
= TCPS_ESTABLISHED
;
2064 tp
->t_timer
[TCPT_KEEP
] = TCP_KEEPIDLE(tp
);
2067 * If segment contains data or ACK, will call tcp_reass()
2068 * later; if not, do so now to pass queued data to user.
2070 if (tlen
== 0 && (thflags
& TH_FIN
) == 0)
2071 (void) tcp_reass(tp
, (struct tcphdr
*)0, 0,
2073 tp
->snd_wl1
= th
->th_seq
- 1;
2077 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2078 * ACKs. If the ack is in the range
2079 * tp->snd_una < th->th_ack <= tp->snd_max
2080 * then advance tp->snd_una to th->th_ack and drop
2081 * data from the retransmission queue. If this ACK reflects
2082 * more up to date window information we update our window information.
2084 case TCPS_ESTABLISHED
:
2085 case TCPS_FIN_WAIT_1
:
2086 case TCPS_FIN_WAIT_2
:
2087 case TCPS_CLOSE_WAIT
:
2090 case TCPS_TIME_WAIT
:
2091 if (SEQ_GT(th
->th_ack
, tp
->snd_max
)) {
2092 tcpstat
.tcps_rcvacktoomuch
++;
2095 if (tp
->sack_enable
&&
2096 (to
.to_nsacks
> 0 || !TAILQ_EMPTY(&tp
->snd_holes
)))
2097 tcp_sack_doack(tp
, &to
, th
->th_ack
);
2098 if (SEQ_LEQ(th
->th_ack
, tp
->snd_una
)) {
2099 if (tlen
== 0 && tiwin
== tp
->snd_wnd
) {
2100 tcpstat
.tcps_rcvdupack
++;
2102 * If we have outstanding data (other than
2103 * a window probe), this is a completely
2104 * duplicate ack (ie, window info didn't
2105 * change), the ack is the biggest we've
2106 * seen and we've seen exactly our rexmt
2107 * threshhold of them, assume a packet
2108 * has been dropped and retransmit it.
2109 * Kludge snd_nxt & the congestion
2110 * window so we send only this one
2113 * We know we're losing at the current
2114 * window size so do congestion avoidance
2115 * (set ssthresh to half the current window
2116 * and pull our congestion window back to
2117 * the new ssthresh).
2119 * Dup acks mean that packets have left the
2120 * network (they're now cached at the receiver)
2121 * so bump cwnd by the amount in the receiver
2122 * to keep a constant cwnd packets in the
2125 if (tp
->t_timer
[TCPT_REXMT
] == 0 ||
2126 th
->th_ack
!= tp
->snd_una
)
2128 else if (++tp
->t_dupacks
> tcprexmtthresh
||
2129 ((tcp_do_newreno
|| tp
->sack_enable
) &&
2130 IN_FASTRECOVERY(tp
))) {
2131 if (tp
->sack_enable
&& IN_FASTRECOVERY(tp
)) {
2135 * Compute the amount of data in flight first.
2136 * We can inject new data into the pipe iff
2137 * we have less than 1/2 the original window's
2138 * worth of data in flight.
2140 awnd
= (tp
->snd_nxt
- tp
->snd_fack
) +
2141 tp
->sackhint
.sack_bytes_rexmit
;
2142 if (awnd
< tp
->snd_ssthresh
) {
2143 tp
->snd_cwnd
+= tp
->t_maxseg
;
2144 if (tp
->snd_cwnd
> tp
->snd_ssthresh
)
2145 tp
->snd_cwnd
= tp
->snd_ssthresh
;
2148 tp
->snd_cwnd
+= tp
->t_maxseg
;
2149 (void) tcp_output(tp
);
2151 } else if (tp
->t_dupacks
== tcprexmtthresh
) {
2152 tcp_seq onxt
= tp
->snd_nxt
;
2156 * If we're doing sack, check to
2157 * see if we're already in sack
2158 * recovery. If we're not doing sack,
2159 * check to see if we're in newreno
2162 if (tp
->sack_enable
) {
2163 if (IN_FASTRECOVERY(tp
)) {
2167 } else if (tcp_do_newreno
) {
2168 if (SEQ_LEQ(th
->th_ack
,
2174 win
= min(tp
->snd_wnd
, tp
->snd_cwnd
) /
2178 tp
->snd_ssthresh
= win
* tp
->t_maxseg
;
2179 ENTER_FASTRECOVERY(tp
);
2180 tp
->snd_recover
= tp
->snd_max
;
2181 tp
->t_timer
[TCPT_REXMT
] = 0;
2183 if (tp
->sack_enable
) {
2184 tcpstat
.tcps_sack_recovery_episode
++;
2185 tp
->sack_newdata
= tp
->snd_nxt
;
2186 tp
->snd_cwnd
= tp
->t_maxseg
;
2187 (void) tcp_output(tp
);
2190 tp
->snd_nxt
= th
->th_ack
;
2191 tp
->snd_cwnd
= tp
->t_maxseg
;
2192 (void) tcp_output(tp
);
2193 tp
->snd_cwnd
= tp
->snd_ssthresh
+
2194 tp
->t_maxseg
* tp
->t_dupacks
;
2195 if (SEQ_GT(onxt
, tp
->snd_nxt
))
2204 * If the congestion window was inflated to account
2205 * for the other side's cached packets, retract it.
2207 if (tcp_do_newreno
|| tp
->sack_enable
) {
2208 if (IN_FASTRECOVERY(tp
)) {
2209 if (SEQ_LT(th
->th_ack
, tp
->snd_recover
)) {
2210 if (tp
->sack_enable
)
2211 tcp_sack_partialack(tp
, th
);
2213 tcp_newreno_partial_ack(tp
, th
);
2216 * Out of fast recovery.
2217 * Window inflation should have left us
2218 * with approximately snd_ssthresh
2220 * But in case we would be inclined to
2221 * send a burst, better to do it via
2222 * the slow start mechanism.
2224 if (SEQ_GT(th
->th_ack
+
2227 tp
->snd_cwnd
= tp
->snd_max
-
2231 tp
->snd_cwnd
= tp
->snd_ssthresh
;
2235 if (tp
->t_dupacks
>= tcprexmtthresh
&&
2236 tp
->snd_cwnd
> tp
->snd_ssthresh
)
2237 tp
->snd_cwnd
= tp
->snd_ssthresh
;
2241 * If we reach this point, ACK is not a duplicate,
2242 * i.e., it ACKs something we sent.
2244 if (tp
->t_flags
& TF_NEEDSYN
) {
2246 * T/TCP: Connection was half-synchronized, and our
2247 * SYN has been ACK'd (so connection is now fully
2248 * synchronized). Go to non-starred state,
2249 * increment snd_una for ACK of SYN, and check if
2250 * we can do window scaling.
2252 tp
->t_flags
&= ~TF_NEEDSYN
;
2254 /* Do window scaling? */
2255 if ((tp
->t_flags
& (TF_RCVD_SCALE
|TF_REQ_SCALE
)) ==
2256 (TF_RCVD_SCALE
|TF_REQ_SCALE
)) {
2257 tp
->snd_scale
= tp
->requested_s_scale
;
2258 tp
->rcv_scale
= tp
->request_r_scale
;
2263 acked
= th
->th_ack
- tp
->snd_una
;
2264 tcpstat
.tcps_rcvackpack
++;
2265 tcpstat
.tcps_rcvackbyte
+= acked
;
2268 * If we just performed our first retransmit, and the ACK
2269 * arrives within our recovery window, then it was a mistake
2270 * to do the retransmit in the first place. Recover our
2271 * original cwnd and ssthresh, and proceed to transmit where
2274 if (tp
->t_rxtshift
== 1 && tcp_now
< tp
->t_badrxtwin
) {
2275 tp
->snd_cwnd
= tp
->snd_cwnd_prev
;
2276 tp
->snd_ssthresh
= tp
->snd_ssthresh_prev
;
2277 tp
->snd_recover
= tp
->snd_recover_prev
;
2278 if (tp
->t_flags
& TF_WASFRECOVERY
)
2279 ENTER_FASTRECOVERY(tp
);
2280 tp
->snd_nxt
= tp
->snd_max
;
2281 tp
->t_badrxtwin
= 0; /* XXX probably not required */
2285 * If we have a timestamp reply, update smoothed
2286 * round trip time. If no timestamp is present but
2287 * transmit timer is running and timed sequence
2288 * number was acked, update smoothed round trip time.
2289 * Since we now have an rtt measurement, cancel the
2290 * timer backoff (cf., Phil Karn's retransmit alg.).
2291 * Recompute the initial retransmit timer.
2292 * Also makes sure we have a valid time stamp in hand
2294 if (((to
.to_flags
& TOF_TS
) != 0) && (to
.to_tsecr
!= 0))
2295 tcp_xmit_timer(tp
, tcp_now
- to
.to_tsecr
+ 1);
2296 else if (tp
->t_rtttime
&& SEQ_GT(th
->th_ack
, tp
->t_rtseq
))
2297 tcp_xmit_timer(tp
, tp
->t_rtttime
);
2300 * If all outstanding data is acked, stop retransmit
2301 * timer and remember to restart (more output or persist).
2302 * If there is more data to be acked, restart retransmit
2303 * timer, using current (possibly backed-off) value.
2305 if (th
->th_ack
== tp
->snd_max
) {
2306 tp
->t_timer
[TCPT_REXMT
] = 0;
2308 } else if (tp
->t_timer
[TCPT_PERSIST
] == 0)
2309 tp
->t_timer
[TCPT_REXMT
] = tp
->t_rxtcur
;
2312 * If no data (only SYN) was ACK'd,
2313 * skip rest of ACK processing.
2319 * When new data is acked, open the congestion window.
2320 * If the window gives us less than ssthresh packets
2321 * in flight, open exponentially (maxseg per packet).
2322 * Otherwise open linearly: maxseg per window
2323 * (maxseg^2 / cwnd per packet).
2325 if ((!tcp_do_newreno
&& !tp
->sack_enable
) ||
2326 !IN_FASTRECOVERY(tp
)) {
2327 register u_int cw
= tp
->snd_cwnd
;
2328 register u_int incr
= tp
->t_maxseg
;
2329 if (cw
> tp
->snd_ssthresh
)
2330 incr
= incr
* incr
/ cw
;
2331 tp
->snd_cwnd
= min(cw
+incr
, TCP_MAXWIN
<<tp
->snd_scale
);
2333 if (acked
> so
->so_snd
.sb_cc
) {
2334 tp
->snd_wnd
-= so
->so_snd
.sb_cc
;
2335 sbdrop(&so
->so_snd
, (int)so
->so_snd
.sb_cc
);
2338 sbdrop(&so
->so_snd
, acked
);
2339 tp
->snd_wnd
-= acked
;
2343 /* detect una wraparound */
2344 if ((tcp_do_newreno
|| tp
->sack_enable
) &&
2345 !IN_FASTRECOVERY(tp
) &&
2346 SEQ_GT(tp
->snd_una
, tp
->snd_recover
) &&
2347 SEQ_LEQ(th
->th_ack
, tp
->snd_recover
))
2348 tp
->snd_recover
= th
->th_ack
- 1;
2349 if ((tcp_do_newreno
|| tp
->sack_enable
) &&
2350 IN_FASTRECOVERY(tp
) &&
2351 SEQ_GEQ(th
->th_ack
, tp
->snd_recover
))
2352 EXIT_FASTRECOVERY(tp
);
2353 tp
->snd_una
= th
->th_ack
;
2354 if (tp
->sack_enable
) {
2355 if (SEQ_GT(tp
->snd_una
, tp
->snd_recover
))
2356 tp
->snd_recover
= tp
->snd_una
;
2358 if (SEQ_LT(tp
->snd_nxt
, tp
->snd_una
))
2359 tp
->snd_nxt
= tp
->snd_una
;
2361 switch (tp
->t_state
) {
2364 * In FIN_WAIT_1 STATE in addition to the processing
2365 * for the ESTABLISHED state if our FIN is now acknowledged
2366 * then enter FIN_WAIT_2.
2368 case TCPS_FIN_WAIT_1
:
2369 if (ourfinisacked
) {
2371 * If we can't receive any more
2372 * data, then closing user can proceed.
2373 * Starting the timer is contrary to the
2374 * specification, but if we don't get a FIN
2375 * we'll hang forever.
2377 if (so
->so_state
& SS_CANTRCVMORE
) {
2378 soisdisconnected(so
);
2379 tp
->t_timer
[TCPT_2MSL
] = tcp_maxidle
;
2381 add_to_time_wait(tp
);
2382 tp
->t_state
= TCPS_FIN_WAIT_2
;
2388 * In CLOSING STATE in addition to the processing for
2389 * the ESTABLISHED state if the ACK acknowledges our FIN
2390 * then enter the TIME-WAIT state, otherwise ignore
2394 if (ourfinisacked
) {
2395 tp
->t_state
= TCPS_TIME_WAIT
;
2396 tcp_canceltimers(tp
);
2397 /* Shorten TIME_WAIT [RFC-1644, p.28] */
2398 if (tp
->cc_recv
!= 0 &&
2399 tp
->t_starttime
< tcp_msl
)
2400 tp
->t_timer
[TCPT_2MSL
] =
2401 tp
->t_rxtcur
* TCPTV_TWTRUNC
;
2403 tp
->t_timer
[TCPT_2MSL
] = 2 * tcp_msl
;
2404 add_to_time_wait(tp
);
2405 soisdisconnected(so
);
2410 * In LAST_ACK, we may still be waiting for data to drain
2411 * and/or to be acked, as well as for the ack of our FIN.
2412 * If our FIN is now acknowledged, delete the TCB,
2413 * enter the closed state and return.
2416 if (ourfinisacked
) {
2423 * In TIME_WAIT state the only thing that should arrive
2424 * is a retransmission of the remote FIN. Acknowledge
2425 * it and restart the finack timer.
2427 case TCPS_TIME_WAIT
:
2428 tp
->t_timer
[TCPT_2MSL
] = 2 * tcp_msl
;
2429 add_to_time_wait(tp
);
2436 * Update window information.
2437 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2439 if ((thflags
& TH_ACK
) &&
2440 (SEQ_LT(tp
->snd_wl1
, th
->th_seq
) ||
2441 (tp
->snd_wl1
== th
->th_seq
&& (SEQ_LT(tp
->snd_wl2
, th
->th_ack
) ||
2442 (tp
->snd_wl2
== th
->th_ack
&& tiwin
> tp
->snd_wnd
))))) {
2443 /* keep track of pure window updates */
2445 tp
->snd_wl2
== th
->th_ack
&& tiwin
> tp
->snd_wnd
)
2446 tcpstat
.tcps_rcvwinupd
++;
2447 tp
->snd_wnd
= tiwin
;
2448 tp
->snd_wl1
= th
->th_seq
;
2449 tp
->snd_wl2
= th
->th_ack
;
2450 if (tp
->snd_wnd
> tp
->max_sndwnd
)
2451 tp
->max_sndwnd
= tp
->snd_wnd
;
2456 * Process segments with URG.
2458 if ((thflags
& TH_URG
) && th
->th_urp
&&
2459 TCPS_HAVERCVDFIN(tp
->t_state
) == 0) {
2461 * This is a kludge, but if we receive and accept
2462 * random urgent pointers, we'll crash in
2463 * soreceive. It's hard to imagine someone
2464 * actually wanting to send this much urgent data.
2466 if (th
->th_urp
+ so
->so_rcv
.sb_cc
> sb_max
) {
2467 th
->th_urp
= 0; /* XXX */
2468 thflags
&= ~TH_URG
; /* XXX */
2469 goto dodata
; /* XXX */
2472 * If this segment advances the known urgent pointer,
2473 * then mark the data stream. This should not happen
2474 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2475 * a FIN has been received from the remote side.
2476 * In these states we ignore the URG.
2478 * According to RFC961 (Assigned Protocols),
2479 * the urgent pointer points to the last octet
2480 * of urgent data. We continue, however,
2481 * to consider it to indicate the first octet
2482 * of data past the urgent section as the original
2483 * spec states (in one of two places).
2485 if (SEQ_GT(th
->th_seq
+th
->th_urp
, tp
->rcv_up
)) {
2486 tp
->rcv_up
= th
->th_seq
+ th
->th_urp
;
2487 so
->so_oobmark
= so
->so_rcv
.sb_cc
+
2488 (tp
->rcv_up
- tp
->rcv_nxt
) - 1;
2489 if (so
->so_oobmark
== 0) {
2490 so
->so_state
|= SS_RCVATMARK
;
2491 postevent(so
, 0, EV_OOB
);
2494 tp
->t_oobflags
&= ~(TCPOOB_HAVEDATA
| TCPOOB_HADDATA
);
2497 * Remove out of band data so doesn't get presented to user.
2498 * This can happen independent of advancing the URG pointer,
2499 * but if two URG's are pending at once, some out-of-band
2500 * data may creep in... ick.
2502 if (th
->th_urp
<= (u_long
)tlen
2504 && (so
->so_options
& SO_OOBINLINE
) == 0
2507 tcp_pulloutofband(so
, th
, m
,
2508 drop_hdrlen
); /* hdr drop is delayed */
2511 * If no out of band data is expected,
2512 * pull receive urgent pointer along
2513 * with the receive window.
2515 if (SEQ_GT(tp
->rcv_nxt
, tp
->rcv_up
))
2516 tp
->rcv_up
= tp
->rcv_nxt
;
2520 * Process the segment text, merging it into the TCP sequencing queue,
2521 * and arranging for acknowledgment of receipt if necessary.
2522 * This process logically involves adjusting tp->rcv_wnd as data
2523 * is presented to the user (this happens in tcp_usrreq.c,
2524 * case PRU_RCVD). If a FIN has already been received on this
2525 * connection then we just ignore the text.
2527 if ((tlen
|| (thflags
&TH_FIN
)) &&
2528 TCPS_HAVERCVDFIN(tp
->t_state
) == 0) {
2529 tcp_seq save_start
= th
->th_seq
;
2530 tcp_seq save_end
= th
->th_seq
+ tlen
;
2531 m_adj(m
, drop_hdrlen
); /* delayed header drop */
2533 * Insert segment which includes th into TCP reassembly queue
2534 * with control block tp. Set thflags to whether reassembly now
2535 * includes a segment with FIN. This handles the common case
2536 * inline (segment is the next to be received on an established
2537 * connection, and the queue is empty), avoiding linkage into
2538 * and removal from the queue and repetition of various
2540 * Set DELACK for segments received in order, but ack
2541 * immediately when segments are out of order (so
2542 * fast retransmit can work).
2544 if (th
->th_seq
== tp
->rcv_nxt
&&
2545 LIST_EMPTY(&tp
->t_segq
) &&
2546 TCPS_HAVEESTABLISHED(tp
->t_state
)) {
2547 if (DELAY_ACK(tp
) && ((tp
->t_flags
& TF_ACKNOW
) == 0)) {
2548 tp
->t_flags
|= TF_DELACK
;
2551 tp
->t_flags
|= TF_ACKNOW
;
2553 tp
->rcv_nxt
+= tlen
;
2554 thflags
= th
->th_flags
& TH_FIN
;
2555 tcpstat
.tcps_rcvpack
++;
2556 tcpstat
.tcps_rcvbyte
+= tlen
;
2558 if (sbappend(&so
->so_rcv
, m
))
2561 thflags
= tcp_reass(tp
, th
, &tlen
, m
);
2562 tp
->t_flags
|= TF_ACKNOW
;
2565 if (tlen
> 0 && tp
->sack_enable
)
2566 tcp_update_sack_list(tp
, save_start
, save_end
);
2568 if (tp
->t_flags
& TF_DELACK
)
2572 KERNEL_DEBUG(DBG_LAYER_END
, ((th
->th_dport
<< 16) | th
->th_sport
),
2573 (((ip6
->ip6_src
.s6_addr16
[0]) << 16) | (ip6
->ip6_dst
.s6_addr16
[0])),
2574 th
->th_seq
, th
->th_ack
, th
->th_win
);
2579 KERNEL_DEBUG(DBG_LAYER_END
, ((th
->th_dport
<< 16) | th
->th_sport
),
2580 (((ip
->ip_src
.s_addr
& 0xffff) << 16) | (ip
->ip_dst
.s_addr
& 0xffff)),
2581 th
->th_seq
, th
->th_ack
, th
->th_win
);
2586 * Note the amount of data that peer has sent into
2587 * our window, in order to estimate the sender's
2590 len
= so
->so_rcv
.sb_hiwat
- (tp
->rcv_adv
- tp
->rcv_nxt
);
2597 * If FIN is received ACK the FIN and let the user know
2598 * that the connection is closing.
2600 if (thflags
& TH_FIN
) {
2601 if (TCPS_HAVERCVDFIN(tp
->t_state
) == 0) {
2603 postevent(so
, 0, EV_FIN
);
2605 * If connection is half-synchronized
2606 * (ie NEEDSYN flag on) then delay ACK,
2607 * If connection is half-synchronized
2608 * (ie NEEDSYN flag on) then delay ACK,
2609 * so it may be piggybacked when SYN is sent.
2610 * Otherwise, since we received a FIN then no
2611 * more input can be expected, send ACK now.
2613 if (DELAY_ACK(tp
) && (tp
->t_flags
& TF_NEEDSYN
)) {
2614 tp
->t_flags
|= TF_DELACK
;
2617 tp
->t_flags
|= TF_ACKNOW
;
2621 switch (tp
->t_state
) {
2624 * In SYN_RECEIVED and ESTABLISHED STATES
2625 * enter the CLOSE_WAIT state.
2627 case TCPS_SYN_RECEIVED
:
2628 tp
->t_starttime
= 0;
2629 case TCPS_ESTABLISHED
:
2630 tp
->t_state
= TCPS_CLOSE_WAIT
;
2634 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2635 * enter the CLOSING state.
2637 case TCPS_FIN_WAIT_1
:
2638 tp
->t_state
= TCPS_CLOSING
;
2642 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2643 * starting the time-wait timer, turning off the other
2646 case TCPS_FIN_WAIT_2
:
2647 tp
->t_state
= TCPS_TIME_WAIT
;
2648 tcp_canceltimers(tp
);
2649 /* Shorten TIME_WAIT [RFC-1644, p.28] */
2650 if (tp
->cc_recv
!= 0 &&
2651 tp
->t_starttime
< tcp_msl
) {
2652 tp
->t_timer
[TCPT_2MSL
] =
2653 tp
->t_rxtcur
* TCPTV_TWTRUNC
;
2654 /* For transaction client, force ACK now. */
2655 tp
->t_flags
|= TF_ACKNOW
;
2658 tp
->t_timer
[TCPT_2MSL
] = 2 * tcp_msl
;
2660 add_to_time_wait(tp
);
2661 soisdisconnected(so
);
2665 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2667 case TCPS_TIME_WAIT
:
2668 tp
->t_timer
[TCPT_2MSL
] = 2 * tcp_msl
;
2669 add_to_time_wait(tp
);
2674 if (so
->so_options
& SO_DEBUG
)
2675 tcp_trace(TA_INPUT
, ostate
, tp
, (void *)tcp_saveipgen
,
2680 * Return any desired output.
2682 if (needoutput
|| (tp
->t_flags
& TF_ACKNOW
))
2683 (void) tcp_output(tp
);
2684 tcp_unlock(so
, 1, 0);
2685 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
2690 * Generate an ACK dropping incoming segment if it occupies
2691 * sequence space, where the ACK reflects our state.
2693 * We can now skip the test for the RST flag since all
2694 * paths to this code happen after packets containing
2695 * RST have been dropped.
2697 * In the SYN-RECEIVED state, don't send an ACK unless the
2698 * segment we received passes the SYN-RECEIVED ACK test.
2699 * If it fails send a RST. This breaks the loop in the
2700 * "LAND" DoS attack, and also prevents an ACK storm
2701 * between two listening ports that have been sent forged
2702 * SYN segments, each with the source address of the other.
2704 if (tp
->t_state
== TCPS_SYN_RECEIVED
&& (thflags
& TH_ACK
) &&
2705 (SEQ_GT(tp
->snd_una
, th
->th_ack
) ||
2706 SEQ_GT(th
->th_ack
, tp
->snd_max
)) ) {
2707 rstreason
= BANDLIM_RST_OPENPORT
;
2711 if (so
->so_options
& SO_DEBUG
)
2712 tcp_trace(TA_DROP
, ostate
, tp
, (void *)tcp_saveipgen
,
2716 tp
->t_flags
|= TF_ACKNOW
;
2717 (void) tcp_output(tp
);
2718 tcp_unlock(so
, 1, 0);
2719 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
2721 dropwithresetnosock
:
2725 * Generate a RST, dropping incoming segment.
2726 * Make ACK acceptable to originator of segment.
2727 * Don't bother to respond if destination was broadcast/multicast.
2729 if ((thflags
& TH_RST
) || m
->m_flags
& (M_BCAST
|M_MCAST
))
2733 if (IN6_IS_ADDR_MULTICAST(&ip6
->ip6_dst
) ||
2734 IN6_IS_ADDR_MULTICAST(&ip6
->ip6_src
))
2738 if (IN_MULTICAST(ntohl(ip
->ip_dst
.s_addr
)) ||
2739 IN_MULTICAST(ntohl(ip
->ip_src
.s_addr
)) ||
2740 ip
->ip_src
.s_addr
== htonl(INADDR_BROADCAST
) ||
2741 in_broadcast(ip
->ip_dst
, m
->m_pkthdr
.rcvif
))
2743 /* IPv6 anycast check is done at tcp6_input() */
2746 * Perform bandwidth limiting.
2749 if (badport_bandlim(rstreason
) < 0)
2754 if (tp
== 0 || (tp
->t_inpcb
->inp_socket
->so_options
& SO_DEBUG
))
2755 tcp_trace(TA_DROP
, ostate
, tp
, (void *)tcp_saveipgen
,
2758 if (thflags
& TH_ACK
)
2759 /* mtod() below is safe as long as hdr dropping is delayed */
2760 tcp_respond(tp
, mtod(m
, void *), th
, m
, (tcp_seq
)0, th
->th_ack
,
2763 if (thflags
& TH_SYN
)
2765 /* mtod() below is safe as long as hdr dropping is delayed */
2766 tcp_respond(tp
, mtod(m
, void *), th
, m
, th
->th_seq
+tlen
,
2767 (tcp_seq
)0, TH_RST
|TH_ACK
);
2769 /* destroy temporarily created socket */
2772 tcp_unlock(so
, 1, 0);
2775 if ((inp
!= NULL
) && (nosock
== 0))
2776 tcp_unlock(so
, 1, 0);
2777 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
2783 * Drop space held by incoming segment and return.
2786 if (tp
== 0 || (tp
->t_inpcb
->inp_socket
->so_options
& SO_DEBUG
))
2787 tcp_trace(TA_DROP
, ostate
, tp
, (void *)tcp_saveipgen
,
2791 /* destroy temporarily created socket */
2794 tcp_unlock(so
, 1, 0);
2798 tcp_unlock(so
, 1, 0);
2799 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
2804 tcp_dooptions(tp
, cp
, cnt
, th
, to
)
2806 * Parse TCP options and place in tcpopt.
2817 for (; cnt
> 0; cnt
-= optlen
, cp
+= optlen
) {
2819 if (opt
== TCPOPT_EOL
)
2821 if (opt
== TCPOPT_NOP
)
2827 if (optlen
< 2 || optlen
> cnt
)
2836 if (optlen
!= TCPOLEN_MAXSEG
)
2838 if (!(th
->th_flags
& TH_SYN
))
2840 bcopy((char *) cp
+ 2, (char *) &mss
, sizeof(mss
));
2845 if (optlen
!= TCPOLEN_WINDOW
)
2847 if (!(th
->th_flags
& TH_SYN
))
2849 tp
->t_flags
|= TF_RCVD_SCALE
;
2850 tp
->requested_s_scale
= min(cp
[2], TCP_MAX_WINSHIFT
);
2853 case TCPOPT_TIMESTAMP
:
2854 if (optlen
!= TCPOLEN_TIMESTAMP
)
2856 to
->to_flags
|= TOF_TS
;
2857 bcopy((char *)cp
+ 2,
2858 (char *)&to
->to_tsval
, sizeof(to
->to_tsval
));
2859 NTOHL(to
->to_tsval
);
2860 bcopy((char *)cp
+ 6,
2861 (char *)&to
->to_tsecr
, sizeof(to
->to_tsecr
));
2862 NTOHL(to
->to_tsecr
);
2865 * A timestamp received in a SYN makes
2866 * it ok to send timestamp requests and replies.
2868 if (th
->th_flags
& TH_SYN
) {
2869 tp
->t_flags
|= TF_RCVD_TSTMP
;
2870 tp
->ts_recent
= to
->to_tsval
;
2871 tp
->ts_recent_age
= tcp_now
;
2874 case TCPOPT_SACK_PERMITTED
:
2876 optlen
!= TCPOLEN_SACK_PERMITTED
)
2878 if (th
->th_flags
& TH_SYN
)
2879 to
->to_flags
|= TOF_SACK
;
2882 if (optlen
<= 2 || (optlen
- 2) % TCPOLEN_SACK
!= 0)
2884 to
->to_nsacks
= (optlen
- 2) / TCPOLEN_SACK
;
2885 to
->to_sacks
= cp
+ 2;
2886 tcpstat
.tcps_sack_rcv_blocks
++;
2891 if (th
->th_flags
& TH_SYN
)
2892 tcp_mss(tp
, mss
); /* sets t_maxseg */
2896 * Pull out of band byte out of a segment so
2897 * it doesn't appear in the user's data queue.
2898 * It is still reflected in the segment length for
2899 * sequencing purposes.
2902 tcp_pulloutofband(so
, th
, m
, off
)
2905 register struct mbuf
*m
;
2906 int off
; /* delayed to be droped hdrlen */
2908 int cnt
= off
+ th
->th_urp
- 1;
2911 if (m
->m_len
> cnt
) {
2912 char *cp
= mtod(m
, caddr_t
) + cnt
;
2913 struct tcpcb
*tp
= sototcpcb(so
);
2916 tp
->t_oobflags
|= TCPOOB_HAVEDATA
;
2917 bcopy(cp
+1, cp
, (unsigned)(m
->m_len
- cnt
- 1));
2919 if (m
->m_flags
& M_PKTHDR
)
2928 panic("tcp_pulloutofband");
2932 * Collect new round-trip time estimate
2933 * and update averages and current timeout.
2936 tcp_xmit_timer(tp
, rtt
)
2937 register struct tcpcb
*tp
;
2942 tcpstat
.tcps_rttupdated
++;
2944 if (tp
->t_srtt
!= 0) {
2946 * srtt is stored as fixed point with 5 bits after the
2947 * binary point (i.e., scaled by 8). The following magic
2948 * is equivalent to the smoothing algorithm in rfc793 with
2949 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2950 * point). Adjust rtt to origin 0.
2952 delta
= ((rtt
- 1) << TCP_DELTA_SHIFT
)
2953 - (tp
->t_srtt
>> (TCP_RTT_SHIFT
- TCP_DELTA_SHIFT
));
2955 if ((tp
->t_srtt
+= delta
) <= 0)
2959 * We accumulate a smoothed rtt variance (actually, a
2960 * smoothed mean difference), then set the retransmit
2961 * timer to smoothed rtt + 4 times the smoothed variance.
2962 * rttvar is stored as fixed point with 4 bits after the
2963 * binary point (scaled by 16). The following is
2964 * equivalent to rfc793 smoothing with an alpha of .75
2965 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2966 * rfc793's wired-in beta.
2970 delta
-= tp
->t_rttvar
>> (TCP_RTTVAR_SHIFT
- TCP_DELTA_SHIFT
);
2971 if ((tp
->t_rttvar
+= delta
) <= 0)
2975 * No rtt measurement yet - use the unsmoothed rtt.
2976 * Set the variance to half the rtt (so our first
2977 * retransmit happens at 3*rtt).
2979 tp
->t_srtt
= rtt
<< TCP_RTT_SHIFT
;
2980 tp
->t_rttvar
= rtt
<< (TCP_RTTVAR_SHIFT
- 1);
2986 * the retransmit should happen at rtt + 4 * rttvar.
2987 * Because of the way we do the smoothing, srtt and rttvar
2988 * will each average +1/2 tick of bias. When we compute
2989 * the retransmit timer, we want 1/2 tick of rounding and
2990 * 1 extra tick because of +-1/2 tick uncertainty in the
2991 * firing of the timer. The bias will give us exactly the
2992 * 1.5 tick we need. But, because the bias is
2993 * statistical, we have to test that we don't drop below
2994 * the minimum feasible timer (which is 2 ticks).
2996 TCPT_RANGESET(tp
->t_rxtcur
, TCP_REXMTVAL(tp
),
2997 max(tp
->t_rttmin
, rtt
+ 2), TCPTV_REXMTMAX
);
3000 * We received an ack for a packet that wasn't retransmitted;
3001 * it is probably safe to discard any error indications we've
3002 * received recently. This isn't quite right, but close enough
3003 * for now (a route might have failed after we sent a segment,
3004 * and the return path might not be symmetrical).
3006 tp
->t_softerror
= 0;
3010 * Determine a reasonable value for maxseg size.
3011 * If the route is known, check route for mtu.
3012 * If none, use an mss that can be handled on the outgoing
3013 * interface without forcing IP to fragment; if bigger than
3014 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
3015 * to utilize large mbufs. If no route is found, route has no mtu,
3016 * or the destination isn't local, use a default, hopefully conservative
3017 * size (usually 512 or the default IP max size, but no more than the mtu
3018 * of the interface), as we can't discover anything about intervening
3019 * gateways or networks. We also initialize the congestion/slow start
3020 * window to be a single segment if the destination isn't local.
3021 * While looking at the routing entry, we also initialize other path-dependent
3022 * parameters from pre-set or cached values in the routing entry.
3024 * Also take into account the space needed for options that we
3025 * send regularly. Make maxseg shorter by that amount to assure
3026 * that we can send maxseg amount of data even when the options
3027 * are present. Store the upper limit of the length of options plus
3030 * NOTE that this routine is only called when we process an incoming
3031 * segment, for outgoing segments only tcp_mssopt is called.
3033 * In case of T/TCP, we call this routine during implicit connection
3034 * setup as well (offer = -1), to initialize maxseg from the cached
3042 register struct rtentry
*rt
;
3044 register int rtt
, mss
;
3048 struct rmxp_tao
*taop
;
3049 int origoffer
= offer
;
3057 isipv6
= ((inp
->inp_vflag
& INP_IPV6
) != 0) ? 1 : 0;
3058 min_protoh
= isipv6
? sizeof (struct ip6_hdr
) + sizeof (struct tcphdr
)
3059 : sizeof (struct tcpiphdr
);
3061 #define min_protoh (sizeof (struct tcpiphdr))
3065 rt
= tcp_rtlookup6(inp
);
3068 rt
= tcp_rtlookup(inp
);
3070 tp
->t_maxopd
= tp
->t_maxseg
=
3072 isipv6
? tcp_v6mssdflt
:
3079 * Slower link window correction:
3080 * If a value is specificied for slowlink_wsize use it for PPP links
3081 * believed to be on a serial modem (speed <128Kbps). Excludes 9600bps as
3082 * it is the default value adversized by pseudo-devices over ppp.
3084 if (ifp
->if_type
== IFT_PPP
&& slowlink_wsize
> 0 &&
3085 ifp
->if_baudrate
> 9600 && ifp
->if_baudrate
<= 128000) {
3086 tp
->t_flags
|= TF_SLOWLINK
;
3088 so
= inp
->inp_socket
;
3090 taop
= rmx_taop(rt
->rt_rmx
);
3092 * Offer == -1 means that we didn't receive SYN yet,
3093 * use cached value in that case;
3096 offer
= taop
->tao_mssopt
;
3098 * Offer == 0 means that there was no MSS on the SYN segment,
3099 * in this case we use tcp_mssdflt.
3104 isipv6
? tcp_v6mssdflt
:
3109 * Prevent DoS attack with too small MSS. Round up
3110 * to at least minmss.
3112 offer
= max(offer
, tcp_minmss
);
3114 * Sanity check: make sure that maxopd will be large
3115 * enough to allow some data on segments even is the
3116 * all the option space is used (40bytes). Otherwise
3117 * funny things may happen in tcp_output.
3119 offer
= max(offer
, 64);
3121 taop
->tao_mssopt
= offer
;
3124 * While we're here, check if there's an initial rtt
3125 * or rttvar. Convert from the route-table units
3126 * to scaled multiples of the slow timeout timer.
3128 if (tp
->t_srtt
== 0 && (rtt
= rt
->rt_rmx
.rmx_rtt
)) {
3130 * XXX the lock bit for RTT indicates that the value
3131 * is also a minimum value; this is subject to time.
3133 if (rt
->rt_rmx
.rmx_locks
& RTV_RTT
)
3134 tp
->t_rttmin
= rtt
/ (RTM_RTTUNIT
/ PR_SLOWHZ
);
3135 tp
->t_srtt
= rtt
/ (RTM_RTTUNIT
/ (PR_SLOWHZ
* TCP_RTT_SCALE
));
3136 tcpstat
.tcps_usedrtt
++;
3137 if (rt
->rt_rmx
.rmx_rttvar
) {
3138 tp
->t_rttvar
= rt
->rt_rmx
.rmx_rttvar
/
3139 (RTM_RTTUNIT
/ (PR_SLOWHZ
* TCP_RTTVAR_SCALE
));
3140 tcpstat
.tcps_usedrttvar
++;
3142 /* default variation is +- 1 rtt */
3144 tp
->t_srtt
* TCP_RTTVAR_SCALE
/ TCP_RTT_SCALE
;
3146 TCPT_RANGESET(tp
->t_rxtcur
,
3147 ((tp
->t_srtt
>> 2) + tp
->t_rttvar
) >> 1,
3148 tp
->t_rttmin
, TCPTV_REXMTMAX
);
3151 * if there's an mtu associated with the route, use it
3152 * else, use the link mtu.
3154 if (rt
->rt_rmx
.rmx_mtu
)
3155 mss
= rt
->rt_rmx
.rmx_mtu
- min_protoh
;
3160 (isipv6
? nd_ifinfo
[rt
->rt_ifp
->if_index
].linkmtu
:
3169 if (!in6_localaddr(&inp
->in6p_faddr
))
3170 mss
= min(mss
, tcp_v6mssdflt
);
3173 if (!in_localaddr(inp
->inp_faddr
))
3174 mss
= min(mss
, tcp_mssdflt
);
3176 mss
= min(mss
, offer
);
3178 * maxopd stores the maximum length of data AND options
3179 * in a segment; maxseg is the amount of data in a normal
3180 * segment. We need to store this value (maxopd) apart
3181 * from maxseg, because now every segment carries options
3182 * and thus we normally have somewhat less data in segments.
3187 * origoffer==-1 indicates, that no segments were received yet.
3188 * In this case we just guess.
3190 if ((tp
->t_flags
& (TF_REQ_TSTMP
|TF_NOOPT
)) == TF_REQ_TSTMP
&&
3192 (tp
->t_flags
& TF_RCVD_TSTMP
) == TF_RCVD_TSTMP
))
3193 mss
-= TCPOLEN_TSTAMP_APPA
;
3197 * If there's a pipesize (ie loopback), change the socket
3198 * buffer to that size only if it's bigger than the current
3199 * sockbuf size. Make the socket buffers an integral
3200 * number of mss units; if the mss is larger than
3201 * the socket buffer, decrease the mss.
3204 bufsize
= rt
->rt_rmx
.rmx_sendpipe
;
3205 if (bufsize
< so
->so_snd
.sb_hiwat
)
3207 bufsize
= so
->so_snd
.sb_hiwat
;
3211 bufsize
= roundup(bufsize
, mss
);
3212 if (bufsize
> sb_max
)
3214 (void)sbreserve(&so
->so_snd
, bufsize
);
3219 bufsize
= rt
->rt_rmx
.rmx_recvpipe
;
3220 if (bufsize
< so
->so_rcv
.sb_hiwat
)
3222 bufsize
= so
->so_rcv
.sb_hiwat
;
3223 if (bufsize
> mss
) {
3224 bufsize
= roundup(bufsize
, mss
);
3225 if (bufsize
> sb_max
)
3227 (void)sbreserve(&so
->so_rcv
, bufsize
);
3231 * Set the slow-start flight size depending on whether this
3232 * is a local network or not.
3236 (isipv6
&& in6_localaddr(&inp
->in6p_faddr
)) ||
3239 in_localaddr(inp
->inp_faddr
)
3244 tp
->snd_cwnd
= mss
* ss_fltsz_local
;
3246 tp
->snd_cwnd
= mss
* ss_fltsz
;
3248 if (rt
->rt_rmx
.rmx_ssthresh
) {
3250 * There's some sort of gateway or interface
3251 * buffer limit on the path. Use this to set
3252 * the slow start threshhold, but set the
3253 * threshold to no less than 2*mss.
3255 tp
->snd_ssthresh
= max(2 * mss
, rt
->rt_rmx
.rmx_ssthresh
);
3256 tcpstat
.tcps_usedssthresh
++;
3261 * Determine the MSS option to send on an outgoing SYN.
3275 isipv6
= ((tp
->t_inpcb
->inp_vflag
& INP_IPV6
) != 0) ? 1 : 0;
3276 min_protoh
= isipv6
? sizeof (struct ip6_hdr
) + sizeof (struct tcphdr
)
3277 : sizeof (struct tcpiphdr
);
3279 #define min_protoh (sizeof (struct tcpiphdr))
3283 rt
= tcp_rtlookup6(tp
->t_inpcb
);
3286 rt
= tcp_rtlookup(tp
->t_inpcb
);
3290 isipv6
? tcp_v6mssdflt
:
3294 * Slower link window correction:
3295 * If a value is specificied for slowlink_wsize use it for PPP links
3296 * believed to be on a serial modem (speed <128Kbps). Excludes 9600bps as
3297 * it is the default value adversized by pseudo-devices over ppp.
3299 if (rt
->rt_ifp
->if_type
== IFT_PPP
&& slowlink_wsize
> 0 &&
3300 rt
->rt_ifp
->if_baudrate
> 9600 && rt
->rt_ifp
->if_baudrate
<= 128000) {
3301 tp
->t_flags
|= TF_SLOWLINK
;
3304 if (rt
->rt_rmx
.rmx_mtu
)
3305 mss
= rt
->rt_rmx
.rmx_mtu
;
3309 (isipv6
? nd_ifinfo
[rt
->rt_ifp
->if_index
].linkmtu
:
3316 return (mss
- min_protoh
);
3320 * On a partial ack arrives, force the retransmission of the
3321 * next unacknowledged segment. Do not clear tp->t_dupacks.
3322 * By setting snd_nxt to ti_ack, this forces retransmission timer to
3326 tcp_newreno_partial_ack(tp
, th
)
3330 tcp_seq onxt
= tp
->snd_nxt
;
3331 u_long ocwnd
= tp
->snd_cwnd
;
3332 tp
->t_timer
[TCPT_REXMT
] = 0;
3334 tp
->snd_nxt
= th
->th_ack
;
3336 * Set snd_cwnd to one segment beyond acknowledged offset
3337 * (tp->snd_una has not yet been updated when this function
3340 tp
->snd_cwnd
= tp
->t_maxseg
+ (th
->th_ack
- tp
->snd_una
);
3341 tp
->t_flags
|= TF_ACKNOW
;
3342 (void) tcp_output(tp
);
3343 tp
->snd_cwnd
= ocwnd
;
3344 if (SEQ_GT(onxt
, tp
->snd_nxt
))
3347 * Partial window deflation. Relies on fact that tp->snd_una
3350 tp
->snd_cwnd
-= (th
->th_ack
- tp
->snd_una
- tp
->t_maxseg
);
3354 * Drop a random TCP connection that hasn't been serviced yet and
3355 * is eligible for discard. There is a one in qlen chance that
3356 * we will return a null, saying that there are no dropable
3357 * requests. In this case, the protocol specific code should drop
3358 * the new request. This insures fairness.
3360 * The listening TCP socket "head" must be locked
3363 tcpdropdropablreq(struct socket
*head
)
3366 unsigned int i
, j
, qlen
;
3368 static struct timeval old_runtime
;
3369 static unsigned int cur_cnt
, old_cnt
;
3371 struct inpcb
*inp
= NULL
;
3375 if ((i
= (tv
.tv_sec
- old_runtime
.tv_sec
)) != 0) {
3377 old_cnt
= cur_cnt
/ i
;
3381 so
= TAILQ_FIRST(&head
->so_incomp
);
3385 qlen
= head
->so_incqlen
;
3386 if (++cur_cnt
> qlen
|| old_cnt
> qlen
) {
3387 rnd
= (314159 * rnd
+ 66329) & 0xffff;
3388 j
= ((qlen
+ 1) * rnd
) >> 16;
3391 so
= TAILQ_NEXT(so
, so_list
);
3393 /* Find a connection that is not already closing */
3395 inp
= (struct inpcb
*)so
->so_pcb
;
3397 if (in_pcb_checkstate(inp
, WNT_ACQUIRE
, 0) != WNT_STOPUSING
)
3400 so
= TAILQ_NEXT(so
, so_list
);
3407 TAILQ_REMOVE(&head
->so_incomp
, so
, so_list
);
3408 tcp_unlock(head
, 0, 0);
3410 /* Let's remove this connection from the incomplete list */
3413 if (in_pcb_checkstate(inp
, WNT_RELEASE
, 1) == WNT_STOPUSING
) {
3414 tcp_unlock(so
, 1, 0);
3419 so
->so_usecount
--; /* No more held by so_head */
3422 * We do not want to lose track of the PCB right away in case we receive
3423 * more segments from the peer
3426 tp
->t_flags
|= TF_LQ_OVERFLOW
;
3427 tp
->t_state
= TCPS_CLOSED
;
3428 (void) tcp_output(tp
);
3429 tcpstat
.tcps_drops
++;
3430 soisdisconnected(so
);
3431 tcp_canceltimers(tp
);
3432 add_to_time_wait(tp
);
3434 tcp_unlock(so
, 1, 0);
3435 tcp_lock(head
, 0, 0);
3442 tcp_getstat SYSCTL_HANDLER_ARGS
3447 if (req
->oldptr
== 0) {
3448 req
->oldlen
= (size_t)sizeof(struct tcpstat
);
3451 error
= SYSCTL_OUT(req
, &tcpstat
, (size_t) req
->oldlen
);
3457 SYSCTL_PROC(_net_inet_tcp
, TCPCTL_STATS
, stats
, CTLFLAG_RD
, 0, 0,
3458 tcp_getstat
, "S,tcpstat", "TCP statistics (struct tcpstat, netinet/tcp_var.h)");