2 * Copyright (c) 2000 Apple Computer, Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * The contents of this file constitute Original Code as defined in and
7 * are subject to the Apple Public Source License Version 1.1 (the
8 * "License"). You may not use this file except in compliance with the
9 * License. Please obtain a copy of the License at
10 * http://www.apple.com/publicsource and read it before using this file.
12 * This Original Code and all software distributed under the License are
13 * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
14 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
15 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
17 * License for the specific language governing rights and limitations
20 * @APPLE_LICENSE_HEADER_END@
23 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
24 * The Regents of the University of California. All rights reserved.
26 * Redistribution and use in source and binary forms, with or without
27 * modification, are permitted provided that the following conditions
29 * 1. Redistributions of source code must retain the above copyright
30 * notice, this list of conditions and the following disclaimer.
31 * 2. Redistributions in binary form must reproduce the above copyright
32 * notice, this list of conditions and the following disclaimer in the
33 * documentation and/or other materials provided with the distribution.
34 * 3. All advertising materials mentioning features or use of this software
35 * must display the following acknowledgement:
36 * This product includes software developed by the University of
37 * California, Berkeley and its contributors.
38 * 4. Neither the name of the University nor the names of its contributors
39 * may be used to endorse or promote products derived from this software
40 * without specific prior written permission.
42 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
43 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
44 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
45 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
46 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
47 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
48 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
49 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
50 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
51 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
54 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
55 * $FreeBSD: src/sys/netinet/tcp_input.c,v 1.107.2.16 2001/08/22 00:59:12 silby Exp $
59 #include <sys/param.h>
60 #include <sys/systm.h>
61 #include <sys/kernel.h>
62 #include <sys/sysctl.h>
63 #include <sys/malloc.h>
65 #include <sys/proc.h> /* for proc0 declaration */
66 #include <sys/protosw.h>
67 #include <sys/socket.h>
68 #include <sys/socketvar.h>
69 #include <sys/syslog.h>
71 #include <kern/cpu_number.h> /* before tcp_seq.h, for tcp_random18() */
74 #include <net/if_types.h>
75 #include <net/route.h>
77 #include <netinet/in.h>
78 #include <netinet/in_systm.h>
79 #include <netinet/ip.h>
80 #include <netinet/ip_icmp.h> /* for ICMP_BANDLIM */
81 #include <netinet/in_var.h>
82 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
83 #include <netinet/in_pcb.h>
84 #include <netinet/ip_var.h>
86 #include <netinet/ip6.h>
87 #include <netinet/icmp6.h>
88 #include <netinet6/nd6.h>
89 #include <netinet6/ip6_var.h>
90 #include <netinet6/in6_pcb.h>
92 #include <netinet/tcp.h>
93 #include <netinet/tcp_fsm.h>
94 #include <netinet/tcp_seq.h>
95 #include <netinet/tcp_timer.h>
96 #include <netinet/tcp_var.h>
98 #include <netinet6/tcp6_var.h>
100 #include <netinet/tcpip.h>
102 #include <netinet/tcp_debug.h>
103 u_char tcp_saveipgen
[40]; /* the size must be of max ip header, now IPv6 */
104 struct tcphdr tcp_savetcp
;
105 #endif /* TCPDEBUG */
108 #include <netinet6/ipsec.h>
110 #include <netinet6/ipsec6.h>
112 #include <netkey/key.h>
115 #include <sys/kdebug.h>
118 MALLOC_DEFINE(M_TSEGQ
, "tseg_qent", "TCP segment queue entry");
121 #define DBG_LAYER_BEG NETDBG_CODE(DBG_NETTCP, 0)
122 #define DBG_LAYER_END NETDBG_CODE(DBG_NETTCP, 2)
123 #define DBG_FNC_TCP_INPUT NETDBG_CODE(DBG_NETTCP, (3 << 8))
124 #define DBG_FNC_TCP_NEWCONN NETDBG_CODE(DBG_NETTCP, (7 << 8))
126 static int tcprexmtthresh
= 3;
128 extern int apple_hwcksum_rx
;
131 extern int ipsec_bypass
;
132 extern lck_mtx_t
*sadb_mutex
;
135 struct tcpstat tcpstat
;
136 SYSCTL_STRUCT(_net_inet_tcp
, TCPCTL_STATS
, stats
, CTLFLAG_RD
,
137 &tcpstat
, tcpstat
, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
139 static int log_in_vain
= 0;
140 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, log_in_vain
, CTLFLAG_RW
,
141 &log_in_vain
, 0, "Log all incoming TCP connections");
143 static int blackhole
= 0;
144 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, blackhole
, CTLFLAG_RW
,
145 &blackhole
, 0, "Do not send RST when dropping refused connections");
147 int tcp_delack_enabled
= 1;
148 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, delayed_ack
, CTLFLAG_RW
,
149 &tcp_delack_enabled
, 0,
150 "Delay ACK to try and piggyback it onto a data packet");
152 int tcp_lq_overflow
= 1;
153 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, tcp_lq_overflow
, CTLFLAG_RW
,
155 "Listen Queue Overflow");
158 static int drop_synfin
= 1;
159 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, drop_synfin
, CTLFLAG_RW
,
160 &drop_synfin
, 0, "Drop TCP packets with SYN+FIN set");
163 SYSCTL_NODE(_net_inet_tcp
, OID_AUTO
, reass
, CTLFLAG_RW
, 0,
164 "TCP Segment Reassembly Queue");
166 __private_extern__
int tcp_reass_maxseg
= 0;
167 SYSCTL_INT(_net_inet_tcp_reass
, OID_AUTO
, maxsegments
, CTLFLAG_RW
,
168 &tcp_reass_maxseg
, 0,
169 "Global maximum number of TCP Segments in Reassembly Queue");
171 __private_extern__
int tcp_reass_qsize
= 0;
172 SYSCTL_INT(_net_inet_tcp_reass
, OID_AUTO
, cursegments
, CTLFLAG_RD
,
174 "Global number of TCP Segments currently in Reassembly Queue");
176 static int tcp_reass_overflows
= 0;
177 SYSCTL_INT(_net_inet_tcp_reass
, OID_AUTO
, overflows
, CTLFLAG_RD
,
178 &tcp_reass_overflows
, 0,
179 "Global number of TCP Segment Reassembly Queue Overflows");
182 __private_extern__
int slowlink_wsize
= 8192;
183 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, slowlink_wsize
, CTLFLAG_RW
,
184 &slowlink_wsize
, 0, "Maximum advertised window size for slowlink");
188 struct inpcbhead tcb
;
189 #define tcb6 tcb /* for KAME src sync over BSD*'s */
190 struct inpcbinfo tcbinfo
;
192 static void tcp_dooptions(struct tcpcb
*,
193 u_char
*, int, struct tcphdr
*, struct tcpopt
*);
194 static void tcp_pulloutofband(struct socket
*,
195 struct tcphdr
*, struct mbuf
*, int);
196 static int tcp_reass(struct tcpcb
*, struct tcphdr
*, int *,
198 static void tcp_xmit_timer(struct tcpcb
*, int);
199 static int tcp_newreno
__P((struct tcpcb
*, struct tcphdr
*));
201 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
203 #define ND6_HINT(tp) \
205 if ((tp) && (tp)->t_inpcb && \
206 ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0 && \
207 (tp)->t_inpcb->in6p_route.ro_rt) \
208 nd6_nud_hint((tp)->t_inpcb->in6p_route.ro_rt, NULL, 0); \
214 extern u_long
*delack_bitmask
;
216 extern void ipfwsyslog( int level
, char *format
,...);
217 extern int ChkAddressOK( __uint32_t dstaddr
, __uint32_t srcaddr
);
218 extern int fw_verbose
;
220 #define log_in_vain_log( a ) { \
221 if ( (log_in_vain == 3 ) && (fw_verbose == 2)) { /* Apple logging, log to ipfw.log */ \
228 * Indicate whether this ack should be delayed.
229 * We can delay the ack if:
230 * - delayed acks are enabled (set to 1) and
231 * - our last ack wasn't a 0-sized window. We never want to delay
232 * the ack that opens up a 0-sized window.
233 * - delayed acks are enabled (set to 2, "more compatible") and
234 * - our last ack wasn't a 0-sized window.
235 * - if the peer hasn't sent us a TH_PUSH data packet (this solves 3649245)
236 * - the peer hasn't sent us a TH_PUSH data packet, if he did, take this as a clue that we
237 * need to ACK with no delay. This helps higher level protocols who won't send
238 * us more data even if the window is open because their last "segment" hasn't been ACKed
242 #define DELAY_ACK(tp) \
243 (((tcp_delack_enabled == 1) && ((tp->t_flags & TF_RXWIN0SENT) == 0)) || \
244 (((tcp_delack_enabled == 2) && (tp->t_flags & TF_RXWIN0SENT) == 0) && \
245 ((thflags & TH_PUSH) == 0) && ((tp->t_flags & TF_DELACK) == 0)))
248 static int tcpdropdropablreq(struct socket
*head
);
252 tcp_reass(tp
, th
, tlenp
, m
)
253 register struct tcpcb
*tp
;
254 register struct tcphdr
*th
;
259 struct tseg_qent
*p
= NULL
;
260 struct tseg_qent
*nq
;
261 struct tseg_qent
*te
;
262 struct socket
*so
= tp
->t_inpcb
->inp_socket
;
267 * Call with th==0 after become established to
268 * force pre-ESTABLISHED data up to user socket.
274 * Limit the number of segments in the reassembly queue to prevent
275 * holding on to too many segments (and thus running out of mbufs).
276 * Make sure to let the missing segment through which caused this
277 * queue. Always keep one global queue entry spare to be able to
278 * process the missing segment.
280 if (th
->th_seq
!= tp
->rcv_nxt
&&
281 tcp_reass_qsize
+ 1 >= tcp_reass_maxseg
) {
282 tcp_reass_overflows
++;
283 tcpstat
.tcps_rcvmemdrop
++;
288 /* Allocate a new queue entry. If we can't, just drop the pkt. XXX */
289 MALLOC(te
, struct tseg_qent
*, sizeof (struct tseg_qent
), M_TSEGQ
,
292 tcpstat
.tcps_rcvmemdrop
++;
299 * Find a segment which begins after this one does.
301 LIST_FOREACH(q
, &tp
->t_segq
, tqe_q
) {
302 if (SEQ_GT(q
->tqe_th
->th_seq
, th
->th_seq
))
308 * If there is a preceding segment, it may provide some of
309 * our data already. If so, drop the data from the incoming
310 * segment. If it provides all of our data, drop us.
314 /* conversion to int (in i) handles seq wraparound */
315 i
= p
->tqe_th
->th_seq
+ p
->tqe_len
- th
->th_seq
;
318 tcpstat
.tcps_rcvduppack
++;
319 tcpstat
.tcps_rcvdupbyte
+= *tlenp
;
324 * Try to present any queued data
325 * at the left window edge to the user.
326 * This is needed after the 3-WHS
329 goto present
; /* ??? */
336 tcpstat
.tcps_rcvoopack
++;
337 tcpstat
.tcps_rcvoobyte
+= *tlenp
;
340 * While we overlap succeeding segments trim them or,
341 * if they are completely covered, dequeue them.
344 register int i
= (th
->th_seq
+ *tlenp
) - q
->tqe_th
->th_seq
;
347 if (i
< q
->tqe_len
) {
348 q
->tqe_th
->th_seq
+= i
;
354 nq
= LIST_NEXT(q
, tqe_q
);
355 LIST_REMOVE(q
, tqe_q
);
362 /* Insert the new segment queue entry into place. */
365 te
->tqe_len
= *tlenp
;
368 LIST_INSERT_HEAD(&tp
->t_segq
, te
, tqe_q
);
370 LIST_INSERT_AFTER(p
, te
, tqe_q
);
375 * Present data to user, advancing rcv_nxt through
376 * completed sequence space.
378 if (!TCPS_HAVEESTABLISHED(tp
->t_state
))
380 q
= LIST_FIRST(&tp
->t_segq
);
381 if (!q
|| q
->tqe_th
->th_seq
!= tp
->rcv_nxt
)
384 tp
->rcv_nxt
+= q
->tqe_len
;
385 flags
= q
->tqe_th
->th_flags
& TH_FIN
;
386 nq
= LIST_NEXT(q
, tqe_q
);
387 LIST_REMOVE(q
, tqe_q
);
388 if (so
->so_state
& SS_CANTRCVMORE
)
391 if (sbappend(&so
->so_rcv
, q
->tqe_m
))
397 } while (q
&& q
->tqe_th
->th_seq
== tp
->rcv_nxt
);
401 if ((tp
->t_inpcb
->inp_vflag
& INP_IPV6
) != 0) {
403 KERNEL_DEBUG(DBG_LAYER_BEG
,
404 ((tp
->t_inpcb
->inp_fport
<< 16) | tp
->t_inpcb
->inp_lport
),
405 (((tp
->t_inpcb
->in6p_laddr
.s6_addr16
[0] & 0xffff) << 16) |
406 (tp
->t_inpcb
->in6p_faddr
.s6_addr16
[0] & 0xffff)),
412 KERNEL_DEBUG(DBG_LAYER_BEG
,
413 ((tp
->t_inpcb
->inp_fport
<< 16) | tp
->t_inpcb
->inp_lport
),
414 (((tp
->t_inpcb
->inp_laddr
.s_addr
& 0xffff) << 16) |
415 (tp
->t_inpcb
->inp_faddr
.s_addr
& 0xffff)),
419 sorwakeup(so
); /* done with socket lock held */
426 * TCP input routine, follows pages 65-76 of the
427 * protocol specification dated September, 1981 very closely.
435 register struct mbuf
*m
= *mp
;
436 struct in6_ifaddr
*ia6
;
438 IP6_EXTHDR_CHECK(m
, *offp
, sizeof(struct tcphdr
), return IPPROTO_DONE
);
441 * draft-itojun-ipv6-tcp-to-anycast
442 * better place to put this in?
444 ia6
= ip6_getdstifaddr(m
);
445 if (ia6
&& (ia6
->ia6_flags
& IN6_IFF_ANYCAST
)) {
448 ip6
= mtod(m
, struct ip6_hdr
*);
449 icmp6_error(m
, ICMP6_DST_UNREACH
, ICMP6_DST_UNREACH_ADDR
,
450 (caddr_t
)&ip6
->ip6_dst
- (caddr_t
)ip6
);
464 register struct tcphdr
*th
;
465 register struct ip
*ip
= NULL
;
466 register struct ipovly
*ipov
;
467 register struct inpcb
*inp
;
472 register struct tcpcb
*tp
= 0;
473 register int thflags
;
474 struct socket
*so
= 0;
475 int todrop
, acked
, ourfinisacked
, needoutput
= 0;
476 struct in_addr laddr
;
478 struct in6_addr laddr6
;
484 struct tcpopt to
; /* options in this segment */
485 struct rmxp_tao
*taop
; /* pointer to our TAO cache entry */
486 struct rmxp_tao tao_noncached
; /* in case there's no cached entry */
487 struct sockaddr_in
*next_hop
= NULL
;
491 struct m_tag
*fwd_tag
;
493 /* Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain. */
494 fwd_tag
= m_tag_locate(m
, KERNEL_MODULE_TAG_ID
, KERNEL_TAG_TYPE_IPFORWARD
, NULL
);
495 if (fwd_tag
!= NULL
) {
496 struct ip_fwd_tag
*ipfwd_tag
= (struct ip_fwd_tag
*)(fwd_tag
+1);
498 next_hop
= ipfwd_tag
->next_hop
;
499 m_tag_delete(m
, fwd_tag
);
503 struct ip6_hdr
*ip6
= NULL
;
506 int rstreason
; /* For badport_bandlim accounting purposes */
507 struct proc
*proc0
=current_proc();
509 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_START
,0,0,0,0,0);
512 isipv6
= (mtod(m
, struct ip
*)->ip_v
== 6) ? 1 : 0;
514 bzero((char *)&to
, sizeof(to
));
516 tcpstat
.tcps_rcvtotal
++;
522 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
523 ip6
= mtod(m
, struct ip6_hdr
*);
524 tlen
= sizeof(*ip6
) + ntohs(ip6
->ip6_plen
) - off0
;
525 if (in6_cksum(m
, IPPROTO_TCP
, off0
, tlen
)) {
526 tcpstat
.tcps_rcvbadsum
++;
529 th
= (struct tcphdr
*)((caddr_t
)ip6
+ off0
);
531 KERNEL_DEBUG(DBG_LAYER_BEG
, ((th
->th_dport
<< 16) | th
->th_sport
),
532 (((ip6
->ip6_src
.s6_addr16
[0]) << 16) | (ip6
->ip6_dst
.s6_addr16
[0])),
533 th
->th_seq
, th
->th_ack
, th
->th_win
);
535 * Be proactive about unspecified IPv6 address in source.
536 * As we use all-zero to indicate unbounded/unconnected pcb,
537 * unspecified IPv6 address can be used to confuse us.
539 * Note that packets with unspecified IPv6 destination is
540 * already dropped in ip6_input.
542 if (IN6_IS_ADDR_UNSPECIFIED(&ip6
->ip6_src
)) {
550 * Get IP and TCP header together in first mbuf.
551 * Note: IP leaves IP header in first mbuf.
553 if (off0
> sizeof (struct ip
)) {
554 ip_stripoptions(m
, (struct mbuf
*)0);
555 off0
= sizeof(struct ip
);
556 if (m
->m_pkthdr
.csum_flags
& CSUM_TCP_SUM16
)
557 m
->m_pkthdr
.csum_flags
= 0; /* invalidate hwcksuming */
560 if (m
->m_len
< sizeof (struct tcpiphdr
)) {
561 if ((m
= m_pullup(m
, sizeof (struct tcpiphdr
))) == 0) {
562 tcpstat
.tcps_rcvshort
++;
566 ip
= mtod(m
, struct ip
*);
567 ipov
= (struct ipovly
*)ip
;
568 th
= (struct tcphdr
*)((caddr_t
)ip
+ off0
);
571 KERNEL_DEBUG(DBG_LAYER_BEG
, ((th
->th_dport
<< 16) | th
->th_sport
),
572 (((ip
->ip_src
.s_addr
& 0xffff) << 16) | (ip
->ip_dst
.s_addr
& 0xffff)),
573 th
->th_seq
, th
->th_ack
, th
->th_win
);
575 if (m
->m_pkthdr
.csum_flags
& CSUM_DATA_VALID
) {
576 if (apple_hwcksum_rx
&& (m
->m_pkthdr
.csum_flags
& CSUM_TCP_SUM16
)) {
579 *(uint32_t*)&b
[0] = *(uint32_t*)&ipov
->ih_x1
[0];
580 *(uint32_t*)&b
[4] = *(uint32_t*)&ipov
->ih_x1
[4];
581 *(uint8_t*)&b
[8] = *(uint8_t*)&ipov
->ih_x1
[8];
583 bzero(ipov
->ih_x1
, sizeof(ipov
->ih_x1
));
584 ipov
->ih_len
= (u_short
)tlen
;
586 pseudo
= in_cksum(m
, sizeof (struct ip
));
588 *(uint32_t*)&ipov
->ih_x1
[0] = *(uint32_t*)&b
[0];
589 *(uint32_t*)&ipov
->ih_x1
[4] = *(uint32_t*)&b
[4];
590 *(uint8_t*)&ipov
->ih_x1
[8] = *(uint8_t*)&b
[8];
592 th
->th_sum
= in_addword(pseudo
, (m
->m_pkthdr
.csum_data
& 0xFFFF));
594 if (m
->m_pkthdr
.csum_flags
& CSUM_PSEUDO_HDR
)
595 th
->th_sum
= m
->m_pkthdr
.csum_data
;
597 th
->th_sum
= in_pseudo(ip
->ip_src
.s_addr
,
598 ip
->ip_dst
.s_addr
, htonl(m
->m_pkthdr
.csum_data
+
599 ip
->ip_len
+ IPPROTO_TCP
));
601 th
->th_sum
^= 0xffff;
605 * Checksum extended TCP header and data.
607 *(uint32_t*)&b
[0] = *(uint32_t*)&ipov
->ih_x1
[0];
608 *(uint32_t*)&b
[4] = *(uint32_t*)&ipov
->ih_x1
[4];
609 *(uint8_t*)&b
[8] = *(uint8_t*)&ipov
->ih_x1
[8];
611 len
= sizeof (struct ip
) + tlen
;
612 bzero(ipov
->ih_x1
, sizeof(ipov
->ih_x1
));
613 ipov
->ih_len
= (u_short
)tlen
;
615 th
->th_sum
= in_cksum(m
, len
);
617 *(uint32_t*)&ipov
->ih_x1
[0] = *(uint32_t*)&b
[0];
618 *(uint32_t*)&ipov
->ih_x1
[4] = *(uint32_t*)&b
[4];
619 *(uint8_t*)&ipov
->ih_x1
[8] = *(uint8_t*)&b
[8];
622 tcpstat
.tcps_rcvbadsum
++;
626 /* Re-initialization for later version check */
627 ip
->ip_v
= IPVERSION
;
632 * Check that TCP offset makes sense,
633 * pull out TCP options and adjust length. XXX
635 off
= th
->th_off
<< 2;
636 if (off
< sizeof (struct tcphdr
) || off
> tlen
) {
637 tcpstat
.tcps_rcvbadoff
++;
640 tlen
-= off
; /* tlen is used instead of ti->ti_len */
641 if (off
> sizeof (struct tcphdr
)) {
644 IP6_EXTHDR_CHECK(m
, off0
, off
, return);
645 ip6
= mtod(m
, struct ip6_hdr
*);
646 th
= (struct tcphdr
*)((caddr_t
)ip6
+ off0
);
650 if (m
->m_len
< sizeof(struct ip
) + off
) {
651 if ((m
= m_pullup(m
, sizeof (struct ip
) + off
)) == 0) {
652 tcpstat
.tcps_rcvshort
++;
655 ip
= mtod(m
, struct ip
*);
656 ipov
= (struct ipovly
*)ip
;
657 th
= (struct tcphdr
*)((caddr_t
)ip
+ off0
);
660 optlen
= off
- sizeof (struct tcphdr
);
661 optp
= (u_char
*)(th
+ 1);
663 * Do quick retrieval of timestamp options ("options
664 * prediction?"). If timestamp is the only option and it's
665 * formatted as recommended in RFC 1323 appendix A, we
666 * quickly get the values now and not bother calling
667 * tcp_dooptions(), etc.
669 if ((optlen
== TCPOLEN_TSTAMP_APPA
||
670 (optlen
> TCPOLEN_TSTAMP_APPA
&&
671 optp
[TCPOLEN_TSTAMP_APPA
] == TCPOPT_EOL
)) &&
672 *(u_int32_t
*)optp
== htonl(TCPOPT_TSTAMP_HDR
) &&
673 (th
->th_flags
& TH_SYN
) == 0) {
674 to
.to_flag
|= TOF_TS
;
675 to
.to_tsval
= ntohl(*(u_int32_t
*)(optp
+ 4));
676 to
.to_tsecr
= ntohl(*(u_int32_t
*)(optp
+ 8));
677 optp
= NULL
; /* we've parsed the options */
680 thflags
= th
->th_flags
;
684 * If the drop_synfin option is enabled, drop all packets with
685 * both the SYN and FIN bits set. This prevents e.g. nmap from
686 * identifying the TCP/IP stack.
688 * This is incompatible with RFC1644 extensions (T/TCP).
690 if (drop_synfin
&& (thflags
& (TH_SYN
|TH_FIN
)) == (TH_SYN
|TH_FIN
))
695 * Convert TCP protocol specific fields to host format.
703 * Delay droping TCP, IP headers, IPv6 ext headers, and TCP options,
704 * until after ip6_savecontrol() is called and before other functions
705 * which don't want those proto headers.
706 * Because ip6_savecontrol() is going to parse the mbuf to
707 * search for data to be passed up to user-land, it wants mbuf
708 * parameters to be unchanged.
710 drop_hdrlen
= off0
+ off
;
713 * Locate pcb for segment.
716 #if IPFIREWALL_FORWARD
719 && isipv6
== NULL
/* IPv6 support is not yet */
723 * Diverted. Pretend to be the destination.
724 * already got one like this?
726 inp
= in_pcblookup_hash(&tcbinfo
, ip
->ip_src
, th
->th_sport
,
727 ip
->ip_dst
, th
->th_dport
, 0, m
->m_pkthdr
.rcvif
);
730 * No, then it's new. Try find the ambushing socket
732 if (!next_hop
->sin_port
) {
733 inp
= in_pcblookup_hash(&tcbinfo
, ip
->ip_src
,
734 th
->th_sport
, next_hop
->sin_addr
,
735 th
->th_dport
, 1, m
->m_pkthdr
.rcvif
);
737 inp
= in_pcblookup_hash(&tcbinfo
,
738 ip
->ip_src
, th
->th_sport
,
740 ntohs(next_hop
->sin_port
), 1,
745 #endif /* IPFIREWALL_FORWARD */
749 inp
= in6_pcblookup_hash(&tcbinfo
, &ip6
->ip6_src
, th
->th_sport
,
750 &ip6
->ip6_dst
, th
->th_dport
, 1,
754 inp
= in_pcblookup_hash(&tcbinfo
, ip
->ip_src
, th
->th_sport
,
755 ip
->ip_dst
, th
->th_dport
, 1, m
->m_pkthdr
.rcvif
);
759 if (ipsec_bypass
== 0) {
760 lck_mtx_lock(sadb_mutex
);
763 if (inp
!= NULL
&& ipsec6_in_reject_so(m
, inp
->inp_socket
)) {
764 ipsec6stat
.in_polvio
++;
765 lck_mtx_unlock(sadb_mutex
);
770 if (inp
!= NULL
&& ipsec4_in_reject_so(m
, inp
->inp_socket
)) {
771 ipsecstat
.in_polvio
++;
772 lck_mtx_unlock(sadb_mutex
);
775 lck_mtx_unlock(sadb_mutex
);
780 * If the state is CLOSED (i.e., TCB does not exist) then
781 * all data in the incoming segment is discarded.
782 * If the TCB exists but is in CLOSED state, it is embryonic,
783 * but should either do a listen or a connect soon.
788 char dbuf
[MAX_IPv6_STR_LEN
], sbuf
[MAX_IPv6_STR_LEN
];
790 char dbuf
[MAX_IPv4_STR_LEN
], sbuf
[MAX_IPv4_STR_LEN
];
795 inet_ntop(AF_INET6
, &ip6
->ip6_dst
, dbuf
, sizeof(dbuf
));
796 inet_ntop(AF_INET6
, &ip6
->ip6_src
, sbuf
, sizeof(sbuf
));
800 inet_ntop(AF_INET
, &ip
->ip_dst
, dbuf
, sizeof(dbuf
));
801 inet_ntop(AF_INET
, &ip
->ip_src
, sbuf
, sizeof(sbuf
));
803 switch (log_in_vain
) {
807 "Connection attempt to TCP %s:%d from %s:%d\n",
808 dbuf
, ntohs(th
->th_dport
),
810 ntohs(th
->th_sport
));
814 "Connection attempt to TCP %s:%d from %s:%d flags:0x%x\n",
815 dbuf
, ntohs(th
->th_dport
), sbuf
,
816 ntohs(th
->th_sport
), thflags
);
819 if ((thflags
& TH_SYN
) &&
820 !(m
->m_flags
& (M_BCAST
| M_MCAST
)) &&
822 ((isipv6
&& !IN6_ARE_ADDR_EQUAL(&ip6
->ip6_dst
, &ip6
->ip6_src
)) ||
823 (!isipv6
&& ip
->ip_dst
.s_addr
!= ip
->ip_src
.s_addr
))
825 ip
->ip_dst
.s_addr
!= ip
->ip_src
.s_addr
828 log_in_vain_log((LOG_INFO
,
829 "Stealth Mode connection attempt to TCP %s:%d from %s:%d\n",
830 dbuf
, ntohs(th
->th_dport
),
832 ntohs(th
->th_sport
)));
839 if (m
->m_pkthdr
.rcvif
&& m
->m_pkthdr
.rcvif
->if_type
!= IFT_LOOP
)
842 if (thflags
& TH_SYN
)
851 rstreason
= BANDLIM_RST_CLOSEDPORT
;
852 goto dropwithresetnosock
;
854 so
= inp
->inp_socket
;
856 if (in_pcb_checkstate(inp
, WNT_RELEASE
, 1) == WNT_STOPUSING
)
857 inp
= NULL
; // pretend we didn't find it
859 printf("tcp_input: no more socket for inp=%x\n", inp
);
864 if (in_pcb_checkstate(inp
, WNT_RELEASE
, 1) == WNT_STOPUSING
) {
865 tcp_unlock(so
, 1, 2);
866 inp
= NULL
; // pretend we didn't find it
872 rstreason
= BANDLIM_RST_CLOSEDPORT
;
875 if (tp
->t_state
== TCPS_CLOSED
)
880 * Bogus state when listening port owned by SharedIP with loopback as the
881 * only configured interface: BlueBox does not filters loopback
883 if (tp
->t_state
== TCP_NSTATES
)
887 /* Unscale the window into a 32-bit value. */
888 if ((thflags
& TH_SYN
) == 0)
889 tiwin
= th
->th_win
<< tp
->snd_scale
;
893 if (so
->so_options
& (SO_DEBUG
|SO_ACCEPTCONN
)) {
895 if (so
->so_options
& SO_DEBUG
) {
896 ostate
= tp
->t_state
;
899 bcopy((char *)ip6
, (char *)tcp_saveipgen
,
903 bcopy((char *)ip
, (char *)tcp_saveipgen
, sizeof(*ip
));
907 if (so
->so_options
& SO_ACCEPTCONN
) {
908 register struct tcpcb
*tp0
= tp
;
911 struct sockaddr_storage from
;
913 struct inpcb
*oinp
= sotoinpcb(so
);
915 int ogencnt
= so
->so_gencnt
;
919 * Current IPsec implementation makes incorrect IPsec
920 * cache if this check is done here.
921 * So delay this until duplicated socket is created.
923 if ((thflags
& (TH_RST
|TH_ACK
|TH_SYN
)) != TH_SYN
) {
925 * Note: dropwithreset makes sure we don't
926 * send a RST in response to a RST.
928 if (thflags
& TH_ACK
) {
929 tcpstat
.tcps_badsyn
++;
930 rstreason
= BANDLIM_RST_OPENPORT
;
936 KERNEL_DEBUG(DBG_FNC_TCP_NEWCONN
| DBG_FUNC_START
,0,0,0,0,0);
940 * If deprecated address is forbidden,
941 * we do not accept SYN to deprecated interface
942 * address to prevent any new inbound connection from
943 * getting established.
944 * When we do not accept SYN, we send a TCP RST,
945 * with deprecated source address (instead of dropping
946 * it). We compromise it as it is much better for peer
947 * to send a RST, and RST will be the final packet
950 * If we do not forbid deprecated addresses, we accept
951 * the SYN packet. RFC2462 does not suggest dropping
953 * If we decipher RFC2462 5.5.4, it says like this:
954 * 1. use of deprecated addr with existing
955 * communication is okay - "SHOULD continue to be
957 * 2. use of it with new communication:
958 * (2a) "SHOULD NOT be used if alternate address
959 * with sufficient scope is available"
960 * (2b) nothing mentioned otherwise.
961 * Here we fall into (2b) case as we have no choice in
962 * our source address selection - we must obey the peer.
964 * The wording in RFC2462 is confusing, and there are
965 * multiple description text for deprecated address
966 * handling - worse, they are not exactly the same.
967 * I believe 5.5.4 is the best one, so we follow 5.5.4.
969 if (isipv6
&& !ip6_use_deprecated
) {
970 struct in6_ifaddr
*ia6
;
972 if ((ia6
= ip6_getdstifaddr(m
)) &&
973 (ia6
->ia6_flags
& IN6_IFF_DEPRECATED
)) {
975 rstreason
= BANDLIM_RST_OPENPORT
;
982 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*)&from
;
984 sin6
->sin6_len
= sizeof(*sin6
);
985 sin6
->sin6_family
= AF_INET6
;
986 sin6
->sin6_port
= th
->th_sport
;
987 sin6
->sin6_flowinfo
= 0;
988 sin6
->sin6_addr
= ip6
->ip6_src
;
989 sin6
->sin6_scope_id
= 0;
991 struct sockaddr_in
*sin
= (struct sockaddr_in
*)&from
;
993 sin
->sin_len
= sizeof(*sin
);
994 sin
->sin_family
= AF_INET
;
995 sin
->sin_port
= th
->th_sport
;
996 sin
->sin_addr
= ip
->ip_src
;
998 so2
= sonewconn(so
, 0, (struct sockaddr
*)&from
);
1000 so2
= sonewconn(so
, 0, NULL
);
1003 tcpstat
.tcps_listendrop
++;
1004 if (tcpdropdropablreq(so
)) {
1006 so2
= sonewconn(so
, 0, (struct sockaddr
*)&from
);
1008 so2
= sonewconn(so
, 0, NULL
);
1014 * Make sure listening socket did not get closed during socket allocation,
1015 * not only this is incorrect but it is know to cause panic
1017 if (so
->so_gencnt
!= ogencnt
)
1021 tcp_unlock(so
, 0, 0); /* Unlock but keep a reference on listener for now */
1026 * This is ugly, but ....
1028 * Mark socket as temporary until we're
1029 * committed to keeping it. The code at
1030 * ``drop'' and ``dropwithreset'' check the
1031 * flag dropsocket to see if the temporary
1032 * socket created here should be discarded.
1033 * We mark the socket as discardable until
1034 * we're committed to it below in TCPS_LISTEN.
1037 inp
= (struct inpcb
*)so
->so_pcb
;
1040 inp
->in6p_laddr
= ip6
->ip6_dst
;
1042 inp
->inp_vflag
&= ~INP_IPV6
;
1043 inp
->inp_vflag
|= INP_IPV4
;
1045 inp
->inp_laddr
= ip
->ip_dst
;
1049 inp
->inp_lport
= th
->th_dport
;
1050 if (in_pcbinshash(inp
, 0) != 0) {
1052 * Undo the assignments above if we failed to
1053 * put the PCB on the hash lists.
1057 inp
->in6p_laddr
= in6addr_any
;
1060 inp
->inp_laddr
.s_addr
= INADDR_ANY
;
1062 tcp_lock(oso
, 0, 0); /* release ref on parent */
1063 tcp_unlock(oso
, 1, 0);
1068 * To avoid creating incorrectly cached IPsec
1069 * association, this is need to be done here.
1071 * Subject: (KAME-snap 748)
1072 * From: Wayne Knowles <w.knowles@niwa.cri.nz>
1073 * ftp://ftp.kame.net/pub/mail-list/snap-users/748
1075 if ((thflags
& (TH_RST
|TH_ACK
|TH_SYN
)) != TH_SYN
) {
1077 * Note: dropwithreset makes sure we don't
1078 * send a RST in response to a RST.
1080 tcp_lock(oso
, 0, 0); /* release ref on parent */
1081 tcp_unlock(oso
, 1, 0);
1082 if (thflags
& TH_ACK
) {
1083 tcpstat
.tcps_badsyn
++;
1084 rstreason
= BANDLIM_RST_OPENPORT
;
1093 * Inherit socket options from the listening
1095 * Note that in6p_inputopts are not (even
1096 * should not be) copied, since it stores
1097 * previously received options and is used to
1098 * detect if each new option is different than
1099 * the previous one and hence should be passed
1101 * If we copied in6p_inputopts, a user would
1102 * not be able to receive options just after
1103 * calling the accept system call.
1106 oinp
->inp_flags
& INP_CONTROLOPTS
;
1107 if (oinp
->in6p_outputopts
)
1108 inp
->in6p_outputopts
=
1109 ip6_copypktopts(oinp
->in6p_outputopts
,
1113 inp
->inp_options
= ip_srcroute();
1114 tcp_lock(oso
, 0, 0);
1116 /* copy old policy into new socket's */
1117 if (sotoinpcb(oso
)->inp_sp
)
1120 lck_mtx_lock(sadb_mutex
);
1121 /* Is it a security hole here to silently fail to copy the policy? */
1122 if (inp
->inp_sp
!= NULL
)
1123 error
= ipsec_init_policy(so
, &inp
->inp_sp
);
1124 if (error
!= 0 || ipsec_copy_policy(sotoinpcb(oso
)->inp_sp
, inp
->inp_sp
))
1125 printf("tcp_input: could not copy policy\n");
1126 lck_mtx_unlock(sadb_mutex
);
1129 tcp_unlock(oso
, 1, 0); /* now drop the reference on the listener */
1130 tp
= intotcpcb(inp
);
1131 tp
->t_state
= TCPS_LISTEN
;
1132 tp
->t_flags
|= tp0
->t_flags
& (TF_NOPUSH
|TF_NOOPT
|TF_NODELAY
);
1133 tp
->t_inpcb
->inp_ip_ttl
= tp0
->t_inpcb
->inp_ip_ttl
;
1134 /* Compute proper scaling value from buffer space */
1135 while (tp
->request_r_scale
< TCP_MAX_WINSHIFT
&&
1136 TCP_MAXWIN
<< tp
->request_r_scale
<
1137 so
->so_rcv
.sb_hiwat
)
1138 tp
->request_r_scale
++;
1140 KERNEL_DEBUG(DBG_FNC_TCP_NEWCONN
| DBG_FUNC_END
,0,0,0,0,0);
1145 lck_mtx_assert(((struct inpcb
*)so
->so_pcb
)->inpcb_mtx
, LCK_MTX_ASSERT_OWNED
);
1149 * This is the second part of the MSS DoS prevention code (after
1150 * minmss on the sending side) and it deals with too many too small
1151 * tcp packets in a too short timeframe (1 second).
1153 * For every full second we count the number of received packets
1154 * and bytes. If we get a lot of packets per second for this connection
1155 * (tcp_minmssoverload) we take a closer look at it and compute the
1156 * average packet size for the past second. If that is less than
1157 * tcp_minmss we get too many packets with very small payload which
1158 * is not good and burdens our system (and every packet generates
1159 * a wakeup to the process connected to our socket). We can reasonable
1160 * expect this to be small packet DoS attack to exhaust our CPU
1163 * Care has to be taken for the minimum packet overload value. This
1164 * value defines the minimum number of packets per second before we
1165 * start to worry. This must not be too low to avoid killing for
1166 * example interactive connections with many small packets like
1169 * Setting either tcp_minmssoverload or tcp_minmss to "0" disables
1172 * Account for packet if payload packet, skip over ACK, etc.
1174 if (tcp_minmss
&& tcp_minmssoverload
&&
1175 tp
->t_state
== TCPS_ESTABLISHED
&& tlen
> 0) {
1176 if (tp
->rcv_reset
> tcp_now
) {
1178 tp
->rcv_byps
+= tlen
+ off
;
1179 if (tp
->rcv_pps
> tcp_minmssoverload
) {
1180 if ((tp
->rcv_byps
/ tp
->rcv_pps
) < tcp_minmss
) {
1181 char ipstrbuf
[MAX_IPv6_STR_LEN
];
1182 printf("too many small tcp packets from "
1183 "%s:%u, av. %lubyte/packet, "
1184 "dropping connection\n",
1187 inet_ntop(AF_INET6
, &inp
->in6p_faddr
, ipstrbuf
,
1190 inet_ntop(AF_INET
, &inp
->inp_faddr
, ipstrbuf
,
1193 tp
->rcv_byps
/ tp
->rcv_pps
);
1194 tp
= tcp_drop(tp
, ECONNRESET
);
1195 /* tcpstat.tcps_minmssdrops++; */
1200 tp
->rcv_reset
= tcp_now
+ PR_SLOWHZ
;
1202 tp
->rcv_byps
= tlen
+ off
;
1207 * Segment received on connection.
1208 * Reset idle time and keep-alive timer.
1211 if (TCPS_HAVEESTABLISHED(tp
->t_state
))
1212 tp
->t_timer
[TCPT_KEEP
] = TCP_KEEPIDLE(tp
);
1215 * Process options if not in LISTEN state,
1216 * else do it below (after getting remote address).
1218 if (tp
->t_state
!= TCPS_LISTEN
&& optp
)
1219 tcp_dooptions(tp
, optp
, optlen
, th
, &to
);
1222 * Header prediction: check for the two common cases
1223 * of a uni-directional data xfer. If the packet has
1224 * no control flags, is in-sequence, the window didn't
1225 * change and we're not retransmitting, it's a
1226 * candidate. If the length is zero and the ack moved
1227 * forward, we're the sender side of the xfer. Just
1228 * free the data acked & wake any higher level process
1229 * that was blocked waiting for space. If the length
1230 * is non-zero and the ack didn't move, we're the
1231 * receiver side. If we're getting packets in-order
1232 * (the reassembly queue is empty), add the data to
1233 * the socket buffer and note that we need a delayed ack.
1234 * Make sure that the hidden state-flags are also off.
1235 * Since we check for TCPS_ESTABLISHED above, it can only
1238 if (tp
->t_state
== TCPS_ESTABLISHED
&&
1239 (thflags
& (TH_SYN
|TH_FIN
|TH_RST
|TH_URG
|TH_ACK
)) == TH_ACK
&&
1240 ((tp
->t_flags
& (TF_NEEDSYN
|TF_NEEDFIN
)) == 0) &&
1241 ((to
.to_flag
& TOF_TS
) == 0 ||
1242 TSTMP_GEQ(to
.to_tsval
, tp
->ts_recent
)) &&
1244 * Using the CC option is compulsory if once started:
1245 * the segment is OK if no T/TCP was negotiated or
1246 * if the segment has a CC option equal to CCrecv
1248 ((tp
->t_flags
& (TF_REQ_CC
|TF_RCVD_CC
)) != (TF_REQ_CC
|TF_RCVD_CC
) ||
1249 ((to
.to_flag
& TOF_CC
) != 0 && to
.to_cc
== tp
->cc_recv
)) &&
1250 th
->th_seq
== tp
->rcv_nxt
&&
1251 tiwin
&& tiwin
== tp
->snd_wnd
&&
1252 tp
->snd_nxt
== tp
->snd_max
) {
1255 * If last ACK falls within this segment's sequence numbers,
1256 * record the timestamp.
1257 * NOTE that the test is modified according to the latest
1258 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1260 if ((to
.to_flag
& TOF_TS
) != 0 &&
1261 SEQ_LEQ(th
->th_seq
, tp
->last_ack_sent
)) {
1262 tp
->ts_recent_age
= tcp_now
;
1263 tp
->ts_recent
= to
.to_tsval
;
1267 if (SEQ_GT(th
->th_ack
, tp
->snd_una
) &&
1268 SEQ_LEQ(th
->th_ack
, tp
->snd_max
) &&
1269 tp
->snd_cwnd
>= tp
->snd_wnd
&&
1270 tp
->t_dupacks
< tcprexmtthresh
) {
1272 * this is a pure ack for outstanding data.
1274 ++tcpstat
.tcps_predack
;
1276 * "bad retransmit" recovery
1278 if (tp
->t_rxtshift
== 1 &&
1279 tcp_now
< tp
->t_badrxtwin
) {
1280 tp
->snd_cwnd
= tp
->snd_cwnd_prev
;
1282 tp
->snd_ssthresh_prev
;
1283 tp
->snd_nxt
= tp
->snd_max
;
1284 tp
->t_badrxtwin
= 0;
1286 if (((to
.to_flag
& TOF_TS
) != 0) && (to
.to_tsecr
!= 0)) /* Makes sure we already have a TS */
1288 tcp_now
- to
.to_tsecr
+ 1);
1289 else if (tp
->t_rtttime
&&
1290 SEQ_GT(th
->th_ack
, tp
->t_rtseq
))
1291 tcp_xmit_timer(tp
, tp
->t_rtttime
);
1292 acked
= th
->th_ack
- tp
->snd_una
;
1293 tcpstat
.tcps_rcvackpack
++;
1294 tcpstat
.tcps_rcvackbyte
+= acked
;
1295 sbdrop(&so
->so_snd
, acked
);
1296 tp
->snd_una
= th
->th_ack
;
1298 ND6_HINT(tp
); /* some progress has been done */
1301 * If all outstanding data are acked, stop
1302 * retransmit timer, otherwise restart timer
1303 * using current (possibly backed-off) value.
1304 * If process is waiting for space,
1305 * wakeup/selwakeup/signal. If data
1306 * are ready to send, let tcp_output
1307 * decide between more output or persist.
1309 if (tp
->snd_una
== tp
->snd_max
)
1310 tp
->t_timer
[TCPT_REXMT
] = 0;
1311 else if (tp
->t_timer
[TCPT_PERSIST
] == 0)
1312 tp
->t_timer
[TCPT_REXMT
] = tp
->t_rxtcur
;
1314 sowwakeup(so
); /* has to be done with socket lock held */
1315 if ((so
->so_snd
.sb_cc
) || (tp
->t_flags
& TF_ACKNOW
))
1316 (void) tcp_output(tp
);
1317 tcp_unlock(so
, 1, 0);
1318 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
1321 } else if (th
->th_ack
== tp
->snd_una
&&
1322 LIST_EMPTY(&tp
->t_segq
) &&
1323 tlen
<= sbspace(&so
->so_rcv
)) {
1325 * this is a pure, in-sequence data packet
1326 * with nothing on the reassembly queue and
1327 * we have enough buffer space to take it.
1329 ++tcpstat
.tcps_preddat
;
1330 tp
->rcv_nxt
+= tlen
;
1331 tcpstat
.tcps_rcvpack
++;
1332 tcpstat
.tcps_rcvbyte
+= tlen
;
1333 ND6_HINT(tp
); /* some progress has been done */
1335 * Add data to socket buffer.
1337 m_adj(m
, drop_hdrlen
); /* delayed header drop */
1338 if (sbappend(&so
->so_rcv
, m
))
1342 KERNEL_DEBUG(DBG_LAYER_END
, ((th
->th_dport
<< 16) | th
->th_sport
),
1343 (((ip6
->ip6_src
.s6_addr16
[0]) << 16) | (ip6
->ip6_dst
.s6_addr16
[0])),
1344 th
->th_seq
, th
->th_ack
, th
->th_win
);
1349 KERNEL_DEBUG(DBG_LAYER_END
, ((th
->th_dport
<< 16) | th
->th_sport
),
1350 (((ip
->ip_src
.s_addr
& 0xffff) << 16) | (ip
->ip_dst
.s_addr
& 0xffff)),
1351 th
->th_seq
, th
->th_ack
, th
->th_win
);
1353 if (DELAY_ACK(tp
)) {
1354 tp
->t_flags
|= TF_DELACK
;
1356 tp
->t_flags
|= TF_ACKNOW
;
1359 tcp_unlock(so
, 1, 0);
1360 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
1366 * Calculate amount of space in receive window,
1367 * and then do TCP input processing.
1368 * Receive window is amount of space in rcv queue,
1369 * but not less than advertised window.
1372 lck_mtx_assert(((struct inpcb
*)so
->so_pcb
)->inpcb_mtx
, LCK_MTX_ASSERT_OWNED
);
1376 win
= sbspace(&so
->so_rcv
);
1379 else { /* clip rcv window to 4K for modems */
1380 if (tp
->t_flags
& TF_SLOWLINK
&& slowlink_wsize
> 0)
1381 win
= min(win
, slowlink_wsize
);
1383 tp
->rcv_wnd
= imax(win
, (int)(tp
->rcv_adv
- tp
->rcv_nxt
));
1386 switch (tp
->t_state
) {
1389 * If the state is LISTEN then ignore segment if it contains an RST.
1390 * If the segment contains an ACK then it is bad and send a RST.
1391 * If it does not contain a SYN then it is not interesting; drop it.
1392 * If it is from this socket, drop it, it must be forged.
1393 * Don't bother responding if the destination was a broadcast.
1394 * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial
1395 * tp->iss, and send a segment:
1396 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
1397 * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
1398 * Fill in remote peer address fields if not previously specified.
1399 * Enter SYN_RECEIVED state, and process any other fields of this
1400 * segment in this state.
1403 register struct sockaddr_in
*sin
;
1405 register struct sockaddr_in6
*sin6
;
1409 lck_mtx_assert(((struct inpcb
*)so
->so_pcb
)->inpcb_mtx
, LCK_MTX_ASSERT_OWNED
);
1411 if (thflags
& TH_RST
)
1413 if (thflags
& TH_ACK
) {
1414 rstreason
= BANDLIM_RST_OPENPORT
;
1417 if ((thflags
& TH_SYN
) == 0)
1419 if (th
->th_dport
== th
->th_sport
) {
1422 if (IN6_ARE_ADDR_EQUAL(&ip6
->ip6_dst
,
1427 if (ip
->ip_dst
.s_addr
== ip
->ip_src
.s_addr
)
1431 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
1432 * in_broadcast() should never return true on a received
1433 * packet with M_BCAST not set.
1435 * Packets with a multicast source address should also
1438 if (m
->m_flags
& (M_BCAST
|M_MCAST
))
1442 if (IN6_IS_ADDR_MULTICAST(&ip6
->ip6_dst
) ||
1443 IN6_IS_ADDR_MULTICAST(&ip6
->ip6_src
))
1447 if (IN_MULTICAST(ntohl(ip
->ip_dst
.s_addr
)) ||
1448 IN_MULTICAST(ntohl(ip
->ip_src
.s_addr
)) ||
1449 ip
->ip_src
.s_addr
== htonl(INADDR_BROADCAST
) ||
1450 in_broadcast(ip
->ip_dst
, m
->m_pkthdr
.rcvif
))
1454 MALLOC(sin6
, struct sockaddr_in6
*, sizeof *sin6
,
1455 M_SONAME
, M_NOWAIT
);
1458 bzero(sin6
, sizeof(*sin6
));
1459 sin6
->sin6_family
= AF_INET6
;
1460 sin6
->sin6_len
= sizeof(*sin6
);
1461 sin6
->sin6_addr
= ip6
->ip6_src
;
1462 sin6
->sin6_port
= th
->th_sport
;
1463 laddr6
= inp
->in6p_laddr
;
1464 if (IN6_IS_ADDR_UNSPECIFIED(&inp
->in6p_laddr
))
1465 inp
->in6p_laddr
= ip6
->ip6_dst
;
1466 if (in6_pcbconnect(inp
, (struct sockaddr
*)sin6
,
1468 inp
->in6p_laddr
= laddr6
;
1469 FREE(sin6
, M_SONAME
);
1472 FREE(sin6
, M_SONAME
);
1477 lck_mtx_assert(((struct inpcb
*)so
->so_pcb
)->inpcb_mtx
, LCK_MTX_ASSERT_OWNED
);
1479 MALLOC(sin
, struct sockaddr_in
*, sizeof *sin
, M_SONAME
,
1483 sin
->sin_family
= AF_INET
;
1484 sin
->sin_len
= sizeof(*sin
);
1485 sin
->sin_addr
= ip
->ip_src
;
1486 sin
->sin_port
= th
->th_sport
;
1487 bzero((caddr_t
)sin
->sin_zero
, sizeof(sin
->sin_zero
));
1488 laddr
= inp
->inp_laddr
;
1489 if (inp
->inp_laddr
.s_addr
== INADDR_ANY
)
1490 inp
->inp_laddr
= ip
->ip_dst
;
1491 if (in_pcbconnect(inp
, (struct sockaddr
*)sin
, proc0
)) {
1492 inp
->inp_laddr
= laddr
;
1493 FREE(sin
, M_SONAME
);
1496 FREE(sin
, M_SONAME
);
1498 if ((taop
= tcp_gettaocache(inp
)) == NULL
) {
1499 taop
= &tao_noncached
;
1500 bzero(taop
, sizeof(*taop
));
1502 tcp_dooptions(tp
, optp
, optlen
, th
, &to
);
1506 tp
->iss
= tcp_new_isn(tp
);
1508 tp
->irs
= th
->th_seq
;
1509 tcp_sendseqinit(tp
);
1511 tp
->snd_recover
= tp
->snd_una
;
1513 * Initialization of the tcpcb for transaction;
1514 * set SND.WND = SEG.WND,
1515 * initialize CCsend and CCrecv.
1517 tp
->snd_wnd
= tiwin
; /* initial send-window */
1518 tp
->cc_send
= CC_INC(tcp_ccgen
);
1519 tp
->cc_recv
= to
.to_cc
;
1521 * Perform TAO test on incoming CC (SEG.CC) option, if any.
1522 * - compare SEG.CC against cached CC from the same host,
1524 * - if SEG.CC > chached value, SYN must be new and is accepted
1525 * immediately: save new CC in the cache, mark the socket
1526 * connected, enter ESTABLISHED state, turn on flag to
1527 * send a SYN in the next segment.
1528 * A virtual advertised window is set in rcv_adv to
1529 * initialize SWS prevention. Then enter normal segment
1530 * processing: drop SYN, process data and FIN.
1531 * - otherwise do a normal 3-way handshake.
1533 if ((to
.to_flag
& TOF_CC
) != 0) {
1534 if (((tp
->t_flags
& TF_NOPUSH
) != 0) &&
1535 taop
->tao_cc
!= 0 && CC_GT(to
.to_cc
, taop
->tao_cc
)) {
1537 taop
->tao_cc
= to
.to_cc
;
1539 tp
->t_state
= TCPS_ESTABLISHED
;
1542 * If there is a FIN, or if there is data and the
1543 * connection is local, then delay SYN,ACK(SYN) in
1544 * the hope of piggy-backing it on a response
1545 * segment. Otherwise must send ACK now in case
1546 * the other side is slow starting.
1548 if (DELAY_ACK(tp
) && ((thflags
& TH_FIN
) ||
1551 (isipv6
&& in6_localaddr(&inp
->in6p_faddr
))
1555 in_localaddr(inp
->inp_faddr
)
1560 tp
->t_flags
|= (TF_DELACK
| TF_NEEDSYN
);
1563 tp
->t_flags
|= (TF_ACKNOW
| TF_NEEDSYN
);
1567 * Limit the `virtual advertised window' to TCP_MAXWIN
1568 * here. Even if we requested window scaling, it will
1569 * become effective only later when our SYN is acked.
1571 if (tp
->t_flags
& TF_SLOWLINK
&& slowlink_wsize
> 0) /* clip window size for for slow link */
1572 tp
->rcv_adv
+= min(tp
->rcv_wnd
, slowlink_wsize
);
1574 tp
->rcv_adv
+= min(tp
->rcv_wnd
, TCP_MAXWIN
);
1575 tcpstat
.tcps_connects
++;
1577 tp
->t_timer
[TCPT_KEEP
] = tcp_keepinit
;
1578 dropsocket
= 0; /* committed to socket */
1579 tcpstat
.tcps_accepts
++;
1582 /* else do standard 3-way handshake */
1585 * No CC option, but maybe CC.NEW:
1586 * invalidate cached value.
1591 * TAO test failed or there was no CC option,
1592 * do a standard 3-way handshake.
1594 tp
->t_flags
|= TF_ACKNOW
;
1595 tp
->t_state
= TCPS_SYN_RECEIVED
;
1596 tp
->t_timer
[TCPT_KEEP
] = tcp_keepinit
;
1597 dropsocket
= 0; /* committed to socket */
1598 tcpstat
.tcps_accepts
++;
1603 * If the state is SYN_RECEIVED:
1604 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1606 case TCPS_SYN_RECEIVED
:
1607 if ((thflags
& TH_ACK
) &&
1608 (SEQ_LEQ(th
->th_ack
, tp
->snd_una
) ||
1609 SEQ_GT(th
->th_ack
, tp
->snd_max
))) {
1610 rstreason
= BANDLIM_RST_OPENPORT
;
1616 * If the state is SYN_SENT:
1617 * if seg contains an ACK, but not for our SYN, drop the input.
1618 * if seg contains a RST, then drop the connection.
1619 * if seg does not contain SYN, then drop it.
1620 * Otherwise this is an acceptable SYN segment
1621 * initialize tp->rcv_nxt and tp->irs
1622 * if seg contains ack then advance tp->snd_una
1623 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1624 * arrange for segment to be acked (eventually)
1625 * continue processing rest of data/controls, beginning with URG
1628 if ((taop
= tcp_gettaocache(inp
)) == NULL
) {
1629 taop
= &tao_noncached
;
1630 bzero(taop
, sizeof(*taop
));
1633 if ((thflags
& TH_ACK
) &&
1634 (SEQ_LEQ(th
->th_ack
, tp
->iss
) ||
1635 SEQ_GT(th
->th_ack
, tp
->snd_max
))) {
1637 * If we have a cached CCsent for the remote host,
1638 * hence we haven't just crashed and restarted,
1639 * do not send a RST. This may be a retransmission
1640 * from the other side after our earlier ACK was lost.
1641 * Our new SYN, when it arrives, will serve as the
1644 if (taop
->tao_ccsent
!= 0)
1647 rstreason
= BANDLIM_UNLIMITED
;
1651 if (thflags
& TH_RST
) {
1652 if (thflags
& TH_ACK
) {
1653 tp
= tcp_drop(tp
, ECONNREFUSED
);
1654 postevent(so
, 0, EV_RESET
);
1658 if ((thflags
& TH_SYN
) == 0)
1660 tp
->snd_wnd
= th
->th_win
; /* initial send window */
1661 tp
->cc_recv
= to
.to_cc
; /* foreign CC */
1663 tp
->irs
= th
->th_seq
;
1665 if (thflags
& TH_ACK
) {
1667 * Our SYN was acked. If segment contains CC.ECHO
1668 * option, check it to make sure this segment really
1669 * matches our SYN. If not, just drop it as old
1670 * duplicate, but send an RST if we're still playing
1671 * by the old rules. If no CC.ECHO option, make sure
1672 * we don't get fooled into using T/TCP.
1674 if (to
.to_flag
& TOF_CCECHO
) {
1675 if (tp
->cc_send
!= to
.to_ccecho
) {
1676 if (taop
->tao_ccsent
!= 0)
1679 rstreason
= BANDLIM_UNLIMITED
;
1684 tp
->t_flags
&= ~TF_RCVD_CC
;
1685 tcpstat
.tcps_connects
++;
1687 /* Do window scaling on this connection? */
1688 if ((tp
->t_flags
& (TF_RCVD_SCALE
|TF_REQ_SCALE
)) ==
1689 (TF_RCVD_SCALE
|TF_REQ_SCALE
)) {
1690 tp
->snd_scale
= tp
->requested_s_scale
;
1691 tp
->rcv_scale
= tp
->request_r_scale
;
1693 /* Segment is acceptable, update cache if undefined. */
1694 if (taop
->tao_ccsent
== 0)
1695 taop
->tao_ccsent
= to
.to_ccecho
;
1697 tp
->rcv_adv
+= tp
->rcv_wnd
;
1698 tp
->snd_una
++; /* SYN is acked */
1700 * If there's data, delay ACK; if there's also a FIN
1701 * ACKNOW will be turned on later.
1703 if (DELAY_ACK(tp
) && tlen
!= 0) {
1704 tp
->t_flags
|= TF_DELACK
;
1707 tp
->t_flags
|= TF_ACKNOW
;
1710 * Received <SYN,ACK> in SYN_SENT[*] state.
1712 * SYN_SENT --> ESTABLISHED
1713 * SYN_SENT* --> FIN_WAIT_1
1715 if (tp
->t_flags
& TF_NEEDFIN
) {
1716 tp
->t_state
= TCPS_FIN_WAIT_1
;
1717 tp
->t_flags
&= ~TF_NEEDFIN
;
1720 tp
->t_state
= TCPS_ESTABLISHED
;
1721 tp
->t_timer
[TCPT_KEEP
] = TCP_KEEPIDLE(tp
);
1725 * Received initial SYN in SYN-SENT[*] state => simul-
1726 * taneous open. If segment contains CC option and there is
1727 * a cached CC, apply TAO test; if it succeeds, connection is
1728 * half-synchronized. Otherwise, do 3-way handshake:
1729 * SYN-SENT -> SYN-RECEIVED
1730 * SYN-SENT* -> SYN-RECEIVED*
1731 * If there was no CC option, clear cached CC value.
1733 tp
->t_flags
|= TF_ACKNOW
;
1734 tp
->t_timer
[TCPT_REXMT
] = 0;
1735 if (to
.to_flag
& TOF_CC
) {
1736 if (taop
->tao_cc
!= 0 &&
1737 CC_GT(to
.to_cc
, taop
->tao_cc
)) {
1739 * update cache and make transition:
1740 * SYN-SENT -> ESTABLISHED*
1741 * SYN-SENT* -> FIN-WAIT-1*
1743 taop
->tao_cc
= to
.to_cc
;
1744 if (tp
->t_flags
& TF_NEEDFIN
) {
1745 tp
->t_state
= TCPS_FIN_WAIT_1
;
1746 tp
->t_flags
&= ~TF_NEEDFIN
;
1748 tp
->t_state
= TCPS_ESTABLISHED
;
1749 tp
->t_timer
[TCPT_KEEP
] = TCP_KEEPIDLE(tp
);
1751 tp
->t_flags
|= TF_NEEDSYN
;
1753 tp
->t_state
= TCPS_SYN_RECEIVED
;
1755 /* CC.NEW or no option => invalidate cache */
1757 tp
->t_state
= TCPS_SYN_RECEIVED
;
1763 * Advance th->th_seq to correspond to first data byte.
1764 * If data, trim to stay within window,
1765 * dropping FIN if necessary.
1768 if (tlen
> tp
->rcv_wnd
) {
1769 todrop
= tlen
- tp
->rcv_wnd
;
1773 tcpstat
.tcps_rcvpackafterwin
++;
1774 tcpstat
.tcps_rcvbyteafterwin
+= todrop
;
1776 tp
->snd_wl1
= th
->th_seq
- 1;
1777 tp
->rcv_up
= th
->th_seq
;
1779 * Client side of transaction: already sent SYN and data.
1780 * If the remote host used T/TCP to validate the SYN,
1781 * our data will be ACK'd; if so, enter normal data segment
1782 * processing in the middle of step 5, ack processing.
1783 * Otherwise, goto step 6.
1785 if (thflags
& TH_ACK
)
1789 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1790 * if segment contains a SYN and CC [not CC.NEW] option:
1791 * if state == TIME_WAIT and connection duration > MSL,
1792 * drop packet and send RST;
1794 * if SEG.CC > CCrecv then is new SYN, and can implicitly
1795 * ack the FIN (and data) in retransmission queue.
1796 * Complete close and delete TCPCB. Then reprocess
1797 * segment, hoping to find new TCPCB in LISTEN state;
1799 * else must be old SYN; drop it.
1800 * else do normal processing.
1804 case TCPS_TIME_WAIT
:
1805 if ((thflags
& TH_SYN
) &&
1806 (to
.to_flag
& TOF_CC
) && tp
->cc_recv
!= 0) {
1807 if (tp
->t_state
== TCPS_TIME_WAIT
&&
1808 tp
->t_starttime
> tcp_msl
) {
1809 rstreason
= BANDLIM_UNLIMITED
;
1812 if (CC_GT(to
.to_cc
, tp
->cc_recv
)) {
1814 tcp_unlock(so
, 1, 50);
1820 break; /* continue normal processing */
1822 /* Received a SYN while connection is already established.
1823 * This is a "half open connection and other anomalies" described
1824 * in RFC793 page 34, send an ACK so the remote reset the connection
1825 * or recovers by adjusting its sequence numberering
1827 case TCPS_ESTABLISHED
:
1828 if (thflags
& TH_SYN
)
1834 * States other than LISTEN or SYN_SENT.
1835 * First check the RST flag and sequence number since reset segments
1836 * are exempt from the timestamp and connection count tests. This
1837 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1838 * below which allowed reset segments in half the sequence space
1839 * to fall though and be processed (which gives forged reset
1840 * segments with a random sequence number a 50 percent chance of
1841 * killing a connection).
1842 * Then check timestamp, if present.
1843 * Then check the connection count, if present.
1844 * Then check that at least some bytes of segment are within
1845 * receive window. If segment begins before rcv_nxt,
1846 * drop leading data (and SYN); if nothing left, just ack.
1849 * If the RST bit is set, check the sequence number to see
1850 * if this is a valid reset segment.
1852 * In all states except SYN-SENT, all reset (RST) segments
1853 * are validated by checking their SEQ-fields. A reset is
1854 * valid if its sequence number is in the window.
1855 * Note: this does not take into account delayed ACKs, so
1856 * we should test against last_ack_sent instead of rcv_nxt.
1857 * The sequence number in the reset segment is normally an
1858 * echo of our outgoing acknowlegement numbers, but some hosts
1859 * send a reset with the sequence number at the rightmost edge
1860 * of our receive window, and we have to handle this case.
1861 * If we have multiple segments in flight, the intial reset
1862 * segment sequence numbers will be to the left of last_ack_sent,
1863 * but they will eventually catch up.
1864 * In any case, it never made sense to trim reset segments to
1865 * fit the receive window since RFC 1122 says:
1866 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1868 * A TCP SHOULD allow a received RST segment to include data.
1871 * It has been suggested that a RST segment could contain
1872 * ASCII text that encoded and explained the cause of the
1873 * RST. No standard has yet been established for such
1876 * If the reset segment passes the sequence number test examine
1878 * SYN_RECEIVED STATE:
1879 * If passive open, return to LISTEN state.
1880 * If active open, inform user that connection was refused.
1881 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
1882 * Inform user that connection was reset, and close tcb.
1883 * CLOSING, LAST_ACK STATES:
1886 * Drop the segment - see Stevens, vol. 2, p. 964 and
1889 if (thflags
& TH_RST
) {
1890 if (SEQ_GEQ(th
->th_seq
, tp
->last_ack_sent
) &&
1891 SEQ_LT(th
->th_seq
, tp
->last_ack_sent
+ tp
->rcv_wnd
)) {
1892 switch (tp
->t_state
) {
1894 case TCPS_SYN_RECEIVED
:
1895 so
->so_error
= ECONNREFUSED
;
1898 case TCPS_ESTABLISHED
:
1899 case TCPS_FIN_WAIT_1
:
1900 case TCPS_CLOSE_WAIT
:
1904 case TCPS_FIN_WAIT_2
:
1905 so
->so_error
= ECONNRESET
;
1907 postevent(so
, 0, EV_RESET
);
1908 tp
->t_state
= TCPS_CLOSED
;
1909 tcpstat
.tcps_drops
++;
1918 case TCPS_TIME_WAIT
:
1926 lck_mtx_assert(((struct inpcb
*)so
->so_pcb
)->inpcb_mtx
, LCK_MTX_ASSERT_OWNED
);
1929 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1930 * and it's less than ts_recent, drop it.
1932 if ((to
.to_flag
& TOF_TS
) != 0 && tp
->ts_recent
&&
1933 TSTMP_LT(to
.to_tsval
, tp
->ts_recent
)) {
1935 /* Check to see if ts_recent is over 24 days old. */
1936 if ((int)(tcp_now
- tp
->ts_recent_age
) > TCP_PAWS_IDLE
) {
1938 * Invalidate ts_recent. If this segment updates
1939 * ts_recent, the age will be reset later and ts_recent
1940 * will get a valid value. If it does not, setting
1941 * ts_recent to zero will at least satisfy the
1942 * requirement that zero be placed in the timestamp
1943 * echo reply when ts_recent isn't valid. The
1944 * age isn't reset until we get a valid ts_recent
1945 * because we don't want out-of-order segments to be
1946 * dropped when ts_recent is old.
1950 tcpstat
.tcps_rcvduppack
++;
1951 tcpstat
.tcps_rcvdupbyte
+= tlen
;
1952 tcpstat
.tcps_pawsdrop
++;
1959 * If T/TCP was negotiated and the segment doesn't have CC,
1960 * or if its CC is wrong then drop the segment.
1961 * RST segments do not have to comply with this.
1963 if ((tp
->t_flags
& (TF_REQ_CC
|TF_RCVD_CC
)) == (TF_REQ_CC
|TF_RCVD_CC
) &&
1964 ((to
.to_flag
& TOF_CC
) == 0 || tp
->cc_recv
!= to
.to_cc
))
1968 * In the SYN-RECEIVED state, validate that the packet belongs to
1969 * this connection before trimming the data to fit the receive
1970 * window. Check the sequence number versus IRS since we know
1971 * the sequence numbers haven't wrapped. This is a partial fix
1972 * for the "LAND" DoS attack.
1974 if (tp
->t_state
== TCPS_SYN_RECEIVED
&& SEQ_LT(th
->th_seq
, tp
->irs
)) {
1975 rstreason
= BANDLIM_RST_OPENPORT
;
1979 todrop
= tp
->rcv_nxt
- th
->th_seq
;
1981 if (thflags
& TH_SYN
) {
1991 * Following if statement from Stevens, vol. 2, p. 960.
1994 || (todrop
== tlen
&& (thflags
& TH_FIN
) == 0)) {
1996 * Any valid FIN must be to the left of the window.
1997 * At this point the FIN must be a duplicate or out
1998 * of sequence; drop it.
2003 * Send an ACK to resynchronize and drop any data.
2004 * But keep on processing for RST or ACK.
2006 tp
->t_flags
|= TF_ACKNOW
;
2008 tcpstat
.tcps_rcvduppack
++;
2009 tcpstat
.tcps_rcvdupbyte
+= todrop
;
2011 tcpstat
.tcps_rcvpartduppack
++;
2012 tcpstat
.tcps_rcvpartdupbyte
+= todrop
;
2014 drop_hdrlen
+= todrop
; /* drop from the top afterwards */
2015 th
->th_seq
+= todrop
;
2017 if (th
->th_urp
> todrop
)
2018 th
->th_urp
-= todrop
;
2026 * If new data are received on a connection after the
2027 * user processes are gone, then RST the other end.
2029 if ((so
->so_state
& SS_NOFDREF
) &&
2030 tp
->t_state
> TCPS_CLOSE_WAIT
&& tlen
) {
2032 tcpstat
.tcps_rcvafterclose
++;
2033 rstreason
= BANDLIM_UNLIMITED
;
2038 * If segment ends after window, drop trailing data
2039 * (and PUSH and FIN); if nothing left, just ACK.
2041 todrop
= (th
->th_seq
+tlen
) - (tp
->rcv_nxt
+tp
->rcv_wnd
);
2043 tcpstat
.tcps_rcvpackafterwin
++;
2044 if (todrop
>= tlen
) {
2045 tcpstat
.tcps_rcvbyteafterwin
+= tlen
;
2047 * If a new connection request is received
2048 * while in TIME_WAIT, drop the old connection
2049 * and start over if the sequence numbers
2050 * are above the previous ones.
2052 if (thflags
& TH_SYN
&&
2053 tp
->t_state
== TCPS_TIME_WAIT
&&
2054 SEQ_GT(th
->th_seq
, tp
->rcv_nxt
)) {
2055 iss
= tcp_new_isn(tp
);
2057 tcp_unlock(so
, 1, 0);
2061 * If window is closed can only take segments at
2062 * window edge, and have to drop data and PUSH from
2063 * incoming segments. Continue processing, but
2064 * remember to ack. Otherwise, drop segment
2067 if (tp
->rcv_wnd
== 0 && th
->th_seq
== tp
->rcv_nxt
) {
2068 tp
->t_flags
|= TF_ACKNOW
;
2069 tcpstat
.tcps_rcvwinprobe
++;
2073 tcpstat
.tcps_rcvbyteafterwin
+= todrop
;
2076 thflags
&= ~(TH_PUSH
|TH_FIN
);
2080 * If last ACK falls within this segment's sequence numbers,
2081 * record its timestamp.
2082 * NOTE that the test is modified according to the latest
2083 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
2085 if ((to
.to_flag
& TOF_TS
) != 0 &&
2086 SEQ_LEQ(th
->th_seq
, tp
->last_ack_sent
)) {
2087 tp
->ts_recent_age
= tcp_now
;
2088 tp
->ts_recent
= to
.to_tsval
;
2092 * If a SYN is in the window, then this is an
2093 * error and we send an RST and drop the connection.
2095 if (thflags
& TH_SYN
) {
2096 tp
= tcp_drop(tp
, ECONNRESET
);
2097 rstreason
= BANDLIM_UNLIMITED
;
2098 postevent(so
, 0, EV_RESET
);
2103 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
2104 * flag is on (half-synchronized state), then queue data for
2105 * later processing; else drop segment and return.
2107 if ((thflags
& TH_ACK
) == 0) {
2108 if (tp
->t_state
== TCPS_SYN_RECEIVED
||
2109 (tp
->t_flags
& TF_NEEDSYN
))
2118 switch (tp
->t_state
) {
2121 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
2122 * ESTABLISHED state and continue processing.
2123 * The ACK was checked above.
2125 case TCPS_SYN_RECEIVED
:
2127 tcpstat
.tcps_connects
++;
2130 /* Do window scaling? */
2131 if ((tp
->t_flags
& (TF_RCVD_SCALE
|TF_REQ_SCALE
)) ==
2132 (TF_RCVD_SCALE
|TF_REQ_SCALE
)) {
2133 tp
->snd_scale
= tp
->requested_s_scale
;
2134 tp
->rcv_scale
= tp
->request_r_scale
;
2137 * Upon successful completion of 3-way handshake,
2138 * update cache.CC if it was undefined, pass any queued
2139 * data to the user, and advance state appropriately.
2141 if ((taop
= tcp_gettaocache(inp
)) != NULL
&&
2143 taop
->tao_cc
= tp
->cc_recv
;
2147 * SYN-RECEIVED -> ESTABLISHED
2148 * SYN-RECEIVED* -> FIN-WAIT-1
2150 if (tp
->t_flags
& TF_NEEDFIN
) {
2151 tp
->t_state
= TCPS_FIN_WAIT_1
;
2152 tp
->t_flags
&= ~TF_NEEDFIN
;
2154 tp
->t_state
= TCPS_ESTABLISHED
;
2155 tp
->t_timer
[TCPT_KEEP
] = TCP_KEEPIDLE(tp
);
2158 * If segment contains data or ACK, will call tcp_reass()
2159 * later; if not, do so now to pass queued data to user.
2161 if (tlen
== 0 && (thflags
& TH_FIN
) == 0)
2162 (void) tcp_reass(tp
, (struct tcphdr
*)0, 0,
2164 tp
->snd_wl1
= th
->th_seq
- 1;
2168 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2169 * ACKs. If the ack is in the range
2170 * tp->snd_una < th->th_ack <= tp->snd_max
2171 * then advance tp->snd_una to th->th_ack and drop
2172 * data from the retransmission queue. If this ACK reflects
2173 * more up to date window information we update our window information.
2175 case TCPS_ESTABLISHED
:
2176 case TCPS_FIN_WAIT_1
:
2177 case TCPS_FIN_WAIT_2
:
2178 case TCPS_CLOSE_WAIT
:
2181 case TCPS_TIME_WAIT
:
2183 if (SEQ_LEQ(th
->th_ack
, tp
->snd_una
)) {
2184 if (tlen
== 0 && tiwin
== tp
->snd_wnd
) {
2185 tcpstat
.tcps_rcvdupack
++;
2187 * If we have outstanding data (other than
2188 * a window probe), this is a completely
2189 * duplicate ack (ie, window info didn't
2190 * change), the ack is the biggest we've
2191 * seen and we've seen exactly our rexmt
2192 * threshhold of them, assume a packet
2193 * has been dropped and retransmit it.
2194 * Kludge snd_nxt & the congestion
2195 * window so we send only this one
2198 * We know we're losing at the current
2199 * window size so do congestion avoidance
2200 * (set ssthresh to half the current window
2201 * and pull our congestion window back to
2202 * the new ssthresh).
2204 * Dup acks mean that packets have left the
2205 * network (they're now cached at the receiver)
2206 * so bump cwnd by the amount in the receiver
2207 * to keep a constant cwnd packets in the
2210 if (tp
->t_timer
[TCPT_REXMT
] == 0 ||
2211 th
->th_ack
!= tp
->snd_una
)
2213 else if (++tp
->t_dupacks
== tcprexmtthresh
) {
2214 tcp_seq onxt
= tp
->snd_nxt
;
2216 min(tp
->snd_wnd
, tp
->snd_cwnd
) / 2 /
2218 if (tcp_do_newreno
&& SEQ_LT(th
->th_ack
,
2220 /* False retransmit, should not
2223 tp
->snd_cwnd
+= tp
->t_maxseg
;
2225 (void) tcp_output(tp
);
2230 tp
->snd_ssthresh
= win
* tp
->t_maxseg
;
2231 tp
->snd_recover
= tp
->snd_max
;
2232 tp
->t_timer
[TCPT_REXMT
] = 0;
2234 tp
->snd_nxt
= th
->th_ack
;
2235 tp
->snd_cwnd
= tp
->t_maxseg
;
2236 (void) tcp_output(tp
);
2237 tp
->snd_cwnd
= tp
->snd_ssthresh
+
2238 tp
->t_maxseg
* tp
->t_dupacks
;
2239 if (SEQ_GT(onxt
, tp
->snd_nxt
))
2242 } else if (tp
->t_dupacks
> tcprexmtthresh
) {
2243 tp
->snd_cwnd
+= tp
->t_maxseg
;
2244 (void) tcp_output(tp
);
2252 * If the congestion window was inflated to account
2253 * for the other side's cached packets, retract it.
2255 if (tcp_do_newreno
== 0) {
2256 if (tp
->t_dupacks
>= tcprexmtthresh
&&
2257 tp
->snd_cwnd
> tp
->snd_ssthresh
)
2258 tp
->snd_cwnd
= tp
->snd_ssthresh
;
2260 } else if (tp
->t_dupacks
>= tcprexmtthresh
&&
2261 !tcp_newreno(tp
, th
)) {
2263 * Window inflation should have left us with approx.
2264 * snd_ssthresh outstanding data. But in case we
2265 * would be inclined to send a burst, better to do
2266 * it via the slow start mechanism.
2268 if (SEQ_GT(th
->th_ack
+ tp
->snd_ssthresh
, tp
->snd_max
))
2270 tp
->snd_max
- th
->th_ack
+ tp
->t_maxseg
;
2272 tp
->snd_cwnd
= tp
->snd_ssthresh
;
2276 if (tp
->t_dupacks
< tcprexmtthresh
)
2279 if (SEQ_GT(th
->th_ack
, tp
->snd_max
)) {
2280 tcpstat
.tcps_rcvacktoomuch
++;
2284 * If we reach this point, ACK is not a duplicate,
2285 * i.e., it ACKs something we sent.
2287 if (tp
->t_flags
& TF_NEEDSYN
) {
2289 * T/TCP: Connection was half-synchronized, and our
2290 * SYN has been ACK'd (so connection is now fully
2291 * synchronized). Go to non-starred state,
2292 * increment snd_una for ACK of SYN, and check if
2293 * we can do window scaling.
2295 tp
->t_flags
&= ~TF_NEEDSYN
;
2297 /* Do window scaling? */
2298 if ((tp
->t_flags
& (TF_RCVD_SCALE
|TF_REQ_SCALE
)) ==
2299 (TF_RCVD_SCALE
|TF_REQ_SCALE
)) {
2300 tp
->snd_scale
= tp
->requested_s_scale
;
2301 tp
->rcv_scale
= tp
->request_r_scale
;
2306 acked
= th
->th_ack
- tp
->snd_una
;
2307 tcpstat
.tcps_rcvackpack
++;
2308 tcpstat
.tcps_rcvackbyte
+= acked
;
2311 * If we just performed our first retransmit, and the ACK
2312 * arrives within our recovery window, then it was a mistake
2313 * to do the retransmit in the first place. Recover our
2314 * original cwnd and ssthresh, and proceed to transmit where
2317 if (tp
->t_rxtshift
== 1 && tcp_now
< tp
->t_badrxtwin
) {
2318 tp
->snd_cwnd
= tp
->snd_cwnd_prev
;
2319 tp
->snd_ssthresh
= tp
->snd_ssthresh_prev
;
2320 tp
->snd_nxt
= tp
->snd_max
;
2321 tp
->t_badrxtwin
= 0; /* XXX probably not required */
2325 * If we have a timestamp reply, update smoothed
2326 * round trip time. If no timestamp is present but
2327 * transmit timer is running and timed sequence
2328 * number was acked, update smoothed round trip time.
2329 * Since we now have an rtt measurement, cancel the
2330 * timer backoff (cf., Phil Karn's retransmit alg.).
2331 * Recompute the initial retransmit timer.
2332 * Also makes sure we have a valid time stamp in hand
2334 if (((to
.to_flag
& TOF_TS
) != 0) && (to
.to_tsecr
!= 0))
2335 tcp_xmit_timer(tp
, tcp_now
- to
.to_tsecr
+ 1);
2336 else if (tp
->t_rtttime
&& SEQ_GT(th
->th_ack
, tp
->t_rtseq
))
2337 tcp_xmit_timer(tp
, tp
->t_rtttime
);
2340 * If all outstanding data is acked, stop retransmit
2341 * timer and remember to restart (more output or persist).
2342 * If there is more data to be acked, restart retransmit
2343 * timer, using current (possibly backed-off) value.
2345 if (th
->th_ack
== tp
->snd_max
) {
2346 tp
->t_timer
[TCPT_REXMT
] = 0;
2348 } else if (tp
->t_timer
[TCPT_PERSIST
] == 0)
2349 tp
->t_timer
[TCPT_REXMT
] = tp
->t_rxtcur
;
2352 * If no data (only SYN) was ACK'd,
2353 * skip rest of ACK processing.
2359 * When new data is acked, open the congestion window.
2360 * If the window gives us less than ssthresh packets
2361 * in flight, open exponentially (maxseg per packet).
2362 * Otherwise open linearly: maxseg per window
2363 * (maxseg^2 / cwnd per packet).
2366 register u_int cw
= tp
->snd_cwnd
;
2367 register u_int incr
= tp
->t_maxseg
;
2369 if (cw
> tp
->snd_ssthresh
)
2370 incr
= incr
* incr
/ cw
;
2372 * If t_dupacks != 0 here, it indicates that we are still
2373 * in NewReno fast recovery mode, so we leave the congestion
2376 if (tcp_do_newreno
== 0 || tp
->t_dupacks
== 0)
2377 tp
->snd_cwnd
= min(cw
+ incr
,TCP_MAXWIN
<<tp
->snd_scale
);
2379 if (acked
> so
->so_snd
.sb_cc
) {
2380 tp
->snd_wnd
-= so
->so_snd
.sb_cc
;
2381 sbdrop(&so
->so_snd
, (int)so
->so_snd
.sb_cc
);
2384 sbdrop(&so
->so_snd
, acked
);
2385 tp
->snd_wnd
-= acked
;
2389 /* detect una wraparound */
2390 if (SEQ_GEQ(tp
->snd_una
, tp
->snd_recover
) &&
2391 SEQ_LT(th
->th_ack
, tp
->snd_recover
))
2392 tp
->snd_recover
= th
->th_ack
;
2393 if (SEQ_GT(tp
->snd_una
, tp
->snd_high
) &&
2394 SEQ_LEQ(th
->th_ack
, tp
->snd_high
))
2395 tp
->snd_high
= th
->th_ack
- 1;
2396 tp
->snd_una
= th
->th_ack
;
2397 if (SEQ_LT(tp
->snd_nxt
, tp
->snd_una
))
2398 tp
->snd_nxt
= tp
->snd_una
;
2400 switch (tp
->t_state
) {
2403 * In FIN_WAIT_1 STATE in addition to the processing
2404 * for the ESTABLISHED state if our FIN is now acknowledged
2405 * then enter FIN_WAIT_2.
2407 case TCPS_FIN_WAIT_1
:
2408 if (ourfinisacked
) {
2410 * If we can't receive any more
2411 * data, then closing user can proceed.
2412 * Starting the timer is contrary to the
2413 * specification, but if we don't get a FIN
2414 * we'll hang forever.
2416 if (so
->so_state
& SS_CANTRCVMORE
) {
2417 soisdisconnected(so
);
2418 tp
->t_timer
[TCPT_2MSL
] = tcp_maxidle
;
2420 add_to_time_wait(tp
);
2421 tp
->t_state
= TCPS_FIN_WAIT_2
;
2427 * In CLOSING STATE in addition to the processing for
2428 * the ESTABLISHED state if the ACK acknowledges our FIN
2429 * then enter the TIME-WAIT state, otherwise ignore
2433 if (ourfinisacked
) {
2434 tp
->t_state
= TCPS_TIME_WAIT
;
2435 tcp_canceltimers(tp
);
2436 /* Shorten TIME_WAIT [RFC-1644, p.28] */
2437 if (tp
->cc_recv
!= 0 &&
2438 tp
->t_starttime
< tcp_msl
)
2439 tp
->t_timer
[TCPT_2MSL
] =
2440 tp
->t_rxtcur
* TCPTV_TWTRUNC
;
2442 tp
->t_timer
[TCPT_2MSL
] = 2 * tcp_msl
;
2443 add_to_time_wait(tp
);
2444 soisdisconnected(so
);
2449 * In LAST_ACK, we may still be waiting for data to drain
2450 * and/or to be acked, as well as for the ack of our FIN.
2451 * If our FIN is now acknowledged, delete the TCB,
2452 * enter the closed state and return.
2455 if (ourfinisacked
) {
2462 * In TIME_WAIT state the only thing that should arrive
2463 * is a retransmission of the remote FIN. Acknowledge
2464 * it and restart the finack timer.
2466 case TCPS_TIME_WAIT
:
2467 tp
->t_timer
[TCPT_2MSL
] = 2 * tcp_msl
;
2468 add_to_time_wait(tp
);
2475 * Update window information.
2476 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2478 if ((thflags
& TH_ACK
) &&
2479 (SEQ_LT(tp
->snd_wl1
, th
->th_seq
) ||
2480 (tp
->snd_wl1
== th
->th_seq
&& (SEQ_LT(tp
->snd_wl2
, th
->th_ack
) ||
2481 (tp
->snd_wl2
== th
->th_ack
&& tiwin
> tp
->snd_wnd
))))) {
2482 /* keep track of pure window updates */
2484 tp
->snd_wl2
== th
->th_ack
&& tiwin
> tp
->snd_wnd
)
2485 tcpstat
.tcps_rcvwinupd
++;
2486 tp
->snd_wnd
= tiwin
;
2487 tp
->snd_wl1
= th
->th_seq
;
2488 tp
->snd_wl2
= th
->th_ack
;
2489 if (tp
->snd_wnd
> tp
->max_sndwnd
)
2490 tp
->max_sndwnd
= tp
->snd_wnd
;
2495 * Process segments with URG.
2497 if ((thflags
& TH_URG
) && th
->th_urp
&&
2498 TCPS_HAVERCVDFIN(tp
->t_state
) == 0) {
2500 * This is a kludge, but if we receive and accept
2501 * random urgent pointers, we'll crash in
2502 * soreceive. It's hard to imagine someone
2503 * actually wanting to send this much urgent data.
2505 if (th
->th_urp
+ so
->so_rcv
.sb_cc
> sb_max
) {
2506 th
->th_urp
= 0; /* XXX */
2507 thflags
&= ~TH_URG
; /* XXX */
2508 goto dodata
; /* XXX */
2511 * If this segment advances the known urgent pointer,
2512 * then mark the data stream. This should not happen
2513 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2514 * a FIN has been received from the remote side.
2515 * In these states we ignore the URG.
2517 * According to RFC961 (Assigned Protocols),
2518 * the urgent pointer points to the last octet
2519 * of urgent data. We continue, however,
2520 * to consider it to indicate the first octet
2521 * of data past the urgent section as the original
2522 * spec states (in one of two places).
2524 if (SEQ_GT(th
->th_seq
+th
->th_urp
, tp
->rcv_up
)) {
2525 tp
->rcv_up
= th
->th_seq
+ th
->th_urp
;
2526 so
->so_oobmark
= so
->so_rcv
.sb_cc
+
2527 (tp
->rcv_up
- tp
->rcv_nxt
) - 1;
2528 if (so
->so_oobmark
== 0) {
2529 so
->so_state
|= SS_RCVATMARK
;
2530 postevent(so
, 0, EV_OOB
);
2533 tp
->t_oobflags
&= ~(TCPOOB_HAVEDATA
| TCPOOB_HADDATA
);
2536 * Remove out of band data so doesn't get presented to user.
2537 * This can happen independent of advancing the URG pointer,
2538 * but if two URG's are pending at once, some out-of-band
2539 * data may creep in... ick.
2541 if (th
->th_urp
<= (u_long
)tlen
2543 && (so
->so_options
& SO_OOBINLINE
) == 0
2546 tcp_pulloutofband(so
, th
, m
,
2547 drop_hdrlen
); /* hdr drop is delayed */
2550 * If no out of band data is expected,
2551 * pull receive urgent pointer along
2552 * with the receive window.
2554 if (SEQ_GT(tp
->rcv_nxt
, tp
->rcv_up
))
2555 tp
->rcv_up
= tp
->rcv_nxt
;
2559 * Process the segment text, merging it into the TCP sequencing queue,
2560 * and arranging for acknowledgment of receipt if necessary.
2561 * This process logically involves adjusting tp->rcv_wnd as data
2562 * is presented to the user (this happens in tcp_usrreq.c,
2563 * case PRU_RCVD). If a FIN has already been received on this
2564 * connection then we just ignore the text.
2566 if ((tlen
|| (thflags
&TH_FIN
)) &&
2567 TCPS_HAVERCVDFIN(tp
->t_state
) == 0) {
2568 m_adj(m
, drop_hdrlen
); /* delayed header drop */
2570 * Insert segment which inludes th into reassembly queue of tcp with
2571 * control block tp. Return TH_FIN if reassembly now includes
2572 * a segment with FIN. This handle the common case inline (segment
2573 * is the next to be received on an established connection, and the
2574 * queue is empty), avoiding linkage into and removal from the queue
2575 * and repetition of various conversions.
2576 * Set DELACK for segments received in order, but ack immediately
2577 * when segments are out of order (so fast retransmit can work).
2579 if (th
->th_seq
== tp
->rcv_nxt
&&
2580 LIST_EMPTY(&tp
->t_segq
) &&
2581 TCPS_HAVEESTABLISHED(tp
->t_state
)) {
2582 if (DELAY_ACK(tp
) && ((tp
->t_flags
& TF_ACKNOW
) == 0)) {
2583 tp
->t_flags
|= TF_DELACK
;
2586 tp
->t_flags
|= TF_ACKNOW
;
2588 tp
->rcv_nxt
+= tlen
;
2589 thflags
= th
->th_flags
& TH_FIN
;
2590 tcpstat
.tcps_rcvpack
++;
2591 tcpstat
.tcps_rcvbyte
+= tlen
;
2593 if (sbappend(&so
->so_rcv
, m
))
2596 thflags
= tcp_reass(tp
, th
, &tlen
, m
);
2597 tp
->t_flags
|= TF_ACKNOW
;
2600 if (tp
->t_flags
& TF_DELACK
)
2604 KERNEL_DEBUG(DBG_LAYER_END
, ((th
->th_dport
<< 16) | th
->th_sport
),
2605 (((ip6
->ip6_src
.s6_addr16
[0]) << 16) | (ip6
->ip6_dst
.s6_addr16
[0])),
2606 th
->th_seq
, th
->th_ack
, th
->th_win
);
2611 KERNEL_DEBUG(DBG_LAYER_END
, ((th
->th_dport
<< 16) | th
->th_sport
),
2612 (((ip
->ip_src
.s_addr
& 0xffff) << 16) | (ip
->ip_dst
.s_addr
& 0xffff)),
2613 th
->th_seq
, th
->th_ack
, th
->th_win
);
2618 * Note the amount of data that peer has sent into
2619 * our window, in order to estimate the sender's
2622 len
= so
->so_rcv
.sb_hiwat
- (tp
->rcv_adv
- tp
->rcv_nxt
);
2629 * If FIN is received ACK the FIN and let the user know
2630 * that the connection is closing.
2632 if (thflags
& TH_FIN
) {
2633 if (TCPS_HAVERCVDFIN(tp
->t_state
) == 0) {
2635 postevent(so
, 0, EV_FIN
);
2637 * If connection is half-synchronized
2638 * (ie NEEDSYN flag on) then delay ACK,
2639 * so it may be piggybacked when SYN is sent.
2640 * Otherwise, since we received a FIN then no
2641 * more input can be expected, send ACK now.
2643 if (DELAY_ACK(tp
) && (tp
->t_flags
& TF_NEEDSYN
)) {
2644 tp
->t_flags
|= TF_DELACK
;
2647 tp
->t_flags
|= TF_ACKNOW
;
2651 switch (tp
->t_state
) {
2654 * In SYN_RECEIVED and ESTABLISHED STATES
2655 * enter the CLOSE_WAIT state.
2657 case TCPS_SYN_RECEIVED
:
2659 case TCPS_ESTABLISHED
:
2660 tp
->t_state
= TCPS_CLOSE_WAIT
;
2664 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2665 * enter the CLOSING state.
2667 case TCPS_FIN_WAIT_1
:
2668 tp
->t_state
= TCPS_CLOSING
;
2672 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2673 * starting the time-wait timer, turning off the other
2676 case TCPS_FIN_WAIT_2
:
2677 tp
->t_state
= TCPS_TIME_WAIT
;
2678 tcp_canceltimers(tp
);
2679 /* Shorten TIME_WAIT [RFC-1644, p.28] */
2680 if (tp
->cc_recv
!= 0 &&
2681 tp
->t_starttime
< tcp_msl
) {
2682 tp
->t_timer
[TCPT_2MSL
] =
2683 tp
->t_rxtcur
* TCPTV_TWTRUNC
;
2684 /* For transaction client, force ACK now. */
2685 tp
->t_flags
|= TF_ACKNOW
;
2688 tp
->t_timer
[TCPT_2MSL
] = 2 * tcp_msl
;
2690 add_to_time_wait(tp
);
2691 soisdisconnected(so
);
2695 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2697 case TCPS_TIME_WAIT
:
2698 tp
->t_timer
[TCPT_2MSL
] = 2 * tcp_msl
;
2699 add_to_time_wait(tp
);
2704 if (so
->so_options
& SO_DEBUG
)
2705 tcp_trace(TA_INPUT
, ostate
, tp
, (void *)tcp_saveipgen
,
2710 * Return any desired output.
2712 if (needoutput
|| (tp
->t_flags
& TF_ACKNOW
))
2713 (void) tcp_output(tp
);
2714 tcp_unlock(so
, 1, 0);
2715 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
2720 * Generate an ACK dropping incoming segment if it occupies
2721 * sequence space, where the ACK reflects our state.
2723 * We can now skip the test for the RST flag since all
2724 * paths to this code happen after packets containing
2725 * RST have been dropped.
2727 * In the SYN-RECEIVED state, don't send an ACK unless the
2728 * segment we received passes the SYN-RECEIVED ACK test.
2729 * If it fails send a RST. This breaks the loop in the
2730 * "LAND" DoS attack, and also prevents an ACK storm
2731 * between two listening ports that have been sent forged
2732 * SYN segments, each with the source address of the other.
2734 if (tp
->t_state
== TCPS_SYN_RECEIVED
&& (thflags
& TH_ACK
) &&
2735 (SEQ_GT(tp
->snd_una
, th
->th_ack
) ||
2736 SEQ_GT(th
->th_ack
, tp
->snd_max
)) ) {
2737 rstreason
= BANDLIM_RST_OPENPORT
;
2741 if (so
->so_options
& SO_DEBUG
)
2742 tcp_trace(TA_DROP
, ostate
, tp
, (void *)tcp_saveipgen
,
2746 tp
->t_flags
|= TF_ACKNOW
;
2747 (void) tcp_output(tp
);
2748 tcp_unlock(so
, 1, 0);
2749 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
2751 dropwithresetnosock
:
2755 * Generate a RST, dropping incoming segment.
2756 * Make ACK acceptable to originator of segment.
2757 * Don't bother to respond if destination was broadcast/multicast.
2759 if ((thflags
& TH_RST
) || m
->m_flags
& (M_BCAST
|M_MCAST
))
2763 if (IN6_IS_ADDR_MULTICAST(&ip6
->ip6_dst
) ||
2764 IN6_IS_ADDR_MULTICAST(&ip6
->ip6_src
))
2768 if (IN_MULTICAST(ntohl(ip
->ip_dst
.s_addr
)) ||
2769 IN_MULTICAST(ntohl(ip
->ip_src
.s_addr
)) ||
2770 ip
->ip_src
.s_addr
== htonl(INADDR_BROADCAST
) ||
2771 in_broadcast(ip
->ip_dst
, m
->m_pkthdr
.rcvif
))
2773 /* IPv6 anycast check is done at tcp6_input() */
2776 * Perform bandwidth limiting.
2779 if (badport_bandlim(rstreason
) < 0)
2784 if (tp
== 0 || (tp
->t_inpcb
->inp_socket
->so_options
& SO_DEBUG
))
2785 tcp_trace(TA_DROP
, ostate
, tp
, (void *)tcp_saveipgen
,
2788 if (thflags
& TH_ACK
)
2789 /* mtod() below is safe as long as hdr dropping is delayed */
2790 tcp_respond(tp
, mtod(m
, void *), th
, m
, (tcp_seq
)0, th
->th_ack
,
2793 if (thflags
& TH_SYN
)
2795 /* mtod() below is safe as long as hdr dropping is delayed */
2796 tcp_respond(tp
, mtod(m
, void *), th
, m
, th
->th_seq
+tlen
,
2797 (tcp_seq
)0, TH_RST
|TH_ACK
);
2799 /* destroy temporarily created socket */
2802 tcp_unlock(so
, 1, 0);
2805 if ((inp
!= NULL
) && (nosock
== 0))
2806 tcp_unlock(so
, 1, 0);
2807 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
2813 * Drop space held by incoming segment and return.
2816 if (tp
== 0 || (tp
->t_inpcb
->inp_socket
->so_options
& SO_DEBUG
))
2817 tcp_trace(TA_DROP
, ostate
, tp
, (void *)tcp_saveipgen
,
2821 /* destroy temporarily created socket */
2824 tcp_unlock(so
, 1, 0);
2828 tcp_unlock(so
, 1, 0);
2829 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
2834 tcp_dooptions(tp
, cp
, cnt
, th
, to
)
2844 for (; cnt
> 0; cnt
-= optlen
, cp
+= optlen
) {
2846 if (opt
== TCPOPT_EOL
)
2848 if (opt
== TCPOPT_NOP
)
2854 if (optlen
< 2 || optlen
> cnt
)
2863 if (optlen
!= TCPOLEN_MAXSEG
)
2865 if (!(th
->th_flags
& TH_SYN
))
2867 bcopy((char *) cp
+ 2, (char *) &mss
, sizeof(mss
));
2872 if (optlen
!= TCPOLEN_WINDOW
)
2874 if (!(th
->th_flags
& TH_SYN
))
2876 tp
->t_flags
|= TF_RCVD_SCALE
;
2877 tp
->requested_s_scale
= min(cp
[2], TCP_MAX_WINSHIFT
);
2880 case TCPOPT_TIMESTAMP
:
2881 if (optlen
!= TCPOLEN_TIMESTAMP
)
2883 to
->to_flag
|= TOF_TS
;
2884 bcopy((char *)cp
+ 2,
2885 (char *)&to
->to_tsval
, sizeof(to
->to_tsval
));
2886 NTOHL(to
->to_tsval
);
2887 bcopy((char *)cp
+ 6,
2888 (char *)&to
->to_tsecr
, sizeof(to
->to_tsecr
));
2889 NTOHL(to
->to_tsecr
);
2892 * A timestamp received in a SYN makes
2893 * it ok to send timestamp requests and replies.
2895 if (th
->th_flags
& TH_SYN
) {
2896 tp
->t_flags
|= TF_RCVD_TSTMP
;
2897 tp
->ts_recent
= to
->to_tsval
;
2898 tp
->ts_recent_age
= tcp_now
;
2902 if (optlen
!= TCPOLEN_CC
)
2904 to
->to_flag
|= TOF_CC
;
2905 bcopy((char *)cp
+ 2,
2906 (char *)&to
->to_cc
, sizeof(to
->to_cc
));
2909 * A CC or CC.new option received in a SYN makes
2910 * it ok to send CC in subsequent segments.
2912 if (th
->th_flags
& TH_SYN
)
2913 tp
->t_flags
|= TF_RCVD_CC
;
2916 if (optlen
!= TCPOLEN_CC
)
2918 if (!(th
->th_flags
& TH_SYN
))
2920 to
->to_flag
|= TOF_CCNEW
;
2921 bcopy((char *)cp
+ 2,
2922 (char *)&to
->to_cc
, sizeof(to
->to_cc
));
2925 * A CC or CC.new option received in a SYN makes
2926 * it ok to send CC in subsequent segments.
2928 tp
->t_flags
|= TF_RCVD_CC
;
2931 if (optlen
!= TCPOLEN_CC
)
2933 if (!(th
->th_flags
& TH_SYN
))
2935 to
->to_flag
|= TOF_CCECHO
;
2936 bcopy((char *)cp
+ 2,
2937 (char *)&to
->to_ccecho
, sizeof(to
->to_ccecho
));
2938 NTOHL(to
->to_ccecho
);
2942 if (th
->th_flags
& TH_SYN
)
2943 tcp_mss(tp
, mss
); /* sets t_maxseg */
2947 * Pull out of band byte out of a segment so
2948 * it doesn't appear in the user's data queue.
2949 * It is still reflected in the segment length for
2950 * sequencing purposes.
2953 tcp_pulloutofband(so
, th
, m
, off
)
2956 register struct mbuf
*m
;
2957 int off
; /* delayed to be droped hdrlen */
2959 int cnt
= off
+ th
->th_urp
- 1;
2962 if (m
->m_len
> cnt
) {
2963 char *cp
= mtod(m
, caddr_t
) + cnt
;
2964 struct tcpcb
*tp
= sototcpcb(so
);
2967 tp
->t_oobflags
|= TCPOOB_HAVEDATA
;
2968 bcopy(cp
+1, cp
, (unsigned)(m
->m_len
- cnt
- 1));
2970 if (m
->m_flags
& M_PKTHDR
)
2979 panic("tcp_pulloutofband");
2983 * Collect new round-trip time estimate
2984 * and update averages and current timeout.
2987 tcp_xmit_timer(tp
, rtt
)
2988 register struct tcpcb
*tp
;
2993 tcpstat
.tcps_rttupdated
++;
2995 if (tp
->t_srtt
!= 0) {
2997 * srtt is stored as fixed point with 5 bits after the
2998 * binary point (i.e., scaled by 8). The following magic
2999 * is equivalent to the smoothing algorithm in rfc793 with
3000 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
3001 * point). Adjust rtt to origin 0.
3003 delta
= ((rtt
- 1) << TCP_DELTA_SHIFT
)
3004 - (tp
->t_srtt
>> (TCP_RTT_SHIFT
- TCP_DELTA_SHIFT
));
3006 if ((tp
->t_srtt
+= delta
) <= 0)
3010 * We accumulate a smoothed rtt variance (actually, a
3011 * smoothed mean difference), then set the retransmit
3012 * timer to smoothed rtt + 4 times the smoothed variance.
3013 * rttvar is stored as fixed point with 4 bits after the
3014 * binary point (scaled by 16). The following is
3015 * equivalent to rfc793 smoothing with an alpha of .75
3016 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
3017 * rfc793's wired-in beta.
3021 delta
-= tp
->t_rttvar
>> (TCP_RTTVAR_SHIFT
- TCP_DELTA_SHIFT
);
3022 if ((tp
->t_rttvar
+= delta
) <= 0)
3026 * No rtt measurement yet - use the unsmoothed rtt.
3027 * Set the variance to half the rtt (so our first
3028 * retransmit happens at 3*rtt).
3030 tp
->t_srtt
= rtt
<< TCP_RTT_SHIFT
;
3031 tp
->t_rttvar
= rtt
<< (TCP_RTTVAR_SHIFT
- 1);
3037 * the retransmit should happen at rtt + 4 * rttvar.
3038 * Because of the way we do the smoothing, srtt and rttvar
3039 * will each average +1/2 tick of bias. When we compute
3040 * the retransmit timer, we want 1/2 tick of rounding and
3041 * 1 extra tick because of +-1/2 tick uncertainty in the
3042 * firing of the timer. The bias will give us exactly the
3043 * 1.5 tick we need. But, because the bias is
3044 * statistical, we have to test that we don't drop below
3045 * the minimum feasible timer (which is 2 ticks).
3047 TCPT_RANGESET(tp
->t_rxtcur
, TCP_REXMTVAL(tp
),
3048 max(tp
->t_rttmin
, rtt
+ 2), TCPTV_REXMTMAX
);
3051 * We received an ack for a packet that wasn't retransmitted;
3052 * it is probably safe to discard any error indications we've
3053 * received recently. This isn't quite right, but close enough
3054 * for now (a route might have failed after we sent a segment,
3055 * and the return path might not be symmetrical).
3057 tp
->t_softerror
= 0;
3061 * Determine a reasonable value for maxseg size.
3062 * If the route is known, check route for mtu.
3063 * If none, use an mss that can be handled on the outgoing
3064 * interface without forcing IP to fragment; if bigger than
3065 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
3066 * to utilize large mbufs. If no route is found, route has no mtu,
3067 * or the destination isn't local, use a default, hopefully conservative
3068 * size (usually 512 or the default IP max size, but no more than the mtu
3069 * of the interface), as we can't discover anything about intervening
3070 * gateways or networks. We also initialize the congestion/slow start
3071 * window to be a single segment if the destination isn't local.
3072 * While looking at the routing entry, we also initialize other path-dependent
3073 * parameters from pre-set or cached values in the routing entry.
3075 * Also take into account the space needed for options that we
3076 * send regularly. Make maxseg shorter by that amount to assure
3077 * that we can send maxseg amount of data even when the options
3078 * are present. Store the upper limit of the length of options plus
3081 * NOTE that this routine is only called when we process an incoming
3082 * segment, for outgoing segments only tcp_mssopt is called.
3084 * In case of T/TCP, we call this routine during implicit connection
3085 * setup as well (offer = -1), to initialize maxseg from the cached
3093 register struct rtentry
*rt
;
3095 register int rtt
, mss
;
3099 struct rmxp_tao
*taop
;
3100 int origoffer
= offer
;
3108 isipv6
= ((inp
->inp_vflag
& INP_IPV6
) != 0) ? 1 : 0;
3109 min_protoh
= isipv6
? sizeof (struct ip6_hdr
) + sizeof (struct tcphdr
)
3110 : sizeof (struct tcpiphdr
);
3112 #define min_protoh (sizeof (struct tcpiphdr))
3116 rt
= tcp_rtlookup6(inp
);
3119 rt
= tcp_rtlookup(inp
);
3121 tp
->t_maxopd
= tp
->t_maxseg
=
3123 isipv6
? tcp_v6mssdflt
:
3130 * Slower link window correction:
3131 * If a value is specificied for slowlink_wsize use it for PPP links
3132 * believed to be on a serial modem (speed <128Kbps). Excludes 9600bps as
3133 * it is the default value adversized by pseudo-devices over ppp.
3135 if (ifp
->if_type
== IFT_PPP
&& slowlink_wsize
> 0 &&
3136 ifp
->if_baudrate
> 9600 && ifp
->if_baudrate
<= 128000) {
3137 tp
->t_flags
|= TF_SLOWLINK
;
3139 so
= inp
->inp_socket
;
3141 taop
= rmx_taop(rt
->rt_rmx
);
3143 * Offer == -1 means that we didn't receive SYN yet,
3144 * use cached value in that case;
3147 offer
= taop
->tao_mssopt
;
3149 * Offer == 0 means that there was no MSS on the SYN segment,
3150 * in this case we use tcp_mssdflt.
3155 isipv6
? tcp_v6mssdflt
:
3160 * Prevent DoS attack with too small MSS. Round up
3161 * to at least minmss.
3163 offer
= max(offer
, tcp_minmss
);
3165 * Sanity check: make sure that maxopd will be large
3166 * enough to allow some data on segments even is the
3167 * all the option space is used (40bytes). Otherwise
3168 * funny things may happen in tcp_output.
3170 offer
= max(offer
, 64);
3172 taop
->tao_mssopt
= offer
;
3175 * While we're here, check if there's an initial rtt
3176 * or rttvar. Convert from the route-table units
3177 * to scaled multiples of the slow timeout timer.
3179 if (tp
->t_srtt
== 0 && (rtt
= rt
->rt_rmx
.rmx_rtt
)) {
3181 * XXX the lock bit for RTT indicates that the value
3182 * is also a minimum value; this is subject to time.
3184 if (rt
->rt_rmx
.rmx_locks
& RTV_RTT
)
3185 tp
->t_rttmin
= rtt
/ (RTM_RTTUNIT
/ PR_SLOWHZ
);
3186 tp
->t_srtt
= rtt
/ (RTM_RTTUNIT
/ (PR_SLOWHZ
* TCP_RTT_SCALE
));
3187 tcpstat
.tcps_usedrtt
++;
3188 if (rt
->rt_rmx
.rmx_rttvar
) {
3189 tp
->t_rttvar
= rt
->rt_rmx
.rmx_rttvar
/
3190 (RTM_RTTUNIT
/ (PR_SLOWHZ
* TCP_RTTVAR_SCALE
));
3191 tcpstat
.tcps_usedrttvar
++;
3193 /* default variation is +- 1 rtt */
3195 tp
->t_srtt
* TCP_RTTVAR_SCALE
/ TCP_RTT_SCALE
;
3197 TCPT_RANGESET(tp
->t_rxtcur
,
3198 ((tp
->t_srtt
>> 2) + tp
->t_rttvar
) >> 1,
3199 tp
->t_rttmin
, TCPTV_REXMTMAX
);
3202 * if there's an mtu associated with the route, use it
3203 * else, use the link mtu.
3205 if (rt
->rt_rmx
.rmx_mtu
)
3206 mss
= rt
->rt_rmx
.rmx_mtu
- min_protoh
;
3211 (isipv6
? nd_ifinfo
[rt
->rt_ifp
->if_index
].linkmtu
:
3220 if (!in6_localaddr(&inp
->in6p_faddr
))
3221 mss
= min(mss
, tcp_v6mssdflt
);
3224 if (!in_localaddr(inp
->inp_faddr
))
3225 mss
= min(mss
, tcp_mssdflt
);
3227 mss
= min(mss
, offer
);
3229 * maxopd stores the maximum length of data AND options
3230 * in a segment; maxseg is the amount of data in a normal
3231 * segment. We need to store this value (maxopd) apart
3232 * from maxseg, because now every segment carries options
3233 * and thus we normally have somewhat less data in segments.
3238 * In case of T/TCP, origoffer==-1 indicates, that no segments
3239 * were received yet. In this case we just guess, otherwise
3240 * we do the same as before T/TCP.
3242 if ((tp
->t_flags
& (TF_REQ_TSTMP
|TF_NOOPT
)) == TF_REQ_TSTMP
&&
3244 (tp
->t_flags
& TF_RCVD_TSTMP
) == TF_RCVD_TSTMP
))
3245 mss
-= TCPOLEN_TSTAMP_APPA
;
3246 if ((tp
->t_flags
& (TF_REQ_CC
|TF_NOOPT
)) == TF_REQ_CC
&&
3248 (tp
->t_flags
& TF_RCVD_CC
) == TF_RCVD_CC
))
3249 mss
-= TCPOLEN_CC_APPA
;
3252 * If there's a pipesize (ie loopback), change the socket
3253 * buffer to that size only if it's bigger than the current
3254 * sockbuf size. Make the socket buffers an integral
3255 * number of mss units; if the mss is larger than
3256 * the socket buffer, decrease the mss.
3259 bufsize
= rt
->rt_rmx
.rmx_sendpipe
;
3260 if (bufsize
< so
->so_snd
.sb_hiwat
)
3262 bufsize
= so
->so_snd
.sb_hiwat
;
3266 bufsize
= roundup(bufsize
, mss
);
3267 if (bufsize
> sb_max
)
3269 (void)sbreserve(&so
->so_snd
, bufsize
);
3274 bufsize
= rt
->rt_rmx
.rmx_recvpipe
;
3275 if (bufsize
< so
->so_rcv
.sb_hiwat
)
3277 bufsize
= so
->so_rcv
.sb_hiwat
;
3278 if (bufsize
> mss
) {
3279 bufsize
= roundup(bufsize
, mss
);
3280 if (bufsize
> sb_max
)
3282 (void)sbreserve(&so
->so_rcv
, bufsize
);
3286 * Set the slow-start flight size depending on whether this
3287 * is a local network or not.
3291 (isipv6
&& in6_localaddr(&inp
->in6p_faddr
)) ||
3294 in_localaddr(inp
->inp_faddr
)
3299 tp
->snd_cwnd
= mss
* ss_fltsz_local
;
3301 tp
->snd_cwnd
= mss
* ss_fltsz
;
3303 if (rt
->rt_rmx
.rmx_ssthresh
) {
3305 * There's some sort of gateway or interface
3306 * buffer limit on the path. Use this to set
3307 * the slow start threshhold, but set the
3308 * threshold to no less than 2*mss.
3310 tp
->snd_ssthresh
= max(2 * mss
, rt
->rt_rmx
.rmx_ssthresh
);
3311 tcpstat
.tcps_usedssthresh
++;
3316 * Determine the MSS option to send on an outgoing SYN.
3329 isipv6
= ((tp
->t_inpcb
->inp_vflag
& INP_IPV6
) != 0) ? 1 : 0;
3330 min_protoh
= isipv6
? sizeof (struct ip6_hdr
) + sizeof (struct tcphdr
)
3331 : sizeof (struct tcpiphdr
);
3333 #define min_protoh (sizeof (struct tcpiphdr))
3337 rt
= tcp_rtlookup6(tp
->t_inpcb
);
3340 rt
= tcp_rtlookup(tp
->t_inpcb
);
3344 isipv6
? tcp_v6mssdflt
:
3348 * Slower link window correction:
3349 * If a value is specificied for slowlink_wsize use it for PPP links
3350 * believed to be on a serial modem (speed <128Kbps). Excludes 9600bps as
3351 * it is the default value adversized by pseudo-devices over ppp.
3353 if (rt
->rt_ifp
->if_type
== IFT_PPP
&& slowlink_wsize
> 0 &&
3354 rt
->rt_ifp
->if_baudrate
> 9600 && rt
->rt_ifp
->if_baudrate
<= 128000) {
3355 tp
->t_flags
|= TF_SLOWLINK
;
3358 return rt
->rt_ifp
->if_mtu
- min_protoh
;
3363 * Checks for partial ack. If partial ack arrives, force the retransmission
3364 * of the next unacknowledged segment, do not clear tp->t_dupacks, and return
3365 * 1. By setting snd_nxt to ti_ack, this forces retransmission timer to
3366 * be started again. If the ack advances at least to tp->snd_recover, return 0.
3373 if (SEQ_LT(th
->th_ack
, tp
->snd_recover
)) {
3374 tcp_seq onxt
= tp
->snd_nxt
;
3375 u_long ocwnd
= tp
->snd_cwnd
;
3377 tp
->t_timer
[TCPT_REXMT
] = 0;
3379 callout_stop(tp
->tt_rexmt
);
3382 tp
->snd_nxt
= th
->th_ack
;
3384 * Set snd_cwnd to one segment beyond acknowledged offset
3385 * (tp->snd_una has not yet been updated when this function
3388 tp
->snd_cwnd
= tp
->t_maxseg
+ (th
->th_ack
- tp
->snd_una
);
3389 tp
->t_flags
|= TF_ACKNOW
;
3390 (void) tcp_output(tp
);
3391 tp
->snd_cwnd
= ocwnd
;
3392 if (SEQ_GT(onxt
, tp
->snd_nxt
))
3395 * Partial window deflation. Relies on fact that tp->snd_una
3398 tp
->snd_cwnd
-= (th
->th_ack
- tp
->snd_una
- tp
->t_maxseg
);
3405 * Drop a random TCP connection that hasn't been serviced yet and
3406 * is eligible for discard. There is a one in qlen chance that
3407 * we will return a null, saying that there are no dropable
3408 * requests. In this case, the protocol specific code should drop
3409 * the new request. This insures fairness.
3411 * The listening TCP socket "head" must be locked
3414 tcpdropdropablreq(struct socket
*head
)
3417 unsigned int i
, j
, qlen
;
3419 static struct timeval old_runtime
;
3420 static unsigned int cur_cnt
, old_cnt
;
3422 struct inpcb
*inp
= NULL
;
3425 if ((i
= (tv
.tv_sec
- old_runtime
.tv_sec
)) != 0) {
3427 old_cnt
= cur_cnt
/ i
;
3431 so
= TAILQ_FIRST(&head
->so_incomp
);
3435 qlen
= head
->so_incqlen
;
3436 if (++cur_cnt
> qlen
|| old_cnt
> qlen
) {
3437 rnd
= (314159 * rnd
+ 66329) & 0xffff;
3438 j
= ((qlen
+ 1) * rnd
) >> 16;
3441 so
= TAILQ_NEXT(so
, so_list
);
3443 /* Find a connection that is not already closing */
3445 inp
= (struct inpcb
*)so
->so_pcb
;
3447 if (in_pcb_checkstate(inp
, WNT_ACQUIRE
, 0) != WNT_STOPUSING
)
3450 so
= TAILQ_NEXT(so
, so_list
);
3455 /* Let's remove this connection from the incomplete list */
3458 if (in_pcb_checkstate(inp
, WNT_RELEASE
, 1) == WNT_STOPUSING
) {
3459 tcp_unlock(so
, 1, 0);
3462 sototcpcb(so
)->t_flags
|= TF_LQ_OVERFLOW
;
3466 TAILQ_REMOVE(&head
->so_incomp
, so
, so_list
);
3467 so
->so_usecount
--; /* No more held by so_head */
3469 tcp_drop(sototcpcb(so
), ETIMEDOUT
);
3471 tcp_unlock(so
, 1, 0);