2 * Copyright (c) 2000 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
);
1238 if (tp
->t_state
== TCPS_SYN_SENT
&& (thflags
& TH_SYN
)) {
1239 if (to
.to_flags
& TOF_SCALE
) {
1240 tp
->t_flags
|= TF_RCVD_SCALE
;
1241 tp
->requested_s_scale
= to
.to_requested_s_scale
;
1243 if (to
.to_flags
& TOF_TS
) {
1244 tp
->t_flags
|= TF_RCVD_TSTMP
;
1245 tp
->ts_recent
= to
.to_tsval
;
1246 tp
->ts_recent_age
= tcp_now
;
1248 if (to
.to_flags
& TOF_MSS
)
1249 tcp_mss(tp
, to
.to_mss
);
1250 if (tp
->sack_enable
) {
1251 if (!(to
.to_flags
& TOF_SACK
))
1252 tp
->sack_enable
= 0;
1254 tp
->t_flags
|= TF_SACK_PERMIT
;
1259 * Header prediction: check for the two common cases
1260 * of a uni-directional data xfer. If the packet has
1261 * no control flags, is in-sequence, the window didn't
1262 * change and we're not retransmitting, it's a
1263 * candidate. If the length is zero and the ack moved
1264 * forward, we're the sender side of the xfer. Just
1265 * free the data acked & wake any higher level process
1266 * that was blocked waiting for space. If the length
1267 * is non-zero and the ack didn't move, we're the
1268 * receiver side. If we're getting packets in-order
1269 * (the reassembly queue is empty), add the data to
1270 * the socket buffer and note that we need a delayed ack.
1271 * Make sure that the hidden state-flags are also off.
1272 * Since we check for TCPS_ESTABLISHED above, it can only
1275 if (tp
->t_state
== TCPS_ESTABLISHED
&&
1276 (thflags
& (TH_SYN
|TH_FIN
|TH_RST
|TH_URG
|TH_ACK
)) == TH_ACK
&&
1277 ((tp
->t_flags
& (TF_NEEDSYN
|TF_NEEDFIN
)) == 0) &&
1278 ((to
.to_flags
& TOF_TS
) == 0 ||
1279 TSTMP_GEQ(to
.to_tsval
, tp
->ts_recent
)) &&
1280 th
->th_seq
== tp
->rcv_nxt
&&
1281 tiwin
&& tiwin
== tp
->snd_wnd
&&
1282 tp
->snd_nxt
== tp
->snd_max
) {
1285 * If last ACK falls within this segment's sequence numbers,
1286 * record the timestamp.
1287 * NOTE that the test is modified according to the latest
1288 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1290 if ((to
.to_flags
& TOF_TS
) != 0 &&
1291 SEQ_LEQ(th
->th_seq
, tp
->last_ack_sent
)) {
1292 tp
->ts_recent_age
= tcp_now
;
1293 tp
->ts_recent
= to
.to_tsval
;
1297 if (SEQ_GT(th
->th_ack
, tp
->snd_una
) &&
1298 SEQ_LEQ(th
->th_ack
, tp
->snd_max
) &&
1299 tp
->snd_cwnd
>= tp
->snd_wnd
&&
1300 ((!tcp_do_newreno
&& !tp
->sack_enable
&&
1301 tp
->t_dupacks
< tcprexmtthresh
) ||
1302 ((tcp_do_newreno
|| tp
->sack_enable
) &&
1303 !IN_FASTRECOVERY(tp
) && to
.to_nsacks
== 0 &&
1304 TAILQ_EMPTY(&tp
->snd_holes
)))) {
1306 * this is a pure ack for outstanding data.
1308 ++tcpstat
.tcps_predack
;
1310 * "bad retransmit" recovery
1312 if (tp
->t_rxtshift
== 1 &&
1313 tcp_now
< tp
->t_badrxtwin
) {
1314 tp
->snd_cwnd
= tp
->snd_cwnd_prev
;
1316 tp
->snd_ssthresh_prev
;
1317 tp
->snd_recover
= tp
->snd_recover_prev
;
1318 if (tp
->t_flags
& TF_WASFRECOVERY
)
1319 ENTER_FASTRECOVERY(tp
);
1320 tp
->snd_nxt
= tp
->snd_max
;
1321 tp
->t_badrxtwin
= 0;
1323 if (((to
.to_flags
& TOF_TS
) != 0) && (to
.to_tsecr
!= 0)) /* Makes sure we already have a TS */
1325 tcp_now
- to
.to_tsecr
+ 1);
1326 else if (tp
->t_rtttime
&&
1327 SEQ_GT(th
->th_ack
, tp
->t_rtseq
))
1328 tcp_xmit_timer(tp
, tp
->t_rtttime
);
1329 acked
= th
->th_ack
- tp
->snd_una
;
1330 tcpstat
.tcps_rcvackpack
++;
1331 tcpstat
.tcps_rcvackbyte
+= acked
;
1332 sbdrop(&so
->so_snd
, acked
);
1333 if (SEQ_GT(tp
->snd_una
, tp
->snd_recover
) &&
1334 SEQ_LEQ(th
->th_ack
, tp
->snd_recover
))
1335 tp
->snd_recover
= th
->th_ack
- 1;
1336 tp
->snd_una
= th
->th_ack
;
1338 * pull snd_wl2 up to prevent seq wrap relative
1341 tp
->snd_wl2
= th
->th_ack
;
1344 ND6_HINT(tp
); /* some progress has been done */
1347 * If all outstanding data are acked, stop
1348 * retransmit timer, otherwise restart timer
1349 * using current (possibly backed-off) value.
1350 * If process is waiting for space,
1351 * wakeup/selwakeup/signal. If data
1352 * are ready to send, let tcp_output
1353 * decide between more output or persist.
1355 if (tp
->snd_una
== tp
->snd_max
)
1356 tp
->t_timer
[TCPT_REXMT
] = 0;
1357 else if (tp
->t_timer
[TCPT_PERSIST
] == 0)
1358 tp
->t_timer
[TCPT_REXMT
] = tp
->t_rxtcur
;
1360 sowwakeup(so
); /* has to be done with socket lock held */
1361 if ((so
->so_snd
.sb_cc
) || (tp
->t_flags
& TF_ACKNOW
))
1362 (void) tcp_output(tp
);
1363 tcp_unlock(so
, 1, 0);
1364 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
1367 } else if (th
->th_ack
== tp
->snd_una
&&
1368 LIST_EMPTY(&tp
->t_segq
) &&
1369 tlen
<= sbspace(&so
->so_rcv
)) {
1371 * this is a pure, in-sequence data packet
1372 * with nothing on the reassembly queue and
1373 * we have enough buffer space to take it.
1375 /* Clean receiver SACK report if present */
1376 if (tp
->sack_enable
&& tp
->rcv_numsacks
)
1377 tcp_clean_sackreport(tp
);
1378 ++tcpstat
.tcps_preddat
;
1379 tp
->rcv_nxt
+= tlen
;
1381 * Pull snd_wl1 up to prevent seq wrap relative to
1384 tp
->snd_wl1
= th
->th_seq
;
1386 * Pull rcv_up up to prevent seq wrap relative to
1389 tp
->rcv_up
= tp
->rcv_nxt
;
1390 tcpstat
.tcps_rcvpack
++;
1391 tcpstat
.tcps_rcvbyte
+= tlen
;
1392 ND6_HINT(tp
); /* some progress has been done */
1394 * Add data to socket buffer.
1396 m_adj(m
, drop_hdrlen
); /* delayed header drop */
1397 if (sbappend(&so
->so_rcv
, m
))
1401 KERNEL_DEBUG(DBG_LAYER_END
, ((th
->th_dport
<< 16) | th
->th_sport
),
1402 (((ip6
->ip6_src
.s6_addr16
[0]) << 16) | (ip6
->ip6_dst
.s6_addr16
[0])),
1403 th
->th_seq
, th
->th_ack
, th
->th_win
);
1408 KERNEL_DEBUG(DBG_LAYER_END
, ((th
->th_dport
<< 16) | th
->th_sport
),
1409 (((ip
->ip_src
.s_addr
& 0xffff) << 16) | (ip
->ip_dst
.s_addr
& 0xffff)),
1410 th
->th_seq
, th
->th_ack
, th
->th_win
);
1412 if (DELAY_ACK(tp
)) {
1413 tp
->t_flags
|= TF_DELACK
;
1415 tp
->t_flags
|= TF_ACKNOW
;
1418 tcp_unlock(so
, 1, 0);
1419 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
1425 * Calculate amount of space in receive window,
1426 * and then do TCP input processing.
1427 * Receive window is amount of space in rcv queue,
1428 * but not less than advertised window.
1431 lck_mtx_assert(((struct inpcb
*)so
->so_pcb
)->inpcb_mtx
, LCK_MTX_ASSERT_OWNED
);
1435 win
= sbspace(&so
->so_rcv
);
1438 else { /* clip rcv window to 4K for modems */
1439 if (tp
->t_flags
& TF_SLOWLINK
&& slowlink_wsize
> 0)
1440 win
= min(win
, slowlink_wsize
);
1442 tp
->rcv_wnd
= imax(win
, (int)(tp
->rcv_adv
- tp
->rcv_nxt
));
1445 switch (tp
->t_state
) {
1448 * If the state is LISTEN then ignore segment if it contains an RST.
1449 * If the segment contains an ACK then it is bad and send a RST.
1450 * If it does not contain a SYN then it is not interesting; drop it.
1451 * If it is from this socket, drop it, it must be forged.
1452 * Don't bother responding if the destination was a broadcast.
1453 * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial
1454 * tp->iss, and send a segment:
1455 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
1456 * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
1457 * Fill in remote peer address fields if not previously specified.
1458 * Enter SYN_RECEIVED state, and process any other fields of this
1459 * segment in this state.
1462 register struct sockaddr_in
*sin
;
1464 register struct sockaddr_in6
*sin6
;
1468 lck_mtx_assert(((struct inpcb
*)so
->so_pcb
)->inpcb_mtx
, LCK_MTX_ASSERT_OWNED
);
1470 if (thflags
& TH_RST
)
1472 if (thflags
& TH_ACK
) {
1473 rstreason
= BANDLIM_RST_OPENPORT
;
1476 if ((thflags
& TH_SYN
) == 0)
1478 if (th
->th_dport
== th
->th_sport
) {
1481 if (IN6_ARE_ADDR_EQUAL(&ip6
->ip6_dst
,
1486 if (ip
->ip_dst
.s_addr
== ip
->ip_src
.s_addr
)
1490 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
1491 * in_broadcast() should never return true on a received
1492 * packet with M_BCAST not set.
1494 * Packets with a multicast source address should also
1497 if (m
->m_flags
& (M_BCAST
|M_MCAST
))
1501 if (IN6_IS_ADDR_MULTICAST(&ip6
->ip6_dst
) ||
1502 IN6_IS_ADDR_MULTICAST(&ip6
->ip6_src
))
1506 if (IN_MULTICAST(ntohl(ip
->ip_dst
.s_addr
)) ||
1507 IN_MULTICAST(ntohl(ip
->ip_src
.s_addr
)) ||
1508 ip
->ip_src
.s_addr
== htonl(INADDR_BROADCAST
) ||
1509 in_broadcast(ip
->ip_dst
, m
->m_pkthdr
.rcvif
))
1513 MALLOC(sin6
, struct sockaddr_in6
*, sizeof *sin6
,
1514 M_SONAME
, M_NOWAIT
);
1517 bzero(sin6
, sizeof(*sin6
));
1518 sin6
->sin6_family
= AF_INET6
;
1519 sin6
->sin6_len
= sizeof(*sin6
);
1520 sin6
->sin6_addr
= ip6
->ip6_src
;
1521 sin6
->sin6_port
= th
->th_sport
;
1522 laddr6
= inp
->in6p_laddr
;
1523 if (IN6_IS_ADDR_UNSPECIFIED(&inp
->in6p_laddr
))
1524 inp
->in6p_laddr
= ip6
->ip6_dst
;
1525 if (in6_pcbconnect(inp
, (struct sockaddr
*)sin6
,
1527 inp
->in6p_laddr
= laddr6
;
1528 FREE(sin6
, M_SONAME
);
1531 FREE(sin6
, M_SONAME
);
1536 lck_mtx_assert(((struct inpcb
*)so
->so_pcb
)->inpcb_mtx
, LCK_MTX_ASSERT_OWNED
);
1538 MALLOC(sin
, struct sockaddr_in
*, sizeof *sin
, M_SONAME
,
1542 sin
->sin_family
= AF_INET
;
1543 sin
->sin_len
= sizeof(*sin
);
1544 sin
->sin_addr
= ip
->ip_src
;
1545 sin
->sin_port
= th
->th_sport
;
1546 bzero((caddr_t
)sin
->sin_zero
, sizeof(sin
->sin_zero
));
1547 laddr
= inp
->inp_laddr
;
1548 if (inp
->inp_laddr
.s_addr
== INADDR_ANY
)
1549 inp
->inp_laddr
= ip
->ip_dst
;
1550 if (in_pcbconnect(inp
, (struct sockaddr
*)sin
, proc0
)) {
1551 inp
->inp_laddr
= laddr
;
1552 FREE(sin
, M_SONAME
);
1555 FREE(sin
, M_SONAME
);
1558 tcp_dooptions(tp
, optp
, optlen
, th
, &to
);
1560 if (tp
->sack_enable
) {
1561 if (!(to
.to_flags
& TOF_SACK
))
1562 tp
->sack_enable
= 0;
1564 tp
->t_flags
|= TF_SACK_PERMIT
;
1570 tp
->iss
= tcp_new_isn(tp
);
1572 tp
->irs
= th
->th_seq
;
1573 tcp_sendseqinit(tp
);
1575 tp
->snd_recover
= tp
->snd_una
;
1577 * Initialization of the tcpcb for transaction;
1578 * set SND.WND = SEG.WND,
1579 * initialize CCsend and CCrecv.
1581 tp
->snd_wnd
= tiwin
; /* initial send-window */
1582 tp
->t_flags
|= TF_ACKNOW
;
1583 tp
->t_state
= TCPS_SYN_RECEIVED
;
1584 tp
->t_timer
[TCPT_KEEP
] = tcp_keepinit
;
1585 dropsocket
= 0; /* committed to socket */
1586 tcpstat
.tcps_accepts
++;
1591 * If the state is SYN_RECEIVED:
1592 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1594 case TCPS_SYN_RECEIVED
:
1595 if ((thflags
& TH_ACK
) &&
1596 (SEQ_LEQ(th
->th_ack
, tp
->snd_una
) ||
1597 SEQ_GT(th
->th_ack
, tp
->snd_max
))) {
1598 rstreason
= BANDLIM_RST_OPENPORT
;
1604 * If the state is SYN_SENT:
1605 * if seg contains an ACK, but not for our SYN, drop the input.
1606 * if seg contains a RST, then drop the connection.
1607 * if seg does not contain SYN, then drop it.
1608 * Otherwise this is an acceptable SYN segment
1609 * initialize tp->rcv_nxt and tp->irs
1610 * if seg contains ack then advance tp->snd_una
1611 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1612 * arrange for segment to be acked (eventually)
1613 * continue processing rest of data/controls, beginning with URG
1616 if ((thflags
& TH_ACK
) &&
1617 (SEQ_LEQ(th
->th_ack
, tp
->iss
) ||
1618 SEQ_GT(th
->th_ack
, tp
->snd_max
))) {
1619 rstreason
= BANDLIM_UNLIMITED
;
1622 if (thflags
& TH_RST
) {
1623 if (thflags
& TH_ACK
) {
1624 tp
= tcp_drop(tp
, ECONNREFUSED
);
1625 postevent(so
, 0, EV_RESET
);
1629 if ((thflags
& TH_SYN
) == 0)
1631 tp
->snd_wnd
= th
->th_win
; /* initial send window */
1633 tp
->irs
= th
->th_seq
;
1635 if (thflags
& TH_ACK
) {
1636 tcpstat
.tcps_connects
++;
1638 /* Do window scaling on this connection? */
1639 if ((tp
->t_flags
& (TF_RCVD_SCALE
|TF_REQ_SCALE
)) ==
1640 (TF_RCVD_SCALE
|TF_REQ_SCALE
)) {
1641 tp
->snd_scale
= tp
->requested_s_scale
;
1642 tp
->rcv_scale
= tp
->request_r_scale
;
1644 tp
->rcv_adv
+= tp
->rcv_wnd
;
1645 tp
->snd_una
++; /* SYN is acked */
1647 * If there's data, delay ACK; if there's also a FIN
1648 * ACKNOW will be turned on later.
1650 if (DELAY_ACK(tp
) && tlen
!= 0) {
1651 tp
->t_flags
|= TF_DELACK
;
1654 tp
->t_flags
|= TF_ACKNOW
;
1657 * Received <SYN,ACK> in SYN_SENT[*] state.
1659 * SYN_SENT --> ESTABLISHED
1660 * SYN_SENT* --> FIN_WAIT_1
1662 tp
->t_starttime
= 0;
1663 if (tp
->t_flags
& TF_NEEDFIN
) {
1664 tp
->t_state
= TCPS_FIN_WAIT_1
;
1665 tp
->t_flags
&= ~TF_NEEDFIN
;
1668 tp
->t_state
= TCPS_ESTABLISHED
;
1669 tp
->t_timer
[TCPT_KEEP
] = TCP_KEEPIDLE(tp
);
1673 * Received initial SYN in SYN-SENT[*] state => simul-
1674 * taneous open. If segment contains CC option and there is
1675 * a cached CC, apply TAO test; if it succeeds, connection is
1676 * half-synchronized. Otherwise, do 3-way handshake:
1677 * SYN-SENT -> SYN-RECEIVED
1678 * SYN-SENT* -> SYN-RECEIVED*
1680 tp
->t_flags
|= TF_ACKNOW
;
1681 tp
->t_timer
[TCPT_REXMT
] = 0;
1682 tp
->t_state
= TCPS_SYN_RECEIVED
;
1688 * Advance th->th_seq to correspond to first data byte.
1689 * If data, trim to stay within window,
1690 * dropping FIN if necessary.
1693 if (tlen
> tp
->rcv_wnd
) {
1694 todrop
= tlen
- tp
->rcv_wnd
;
1698 tcpstat
.tcps_rcvpackafterwin
++;
1699 tcpstat
.tcps_rcvbyteafterwin
+= todrop
;
1701 tp
->snd_wl1
= th
->th_seq
- 1;
1702 tp
->rcv_up
= th
->th_seq
;
1704 * Client side of transaction: already sent SYN and data.
1705 * If the remote host used T/TCP to validate the SYN,
1706 * our data will be ACK'd; if so, enter normal data segment
1707 * processing in the middle of step 5, ack processing.
1708 * Otherwise, goto step 6.
1710 if (thflags
& TH_ACK
)
1714 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1715 * do normal processing.
1717 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
1721 case TCPS_TIME_WAIT
:
1722 break; /* continue normal processing */
1724 /* Received a SYN while connection is already established.
1725 * This is a "half open connection and other anomalies" described
1726 * in RFC793 page 34, send an ACK so the remote reset the connection
1727 * or recovers by adjusting its sequence numberering
1729 case TCPS_ESTABLISHED
:
1730 if (thflags
& TH_SYN
)
1736 * States other than LISTEN or SYN_SENT.
1737 * First check the RST flag and sequence number since reset segments
1738 * are exempt from the timestamp and connection count tests. This
1739 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1740 * below which allowed reset segments in half the sequence space
1741 * to fall though and be processed (which gives forged reset
1742 * segments with a random sequence number a 50 percent chance of
1743 * killing a connection).
1744 * Then check timestamp, if present.
1745 * Then check the connection count, if present.
1746 * Then check that at least some bytes of segment are within
1747 * receive window. If segment begins before rcv_nxt,
1748 * drop leading data (and SYN); if nothing left, just ack.
1751 * If the RST bit is set, check the sequence number to see
1752 * if this is a valid reset segment.
1754 * In all states except SYN-SENT, all reset (RST) segments
1755 * are validated by checking their SEQ-fields. A reset is
1756 * valid if its sequence number is in the window.
1757 * Note: this does not take into account delayed ACKs, so
1758 * we should test against last_ack_sent instead of rcv_nxt.
1759 * The sequence number in the reset segment is normally an
1760 * echo of our outgoing acknowlegement numbers, but some hosts
1761 * send a reset with the sequence number at the rightmost edge
1762 * of our receive window, and we have to handle this case.
1763 * Note 2: Paul Watson's paper "Slipping in the Window" has shown
1764 * that brute force RST attacks are possible. To combat this,
1765 * we use a much stricter check while in the ESTABLISHED state,
1766 * only accepting RSTs where the sequence number is equal to
1767 * last_ack_sent. In all other states (the states in which a
1768 * RST is more likely), the more permissive check is used.
1769 * If we have multiple segments in flight, the intial reset
1770 * segment sequence numbers will be to the left of last_ack_sent,
1771 * but they will eventually catch up.
1772 * In any case, it never made sense to trim reset segments to
1773 * fit the receive window since RFC 1122 says:
1774 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1776 * A TCP SHOULD allow a received RST segment to include data.
1779 * It has been suggested that a RST segment could contain
1780 * ASCII text that encoded and explained the cause of the
1781 * RST. No standard has yet been established for such
1784 * If the reset segment passes the sequence number test examine
1786 * SYN_RECEIVED STATE:
1787 * If passive open, return to LISTEN state.
1788 * If active open, inform user that connection was refused.
1789 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1790 * Inform user that connection was reset, and close tcb.
1791 * CLOSING, LAST_ACK STATES:
1794 * Drop the segment - see Stevens, vol. 2, p. 964 and
1797 if (thflags
& TH_RST
) {
1798 if ((SEQ_GEQ(th
->th_seq
, tp
->last_ack_sent
) &&
1799 SEQ_LT(th
->th_seq
, tp
->last_ack_sent
+ tp
->rcv_wnd
)) ||
1800 (tp
->rcv_wnd
== 0 && tp
->last_ack_sent
== th
->th_seq
)) {
1801 switch (tp
->t_state
) {
1803 case TCPS_SYN_RECEIVED
:
1804 so
->so_error
= ECONNREFUSED
;
1807 case TCPS_ESTABLISHED
:
1808 if (tp
->last_ack_sent
!= th
->th_seq
) {
1811 case TCPS_FIN_WAIT_1
:
1812 case TCPS_CLOSE_WAIT
:
1816 case TCPS_FIN_WAIT_2
:
1817 so
->so_error
= ECONNRESET
;
1819 postevent(so
, 0, EV_RESET
);
1820 tp
->t_state
= TCPS_CLOSED
;
1821 tcpstat
.tcps_drops
++;
1830 case TCPS_TIME_WAIT
:
1838 lck_mtx_assert(((struct inpcb
*)so
->so_pcb
)->inpcb_mtx
, LCK_MTX_ASSERT_OWNED
);
1841 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1842 * and it's less than ts_recent, drop it.
1844 if ((to
.to_flags
& TOF_TS
) != 0 && tp
->ts_recent
&&
1845 TSTMP_LT(to
.to_tsval
, tp
->ts_recent
)) {
1847 /* Check to see if ts_recent is over 24 days old. */
1848 if ((int)(tcp_now
- tp
->ts_recent_age
) > TCP_PAWS_IDLE
) {
1850 * Invalidate ts_recent. If this segment updates
1851 * ts_recent, the age will be reset later and ts_recent
1852 * will get a valid value. If it does not, setting
1853 * ts_recent to zero will at least satisfy the
1854 * requirement that zero be placed in the timestamp
1855 * echo reply when ts_recent isn't valid. The
1856 * age isn't reset until we get a valid ts_recent
1857 * because we don't want out-of-order segments to be
1858 * dropped when ts_recent is old.
1862 tcpstat
.tcps_rcvduppack
++;
1863 tcpstat
.tcps_rcvdupbyte
+= tlen
;
1864 tcpstat
.tcps_pawsdrop
++;
1872 * In the SYN-RECEIVED state, validate that the packet belongs to
1873 * this connection before trimming the data to fit the receive
1874 * window. Check the sequence number versus IRS since we know
1875 * the sequence numbers haven't wrapped. This is a partial fix
1876 * for the "LAND" DoS attack.
1878 if (tp
->t_state
== TCPS_SYN_RECEIVED
&& SEQ_LT(th
->th_seq
, tp
->irs
)) {
1879 rstreason
= BANDLIM_RST_OPENPORT
;
1883 todrop
= tp
->rcv_nxt
- th
->th_seq
;
1885 if (thflags
& TH_SYN
) {
1895 * Following if statement from Stevens, vol. 2, p. 960.
1898 || (todrop
== tlen
&& (thflags
& TH_FIN
) == 0)) {
1900 * Any valid FIN must be to the left of the window.
1901 * At this point the FIN must be a duplicate or out
1902 * of sequence; drop it.
1907 * Send an ACK to resynchronize and drop any data.
1908 * But keep on processing for RST or ACK.
1910 tp
->t_flags
|= TF_ACKNOW
;
1912 tcpstat
.tcps_rcvduppack
++;
1913 tcpstat
.tcps_rcvdupbyte
+= todrop
;
1915 tcpstat
.tcps_rcvpartduppack
++;
1916 tcpstat
.tcps_rcvpartdupbyte
+= todrop
;
1918 drop_hdrlen
+= todrop
; /* drop from the top afterwards */
1919 th
->th_seq
+= todrop
;
1921 if (th
->th_urp
> todrop
)
1922 th
->th_urp
-= todrop
;
1930 * If new data are received on a connection after the
1931 * user processes are gone, then RST the other end.
1933 if ((so
->so_state
& SS_NOFDREF
) &&
1934 tp
->t_state
> TCPS_CLOSE_WAIT
&& tlen
) {
1936 tcpstat
.tcps_rcvafterclose
++;
1937 rstreason
= BANDLIM_UNLIMITED
;
1942 * If segment ends after window, drop trailing data
1943 * (and PUSH and FIN); if nothing left, just ACK.
1945 todrop
= (th
->th_seq
+tlen
) - (tp
->rcv_nxt
+tp
->rcv_wnd
);
1947 tcpstat
.tcps_rcvpackafterwin
++;
1948 if (todrop
>= tlen
) {
1949 tcpstat
.tcps_rcvbyteafterwin
+= tlen
;
1951 * If a new connection request is received
1952 * while in TIME_WAIT, drop the old connection
1953 * and start over if the sequence numbers
1954 * are above the previous ones.
1956 if (thflags
& TH_SYN
&&
1957 tp
->t_state
== TCPS_TIME_WAIT
&&
1958 SEQ_GT(th
->th_seq
, tp
->rcv_nxt
)) {
1959 iss
= tcp_new_isn(tp
);
1961 tcp_unlock(so
, 1, 0);
1965 * If window is closed can only take segments at
1966 * window edge, and have to drop data and PUSH from
1967 * incoming segments. Continue processing, but
1968 * remember to ack. Otherwise, drop segment
1971 if (tp
->rcv_wnd
== 0 && th
->th_seq
== tp
->rcv_nxt
) {
1972 tp
->t_flags
|= TF_ACKNOW
;
1973 tcpstat
.tcps_rcvwinprobe
++;
1977 tcpstat
.tcps_rcvbyteafterwin
+= todrop
;
1980 thflags
&= ~(TH_PUSH
|TH_FIN
);
1984 * If last ACK falls within this segment's sequence numbers,
1985 * record its timestamp.
1987 * 1) That the test incorporates suggestions from the latest
1988 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1989 * 2) That updating only on newer timestamps interferes with
1990 * our earlier PAWS tests, so this check should be solely
1991 * predicated on the sequence space of this segment.
1992 * 3) That we modify the segment boundary check to be
1993 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
1994 * instead of RFC1323's
1995 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
1996 * This modified check allows us to overcome RFC1323's
1997 * limitations as described in Stevens TCP/IP Illustrated
1998 * Vol. 2 p.869. In such cases, we can still calculate the
1999 * RTT correctly when RCV.NXT == Last.ACK.Sent.
2001 if ((to
.to_flags
& TOF_TS
) != 0 &&
2002 SEQ_LEQ(th
->th_seq
, tp
->last_ack_sent
) &&
2003 SEQ_LEQ(tp
->last_ack_sent
, th
->th_seq
+ tlen
+
2004 ((thflags
& (TH_SYN
|TH_FIN
)) != 0))) {
2005 tp
->ts_recent_age
= tcp_now
;
2006 tp
->ts_recent
= to
.to_tsval
;
2010 * If a SYN is in the window, then this is an
2011 * error and we send an RST and drop the connection.
2013 if (thflags
& TH_SYN
) {
2014 tp
= tcp_drop(tp
, ECONNRESET
);
2015 rstreason
= BANDLIM_UNLIMITED
;
2016 postevent(so
, 0, EV_RESET
);
2021 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
2022 * flag is on (half-synchronized state), then queue data for
2023 * later processing; else drop segment and return.
2025 if ((thflags
& TH_ACK
) == 0) {
2026 if (tp
->t_state
== TCPS_SYN_RECEIVED
||
2027 (tp
->t_flags
& TF_NEEDSYN
))
2036 switch (tp
->t_state
) {
2039 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
2040 * ESTABLISHED state and continue processing.
2041 * The ACK was checked above.
2043 case TCPS_SYN_RECEIVED
:
2045 tcpstat
.tcps_connects
++;
2048 /* Do window scaling? */
2049 if ((tp
->t_flags
& (TF_RCVD_SCALE
|TF_REQ_SCALE
)) ==
2050 (TF_RCVD_SCALE
|TF_REQ_SCALE
)) {
2051 tp
->snd_scale
= tp
->requested_s_scale
;
2052 tp
->rcv_scale
= tp
->request_r_scale
;
2056 * SYN-RECEIVED -> ESTABLISHED
2057 * SYN-RECEIVED* -> FIN-WAIT-1
2059 tp
->t_starttime
= 0;
2060 if (tp
->t_flags
& TF_NEEDFIN
) {
2061 tp
->t_state
= TCPS_FIN_WAIT_1
;
2062 tp
->t_flags
&= ~TF_NEEDFIN
;
2064 tp
->t_state
= TCPS_ESTABLISHED
;
2065 tp
->t_timer
[TCPT_KEEP
] = TCP_KEEPIDLE(tp
);
2068 * If segment contains data or ACK, will call tcp_reass()
2069 * later; if not, do so now to pass queued data to user.
2071 if (tlen
== 0 && (thflags
& TH_FIN
) == 0)
2072 (void) tcp_reass(tp
, (struct tcphdr
*)0, 0,
2074 tp
->snd_wl1
= th
->th_seq
- 1;
2078 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2079 * ACKs. If the ack is in the range
2080 * tp->snd_una < th->th_ack <= tp->snd_max
2081 * then advance tp->snd_una to th->th_ack and drop
2082 * data from the retransmission queue. If this ACK reflects
2083 * more up to date window information we update our window information.
2085 case TCPS_ESTABLISHED
:
2086 case TCPS_FIN_WAIT_1
:
2087 case TCPS_FIN_WAIT_2
:
2088 case TCPS_CLOSE_WAIT
:
2091 case TCPS_TIME_WAIT
:
2092 if (SEQ_GT(th
->th_ack
, tp
->snd_max
)) {
2093 tcpstat
.tcps_rcvacktoomuch
++;
2096 if (tp
->sack_enable
&&
2097 (to
.to_nsacks
> 0 || !TAILQ_EMPTY(&tp
->snd_holes
)))
2098 tcp_sack_doack(tp
, &to
, th
->th_ack
);
2099 if (SEQ_LEQ(th
->th_ack
, tp
->snd_una
)) {
2100 if (tlen
== 0 && tiwin
== tp
->snd_wnd
) {
2101 tcpstat
.tcps_rcvdupack
++;
2103 * If we have outstanding data (other than
2104 * a window probe), this is a completely
2105 * duplicate ack (ie, window info didn't
2106 * change), the ack is the biggest we've
2107 * seen and we've seen exactly our rexmt
2108 * threshhold of them, assume a packet
2109 * has been dropped and retransmit it.
2110 * Kludge snd_nxt & the congestion
2111 * window so we send only this one
2114 * We know we're losing at the current
2115 * window size so do congestion avoidance
2116 * (set ssthresh to half the current window
2117 * and pull our congestion window back to
2118 * the new ssthresh).
2120 * Dup acks mean that packets have left the
2121 * network (they're now cached at the receiver)
2122 * so bump cwnd by the amount in the receiver
2123 * to keep a constant cwnd packets in the
2126 if (tp
->t_timer
[TCPT_REXMT
] == 0 ||
2127 th
->th_ack
!= tp
->snd_una
)
2129 else if (++tp
->t_dupacks
> tcprexmtthresh
||
2130 ((tcp_do_newreno
|| tp
->sack_enable
) &&
2131 IN_FASTRECOVERY(tp
))) {
2132 if (tp
->sack_enable
&& IN_FASTRECOVERY(tp
)) {
2136 * Compute the amount of data in flight first.
2137 * We can inject new data into the pipe iff
2138 * we have less than 1/2 the original window's
2139 * worth of data in flight.
2141 awnd
= (tp
->snd_nxt
- tp
->snd_fack
) +
2142 tp
->sackhint
.sack_bytes_rexmit
;
2143 if (awnd
< tp
->snd_ssthresh
) {
2144 tp
->snd_cwnd
+= tp
->t_maxseg
;
2145 if (tp
->snd_cwnd
> tp
->snd_ssthresh
)
2146 tp
->snd_cwnd
= tp
->snd_ssthresh
;
2149 tp
->snd_cwnd
+= tp
->t_maxseg
;
2150 (void) tcp_output(tp
);
2152 } else if (tp
->t_dupacks
== tcprexmtthresh
) {
2153 tcp_seq onxt
= tp
->snd_nxt
;
2157 * If we're doing sack, check to
2158 * see if we're already in sack
2159 * recovery. If we're not doing sack,
2160 * check to see if we're in newreno
2163 if (tp
->sack_enable
) {
2164 if (IN_FASTRECOVERY(tp
)) {
2168 } else if (tcp_do_newreno
) {
2169 if (SEQ_LEQ(th
->th_ack
,
2175 win
= min(tp
->snd_wnd
, tp
->snd_cwnd
) /
2179 tp
->snd_ssthresh
= win
* tp
->t_maxseg
;
2180 ENTER_FASTRECOVERY(tp
);
2181 tp
->snd_recover
= tp
->snd_max
;
2182 tp
->t_timer
[TCPT_REXMT
] = 0;
2184 if (tp
->sack_enable
) {
2185 tcpstat
.tcps_sack_recovery_episode
++;
2186 tp
->sack_newdata
= tp
->snd_nxt
;
2187 tp
->snd_cwnd
= tp
->t_maxseg
;
2188 (void) tcp_output(tp
);
2191 tp
->snd_nxt
= th
->th_ack
;
2192 tp
->snd_cwnd
= tp
->t_maxseg
;
2193 (void) tcp_output(tp
);
2194 tp
->snd_cwnd
= tp
->snd_ssthresh
+
2195 tp
->t_maxseg
* tp
->t_dupacks
;
2196 if (SEQ_GT(onxt
, tp
->snd_nxt
))
2205 * If the congestion window was inflated to account
2206 * for the other side's cached packets, retract it.
2208 if (tcp_do_newreno
|| tp
->sack_enable
) {
2209 if (IN_FASTRECOVERY(tp
)) {
2210 if (SEQ_LT(th
->th_ack
, tp
->snd_recover
)) {
2211 if (tp
->sack_enable
)
2212 tcp_sack_partialack(tp
, th
);
2214 tcp_newreno_partial_ack(tp
, th
);
2217 * Out of fast recovery.
2218 * Window inflation should have left us
2219 * with approximately snd_ssthresh
2221 * But in case we would be inclined to
2222 * send a burst, better to do it via
2223 * the slow start mechanism.
2225 if (SEQ_GT(th
->th_ack
+
2228 tp
->snd_cwnd
= tp
->snd_max
-
2232 tp
->snd_cwnd
= tp
->snd_ssthresh
;
2236 if (tp
->t_dupacks
>= tcprexmtthresh
&&
2237 tp
->snd_cwnd
> tp
->snd_ssthresh
)
2238 tp
->snd_cwnd
= tp
->snd_ssthresh
;
2242 * If we reach this point, ACK is not a duplicate,
2243 * i.e., it ACKs something we sent.
2245 if (tp
->t_flags
& TF_NEEDSYN
) {
2247 * T/TCP: Connection was half-synchronized, and our
2248 * SYN has been ACK'd (so connection is now fully
2249 * synchronized). Go to non-starred state,
2250 * increment snd_una for ACK of SYN, and check if
2251 * we can do window scaling.
2253 tp
->t_flags
&= ~TF_NEEDSYN
;
2255 /* Do window scaling? */
2256 if ((tp
->t_flags
& (TF_RCVD_SCALE
|TF_REQ_SCALE
)) ==
2257 (TF_RCVD_SCALE
|TF_REQ_SCALE
)) {
2258 tp
->snd_scale
= tp
->requested_s_scale
;
2259 tp
->rcv_scale
= tp
->request_r_scale
;
2264 acked
= th
->th_ack
- tp
->snd_una
;
2265 tcpstat
.tcps_rcvackpack
++;
2266 tcpstat
.tcps_rcvackbyte
+= acked
;
2269 * If we just performed our first retransmit, and the ACK
2270 * arrives within our recovery window, then it was a mistake
2271 * to do the retransmit in the first place. Recover our
2272 * original cwnd and ssthresh, and proceed to transmit where
2275 if (tp
->t_rxtshift
== 1 && tcp_now
< tp
->t_badrxtwin
) {
2276 tp
->snd_cwnd
= tp
->snd_cwnd_prev
;
2277 tp
->snd_ssthresh
= tp
->snd_ssthresh_prev
;
2278 tp
->snd_recover
= tp
->snd_recover_prev
;
2279 if (tp
->t_flags
& TF_WASFRECOVERY
)
2280 ENTER_FASTRECOVERY(tp
);
2281 tp
->snd_nxt
= tp
->snd_max
;
2282 tp
->t_badrxtwin
= 0; /* XXX probably not required */
2286 * If we have a timestamp reply, update smoothed
2287 * round trip time. If no timestamp is present but
2288 * transmit timer is running and timed sequence
2289 * number was acked, update smoothed round trip time.
2290 * Since we now have an rtt measurement, cancel the
2291 * timer backoff (cf., Phil Karn's retransmit alg.).
2292 * Recompute the initial retransmit timer.
2293 * Also makes sure we have a valid time stamp in hand
2295 if (((to
.to_flags
& TOF_TS
) != 0) && (to
.to_tsecr
!= 0))
2296 tcp_xmit_timer(tp
, tcp_now
- to
.to_tsecr
+ 1);
2297 else if (tp
->t_rtttime
&& SEQ_GT(th
->th_ack
, tp
->t_rtseq
))
2298 tcp_xmit_timer(tp
, tp
->t_rtttime
);
2301 * If all outstanding data is acked, stop retransmit
2302 * timer and remember to restart (more output or persist).
2303 * If there is more data to be acked, restart retransmit
2304 * timer, using current (possibly backed-off) value.
2306 if (th
->th_ack
== tp
->snd_max
) {
2307 tp
->t_timer
[TCPT_REXMT
] = 0;
2309 } else if (tp
->t_timer
[TCPT_PERSIST
] == 0)
2310 tp
->t_timer
[TCPT_REXMT
] = tp
->t_rxtcur
;
2313 * If no data (only SYN) was ACK'd,
2314 * skip rest of ACK processing.
2320 * When new data is acked, open the congestion window.
2321 * If the window gives us less than ssthresh packets
2322 * in flight, open exponentially (maxseg per packet).
2323 * Otherwise open linearly: maxseg per window
2324 * (maxseg^2 / cwnd per packet).
2326 if ((!tcp_do_newreno
&& !tp
->sack_enable
) ||
2327 !IN_FASTRECOVERY(tp
)) {
2328 register u_int cw
= tp
->snd_cwnd
;
2329 register u_int incr
= tp
->t_maxseg
;
2330 if (cw
> tp
->snd_ssthresh
)
2331 incr
= incr
* incr
/ cw
;
2332 tp
->snd_cwnd
= min(cw
+incr
, TCP_MAXWIN
<<tp
->snd_scale
);
2334 if (acked
> so
->so_snd
.sb_cc
) {
2335 tp
->snd_wnd
-= so
->so_snd
.sb_cc
;
2336 sbdrop(&so
->so_snd
, (int)so
->so_snd
.sb_cc
);
2339 sbdrop(&so
->so_snd
, acked
);
2340 tp
->snd_wnd
-= acked
;
2344 /* detect una wraparound */
2345 if ((tcp_do_newreno
|| tp
->sack_enable
) &&
2346 !IN_FASTRECOVERY(tp
) &&
2347 SEQ_GT(tp
->snd_una
, tp
->snd_recover
) &&
2348 SEQ_LEQ(th
->th_ack
, tp
->snd_recover
))
2349 tp
->snd_recover
= th
->th_ack
- 1;
2350 if ((tcp_do_newreno
|| tp
->sack_enable
) &&
2351 IN_FASTRECOVERY(tp
) &&
2352 SEQ_GEQ(th
->th_ack
, tp
->snd_recover
))
2353 EXIT_FASTRECOVERY(tp
);
2354 tp
->snd_una
= th
->th_ack
;
2355 if (tp
->sack_enable
) {
2356 if (SEQ_GT(tp
->snd_una
, tp
->snd_recover
))
2357 tp
->snd_recover
= tp
->snd_una
;
2359 if (SEQ_LT(tp
->snd_nxt
, tp
->snd_una
))
2360 tp
->snd_nxt
= tp
->snd_una
;
2362 switch (tp
->t_state
) {
2365 * In FIN_WAIT_1 STATE in addition to the processing
2366 * for the ESTABLISHED state if our FIN is now acknowledged
2367 * then enter FIN_WAIT_2.
2369 case TCPS_FIN_WAIT_1
:
2370 if (ourfinisacked
) {
2372 * If we can't receive any more
2373 * data, then closing user can proceed.
2374 * Starting the timer is contrary to the
2375 * specification, but if we don't get a FIN
2376 * we'll hang forever.
2378 if (so
->so_state
& SS_CANTRCVMORE
) {
2379 soisdisconnected(so
);
2380 tp
->t_timer
[TCPT_2MSL
] = tcp_maxidle
;
2382 add_to_time_wait(tp
);
2383 tp
->t_state
= TCPS_FIN_WAIT_2
;
2389 * In CLOSING STATE in addition to the processing for
2390 * the ESTABLISHED state if the ACK acknowledges our FIN
2391 * then enter the TIME-WAIT state, otherwise ignore
2395 if (ourfinisacked
) {
2396 tp
->t_state
= TCPS_TIME_WAIT
;
2397 tcp_canceltimers(tp
);
2398 /* Shorten TIME_WAIT [RFC-1644, p.28] */
2399 if (tp
->cc_recv
!= 0 &&
2400 tp
->t_starttime
< tcp_msl
)
2401 tp
->t_timer
[TCPT_2MSL
] =
2402 tp
->t_rxtcur
* TCPTV_TWTRUNC
;
2404 tp
->t_timer
[TCPT_2MSL
] = 2 * tcp_msl
;
2405 add_to_time_wait(tp
);
2406 soisdisconnected(so
);
2411 * In LAST_ACK, we may still be waiting for data to drain
2412 * and/or to be acked, as well as for the ack of our FIN.
2413 * If our FIN is now acknowledged, delete the TCB,
2414 * enter the closed state and return.
2417 if (ourfinisacked
) {
2424 * In TIME_WAIT state the only thing that should arrive
2425 * is a retransmission of the remote FIN. Acknowledge
2426 * it and restart the finack timer.
2428 case TCPS_TIME_WAIT
:
2429 tp
->t_timer
[TCPT_2MSL
] = 2 * tcp_msl
;
2430 add_to_time_wait(tp
);
2437 * Update window information.
2438 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2440 if ((thflags
& TH_ACK
) &&
2441 (SEQ_LT(tp
->snd_wl1
, th
->th_seq
) ||
2442 (tp
->snd_wl1
== th
->th_seq
&& (SEQ_LT(tp
->snd_wl2
, th
->th_ack
) ||
2443 (tp
->snd_wl2
== th
->th_ack
&& tiwin
> tp
->snd_wnd
))))) {
2444 /* keep track of pure window updates */
2446 tp
->snd_wl2
== th
->th_ack
&& tiwin
> tp
->snd_wnd
)
2447 tcpstat
.tcps_rcvwinupd
++;
2448 tp
->snd_wnd
= tiwin
;
2449 tp
->snd_wl1
= th
->th_seq
;
2450 tp
->snd_wl2
= th
->th_ack
;
2451 if (tp
->snd_wnd
> tp
->max_sndwnd
)
2452 tp
->max_sndwnd
= tp
->snd_wnd
;
2457 * Process segments with URG.
2459 if ((thflags
& TH_URG
) && th
->th_urp
&&
2460 TCPS_HAVERCVDFIN(tp
->t_state
) == 0) {
2462 * This is a kludge, but if we receive and accept
2463 * random urgent pointers, we'll crash in
2464 * soreceive. It's hard to imagine someone
2465 * actually wanting to send this much urgent data.
2467 if (th
->th_urp
+ so
->so_rcv
.sb_cc
> sb_max
) {
2468 th
->th_urp
= 0; /* XXX */
2469 thflags
&= ~TH_URG
; /* XXX */
2470 goto dodata
; /* XXX */
2473 * If this segment advances the known urgent pointer,
2474 * then mark the data stream. This should not happen
2475 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2476 * a FIN has been received from the remote side.
2477 * In these states we ignore the URG.
2479 * According to RFC961 (Assigned Protocols),
2480 * the urgent pointer points to the last octet
2481 * of urgent data. We continue, however,
2482 * to consider it to indicate the first octet
2483 * of data past the urgent section as the original
2484 * spec states (in one of two places).
2486 if (SEQ_GT(th
->th_seq
+th
->th_urp
, tp
->rcv_up
)) {
2487 tp
->rcv_up
= th
->th_seq
+ th
->th_urp
;
2488 so
->so_oobmark
= so
->so_rcv
.sb_cc
+
2489 (tp
->rcv_up
- tp
->rcv_nxt
) - 1;
2490 if (so
->so_oobmark
== 0) {
2491 so
->so_state
|= SS_RCVATMARK
;
2492 postevent(so
, 0, EV_OOB
);
2495 tp
->t_oobflags
&= ~(TCPOOB_HAVEDATA
| TCPOOB_HADDATA
);
2498 * Remove out of band data so doesn't get presented to user.
2499 * This can happen independent of advancing the URG pointer,
2500 * but if two URG's are pending at once, some out-of-band
2501 * data may creep in... ick.
2503 if (th
->th_urp
<= (u_long
)tlen
2505 && (so
->so_options
& SO_OOBINLINE
) == 0
2508 tcp_pulloutofband(so
, th
, m
,
2509 drop_hdrlen
); /* hdr drop is delayed */
2512 * If no out of band data is expected,
2513 * pull receive urgent pointer along
2514 * with the receive window.
2516 if (SEQ_GT(tp
->rcv_nxt
, tp
->rcv_up
))
2517 tp
->rcv_up
= tp
->rcv_nxt
;
2521 * Process the segment text, merging it into the TCP sequencing queue,
2522 * and arranging for acknowledgment of receipt if necessary.
2523 * This process logically involves adjusting tp->rcv_wnd as data
2524 * is presented to the user (this happens in tcp_usrreq.c,
2525 * case PRU_RCVD). If a FIN has already been received on this
2526 * connection then we just ignore the text.
2528 if ((tlen
|| (thflags
&TH_FIN
)) &&
2529 TCPS_HAVERCVDFIN(tp
->t_state
) == 0) {
2530 tcp_seq save_start
= th
->th_seq
;
2531 tcp_seq save_end
= th
->th_seq
+ tlen
;
2532 m_adj(m
, drop_hdrlen
); /* delayed header drop */
2534 * Insert segment which includes th into TCP reassembly queue
2535 * with control block tp. Set thflags to whether reassembly now
2536 * includes a segment with FIN. This handles the common case
2537 * inline (segment is the next to be received on an established
2538 * connection, and the queue is empty), avoiding linkage into
2539 * and removal from the queue and repetition of various
2541 * Set DELACK for segments received in order, but ack
2542 * immediately when segments are out of order (so
2543 * fast retransmit can work).
2545 if (th
->th_seq
== tp
->rcv_nxt
&&
2546 LIST_EMPTY(&tp
->t_segq
) &&
2547 TCPS_HAVEESTABLISHED(tp
->t_state
)) {
2548 if (DELAY_ACK(tp
) && ((tp
->t_flags
& TF_ACKNOW
) == 0)) {
2549 tp
->t_flags
|= TF_DELACK
;
2552 tp
->t_flags
|= TF_ACKNOW
;
2554 tp
->rcv_nxt
+= tlen
;
2555 thflags
= th
->th_flags
& TH_FIN
;
2556 tcpstat
.tcps_rcvpack
++;
2557 tcpstat
.tcps_rcvbyte
+= tlen
;
2559 if (sbappend(&so
->so_rcv
, m
))
2562 thflags
= tcp_reass(tp
, th
, &tlen
, m
);
2563 tp
->t_flags
|= TF_ACKNOW
;
2566 if (tlen
> 0 && tp
->sack_enable
)
2567 tcp_update_sack_list(tp
, save_start
, save_end
);
2569 if (tp
->t_flags
& TF_DELACK
)
2573 KERNEL_DEBUG(DBG_LAYER_END
, ((th
->th_dport
<< 16) | th
->th_sport
),
2574 (((ip6
->ip6_src
.s6_addr16
[0]) << 16) | (ip6
->ip6_dst
.s6_addr16
[0])),
2575 th
->th_seq
, th
->th_ack
, th
->th_win
);
2580 KERNEL_DEBUG(DBG_LAYER_END
, ((th
->th_dport
<< 16) | th
->th_sport
),
2581 (((ip
->ip_src
.s_addr
& 0xffff) << 16) | (ip
->ip_dst
.s_addr
& 0xffff)),
2582 th
->th_seq
, th
->th_ack
, th
->th_win
);
2587 * Note the amount of data that peer has sent into
2588 * our window, in order to estimate the sender's
2591 len
= so
->so_rcv
.sb_hiwat
- (tp
->rcv_adv
- tp
->rcv_nxt
);
2598 * If FIN is received ACK the FIN and let the user know
2599 * that the connection is closing.
2601 if (thflags
& TH_FIN
) {
2602 if (TCPS_HAVERCVDFIN(tp
->t_state
) == 0) {
2604 postevent(so
, 0, EV_FIN
);
2606 * If connection is half-synchronized
2607 * (ie NEEDSYN flag on) then delay ACK,
2608 * If connection is half-synchronized
2609 * (ie NEEDSYN flag on) then delay ACK,
2610 * so it may be piggybacked when SYN is sent.
2611 * Otherwise, since we received a FIN then no
2612 * more input can be expected, send ACK now.
2614 if (DELAY_ACK(tp
) && (tp
->t_flags
& TF_NEEDSYN
)) {
2615 tp
->t_flags
|= TF_DELACK
;
2618 tp
->t_flags
|= TF_ACKNOW
;
2622 switch (tp
->t_state
) {
2625 * In SYN_RECEIVED and ESTABLISHED STATES
2626 * enter the CLOSE_WAIT state.
2628 case TCPS_SYN_RECEIVED
:
2629 tp
->t_starttime
= 0;
2630 case TCPS_ESTABLISHED
:
2631 tp
->t_state
= TCPS_CLOSE_WAIT
;
2635 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2636 * enter the CLOSING state.
2638 case TCPS_FIN_WAIT_1
:
2639 tp
->t_state
= TCPS_CLOSING
;
2643 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2644 * starting the time-wait timer, turning off the other
2647 case TCPS_FIN_WAIT_2
:
2648 tp
->t_state
= TCPS_TIME_WAIT
;
2649 tcp_canceltimers(tp
);
2650 /* Shorten TIME_WAIT [RFC-1644, p.28] */
2651 if (tp
->cc_recv
!= 0 &&
2652 tp
->t_starttime
< tcp_msl
) {
2653 tp
->t_timer
[TCPT_2MSL
] =
2654 tp
->t_rxtcur
* TCPTV_TWTRUNC
;
2655 /* For transaction client, force ACK now. */
2656 tp
->t_flags
|= TF_ACKNOW
;
2659 tp
->t_timer
[TCPT_2MSL
] = 2 * tcp_msl
;
2661 add_to_time_wait(tp
);
2662 soisdisconnected(so
);
2666 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2668 case TCPS_TIME_WAIT
:
2669 tp
->t_timer
[TCPT_2MSL
] = 2 * tcp_msl
;
2670 add_to_time_wait(tp
);
2675 if (so
->so_options
& SO_DEBUG
)
2676 tcp_trace(TA_INPUT
, ostate
, tp
, (void *)tcp_saveipgen
,
2681 * Return any desired output.
2683 if (needoutput
|| (tp
->t_flags
& TF_ACKNOW
))
2684 (void) tcp_output(tp
);
2685 tcp_unlock(so
, 1, 0);
2686 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
2691 * Generate an ACK dropping incoming segment if it occupies
2692 * sequence space, where the ACK reflects our state.
2694 * We can now skip the test for the RST flag since all
2695 * paths to this code happen after packets containing
2696 * RST have been dropped.
2698 * In the SYN-RECEIVED state, don't send an ACK unless the
2699 * segment we received passes the SYN-RECEIVED ACK test.
2700 * If it fails send a RST. This breaks the loop in the
2701 * "LAND" DoS attack, and also prevents an ACK storm
2702 * between two listening ports that have been sent forged
2703 * SYN segments, each with the source address of the other.
2705 if (tp
->t_state
== TCPS_SYN_RECEIVED
&& (thflags
& TH_ACK
) &&
2706 (SEQ_GT(tp
->snd_una
, th
->th_ack
) ||
2707 SEQ_GT(th
->th_ack
, tp
->snd_max
)) ) {
2708 rstreason
= BANDLIM_RST_OPENPORT
;
2712 if (so
->so_options
& SO_DEBUG
)
2713 tcp_trace(TA_DROP
, ostate
, tp
, (void *)tcp_saveipgen
,
2717 tp
->t_flags
|= TF_ACKNOW
;
2718 (void) tcp_output(tp
);
2719 tcp_unlock(so
, 1, 0);
2720 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
2722 dropwithresetnosock
:
2726 * Generate a RST, dropping incoming segment.
2727 * Make ACK acceptable to originator of segment.
2728 * Don't bother to respond if destination was broadcast/multicast.
2730 if ((thflags
& TH_RST
) || m
->m_flags
& (M_BCAST
|M_MCAST
))
2734 if (IN6_IS_ADDR_MULTICAST(&ip6
->ip6_dst
) ||
2735 IN6_IS_ADDR_MULTICAST(&ip6
->ip6_src
))
2739 if (IN_MULTICAST(ntohl(ip
->ip_dst
.s_addr
)) ||
2740 IN_MULTICAST(ntohl(ip
->ip_src
.s_addr
)) ||
2741 ip
->ip_src
.s_addr
== htonl(INADDR_BROADCAST
) ||
2742 in_broadcast(ip
->ip_dst
, m
->m_pkthdr
.rcvif
))
2744 /* IPv6 anycast check is done at tcp6_input() */
2747 * Perform bandwidth limiting.
2750 if (badport_bandlim(rstreason
) < 0)
2755 if (tp
== 0 || (tp
->t_inpcb
->inp_socket
->so_options
& SO_DEBUG
))
2756 tcp_trace(TA_DROP
, ostate
, tp
, (void *)tcp_saveipgen
,
2759 if (thflags
& TH_ACK
)
2760 /* mtod() below is safe as long as hdr dropping is delayed */
2761 tcp_respond(tp
, mtod(m
, void *), th
, m
, (tcp_seq
)0, th
->th_ack
,
2764 if (thflags
& TH_SYN
)
2766 /* mtod() below is safe as long as hdr dropping is delayed */
2767 tcp_respond(tp
, mtod(m
, void *), th
, m
, th
->th_seq
+tlen
,
2768 (tcp_seq
)0, TH_RST
|TH_ACK
);
2770 /* destroy temporarily created socket */
2773 tcp_unlock(so
, 1, 0);
2776 if ((inp
!= NULL
) && (nosock
== 0))
2777 tcp_unlock(so
, 1, 0);
2778 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
2784 * Drop space held by incoming segment and return.
2787 if (tp
== 0 || (tp
->t_inpcb
->inp_socket
->so_options
& SO_DEBUG
))
2788 tcp_trace(TA_DROP
, ostate
, tp
, (void *)tcp_saveipgen
,
2792 /* destroy temporarily created socket */
2795 tcp_unlock(so
, 1, 0);
2799 tcp_unlock(so
, 1, 0);
2800 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
2805 tcp_dooptions(tp
, cp
, cnt
, th
, to
)
2807 * Parse TCP options and place in tcpopt.
2818 for (; cnt
> 0; cnt
-= optlen
, cp
+= optlen
) {
2820 if (opt
== TCPOPT_EOL
)
2822 if (opt
== TCPOPT_NOP
)
2828 if (optlen
< 2 || optlen
> cnt
)
2837 if (optlen
!= TCPOLEN_MAXSEG
)
2839 if (!(th
->th_flags
& TH_SYN
))
2841 bcopy((char *) cp
+ 2, (char *) &mss
, sizeof(mss
));
2846 if (optlen
!= TCPOLEN_WINDOW
)
2848 if (!(th
->th_flags
& TH_SYN
))
2850 tp
->t_flags
|= TF_RCVD_SCALE
;
2851 tp
->requested_s_scale
= min(cp
[2], TCP_MAX_WINSHIFT
);
2854 case TCPOPT_TIMESTAMP
:
2855 if (optlen
!= TCPOLEN_TIMESTAMP
)
2857 to
->to_flags
|= TOF_TS
;
2858 bcopy((char *)cp
+ 2,
2859 (char *)&to
->to_tsval
, sizeof(to
->to_tsval
));
2860 NTOHL(to
->to_tsval
);
2861 bcopy((char *)cp
+ 6,
2862 (char *)&to
->to_tsecr
, sizeof(to
->to_tsecr
));
2863 NTOHL(to
->to_tsecr
);
2866 * A timestamp received in a SYN makes
2867 * it ok to send timestamp requests and replies.
2869 if (th
->th_flags
& TH_SYN
) {
2870 tp
->t_flags
|= TF_RCVD_TSTMP
;
2871 tp
->ts_recent
= to
->to_tsval
;
2872 tp
->ts_recent_age
= tcp_now
;
2875 case TCPOPT_SACK_PERMITTED
:
2877 optlen
!= TCPOLEN_SACK_PERMITTED
)
2879 if (th
->th_flags
& TH_SYN
)
2880 to
->to_flags
|= TOF_SACK
;
2883 if (optlen
<= 2 || (optlen
- 2) % TCPOLEN_SACK
!= 0)
2885 to
->to_nsacks
= (optlen
- 2) / TCPOLEN_SACK
;
2886 to
->to_sacks
= cp
+ 2;
2887 tcpstat
.tcps_sack_rcv_blocks
++;
2892 if (th
->th_flags
& TH_SYN
)
2893 tcp_mss(tp
, mss
); /* sets t_maxseg */
2897 * Pull out of band byte out of a segment so
2898 * it doesn't appear in the user's data queue.
2899 * It is still reflected in the segment length for
2900 * sequencing purposes.
2903 tcp_pulloutofband(so
, th
, m
, off
)
2906 register struct mbuf
*m
;
2907 int off
; /* delayed to be droped hdrlen */
2909 int cnt
= off
+ th
->th_urp
- 1;
2912 if (m
->m_len
> cnt
) {
2913 char *cp
= mtod(m
, caddr_t
) + cnt
;
2914 struct tcpcb
*tp
= sototcpcb(so
);
2917 tp
->t_oobflags
|= TCPOOB_HAVEDATA
;
2918 bcopy(cp
+1, cp
, (unsigned)(m
->m_len
- cnt
- 1));
2920 if (m
->m_flags
& M_PKTHDR
)
2929 panic("tcp_pulloutofband");
2933 * Collect new round-trip time estimate
2934 * and update averages and current timeout.
2937 tcp_xmit_timer(tp
, rtt
)
2938 register struct tcpcb
*tp
;
2943 tcpstat
.tcps_rttupdated
++;
2945 if (tp
->t_srtt
!= 0) {
2947 * srtt is stored as fixed point with 5 bits after the
2948 * binary point (i.e., scaled by 8). The following magic
2949 * is equivalent to the smoothing algorithm in rfc793 with
2950 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2951 * point). Adjust rtt to origin 0.
2953 delta
= ((rtt
- 1) << TCP_DELTA_SHIFT
)
2954 - (tp
->t_srtt
>> (TCP_RTT_SHIFT
- TCP_DELTA_SHIFT
));
2956 if ((tp
->t_srtt
+= delta
) <= 0)
2960 * We accumulate a smoothed rtt variance (actually, a
2961 * smoothed mean difference), then set the retransmit
2962 * timer to smoothed rtt + 4 times the smoothed variance.
2963 * rttvar is stored as fixed point with 4 bits after the
2964 * binary point (scaled by 16). The following is
2965 * equivalent to rfc793 smoothing with an alpha of .75
2966 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2967 * rfc793's wired-in beta.
2971 delta
-= tp
->t_rttvar
>> (TCP_RTTVAR_SHIFT
- TCP_DELTA_SHIFT
);
2972 if ((tp
->t_rttvar
+= delta
) <= 0)
2976 * No rtt measurement yet - use the unsmoothed rtt.
2977 * Set the variance to half the rtt (so our first
2978 * retransmit happens at 3*rtt).
2980 tp
->t_srtt
= rtt
<< TCP_RTT_SHIFT
;
2981 tp
->t_rttvar
= rtt
<< (TCP_RTTVAR_SHIFT
- 1);
2987 * the retransmit should happen at rtt + 4 * rttvar.
2988 * Because of the way we do the smoothing, srtt and rttvar
2989 * will each average +1/2 tick of bias. When we compute
2990 * the retransmit timer, we want 1/2 tick of rounding and
2991 * 1 extra tick because of +-1/2 tick uncertainty in the
2992 * firing of the timer. The bias will give us exactly the
2993 * 1.5 tick we need. But, because the bias is
2994 * statistical, we have to test that we don't drop below
2995 * the minimum feasible timer (which is 2 ticks).
2997 TCPT_RANGESET(tp
->t_rxtcur
, TCP_REXMTVAL(tp
),
2998 max(tp
->t_rttmin
, rtt
+ 2), TCPTV_REXMTMAX
);
3001 * We received an ack for a packet that wasn't retransmitted;
3002 * it is probably safe to discard any error indications we've
3003 * received recently. This isn't quite right, but close enough
3004 * for now (a route might have failed after we sent a segment,
3005 * and the return path might not be symmetrical).
3007 tp
->t_softerror
= 0;
3011 * Determine a reasonable value for maxseg size.
3012 * If the route is known, check route for mtu.
3013 * If none, use an mss that can be handled on the outgoing
3014 * interface without forcing IP to fragment; if bigger than
3015 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
3016 * to utilize large mbufs. If no route is found, route has no mtu,
3017 * or the destination isn't local, use a default, hopefully conservative
3018 * size (usually 512 or the default IP max size, but no more than the mtu
3019 * of the interface), as we can't discover anything about intervening
3020 * gateways or networks. We also initialize the congestion/slow start
3021 * window to be a single segment if the destination isn't local.
3022 * While looking at the routing entry, we also initialize other path-dependent
3023 * parameters from pre-set or cached values in the routing entry.
3025 * Also take into account the space needed for options that we
3026 * send regularly. Make maxseg shorter by that amount to assure
3027 * that we can send maxseg amount of data even when the options
3028 * are present. Store the upper limit of the length of options plus
3031 * NOTE that this routine is only called when we process an incoming
3032 * segment, for outgoing segments only tcp_mssopt is called.
3034 * In case of T/TCP, we call this routine during implicit connection
3035 * setup as well (offer = -1), to initialize maxseg from the cached
3043 register struct rtentry
*rt
;
3045 register int rtt
, mss
;
3049 struct rmxp_tao
*taop
;
3050 int origoffer
= offer
;
3058 isipv6
= ((inp
->inp_vflag
& INP_IPV6
) != 0) ? 1 : 0;
3059 min_protoh
= isipv6
? sizeof (struct ip6_hdr
) + sizeof (struct tcphdr
)
3060 : sizeof (struct tcpiphdr
);
3062 #define min_protoh (sizeof (struct tcpiphdr))
3066 rt
= tcp_rtlookup6(inp
);
3069 rt
= tcp_rtlookup(inp
);
3071 tp
->t_maxopd
= tp
->t_maxseg
=
3073 isipv6
? tcp_v6mssdflt
:
3080 * Slower link window correction:
3081 * If a value is specificied for slowlink_wsize use it for PPP links
3082 * believed to be on a serial modem (speed <128Kbps). Excludes 9600bps as
3083 * it is the default value adversized by pseudo-devices over ppp.
3085 if (ifp
->if_type
== IFT_PPP
&& slowlink_wsize
> 0 &&
3086 ifp
->if_baudrate
> 9600 && ifp
->if_baudrate
<= 128000) {
3087 tp
->t_flags
|= TF_SLOWLINK
;
3089 so
= inp
->inp_socket
;
3091 taop
= rmx_taop(rt
->rt_rmx
);
3093 * Offer == -1 means that we didn't receive SYN yet,
3094 * use cached value in that case;
3097 offer
= taop
->tao_mssopt
;
3099 * Offer == 0 means that there was no MSS on the SYN segment,
3100 * in this case we use tcp_mssdflt.
3105 isipv6
? tcp_v6mssdflt
:
3110 * Prevent DoS attack with too small MSS. Round up
3111 * to at least minmss.
3113 offer
= max(offer
, tcp_minmss
);
3115 * Sanity check: make sure that maxopd will be large
3116 * enough to allow some data on segments even is the
3117 * all the option space is used (40bytes). Otherwise
3118 * funny things may happen in tcp_output.
3120 offer
= max(offer
, 64);
3122 taop
->tao_mssopt
= offer
;
3125 * While we're here, check if there's an initial rtt
3126 * or rttvar. Convert from the route-table units
3127 * to scaled multiples of the slow timeout timer.
3129 if (tp
->t_srtt
== 0 && (rtt
= rt
->rt_rmx
.rmx_rtt
)) {
3131 * XXX the lock bit for RTT indicates that the value
3132 * is also a minimum value; this is subject to time.
3134 if (rt
->rt_rmx
.rmx_locks
& RTV_RTT
)
3135 tp
->t_rttmin
= rtt
/ (RTM_RTTUNIT
/ PR_SLOWHZ
);
3136 tp
->t_srtt
= rtt
/ (RTM_RTTUNIT
/ (PR_SLOWHZ
* TCP_RTT_SCALE
));
3137 tcpstat
.tcps_usedrtt
++;
3138 if (rt
->rt_rmx
.rmx_rttvar
) {
3139 tp
->t_rttvar
= rt
->rt_rmx
.rmx_rttvar
/
3140 (RTM_RTTUNIT
/ (PR_SLOWHZ
* TCP_RTTVAR_SCALE
));
3141 tcpstat
.tcps_usedrttvar
++;
3143 /* default variation is +- 1 rtt */
3145 tp
->t_srtt
* TCP_RTTVAR_SCALE
/ TCP_RTT_SCALE
;
3147 TCPT_RANGESET(tp
->t_rxtcur
,
3148 ((tp
->t_srtt
>> 2) + tp
->t_rttvar
) >> 1,
3149 tp
->t_rttmin
, TCPTV_REXMTMAX
);
3152 * if there's an mtu associated with the route, use it
3153 * else, use the link mtu.
3155 if (rt
->rt_rmx
.rmx_mtu
)
3156 mss
= rt
->rt_rmx
.rmx_mtu
- min_protoh
;
3161 (isipv6
? nd_ifinfo
[rt
->rt_ifp
->if_index
].linkmtu
:
3170 if (!in6_localaddr(&inp
->in6p_faddr
))
3171 mss
= min(mss
, tcp_v6mssdflt
);
3174 if (!in_localaddr(inp
->inp_faddr
))
3175 mss
= min(mss
, tcp_mssdflt
);
3177 mss
= min(mss
, offer
);
3179 * maxopd stores the maximum length of data AND options
3180 * in a segment; maxseg is the amount of data in a normal
3181 * segment. We need to store this value (maxopd) apart
3182 * from maxseg, because now every segment carries options
3183 * and thus we normally have somewhat less data in segments.
3188 * origoffer==-1 indicates, that no segments were received yet.
3189 * In this case we just guess.
3191 if ((tp
->t_flags
& (TF_REQ_TSTMP
|TF_NOOPT
)) == TF_REQ_TSTMP
&&
3193 (tp
->t_flags
& TF_RCVD_TSTMP
) == TF_RCVD_TSTMP
))
3194 mss
-= TCPOLEN_TSTAMP_APPA
;
3198 * If there's a pipesize (ie loopback), change the socket
3199 * buffer to that size only if it's bigger than the current
3200 * sockbuf size. Make the socket buffers an integral
3201 * number of mss units; if the mss is larger than
3202 * the socket buffer, decrease the mss.
3205 bufsize
= rt
->rt_rmx
.rmx_sendpipe
;
3206 if (bufsize
< so
->so_snd
.sb_hiwat
)
3208 bufsize
= so
->so_snd
.sb_hiwat
;
3212 bufsize
= roundup(bufsize
, mss
);
3213 if (bufsize
> sb_max
)
3215 (void)sbreserve(&so
->so_snd
, bufsize
);
3220 bufsize
= rt
->rt_rmx
.rmx_recvpipe
;
3221 if (bufsize
< so
->so_rcv
.sb_hiwat
)
3223 bufsize
= so
->so_rcv
.sb_hiwat
;
3224 if (bufsize
> mss
) {
3225 bufsize
= roundup(bufsize
, mss
);
3226 if (bufsize
> sb_max
)
3228 (void)sbreserve(&so
->so_rcv
, bufsize
);
3232 * Set the slow-start flight size depending on whether this
3233 * is a local network or not.
3237 (isipv6
&& in6_localaddr(&inp
->in6p_faddr
)) ||
3240 in_localaddr(inp
->inp_faddr
)
3245 tp
->snd_cwnd
= mss
* ss_fltsz_local
;
3247 tp
->snd_cwnd
= mss
* ss_fltsz
;
3249 if (rt
->rt_rmx
.rmx_ssthresh
) {
3251 * There's some sort of gateway or interface
3252 * buffer limit on the path. Use this to set
3253 * the slow start threshhold, but set the
3254 * threshold to no less than 2*mss.
3256 tp
->snd_ssthresh
= max(2 * mss
, rt
->rt_rmx
.rmx_ssthresh
);
3257 tcpstat
.tcps_usedssthresh
++;
3262 * Determine the MSS option to send on an outgoing SYN.
3276 isipv6
= ((tp
->t_inpcb
->inp_vflag
& INP_IPV6
) != 0) ? 1 : 0;
3277 min_protoh
= isipv6
? sizeof (struct ip6_hdr
) + sizeof (struct tcphdr
)
3278 : sizeof (struct tcpiphdr
);
3280 #define min_protoh (sizeof (struct tcpiphdr))
3284 rt
= tcp_rtlookup6(tp
->t_inpcb
);
3287 rt
= tcp_rtlookup(tp
->t_inpcb
);
3291 isipv6
? tcp_v6mssdflt
:
3295 * Slower link window correction:
3296 * If a value is specificied for slowlink_wsize use it for PPP links
3297 * believed to be on a serial modem (speed <128Kbps). Excludes 9600bps as
3298 * it is the default value adversized by pseudo-devices over ppp.
3300 if (rt
->rt_ifp
->if_type
== IFT_PPP
&& slowlink_wsize
> 0 &&
3301 rt
->rt_ifp
->if_baudrate
> 9600 && rt
->rt_ifp
->if_baudrate
<= 128000) {
3302 tp
->t_flags
|= TF_SLOWLINK
;
3305 if (rt
->rt_rmx
.rmx_mtu
)
3306 mss
= rt
->rt_rmx
.rmx_mtu
;
3310 (isipv6
? nd_ifinfo
[rt
->rt_ifp
->if_index
].linkmtu
:
3317 return (mss
- min_protoh
);
3321 * On a partial ack arrives, force the retransmission of the
3322 * next unacknowledged segment. Do not clear tp->t_dupacks.
3323 * By setting snd_nxt to ti_ack, this forces retransmission timer to
3327 tcp_newreno_partial_ack(tp
, th
)
3331 tcp_seq onxt
= tp
->snd_nxt
;
3332 u_long ocwnd
= tp
->snd_cwnd
;
3333 tp
->t_timer
[TCPT_REXMT
] = 0;
3335 tp
->snd_nxt
= th
->th_ack
;
3337 * Set snd_cwnd to one segment beyond acknowledged offset
3338 * (tp->snd_una has not yet been updated when this function
3341 tp
->snd_cwnd
= tp
->t_maxseg
+ (th
->th_ack
- tp
->snd_una
);
3342 tp
->t_flags
|= TF_ACKNOW
;
3343 (void) tcp_output(tp
);
3344 tp
->snd_cwnd
= ocwnd
;
3345 if (SEQ_GT(onxt
, tp
->snd_nxt
))
3348 * Partial window deflation. Relies on fact that tp->snd_una
3351 tp
->snd_cwnd
-= (th
->th_ack
- tp
->snd_una
- tp
->t_maxseg
);
3355 * Drop a random TCP connection that hasn't been serviced yet and
3356 * is eligible for discard. There is a one in qlen chance that
3357 * we will return a null, saying that there are no dropable
3358 * requests. In this case, the protocol specific code should drop
3359 * the new request. This insures fairness.
3361 * The listening TCP socket "head" must be locked
3364 tcpdropdropablreq(struct socket
*head
)
3367 unsigned int i
, j
, qlen
;
3369 static struct timeval old_runtime
;
3370 static unsigned int cur_cnt
, old_cnt
;
3372 struct inpcb
*inp
= NULL
;
3376 if ((i
= (tv
.tv_sec
- old_runtime
.tv_sec
)) != 0) {
3378 old_cnt
= cur_cnt
/ i
;
3382 so
= TAILQ_FIRST(&head
->so_incomp
);
3386 qlen
= head
->so_incqlen
;
3387 if (++cur_cnt
> qlen
|| old_cnt
> qlen
) {
3388 rnd
= (314159 * rnd
+ 66329) & 0xffff;
3389 j
= ((qlen
+ 1) * rnd
) >> 16;
3392 so
= TAILQ_NEXT(so
, so_list
);
3394 /* Find a connection that is not already closing */
3396 inp
= (struct inpcb
*)so
->so_pcb
;
3398 if (in_pcb_checkstate(inp
, WNT_ACQUIRE
, 0) != WNT_STOPUSING
)
3401 so
= TAILQ_NEXT(so
, so_list
);
3408 TAILQ_REMOVE(&head
->so_incomp
, so
, so_list
);
3409 tcp_unlock(head
, 0, 0);
3411 /* Let's remove this connection from the incomplete list */
3414 if (in_pcb_checkstate(inp
, WNT_RELEASE
, 1) == WNT_STOPUSING
) {
3415 tcp_unlock(so
, 1, 0);
3420 so
->so_usecount
--; /* No more held by so_head */
3423 * We do not want to lose track of the PCB right away in case we receive
3424 * more segments from the peer
3427 tp
->t_flags
|= TF_LQ_OVERFLOW
;
3428 tp
->t_state
= TCPS_CLOSED
;
3429 (void) tcp_output(tp
);
3430 tcpstat
.tcps_drops
++;
3431 soisdisconnected(so
);
3432 tcp_canceltimers(tp
);
3433 add_to_time_wait(tp
);
3435 tcp_unlock(so
, 1, 0);
3436 tcp_lock(head
, 0, 0);
3443 tcp_getstat SYSCTL_HANDLER_ARGS
3448 if (req
->oldptr
== 0) {
3449 req
->oldlen
= (size_t)sizeof(struct tcpstat
);
3452 error
= SYSCTL_OUT(req
, &tcpstat
, (size_t) req
->oldlen
);
3458 SYSCTL_PROC(_net_inet_tcp
, TCPCTL_STATS
, stats
, CTLFLAG_RD
, 0, 0,
3459 tcp_getstat
, "S,tcpstat", "TCP statistics (struct tcpstat, netinet/tcp_var.h)");