2 * Copyright (c) 2002-2003 Jeffrey Hsu
3 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
4 * The Regents of the University of California. All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * 3. All advertising materials mentioning features or use of this software
15 * must display the following acknowledgement:
16 * This product includes software developed by the University of
17 * California, Berkeley and its contributors.
18 * 4. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
35 * $FreeBSD: src/sys/netinet/tcp_input.c,v 1.107.2.38 2003/05/21 04:46:41 cjc Exp $
36 * $DragonFly: src/sys/netinet/tcp_input.c,v 1.15 2004/03/02 20:41:13 rob Exp $
39 #include "opt_ipfw.h" /* for ipfw_fwd */
40 #include "opt_inet6.h"
41 #include "opt_ipsec.h"
42 #include "opt_tcpdebug.h"
43 #include "opt_tcp_input.h"
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/kernel.h>
48 #include <sys/sysctl.h>
49 #include <sys/malloc.h>
51 #include <sys/proc.h> /* for proc0 declaration */
52 #include <sys/protosw.h>
53 #include <sys/socket.h>
54 #include <sys/socketvar.h>
55 #include <sys/syslog.h>
56 #include <sys/in_cksum.h>
58 #include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
61 #include <net/route.h>
63 #include <netinet/in.h>
64 #include <netinet/in_systm.h>
65 #include <netinet/ip.h>
66 #include <netinet/ip_icmp.h> /* for ICMP_BANDLIM */
67 #include <netinet/in_var.h>
68 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
69 #include <netinet/in_pcb.h>
70 #include <netinet/ip_var.h>
71 #include <netinet/ip6.h>
72 #include <netinet/icmp6.h>
73 #include <netinet6/nd6.h>
74 #include <netinet6/ip6_var.h>
75 #include <netinet6/in6_pcb.h>
76 #include <netinet/tcp.h>
77 #include <netinet/tcp_fsm.h>
78 #include <netinet/tcp_seq.h>
79 #include <netinet/tcp_timer.h>
80 #include <netinet/tcp_var.h>
81 #include <netinet6/tcp6_var.h>
82 #include <netinet/tcpip.h>
84 #include <netinet/tcp_debug.h>
86 u_char tcp_saveipgen[40]; /* the size must be of max ip header, now IPv6 */
87 struct tcphdr tcp_savetcp;
91 #include <netipsec/ipsec.h>
92 #include <netipsec/ipsec6.h>
96 #include <netinet6/ipsec.h>
97 #include <netinet6/ipsec6.h>
98 #include <netproto/key/key.h>
101 MALLOC_DEFINE(M_TSEGQ, "tseg_qent", "TCP segment queue entry");
103 static const int tcprexmtthresh = 3;
106 struct tcpstat tcpstat;
107 SYSCTL_STRUCT(_net_inet_tcp, TCPCTL_STATS, stats, CTLFLAG_RW,
108 &tcpstat , tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
110 static int log_in_vain = 0;
111 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
112 &log_in_vain, 0, "Log all incoming TCP connections");
114 static int blackhole = 0;
115 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
116 &blackhole, 0, "Do not send RST when dropping refused connections");
118 int tcp_delack_enabled = 1;
119 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
120 &tcp_delack_enabled, 0,
121 "Delay ACK to try and piggyback it onto a data packet");
123 #ifdef TCP_DROP_SYNFIN
124 static int drop_synfin = 0;
125 SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
126 &drop_synfin, 0, "Drop TCP packets with SYN+FIN set");
129 static int tcp_do_limitedtransmit = 1;
130 SYSCTL_INT(_net_inet_tcp, OID_AUTO, limitedtransmit, CTLFLAG_RW,
131 &tcp_do_limitedtransmit, 0, "Enable RFC 3042 (Limited Transmit)");
133 static int tcp_do_rfc3390 = 1;
134 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_RW,
136 "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
138 static int tcp_do_eifel_detect = 1;
139 SYSCTL_INT(_net_inet_tcp, OID_AUTO, eifel, CTLFLAG_RW,
140 &tcp_do_eifel_detect, 0, "Eifel detection algorithm (RFC 3522)");
142 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, reass, CTLFLAG_RW, 0,
143 "TCP Segment Reassembly Queue");
145 int tcp_reass_maxseg = 0;
146 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxsegments, CTLFLAG_RD,
147 &tcp_reass_maxseg, 0,
148 "Global maximum number of TCP Segments in Reassembly Queue");
150 int tcp_reass_qsize = 0;
151 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, cursegments, CTLFLAG_RD,
153 "Global number of TCP Segments currently in Reassembly Queue");
155 static int tcp_reass_overflows = 0;
156 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, overflows, CTLFLAG_RD,
157 &tcp_reass_overflows, 0,
158 "Global number of TCP Segment Reassembly Queue Overflows");
160 struct inpcbhead tcb;
161 #define tcb6 tcb /* for KAME src sync over BSD*'s */
162 struct inpcbinfo tcbinfo;
164 static void tcp_dooptions(struct tcpopt *, u_char *, int, int);
165 static void tcp_pulloutofband(struct socket *,
166 struct tcphdr *, struct mbuf *, int);
167 static int tcp_reass(struct tcpcb *, struct tcphdr *, int *,
169 static void tcp_xmit_timer(struct tcpcb *, int);
170 static void tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
172 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
174 #define ND6_HINT(tp) \
176 if ((tp) && (tp)->t_inpcb && \
177 ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0 && \
178 (tp)->t_inpcb->in6p_route.ro_rt) \
179 nd6_nud_hint((tp)->t_inpcb->in6p_route.ro_rt, NULL, 0); \
186 * Indicate whether this ack should be delayed. We can delay the ack if
187 * - delayed acks are enabled and
188 * - there is no delayed ack timer in progress and
189 * - our last ack wasn't a 0-sized window. We never want to delay
190 * the ack that opens up a 0-sized window.
192 #define DELAY_ACK(tp) \
193 (tcp_delack_enabled && !callout_pending(tp->tt_delack) && \
194 (tp->t_flags & TF_RXWIN0SENT) == 0)
197 tcp_reass(tp, th, tlenp, m)
204 struct tseg_qent *p = NULL;
205 struct tseg_qent *nq;
206 struct tseg_qent *te;
207 struct socket *so = tp->t_inpcb->inp_socket;
211 * Call with th==0 after become established to
212 * force pre-ESTABLISHED data up to user socket.
218 * Limit the number of segments in the reassembly queue to prevent
219 * holding on to too many segments (and thus running out of mbufs).
220 * Make sure to let the missing segment through which caused this
221 * queue. Always keep one global queue entry spare to be able to
222 * process the missing segment.
224 if (th->th_seq != tp->rcv_nxt &&
225 tcp_reass_qsize + 1 >= tcp_reass_maxseg) {
226 tcp_reass_overflows++;
227 tcpstat.tcps_rcvmemdrop++;
232 /* Allocate a new queue entry. If we can't, just drop the pkt. XXX */
233 MALLOC(te, struct tseg_qent *, sizeof(struct tseg_qent), M_TSEGQ,
236 tcpstat.tcps_rcvmemdrop++;
243 * Find a segment which begins after this one does.
245 LIST_FOREACH(q, &tp->t_segq, tqe_q) {
246 if (SEQ_GT(q->tqe_th->th_seq, th->th_seq))
252 * If there is a preceding segment, it may provide some of
253 * our data already. If so, drop the data from the incoming
254 * segment. If it provides all of our data, drop us.
258 /* conversion to int (in i) handles seq wraparound */
259 i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
262 tcpstat.tcps_rcvduppack++;
263 tcpstat.tcps_rcvdupbyte += *tlenp;
268 * Try to present any queued data
269 * at the left window edge to the user.
270 * This is needed after the 3-WHS
273 goto present; /* ??? */
280 tcpstat.tcps_rcvoopack++;
281 tcpstat.tcps_rcvoobyte += *tlenp;
284 * While we overlap succeeding segments trim them or,
285 * if they are completely covered, dequeue them.
288 int i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
291 if (i < q->tqe_len) {
292 q->tqe_th->th_seq += i;
298 nq = LIST_NEXT(q, tqe_q);
299 LIST_REMOVE(q, tqe_q);
306 /* Insert the new segment queue entry into place. */
309 te->tqe_len = *tlenp;
312 LIST_INSERT_HEAD(&tp->t_segq, te, tqe_q);
314 LIST_INSERT_AFTER(p, te, tqe_q);
319 * Present data to user, advancing rcv_nxt through
320 * completed sequence space.
322 if (!TCPS_HAVEESTABLISHED(tp->t_state))
324 q = LIST_FIRST(&tp->t_segq);
325 if (!q || q->tqe_th->th_seq != tp->rcv_nxt)
328 tp->rcv_nxt += q->tqe_len;
329 flags = q->tqe_th->th_flags & TH_FIN;
330 nq = LIST_NEXT(q, tqe_q);
331 LIST_REMOVE(q, tqe_q);
332 if (so->so_state & SS_CANTRCVMORE)
335 sbappend(&so->so_rcv, q->tqe_m);
339 } while (q && q->tqe_th->th_seq == tp->rcv_nxt);
346 * TCP input routine, follows pages 65-76 of the
347 * protocol specification dated September, 1981 very closely.
351 tcp6_input(mp, offp, proto)
355 struct mbuf *m = *mp;
356 struct in6_ifaddr *ia6;
358 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
361 * draft-itojun-ipv6-tcp-to-anycast
362 * better place to put this in?
364 ia6 = ip6_getdstifaddr(m);
365 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
368 ip6 = mtod(m, struct ip6_hdr *);
369 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
370 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
374 tcp_input(m, *offp, proto);
380 tcp_input(m, off0, proto)
385 struct ip *ip = NULL;
387 struct inpcb *inp = NULL;
392 struct tcpcb *tp = NULL;
394 struct socket *so = 0;
395 int todrop, acked, ourfinisacked, needoutput = 0;
397 struct tcpopt to; /* options in this segment */
398 struct rmxp_tao *taop; /* pointer to our TAO cache entry */
399 struct rmxp_tao tao_noncached; /* in case there's no cached entry */
400 struct sockaddr_in *next_hop = NULL;
401 int rstreason; /* For badport_bandlim accounting purposes */
402 struct ip6_hdr *ip6 = NULL;
406 const int isipv6 = 0;
412 /* Grab info from MT_TAG mbufs prepended to the chain. */
413 for (;m && m->m_type == MT_TAG; m = m->m_next) {
414 if (m->_m_tag_id == PACKET_TAG_IPFORWARD)
415 next_hop = (struct sockaddr_in *)m->m_hdr.mh_data;
418 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
420 bzero((char *)&to, sizeof(to));
422 tcpstat.tcps_rcvtotal++;
425 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
426 ip6 = mtod(m, struct ip6_hdr *);
427 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
428 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
429 tcpstat.tcps_rcvbadsum++;
432 th = (struct tcphdr *)((caddr_t)ip6 + off0);
435 * Be proactive about unspecified IPv6 address in source.
436 * As we use all-zero to indicate unbounded/unconnected pcb,
437 * unspecified IPv6 address can be used to confuse us.
439 * Note that packets with unspecified IPv6 destination is
440 * already dropped in ip6_input.
442 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
448 * Get IP and TCP header together in first mbuf.
449 * Note: IP leaves IP header in first mbuf.
451 if (off0 > sizeof(struct ip)) {
452 ip_stripoptions(m, (struct mbuf *)0);
453 off0 = sizeof(struct ip);
455 if (m->m_len < sizeof(struct tcpiphdr)) {
456 if ((m = m_pullup(m, sizeof(struct tcpiphdr))) == 0) {
457 tcpstat.tcps_rcvshort++;
461 ip = mtod(m, struct ip *);
462 ipov = (struct ipovly *)ip;
463 th = (struct tcphdr *)((caddr_t)ip + off0);
466 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
467 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
468 th->th_sum = m->m_pkthdr.csum_data;
470 th->th_sum = in_pseudo(ip->ip_src.s_addr,
472 htonl(m->m_pkthdr.csum_data +
475 th->th_sum ^= 0xffff;
478 * Checksum extended TCP header and data.
480 len = sizeof(struct ip) + tlen;
481 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
482 ipov->ih_len = (u_short)tlen;
483 ipov->ih_len = htons(ipov->ih_len);
484 th->th_sum = in_cksum(m, len);
487 tcpstat.tcps_rcvbadsum++;
491 /* Re-initialization for later version check */
492 ip->ip_v = IPVERSION;
497 * Check that TCP offset makes sense,
498 * pull out TCP options and adjust length. XXX
500 off = th->th_off << 2;
501 if (off < sizeof(struct tcphdr) || off > tlen) {
502 tcpstat.tcps_rcvbadoff++;
505 tlen -= off; /* tlen is used instead of ti->ti_len */
506 if (off > sizeof(struct tcphdr)) {
508 IP6_EXTHDR_CHECK(m, off0, off, );
509 ip6 = mtod(m, struct ip6_hdr *);
510 th = (struct tcphdr *)((caddr_t)ip6 + off0);
512 if (m->m_len < sizeof(struct ip) + off) {
513 if ((m = m_pullup(m, sizeof(struct ip) + off))
515 tcpstat.tcps_rcvshort++;
518 ip = mtod(m, struct ip *);
519 ipov = (struct ipovly *)ip;
520 th = (struct tcphdr *)((caddr_t)ip + off0);
523 optlen = off - sizeof(struct tcphdr);
524 optp = (u_char *)(th + 1);
526 thflags = th->th_flags;
528 #ifdef TCP_DROP_SYNFIN
530 * If the drop_synfin option is enabled, drop all packets with
531 * both the SYN and FIN bits set. This prevents e.g. nmap from
532 * identifying the TCP/IP stack.
534 * This is a violation of the TCP specification.
536 if (drop_synfin && (thflags & (TH_SYN|TH_FIN)) == (TH_SYN|TH_FIN))
541 * Convert TCP protocol specific fields to host format.
543 th->th_seq = ntohl(th->th_seq);
544 th->th_ack = ntohl(th->th_ack);
545 th->th_win = ntohs(th->th_win);
546 th->th_urp = ntohs(th->th_urp);
549 * Delay droping TCP, IP headers, IPv6 ext headers, and TCP options,
550 * until after ip6_savecontrol() is called and before other functions
551 * which don't want those proto headers.
552 * Because ip6_savecontrol() is going to parse the mbuf to
553 * search for data to be passed up to user-land, it wants mbuf
554 * parameters to be unchanged.
555 * XXX: the call of ip6_savecontrol() has been obsoleted based on
556 * latest version of the advanced API (20020110).
558 drop_hdrlen = off0 + off;
561 * Locate pcb for segment.
564 /* IPFIREWALL_FORWARD section */
565 if (next_hop != NULL && isipv6 == 0) { /* IPv6 support is not yet */
567 * Transparently forwarded. Pretend to be the destination.
568 * already got one like this?
570 inp = in_pcblookup_hash(&tcbinfo, ip->ip_src, th->th_sport,
571 ip->ip_dst, th->th_dport,
572 0, m->m_pkthdr.rcvif);
574 /* It's new. Try find the ambushing socket. */
575 inp = in_pcblookup_hash(&tcbinfo,
576 ip->ip_src, th->th_sport,
579 ntohs(next_hop->sin_port) :
581 1, m->m_pkthdr.rcvif);
585 inp = in6_pcblookup_hash(&tcbinfo,
586 &ip6->ip6_src, th->th_sport,
587 &ip6->ip6_dst, th->th_dport,
588 1, m->m_pkthdr.rcvif);
590 inp = in_pcblookup_hash(&tcbinfo,
591 ip->ip_src, th->th_sport,
592 ip->ip_dst, th->th_dport,
593 1, m->m_pkthdr.rcvif);
598 if (inp != NULL && ipsec6_in_reject_so(m, inp->inp_socket)) {
599 ipsec6stat.in_polvio++;
603 if (inp != NULL && ipsec4_in_reject_so(m, inp->inp_socket)) {
604 ipsecstat.in_polvio++;
611 if (inp != NULL && ipsec6_in_reject(m, inp)) {
615 if (inp != NULL && ipsec4_in_reject(m, inp)) {
622 * If the state is CLOSED (i.e., TCB does not exist) then
623 * all data in the incoming segment is discarded.
624 * If the TCB exists but is in CLOSED state, it is embryonic,
625 * but should either do a listen or a connect soon.
630 char dbuf[INET6_ADDRSTRLEN+2], sbuf[INET6_ADDRSTRLEN+2];
632 char dbuf[4*sizeof "123"], sbuf[4*sizeof "123"];
637 strcat(dbuf, ip6_sprintf(&ip6->ip6_dst));
638 strcat(sbuf, ip6_sprintf(&ip6->ip6_src));
642 strcpy(dbuf, inet_ntoa(ip->ip_dst));
643 strcpy(sbuf, inet_ntoa(ip->ip_src));
645 switch (log_in_vain) {
647 if ((thflags & TH_SYN) == 0)
651 "Connection attempt to TCP %s:%d "
652 "from %s:%d flags:0x%02x\n",
653 dbuf, ntohs(th->th_dport), sbuf,
654 ntohs(th->th_sport), thflags);
663 if (thflags & TH_SYN)
672 rstreason = BANDLIM_RST_CLOSEDPORT;
677 rstreason = BANDLIM_RST_CLOSEDPORT;
680 if (tp->t_state == TCPS_CLOSED)
683 /* Unscale the window into a 32-bit value. */
684 if ((thflags & TH_SYN) == 0)
685 tiwin = th->th_win << tp->snd_scale;
689 so = inp->inp_socket;
692 if (so->so_options & SO_DEBUG) {
693 ostate = tp->t_state;
695 bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
697 bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
702 if (so->so_options & SO_ACCEPTCONN) {
703 struct in_conninfo inc;
706 inc.inc_isipv6 = isipv6;
709 inc.inc6_faddr = ip6->ip6_src;
710 inc.inc6_laddr = ip6->ip6_dst;
711 inc.inc6_route.ro_rt = NULL; /* XXX */
713 inc.inc_faddr = ip->ip_src;
714 inc.inc_laddr = ip->ip_dst;
715 inc.inc_route.ro_rt = NULL; /* XXX */
717 inc.inc_fport = th->th_sport;
718 inc.inc_lport = th->th_dport;
721 * If the state is LISTEN then ignore segment if it contains
722 * a RST. If the segment contains an ACK then it is bad and
723 * send a RST. If it does not contain a SYN then it is not
724 * interesting; drop it.
726 * If the state is SYN_RECEIVED (syncache) and seg contains
727 * an ACK, but not for our SYN/ACK, send a RST. If the seg
728 * contains a RST, check the sequence number to see if it
729 * is a valid reset segment.
731 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
732 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
733 if (!syncache_expand(&inc, th, &so, m)) {
735 * No syncache entry, or ACK was not
736 * for our SYN/ACK. Send a RST.
738 tcpstat.tcps_badsyn++;
739 rstreason = BANDLIM_RST_OPENPORT;
744 * Could not complete 3-way handshake,
745 * connection is being closed down, and
746 * syncache will free mbuf.
750 * Socket is created in state SYN_RECEIVED.
751 * Continue processing segment.
756 * This is what would have happened in
757 * tcp_output() when the SYN,ACK was sent.
759 tp->snd_up = tp->snd_una;
760 tp->snd_max = tp->snd_nxt = tp->iss + 1;
761 tp->last_ack_sent = tp->rcv_nxt;
763 * XXX possible bug - it doesn't appear that tp->snd_wnd is unscaled
764 * until the _second_ ACK is received:
765 * rcv SYN (set wscale opts) --> send SYN/ACK, set snd_wnd = window.
766 * rcv ACK, calculate tiwin --> process SYN_RECEIVED, determine wscale,
767 * move to ESTAB, set snd_wnd to tiwin.
769 tp->snd_wnd = tiwin; /* unscaled */
772 if (thflags & TH_RST) {
773 syncache_chkrst(&inc, th);
776 if (thflags & TH_ACK) {
777 syncache_badack(&inc);
778 tcpstat.tcps_badsyn++;
779 rstreason = BANDLIM_RST_OPENPORT;
786 * Segment's flags are (SYN) or (SYN|FIN).
790 * If deprecated address is forbidden,
791 * we do not accept SYN to deprecated interface
792 * address to prevent any new inbound connection from
793 * getting established.
794 * When we do not accept SYN, we send a TCP RST,
795 * with deprecated source address (instead of dropping
796 * it). We compromise it as it is much better for peer
797 * to send a RST, and RST will be the final packet
800 * If we do not forbid deprecated addresses, we accept
801 * the SYN packet. RFC2462 does not suggest dropping
803 * If we decipher RFC2462 5.5.4, it says like this:
804 * 1. use of deprecated addr with existing
805 * communication is okay - "SHOULD continue to be
807 * 2. use of it with new communication:
808 * (2a) "SHOULD NOT be used if alternate address
809 * with sufficient scope is available"
810 * (2b) nothing mentioned otherwise.
811 * Here we fall into (2b) case as we have no choice in
812 * our source address selection - we must obey the peer.
814 * The wording in RFC2462 is confusing, and there are
815 * multiple description text for deprecated address
816 * handling - worse, they are not exactly the same.
817 * I believe 5.5.4 is the best one, so we follow 5.5.4.
819 if (isipv6 && !ip6_use_deprecated) {
820 struct in6_ifaddr *ia6;
822 if ((ia6 = ip6_getdstifaddr(m)) &&
823 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
825 rstreason = BANDLIM_RST_OPENPORT;
831 * If it is from this socket, drop it, it must be forged.
832 * Don't bother responding if the destination was a broadcast.
834 if (th->th_dport == th->th_sport) {
836 if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
840 if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
845 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
847 * Note that it is quite possible to receive unicast
848 * link-layer packets with a broadcast IP address. Use
849 * in_broadcast() to find them.
851 if (m->m_flags & (M_BCAST|M_MCAST))
854 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
855 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
858 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
859 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
860 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
861 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
865 * SYN appears to be valid; create compressed TCP state
866 * for syncache, or perform t/tcp connection.
868 if (so->so_qlen <= so->so_qlimit) {
869 tcp_dooptions(&to, optp, optlen, 1);
870 if (!syncache_add(&inc, &to, th, &so, m))
874 * Entry added to syncache, mbuf used to
875 * send SYN,ACK packet.
879 * Segment passed TAO tests.
884 tp->t_starttime = ticks;
885 tp->t_state = TCPS_ESTABLISHED;
888 * If there is a FIN, or if there is data and the
889 * connection is local, then delay SYN,ACK(SYN) in
890 * the hope of piggy-backing it on a response
891 * segment. Otherwise must send ACK now in case
892 * the other side is slow starting.
895 ((thflags & TH_FIN) ||
897 ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
898 (!isipv6 && in_localaddr(inp->inp_faddr)))))) {
899 callout_reset(tp->tt_delack, tcp_delacktime,
900 tcp_timer_delack, tp);
901 tp->t_flags |= TF_NEEDSYN;
903 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
905 tcpstat.tcps_connects++;
913 /* XXX temp debugging */
914 /* should not happen - syncache should pick up these connections */
915 if (tp->t_state == TCPS_LISTEN)
916 panic("tcp_input: TCPS_LISTEN");
919 * Segment received on connection.
920 * Reset idle time and keep-alive timer.
922 tp->t_rcvtime = ticks;
923 if (TCPS_HAVEESTABLISHED(tp->t_state))
924 callout_reset(tp->tt_keep, tcp_keepidle, tcp_timer_keep, tp);
928 * XXX this is tradtitional behavior, may need to be cleaned up.
930 tcp_dooptions(&to, optp, optlen, thflags & TH_SYN);
931 if (thflags & TH_SYN) {
932 if (to.to_flags & TOF_SCALE) {
933 tp->t_flags |= TF_RCVD_SCALE;
934 tp->requested_s_scale = to.to_requested_s_scale;
936 if (to.to_flags & TOF_TS) {
937 tp->t_flags |= TF_RCVD_TSTMP;
938 tp->ts_recent = to.to_tsval;
939 tp->ts_recent_age = ticks;
941 if (to.to_flags & (TOF_CC|TOF_CCNEW))
942 tp->t_flags |= TF_RCVD_CC;
943 if (to.to_flags & TOF_MSS)
944 tcp_mss(tp, to.to_mss);
948 * Header prediction: check for the two common cases
949 * of a uni-directional data xfer. If the packet has
950 * no control flags, is in-sequence, the window didn't
951 * change and we're not retransmitting, it's a
952 * candidate. If the length is zero and the ack moved
953 * forward, we're the sender side of the xfer. Just
954 * free the data acked & wake any higher level process
955 * that was blocked waiting for space. If the length
956 * is non-zero and the ack didn't move, we're the
957 * receiver side. If we're getting packets in-order
958 * (the reassembly queue is empty), add the data to
959 * the socket buffer and note that we need a delayed ack.
960 * Make sure that the hidden state-flags are also off.
961 * Since we check for TCPS_ESTABLISHED above, it can only
964 if (tp->t_state == TCPS_ESTABLISHED &&
965 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
966 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
967 ((to.to_flags & TOF_TS) == 0 ||
968 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
970 * Using the CC option is compulsory if once started:
971 * the segment is OK if no T/TCP was negotiated or
972 * if the segment has a CC option equal to CCrecv
974 ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) != (TF_REQ_CC|TF_RCVD_CC) ||
975 ((to.to_flags & TOF_CC) != 0 && to.to_cc == tp->cc_recv)) &&
976 th->th_seq == tp->rcv_nxt &&
977 tiwin && tiwin == tp->snd_wnd &&
978 tp->snd_nxt == tp->snd_max) {
981 * If last ACK falls within this segment's sequence numbers,
982 * record the timestamp.
983 * NOTE that the test is modified according to the latest
984 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
986 if ((to.to_flags & TOF_TS) != 0 &&
987 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
988 tp->ts_recent_age = ticks;
989 tp->ts_recent = to.to_tsval;
993 if (SEQ_GT(th->th_ack, tp->snd_una) &&
994 SEQ_LEQ(th->th_ack, tp->snd_max) &&
995 tp->snd_cwnd >= tp->snd_wnd &&
997 tp->t_dupacks < tcprexmtthresh) ||
998 (tcp_do_newreno && !IN_FASTRECOVERY(tp)))) {
1000 * this is a pure ack for outstanding data.
1002 ++tcpstat.tcps_predack;
1004 * "bad retransmit" recovery
1006 * If Eifel detection applies, then
1007 * it is deterministic, so use it
1008 * unconditionally over the old heuristic.
1009 * Otherwise, fall back to the old heuristic.
1011 if (tcp_do_eifel_detect &&
1012 (to.to_flags & TOF_TS) && to.to_tsecr &&
1013 (tp->t_flags & TF_FIRSTACCACK)) {
1014 /* Eifel detection applicable. */
1015 if (to.to_tsecr < tp->t_rexmtTS) {
1016 tcp_revert_congestion_state(tp);
1017 ++tcpstat.tcps_eifeldetected;
1019 } else if (tp->t_rxtshift == 1 &&
1020 ticks < tp->t_badrxtwin) {
1021 tcp_revert_congestion_state(tp);
1022 ++tcpstat.tcps_rttdetected;
1024 tp->t_flags &= ~(TF_FIRSTACCACK | TF_FASTREXMT);
1026 * Recalculate the retransmit timer / rtt.
1028 * Some machines (certain windows boxes)
1029 * send broken timestamp replies during the
1030 * SYN+ACK phase, ignore timestamps of 0.
1032 if ((to.to_flags & TOF_TS) != 0 &&
1035 ticks - to.to_tsecr + 1);
1036 } else if (tp->t_rtttime &&
1037 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1039 ticks - tp->t_rtttime);
1041 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1042 acked = th->th_ack - tp->snd_una;
1043 tcpstat.tcps_rcvackpack++;
1044 tcpstat.tcps_rcvackbyte += acked;
1045 sbdrop(&so->so_snd, acked);
1046 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1047 SEQ_LEQ(th->th_ack, tp->snd_recover))
1048 tp->snd_recover = th->th_ack - 1;
1049 tp->snd_una = th->th_ack;
1052 ND6_HINT(tp); /* some progress has been done */
1055 * If all outstanding data are acked, stop
1056 * retransmit timer, otherwise restart timer
1057 * using current (possibly backed-off) value.
1058 * If process is waiting for space,
1059 * wakeup/selwakeup/signal. If data
1060 * are ready to send, let tcp_output
1061 * decide between more output or persist.
1063 if (tp->snd_una == tp->snd_max)
1064 callout_stop(tp->tt_rexmt);
1065 else if (!callout_active(tp->tt_persist))
1066 callout_reset(tp->tt_rexmt,
1068 tcp_timer_rexmt, tp);
1071 if (so->so_snd.sb_cc)
1072 (void) tcp_output(tp);
1075 } else if (th->th_ack == tp->snd_una &&
1076 LIST_EMPTY(&tp->t_segq) &&
1077 tlen <= sbspace(&so->so_rcv)) {
1079 * this is a pure, in-sequence data packet
1080 * with nothing on the reassembly queue and
1081 * we have enough buffer space to take it.
1083 ++tcpstat.tcps_preddat;
1084 tp->rcv_nxt += tlen;
1085 tcpstat.tcps_rcvpack++;
1086 tcpstat.tcps_rcvbyte += tlen;
1087 ND6_HINT(tp); /* some progress has been done */
1089 * Add data to socket buffer.
1091 if (so->so_state & SS_CANTRCVMORE) {
1094 m_adj(m, drop_hdrlen); /* delayed header drop */
1095 sbappend(&so->so_rcv, m);
1098 if (DELAY_ACK(tp)) {
1099 callout_reset(tp->tt_delack, tcp_delacktime,
1100 tcp_timer_delack, tp);
1102 tp->t_flags |= TF_ACKNOW;
1110 * Calculate amount of space in receive window,
1111 * and then do TCP input processing.
1112 * Receive window is amount of space in rcv queue,
1113 * but not less than advertised window.
1117 win = sbspace(&so->so_rcv);
1120 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1123 switch (tp->t_state) {
1126 * If the state is SYN_RECEIVED:
1127 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1129 case TCPS_SYN_RECEIVED:
1130 if ((thflags & TH_ACK) &&
1131 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1132 SEQ_GT(th->th_ack, tp->snd_max))) {
1133 rstreason = BANDLIM_RST_OPENPORT;
1139 * If the state is SYN_SENT:
1140 * if seg contains an ACK, but not for our SYN, drop the input.
1141 * if seg contains a RST, then drop the connection.
1142 * if seg does not contain SYN, then drop it.
1143 * Otherwise this is an acceptable SYN segment
1144 * initialize tp->rcv_nxt and tp->irs
1145 * if seg contains ack then advance tp->snd_una
1146 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1147 * arrange for segment to be acked (eventually)
1148 * continue processing rest of data/controls, beginning with URG
1151 if ((taop = tcp_gettaocache(&inp->inp_inc)) == NULL) {
1152 taop = &tao_noncached;
1153 bzero(taop, sizeof(*taop));
1156 if ((thflags & TH_ACK) &&
1157 (SEQ_LEQ(th->th_ack, tp->iss) ||
1158 SEQ_GT(th->th_ack, tp->snd_max))) {
1160 * If we have a cached CCsent for the remote host,
1161 * hence we haven't just crashed and restarted,
1162 * do not send a RST. This may be a retransmission
1163 * from the other side after our earlier ACK was lost.
1164 * Our new SYN, when it arrives, will serve as the
1167 if (taop->tao_ccsent != 0)
1170 rstreason = BANDLIM_UNLIMITED;
1174 if (thflags & TH_RST) {
1175 if (thflags & TH_ACK)
1176 tp = tcp_drop(tp, ECONNREFUSED);
1179 if ((thflags & TH_SYN) == 0)
1181 tp->snd_wnd = th->th_win; /* initial send window */
1182 tp->cc_recv = to.to_cc; /* foreign CC */
1184 tp->irs = th->th_seq;
1186 if (thflags & TH_ACK) {
1188 * Our SYN was acked. If segment contains CC.ECHO
1189 * option, check it to make sure this segment really
1190 * matches our SYN. If not, just drop it as old
1191 * duplicate, but send an RST if we're still playing
1192 * by the old rules. If no CC.ECHO option, make sure
1193 * we don't get fooled into using T/TCP.
1195 if (to.to_flags & TOF_CCECHO) {
1196 if (tp->cc_send != to.to_ccecho) {
1197 if (taop->tao_ccsent != 0)
1200 rstreason = BANDLIM_UNLIMITED;
1205 tp->t_flags &= ~TF_RCVD_CC;
1206 tcpstat.tcps_connects++;
1208 /* Do window scaling on this connection? */
1209 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1210 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1211 tp->snd_scale = tp->requested_s_scale;
1212 tp->rcv_scale = tp->request_r_scale;
1214 /* Segment is acceptable, update cache if undefined. */
1215 if (taop->tao_ccsent == 0)
1216 taop->tao_ccsent = to.to_ccecho;
1218 tp->rcv_adv += tp->rcv_wnd;
1219 tp->snd_una++; /* SYN is acked */
1221 * If there's data, delay ACK; if there's also a FIN
1222 * ACKNOW will be turned on later.
1224 if (DELAY_ACK(tp) && tlen != 0)
1225 callout_reset(tp->tt_delack, tcp_delacktime,
1226 tcp_timer_delack, tp);
1228 tp->t_flags |= TF_ACKNOW;
1230 * Received <SYN,ACK> in SYN_SENT[*] state.
1232 * SYN_SENT --> ESTABLISHED
1233 * SYN_SENT* --> FIN_WAIT_1
1235 tp->t_starttime = ticks;
1236 if (tp->t_flags & TF_NEEDFIN) {
1237 tp->t_state = TCPS_FIN_WAIT_1;
1238 tp->t_flags &= ~TF_NEEDFIN;
1241 tp->t_state = TCPS_ESTABLISHED;
1242 callout_reset(tp->tt_keep, tcp_keepidle,
1243 tcp_timer_keep, tp);
1247 * Received initial SYN in SYN-SENT[*] state =>
1248 * simultaneous open. If segment contains CC option
1249 * and there is a cached CC, apply TAO test.
1250 * If it succeeds, connection is * half-synchronized.
1251 * Otherwise, do 3-way handshake:
1252 * SYN-SENT -> SYN-RECEIVED
1253 * SYN-SENT* -> SYN-RECEIVED*
1254 * If there was no CC option, clear cached CC value.
1256 tp->t_flags |= TF_ACKNOW;
1257 callout_stop(tp->tt_rexmt);
1258 if (to.to_flags & TOF_CC) {
1259 if (taop->tao_cc != 0 &&
1260 CC_GT(to.to_cc, taop->tao_cc)) {
1262 * update cache and make transition:
1263 * SYN-SENT -> ESTABLISHED*
1264 * SYN-SENT* -> FIN-WAIT-1*
1266 taop->tao_cc = to.to_cc;
1267 tp->t_starttime = ticks;
1268 if (tp->t_flags & TF_NEEDFIN) {
1269 tp->t_state = TCPS_FIN_WAIT_1;
1270 tp->t_flags &= ~TF_NEEDFIN;
1272 tp->t_state = TCPS_ESTABLISHED;
1273 callout_reset(tp->tt_keep,
1278 tp->t_flags |= TF_NEEDSYN;
1280 tp->t_state = TCPS_SYN_RECEIVED;
1282 /* CC.NEW or no option => invalidate cache */
1284 tp->t_state = TCPS_SYN_RECEIVED;
1290 * Advance th->th_seq to correspond to first data byte.
1291 * If data, trim to stay within window,
1292 * dropping FIN if necessary.
1295 if (tlen > tp->rcv_wnd) {
1296 todrop = tlen - tp->rcv_wnd;
1300 tcpstat.tcps_rcvpackafterwin++;
1301 tcpstat.tcps_rcvbyteafterwin += todrop;
1303 tp->snd_wl1 = th->th_seq - 1;
1304 tp->rcv_up = th->th_seq;
1306 * Client side of transaction: already sent SYN and data.
1307 * If the remote host used T/TCP to validate the SYN,
1308 * our data will be ACK'd; if so, enter normal data segment
1309 * processing in the middle of step 5, ack processing.
1310 * Otherwise, goto step 6.
1312 if (thflags & TH_ACK)
1318 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1319 * if segment contains a SYN and CC [not CC.NEW] option:
1320 * if state == TIME_WAIT and connection duration > MSL,
1321 * drop packet and send RST;
1323 * if SEG.CC > CCrecv then is new SYN, and can implicitly
1324 * ack the FIN (and data) in retransmission queue.
1325 * Complete close and delete TCPCB. Then reprocess
1326 * segment, hoping to find new TCPCB in LISTEN state;
1328 * else must be old SYN; drop it.
1329 * else do normal processing.
1333 case TCPS_TIME_WAIT:
1334 if ((thflags & TH_SYN) &&
1335 (to.to_flags & TOF_CC) && tp->cc_recv != 0) {
1336 if (tp->t_state == TCPS_TIME_WAIT &&
1337 (ticks - tp->t_starttime) > tcp_msl) {
1338 rstreason = BANDLIM_UNLIMITED;
1341 if (CC_GT(to.to_cc, tp->cc_recv)) {
1348 break; /* continue normal processing */
1352 * States other than LISTEN or SYN_SENT.
1353 * First check the RST flag and sequence number since reset segments
1354 * are exempt from the timestamp and connection count tests. This
1355 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1356 * below which allowed reset segments in half the sequence space
1357 * to fall though and be processed (which gives forged reset
1358 * segments with a random sequence number a 50 percent chance of
1359 * killing a connection).
1360 * Then check timestamp, if present.
1361 * Then check the connection count, if present.
1362 * Then check that at least some bytes of segment are within
1363 * receive window. If segment begins before rcv_nxt,
1364 * drop leading data (and SYN); if nothing left, just ack.
1367 * If the RST bit is set, check the sequence number to see
1368 * if this is a valid reset segment.
1370 * In all states except SYN-SENT, all reset (RST) segments
1371 * are validated by checking their SEQ-fields. A reset is
1372 * valid if its sequence number is in the window.
1373 * Note: this does not take into account delayed ACKs, so
1374 * we should test against last_ack_sent instead of rcv_nxt.
1375 * The sequence number in the reset segment is normally an
1376 * echo of our outgoing acknowlegement numbers, but some hosts
1377 * send a reset with the sequence number at the rightmost edge
1378 * of our receive window, and we have to handle this case.
1379 * If we have multiple segments in flight, the intial reset
1380 * segment sequence numbers will be to the left of last_ack_sent,
1381 * but they will eventually catch up.
1382 * In any case, it never made sense to trim reset segments to
1383 * fit the receive window since RFC 1122 says:
1384 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1386 * A TCP SHOULD allow a received RST segment to include data.
1389 * It has been suggested that a RST segment could contain
1390 * ASCII text that encoded and explained the cause of the
1391 * RST. No standard has yet been established for such
1394 * If the reset segment passes the sequence number test examine
1396 * SYN_RECEIVED STATE:
1397 * If passive open, return to LISTEN state.
1398 * If active open, inform user that connection was refused.
1399 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1400 * Inform user that connection was reset, and close tcb.
1401 * CLOSING, LAST_ACK STATES:
1404 * Drop the segment - see Stevens, vol. 2, p. 964 and
1407 if (thflags & TH_RST) {
1408 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
1409 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1410 switch (tp->t_state) {
1412 case TCPS_SYN_RECEIVED:
1413 so->so_error = ECONNREFUSED;
1416 case TCPS_ESTABLISHED:
1417 case TCPS_FIN_WAIT_1:
1418 case TCPS_FIN_WAIT_2:
1419 case TCPS_CLOSE_WAIT:
1420 so->so_error = ECONNRESET;
1422 tp->t_state = TCPS_CLOSED;
1423 tcpstat.tcps_drops++;
1432 case TCPS_TIME_WAIT:
1440 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1441 * and it's less than ts_recent, drop it.
1443 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
1444 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1446 /* Check to see if ts_recent is over 24 days old. */
1447 if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1449 * Invalidate ts_recent. If this segment updates
1450 * ts_recent, the age will be reset later and ts_recent
1451 * will get a valid value. If it does not, setting
1452 * ts_recent to zero will at least satisfy the
1453 * requirement that zero be placed in the timestamp
1454 * echo reply when ts_recent isn't valid. The
1455 * age isn't reset until we get a valid ts_recent
1456 * because we don't want out-of-order segments to be
1457 * dropped when ts_recent is old.
1461 tcpstat.tcps_rcvduppack++;
1462 tcpstat.tcps_rcvdupbyte += tlen;
1463 tcpstat.tcps_pawsdrop++;
1472 * If T/TCP was negotiated and the segment doesn't have CC,
1473 * or if its CC is wrong then drop the segment.
1474 * RST segments do not have to comply with this.
1476 if ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) == (TF_REQ_CC|TF_RCVD_CC) &&
1477 ((to.to_flags & TOF_CC) == 0 || tp->cc_recv != to.to_cc))
1481 * In the SYN-RECEIVED state, validate that the packet belongs to
1482 * this connection before trimming the data to fit the receive
1483 * window. Check the sequence number versus IRS since we know
1484 * the sequence numbers haven't wrapped. This is a partial fix
1485 * for the "LAND" DoS attack.
1487 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1488 rstreason = BANDLIM_RST_OPENPORT;
1492 todrop = tp->rcv_nxt - th->th_seq;
1494 if (thflags & TH_SYN) {
1504 * Following if statement from Stevens, vol. 2, p. 960.
1507 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1509 * Any valid FIN must be to the left of the window.
1510 * At this point the FIN must be a duplicate or out
1511 * of sequence; drop it.
1516 * Send an ACK to resynchronize and drop any data.
1517 * But keep on processing for RST or ACK.
1519 tp->t_flags |= TF_ACKNOW;
1521 tcpstat.tcps_rcvduppack++;
1522 tcpstat.tcps_rcvdupbyte += todrop;
1524 tcpstat.tcps_rcvpartduppack++;
1525 tcpstat.tcps_rcvpartdupbyte += todrop;
1527 drop_hdrlen += todrop; /* drop from the top afterwards */
1528 th->th_seq += todrop;
1530 if (th->th_urp > todrop)
1531 th->th_urp -= todrop;
1539 * If new data are received on a connection after the
1540 * user processes are gone, then RST the other end.
1542 if ((so->so_state & SS_NOFDREF) &&
1543 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1545 tcpstat.tcps_rcvafterclose++;
1546 rstreason = BANDLIM_UNLIMITED;
1551 * If segment ends after window, drop trailing data
1552 * (and PUSH and FIN); if nothing left, just ACK.
1554 todrop = (th->th_seq+tlen) - (tp->rcv_nxt+tp->rcv_wnd);
1556 tcpstat.tcps_rcvpackafterwin++;
1557 if (todrop >= tlen) {
1558 tcpstat.tcps_rcvbyteafterwin += tlen;
1560 * If a new connection request is received
1561 * while in TIME_WAIT, drop the old connection
1562 * and start over if the sequence numbers
1563 * are above the previous ones.
1565 if (thflags & TH_SYN &&
1566 tp->t_state == TCPS_TIME_WAIT &&
1567 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1572 * If window is closed can only take segments at
1573 * window edge, and have to drop data and PUSH from
1574 * incoming segments. Continue processing, but
1575 * remember to ack. Otherwise, drop segment
1578 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1579 tp->t_flags |= TF_ACKNOW;
1580 tcpstat.tcps_rcvwinprobe++;
1584 tcpstat.tcps_rcvbyteafterwin += todrop;
1587 thflags &= ~(TH_PUSH|TH_FIN);
1591 * If last ACK falls within this segment's sequence numbers,
1592 * record its timestamp.
1593 * NOTE that the test is modified according to the latest
1594 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1596 if ((to.to_flags & TOF_TS) != 0 &&
1597 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1598 tp->ts_recent_age = ticks;
1599 tp->ts_recent = to.to_tsval;
1603 * If a SYN is in the window, then this is an
1604 * error and we send an RST and drop the connection.
1606 if (thflags & TH_SYN) {
1607 tp = tcp_drop(tp, ECONNRESET);
1608 rstreason = BANDLIM_UNLIMITED;
1613 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1614 * flag is on (half-synchronized state), then queue data for
1615 * later processing; else drop segment and return.
1617 if ((thflags & TH_ACK) == 0) {
1618 if (tp->t_state == TCPS_SYN_RECEIVED ||
1619 (tp->t_flags & TF_NEEDSYN))
1628 switch (tp->t_state) {
1631 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1632 * ESTABLISHED state and continue processing.
1633 * The ACK was checked above.
1635 case TCPS_SYN_RECEIVED:
1637 tcpstat.tcps_connects++;
1639 /* Do window scaling? */
1640 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1641 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1642 tp->snd_scale = tp->requested_s_scale;
1643 tp->rcv_scale = tp->request_r_scale;
1646 * Upon successful completion of 3-way handshake,
1647 * update cache.CC if it was undefined, pass any queued
1648 * data to the user, and advance state appropriately.
1650 if ((taop = tcp_gettaocache(&inp->inp_inc)) != NULL &&
1652 taop->tao_cc = tp->cc_recv;
1656 * SYN-RECEIVED -> ESTABLISHED
1657 * SYN-RECEIVED* -> FIN-WAIT-1
1659 tp->t_starttime = ticks;
1660 if (tp->t_flags & TF_NEEDFIN) {
1661 tp->t_state = TCPS_FIN_WAIT_1;
1662 tp->t_flags &= ~TF_NEEDFIN;
1664 tp->t_state = TCPS_ESTABLISHED;
1665 callout_reset(tp->tt_keep, tcp_keepidle,
1666 tcp_timer_keep, tp);
1669 * If segment contains data or ACK, will call tcp_reass()
1670 * later; if not, do so now to pass queued data to user.
1672 if (tlen == 0 && (thflags & TH_FIN) == 0)
1673 (void) tcp_reass(tp, (struct tcphdr *)0, 0,
1675 tp->snd_wl1 = th->th_seq - 1;
1679 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1680 * ACKs. If the ack is in the range
1681 * tp->snd_una < th->th_ack <= tp->snd_max
1682 * then advance tp->snd_una to th->th_ack and drop
1683 * data from the retransmission queue. If this ACK reflects
1684 * more up to date window information we update our window information.
1686 case TCPS_ESTABLISHED:
1687 case TCPS_FIN_WAIT_1:
1688 case TCPS_FIN_WAIT_2:
1689 case TCPS_CLOSE_WAIT:
1692 case TCPS_TIME_WAIT:
1694 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1695 if (tlen == 0 && tiwin == tp->snd_wnd) {
1696 tcpstat.tcps_rcvdupack++;
1698 * If we have outstanding data (other than
1699 * a window probe), this is a completely
1700 * duplicate ack (ie, window info didn't
1701 * change), the ack is the biggest we've
1702 * seen and we've seen exactly our rexmt
1703 * threshhold of them, assume a packet
1704 * has been dropped and retransmit it.
1705 * Kludge snd_nxt & the congestion
1706 * window so we send only this one
1709 * We know we're losing at the current
1710 * window size so do congestion avoidance
1711 * (set ssthresh to half the current window
1712 * and pull our congestion window back to
1713 * the new ssthresh).
1715 * Dup acks mean that packets have left the
1716 * network (they're now cached at the receiver)
1717 * so bump cwnd by the amount in the receiver
1718 * to keep a constant cwnd packets in the
1721 if (!callout_active(tp->tt_rexmt) ||
1722 th->th_ack != tp->snd_una)
1724 else if (++tp->t_dupacks > tcprexmtthresh ||
1726 IN_FASTRECOVERY(tp))) {
1727 tp->snd_cwnd += tp->t_maxseg;
1728 (void) tcp_output(tp);
1730 } else if (tp->t_dupacks == tcprexmtthresh) {
1731 tcp_seq onxt = tp->snd_nxt;
1733 if (tcp_do_newreno &&
1739 if (tcp_do_eifel_detect &&
1740 (tp->t_flags & TF_RCVD_TSTMP)) {
1741 tcp_save_congestion_state(tp);
1742 tp->t_flags |= TF_FASTREXMT;
1744 win = min(tp->snd_wnd, tp->snd_cwnd) /
1748 tp->snd_ssthresh = win * tp->t_maxseg;
1749 ENTER_FASTRECOVERY(tp);
1750 tp->snd_recover = tp->snd_max;
1751 callout_stop(tp->tt_rexmt);
1753 tp->snd_nxt = th->th_ack;
1754 tp->snd_cwnd = tp->t_maxseg;
1755 (void) tcp_output(tp);
1756 KASSERT(tp->snd_limited <= 2,
1757 ("tp->snd_limited too big"));
1758 tp->snd_cwnd = tp->snd_ssthresh +
1760 (tp->t_dupacks - tp->snd_limited));
1761 if (SEQ_GT(onxt, tp->snd_nxt))
1764 } else if (tcp_do_limitedtransmit) {
1765 u_long oldcwnd = tp->snd_cwnd;
1766 tcp_seq oldsndmax = tp->snd_max;
1769 KASSERT(tp->t_dupacks == 1 ||
1771 ("dupacks not 1 or 2"));
1772 if (tp->t_dupacks == 1)
1773 tp->snd_limited = 0;
1775 (tp->snd_nxt - tp->snd_una) +
1776 (tp->t_dupacks - tp->snd_limited) *
1778 (void) tcp_output(tp);
1779 sent = tp->snd_max - oldsndmax;
1780 if (sent > tp->t_maxseg) {
1781 KASSERT((tp->t_dupacks == 2 &&
1782 tp->snd_limited == 0) ||
1783 (sent == tp->t_maxseg + 1 &&
1784 tp->t_flags & TF_SENTFIN),
1786 tp->snd_limited = 2;
1787 } else if (sent > 0)
1789 tp->snd_cwnd = oldcwnd;
1797 KASSERT(SEQ_GT(th->th_ack, tp->snd_una), ("th_ack <= snd_una"));
1800 * If the congestion window was inflated to account
1801 * for the other side's cached packets, retract it.
1803 if (tcp_do_newreno) {
1804 if (IN_FASTRECOVERY(tp)) {
1805 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
1806 tcp_newreno_partial_ack(tp, th);
1809 * Window inflation should have left us
1810 * with approximately snd_ssthresh
1812 * But in case we would be inclined to
1813 * send a burst, better to do it via
1814 * the slow start mechanism.
1816 if (SEQ_GT(th->th_ack +
1819 tp->snd_cwnd = tp->snd_max -
1823 tp->snd_cwnd = tp->snd_ssthresh;
1827 if (tp->t_dupacks >= tcprexmtthresh &&
1828 tp->snd_cwnd > tp->snd_ssthresh)
1829 tp->snd_cwnd = tp->snd_ssthresh;
1832 if (SEQ_GT(th->th_ack, tp->snd_max)) {
1833 tcpstat.tcps_rcvacktoomuch++;
1837 * If we reach this point, ACK is not a duplicate,
1838 * i.e., it ACKs something we sent.
1840 if (tp->t_flags & TF_NEEDSYN) {
1842 * T/TCP: Connection was half-synchronized, and our
1843 * SYN has been ACK'd (so connection is now fully
1844 * synchronized). Go to non-starred state,
1845 * increment snd_una for ACK of SYN, and check if
1846 * we can do window scaling.
1848 tp->t_flags &= ~TF_NEEDSYN;
1850 /* Do window scaling? */
1851 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1852 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1853 tp->snd_scale = tp->requested_s_scale;
1854 tp->rcv_scale = tp->request_r_scale;
1859 acked = th->th_ack - tp->snd_una;
1860 tcpstat.tcps_rcvackpack++;
1861 tcpstat.tcps_rcvackbyte += acked;
1864 * If we just performed our first retransmit, and the ACK
1865 * arrives within our recovery window, then it was a mistake
1866 * to do the retransmit in the first place. Recover our
1867 * original cwnd and ssthresh, and proceed to transmit where
1870 if (tcp_do_eifel_detect && acked &&
1871 (to.to_flags & TOF_TS) && to.to_tsecr &&
1872 (tp->t_flags & TF_FIRSTACCACK)) {
1873 /* Eifel detection applicable. */
1874 if (to.to_tsecr < tp->t_rexmtTS) {
1875 tcp_revert_congestion_state(tp);
1876 ++tcpstat.tcps_eifeldetected;
1878 } else if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
1879 tcp_revert_congestion_state(tp);
1880 ++tcpstat.tcps_rttdetected;
1884 * If we have a timestamp reply, update smoothed
1885 * round trip time. If no timestamp is present but
1886 * transmit timer is running and timed sequence
1887 * number was acked, update smoothed round trip time.
1888 * Since we now have an rtt measurement, cancel the
1889 * timer backoff (cf., Phil Karn's retransmit alg.).
1890 * Recompute the initial retransmit timer.
1892 * Some machines (certain windows boxes) send broken
1893 * timestamp replies during the SYN+ACK phase, ignore
1896 if ((to.to_flags & TOF_TS) != 0 &&
1898 tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
1899 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
1900 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
1902 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1905 * If all outstanding data is acked, stop retransmit
1906 * timer and remember to restart (more output or persist).
1907 * If there is more data to be acked, restart retransmit
1908 * timer, using current (possibly backed-off) value.
1910 if (th->th_ack == tp->snd_max) {
1911 callout_stop(tp->tt_rexmt);
1913 } else if (!callout_active(tp->tt_persist))
1914 callout_reset(tp->tt_rexmt, tp->t_rxtcur,
1915 tcp_timer_rexmt, tp);
1918 * If no data (only SYN) was ACK'd,
1919 * skip rest of ACK processing.
1924 /* Stop looking for an acceptable ACK since one was received. */
1925 tp->t_flags &= ~(TF_FIRSTACCACK | TF_FASTREXMT);
1928 * When new data is acked, open the congestion window.
1929 * If the window gives us less than ssthresh packets
1930 * in flight, open exponentially (maxseg per packet).
1931 * Otherwise open linearly: maxseg per window
1932 * (maxseg^2 / cwnd per packet).
1934 if (!tcp_do_newreno || !IN_FASTRECOVERY(tp)) {
1935 u_int cw = tp->snd_cwnd;
1936 u_int incr = tp->t_maxseg;
1937 if (cw > tp->snd_ssthresh)
1938 incr = incr * incr / cw;
1939 tp->snd_cwnd = min(cw+incr, TCP_MAXWIN<<tp->snd_scale);
1941 if (acked > so->so_snd.sb_cc) {
1942 tp->snd_wnd -= so->so_snd.sb_cc;
1943 sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
1946 sbdrop(&so->so_snd, acked);
1947 tp->snd_wnd -= acked;
1951 /* detect una wraparound */
1952 if (tcp_do_newreno && !IN_FASTRECOVERY(tp) &&
1953 SEQ_GT(tp->snd_una, tp->snd_recover) &&
1954 SEQ_LEQ(th->th_ack, tp->snd_recover))
1955 tp->snd_recover = th->th_ack - 1;
1956 if (tcp_do_newreno && IN_FASTRECOVERY(tp) &&
1957 SEQ_GEQ(th->th_ack, tp->snd_recover))
1958 EXIT_FASTRECOVERY(tp);
1959 tp->snd_una = th->th_ack;
1960 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1961 tp->snd_nxt = tp->snd_una;
1963 switch (tp->t_state) {
1966 * In FIN_WAIT_1 STATE in addition to the processing
1967 * for the ESTABLISHED state if our FIN is now acknowledged
1968 * then enter FIN_WAIT_2.
1970 case TCPS_FIN_WAIT_1:
1971 if (ourfinisacked) {
1973 * If we can't receive any more
1974 * data, then closing user can proceed.
1975 * Starting the timer is contrary to the
1976 * specification, but if we don't get a FIN
1977 * we'll hang forever.
1979 if (so->so_state & SS_CANTRCVMORE) {
1980 soisdisconnected(so);
1981 callout_reset(tp->tt_2msl, tcp_maxidle,
1982 tcp_timer_2msl, tp);
1984 tp->t_state = TCPS_FIN_WAIT_2;
1989 * In CLOSING STATE in addition to the processing for
1990 * the ESTABLISHED state if the ACK acknowledges our FIN
1991 * then enter the TIME-WAIT state, otherwise ignore
1995 if (ourfinisacked) {
1996 tp->t_state = TCPS_TIME_WAIT;
1997 tcp_canceltimers(tp);
1998 /* Shorten TIME_WAIT [RFC-1644, p.28] */
1999 if (tp->cc_recv != 0 &&
2000 (ticks - tp->t_starttime) < tcp_msl)
2001 callout_reset(tp->tt_2msl,
2004 tcp_timer_2msl, tp);
2006 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2007 tcp_timer_2msl, tp);
2008 soisdisconnected(so);
2013 * In LAST_ACK, we may still be waiting for data to drain
2014 * and/or to be acked, as well as for the ack of our FIN.
2015 * If our FIN is now acknowledged, delete the TCB,
2016 * enter the closed state and return.
2019 if (ourfinisacked) {
2026 * In TIME_WAIT state the only thing that should arrive
2027 * is a retransmission of the remote FIN. Acknowledge
2028 * it and restart the finack timer.
2030 case TCPS_TIME_WAIT:
2031 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2032 tcp_timer_2msl, tp);
2039 * Update window information.
2040 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2042 if ((thflags & TH_ACK) &&
2043 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2044 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2045 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2046 /* keep track of pure window updates */
2048 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2049 tcpstat.tcps_rcvwinupd++;
2050 tp->snd_wnd = tiwin;
2051 tp->snd_wl1 = th->th_seq;
2052 tp->snd_wl2 = th->th_ack;
2053 if (tp->snd_wnd > tp->max_sndwnd)
2054 tp->max_sndwnd = tp->snd_wnd;
2059 * Process segments with URG.
2061 if ((thflags & TH_URG) && th->th_urp &&
2062 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2064 * This is a kludge, but if we receive and accept
2065 * random urgent pointers, we'll crash in
2066 * soreceive. It's hard to imagine someone
2067 * actually wanting to send this much urgent data.
2069 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2070 th->th_urp = 0; /* XXX */
2071 thflags &= ~TH_URG; /* XXX */
2072 goto dodata; /* XXX */
2075 * If this segment advances the known urgent pointer,
2076 * then mark the data stream. This should not happen
2077 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2078 * a FIN has been received from the remote side.
2079 * In these states we ignore the URG.
2081 * According to RFC961 (Assigned Protocols),
2082 * the urgent pointer points to the last octet
2083 * of urgent data. We continue, however,
2084 * to consider it to indicate the first octet
2085 * of data past the urgent section as the original
2086 * spec states (in one of two places).
2088 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2089 tp->rcv_up = th->th_seq + th->th_urp;
2090 so->so_oobmark = so->so_rcv.sb_cc +
2091 (tp->rcv_up - tp->rcv_nxt) - 1;
2092 if (so->so_oobmark == 0)
2093 so->so_state |= SS_RCVATMARK;
2095 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2098 * Remove out of band data so doesn't get presented to user.
2099 * This can happen independent of advancing the URG pointer,
2100 * but if two URG's are pending at once, some out-of-band
2101 * data may creep in... ick.
2103 if (th->th_urp <= (u_long)tlen
2105 && (so->so_options & SO_OOBINLINE) == 0
2108 tcp_pulloutofband(so, th, m,
2109 drop_hdrlen); /* hdr drop is delayed */
2112 * If no out of band data is expected,
2113 * pull receive urgent pointer along
2114 * with the receive window.
2116 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2117 tp->rcv_up = tp->rcv_nxt;
2122 * Process the segment text, merging it into the TCP sequencing queue,
2123 * and arranging for acknowledgment of receipt if necessary.
2124 * This process logically involves adjusting tp->rcv_wnd as data
2125 * is presented to the user (this happens in tcp_usrreq.c,
2126 * case PRU_RCVD). If a FIN has already been received on this
2127 * connection then we just ignore the text.
2129 if ((tlen || (thflags & TH_FIN)) &&
2130 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2131 m_adj(m, drop_hdrlen); /* delayed header drop */
2133 * Insert segment which includes th into TCP reassembly queue
2134 * with control block tp. Set thflags to whether reassembly now
2135 * includes a segment with FIN. This handles the common case
2136 * inline (segment is the next to be received on an established
2137 * connection, and the queue is empty), avoiding linkage into
2138 * and removal from the queue and repetition of various
2140 * Set DELACK for segments received in order, but ack
2141 * immediately when segments are out of order (so
2142 * fast retransmit can work).
2144 if (th->th_seq == tp->rcv_nxt &&
2145 LIST_EMPTY(&tp->t_segq) &&
2146 TCPS_HAVEESTABLISHED(tp->t_state)) {
2148 callout_reset(tp->tt_delack, tcp_delacktime,
2149 tcp_timer_delack, tp);
2151 tp->t_flags |= TF_ACKNOW;
2152 tp->rcv_nxt += tlen;
2153 thflags = th->th_flags & TH_FIN;
2154 tcpstat.tcps_rcvpack++;
2155 tcpstat.tcps_rcvbyte += tlen;
2157 if (so->so_state & SS_CANTRCVMORE)
2160 sbappend(&so->so_rcv, m);
2163 thflags = tcp_reass(tp, th, &tlen, m);
2164 tp->t_flags |= TF_ACKNOW;
2168 * Note the amount of data that peer has sent into
2169 * our window, in order to estimate the sender's
2172 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2179 * If FIN is received ACK the FIN and let the user know
2180 * that the connection is closing.
2182 if (thflags & TH_FIN) {
2183 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2186 * If connection is half-synchronized
2187 * (ie NEEDSYN flag on) then delay ACK,
2188 * so it may be piggybacked when SYN is sent.
2189 * Otherwise, since we received a FIN then no
2190 * more input can be expected, send ACK now.
2192 if (DELAY_ACK(tp) && (tp->t_flags & TF_NEEDSYN))
2193 callout_reset(tp->tt_delack, tcp_delacktime,
2194 tcp_timer_delack, tp);
2196 tp->t_flags |= TF_ACKNOW;
2199 switch (tp->t_state) {
2202 * In SYN_RECEIVED and ESTABLISHED STATES
2203 * enter the CLOSE_WAIT state.
2205 case TCPS_SYN_RECEIVED:
2206 tp->t_starttime = ticks;
2208 case TCPS_ESTABLISHED:
2209 tp->t_state = TCPS_CLOSE_WAIT;
2213 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2214 * enter the CLOSING state.
2216 case TCPS_FIN_WAIT_1:
2217 tp->t_state = TCPS_CLOSING;
2221 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2222 * starting the time-wait timer, turning off the other
2225 case TCPS_FIN_WAIT_2:
2226 tp->t_state = TCPS_TIME_WAIT;
2227 tcp_canceltimers(tp);
2228 /* Shorten TIME_WAIT [RFC-1644, p.28] */
2229 if (tp->cc_recv != 0 &&
2230 (ticks - tp->t_starttime) < tcp_msl) {
2231 callout_reset(tp->tt_2msl,
2232 tp->t_rxtcur * TCPTV_TWTRUNC,
2233 tcp_timer_2msl, tp);
2234 /* For transaction client, force ACK now. */
2235 tp->t_flags |= TF_ACKNOW;
2238 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2239 tcp_timer_2msl, tp);
2240 soisdisconnected(so);
2244 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2246 case TCPS_TIME_WAIT:
2247 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2248 tcp_timer_2msl, tp);
2253 if (so->so_options & SO_DEBUG)
2254 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2259 * Return any desired output.
2261 if (needoutput || (tp->t_flags & TF_ACKNOW))
2262 (void) tcp_output(tp);
2267 * Generate an ACK dropping incoming segment if it occupies
2268 * sequence space, where the ACK reflects our state.
2270 * We can now skip the test for the RST flag since all
2271 * paths to this code happen after packets containing
2272 * RST have been dropped.
2274 * In the SYN-RECEIVED state, don't send an ACK unless the
2275 * segment we received passes the SYN-RECEIVED ACK test.
2276 * If it fails send a RST. This breaks the loop in the
2277 * "LAND" DoS attack, and also prevents an ACK storm
2278 * between two listening ports that have been sent forged
2279 * SYN segments, each with the source address of the other.
2281 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2282 (SEQ_GT(tp->snd_una, th->th_ack) ||
2283 SEQ_GT(th->th_ack, tp->snd_max)) ) {
2284 rstreason = BANDLIM_RST_OPENPORT;
2288 if (so->so_options & SO_DEBUG)
2289 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2293 tp->t_flags |= TF_ACKNOW;
2294 (void) tcp_output(tp);
2299 * Generate a RST, dropping incoming segment.
2300 * Make ACK acceptable to originator of segment.
2301 * Don't bother to respond if destination was broadcast/multicast.
2303 if ((thflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
2306 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2307 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2310 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2311 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2312 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2313 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2316 /* IPv6 anycast check is done at tcp6_input() */
2319 * Perform bandwidth limiting.
2322 if (badport_bandlim(rstreason) < 0)
2327 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2328 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2331 if (thflags & TH_ACK)
2332 /* mtod() below is safe as long as hdr dropping is delayed */
2333 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
2336 if (thflags & TH_SYN)
2338 /* mtod() below is safe as long as hdr dropping is delayed */
2339 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
2340 (tcp_seq)0, TH_RST|TH_ACK);
2346 * Drop space held by incoming segment and return.
2349 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2350 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2358 * Parse TCP options and place in tcpopt.
2361 tcp_dooptions(to, cp, cnt, is_syn)
2369 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2371 if (opt == TCPOPT_EOL)
2373 if (opt == TCPOPT_NOP)
2379 if (optlen < 2 || optlen > cnt)
2384 if (optlen != TCPOLEN_MAXSEG)
2388 to->to_flags |= TOF_MSS;
2389 bcopy((char *)cp + 2,
2390 (char *)&to->to_mss, sizeof(to->to_mss));
2391 to->to_mss = ntohs(to->to_mss);
2394 if (optlen != TCPOLEN_WINDOW)
2398 to->to_flags |= TOF_SCALE;
2399 to->to_requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
2401 case TCPOPT_TIMESTAMP:
2402 if (optlen != TCPOLEN_TIMESTAMP)
2404 to->to_flags |= TOF_TS;
2405 bcopy((char *)cp + 2,
2406 (char *)&to->to_tsval, sizeof(to->to_tsval));
2407 to->to_tsval = ntohl(to->to_tsval);
2408 bcopy((char *)cp + 6,
2409 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
2410 to->to_tsecr = ntohl(to->to_tsecr);
2413 if (optlen != TCPOLEN_CC)
2415 to->to_flags |= TOF_CC;
2416 bcopy((char *)cp + 2,
2417 (char *)&to->to_cc, sizeof(to->to_cc));
2418 to->to_cc = ntohl(to->to_cc);
2421 if (optlen != TCPOLEN_CC)
2425 to->to_flags |= TOF_CCNEW;
2426 bcopy((char *)cp + 2,
2427 (char *)&to->to_cc, sizeof(to->to_cc));
2428 to->to_cc = ntohl(to->to_cc);
2431 if (optlen != TCPOLEN_CC)
2435 to->to_flags |= TOF_CCECHO;
2436 bcopy((char *)cp + 2,
2437 (char *)&to->to_ccecho, sizeof(to->to_ccecho));
2438 to->to_ccecho = ntohl(to->to_ccecho);
2447 * Pull out of band byte out of a segment so
2448 * it doesn't appear in the user's data queue.
2449 * It is still reflected in the segment length for
2450 * sequencing purposes.
2453 tcp_pulloutofband(so, th, m, off)
2457 int off; /* delayed to be droped hdrlen */
2459 int cnt = off + th->th_urp - 1;
2462 if (m->m_len > cnt) {
2463 char *cp = mtod(m, caddr_t) + cnt;
2464 struct tcpcb *tp = sototcpcb(so);
2467 tp->t_oobflags |= TCPOOB_HAVEDATA;
2468 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2470 if (m->m_flags & M_PKTHDR)
2479 panic("tcp_pulloutofband");
2483 * Collect new round-trip time estimate
2484 * and update averages and current timeout.
2487 tcp_xmit_timer(tp, rtt)
2493 tcpstat.tcps_rttupdated++;
2495 if (tp->t_srtt != 0) {
2497 * srtt is stored as fixed point with 5 bits after the
2498 * binary point (i.e., scaled by 8). The following magic
2499 * is equivalent to the smoothing algorithm in rfc793 with
2500 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2501 * point). Adjust rtt to origin 0.
2503 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2504 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2506 if ((tp->t_srtt += delta) <= 0)
2510 * We accumulate a smoothed rtt variance (actually, a
2511 * smoothed mean difference), then set the retransmit
2512 * timer to smoothed rtt + 4 times the smoothed variance.
2513 * rttvar is stored as fixed point with 4 bits after the
2514 * binary point (scaled by 16). The following is
2515 * equivalent to rfc793 smoothing with an alpha of .75
2516 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2517 * rfc793's wired-in beta.
2521 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2522 if ((tp->t_rttvar += delta) <= 0)
2524 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2525 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2528 * No rtt measurement yet - use the unsmoothed rtt.
2529 * Set the variance to half the rtt (so our first
2530 * retransmit happens at 3*rtt).
2532 tp->t_srtt = rtt << TCP_RTT_SHIFT;
2533 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2534 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2540 * the retransmit should happen at rtt + 4 * rttvar.
2541 * Because of the way we do the smoothing, srtt and rttvar
2542 * will each average +1/2 tick of bias. When we compute
2543 * the retransmit timer, we want 1/2 tick of rounding and
2544 * 1 extra tick because of +-1/2 tick uncertainty in the
2545 * firing of the timer. The bias will give us exactly the
2546 * 1.5 tick we need. But, because the bias is
2547 * statistical, we have to test that we don't drop below
2548 * the minimum feasible timer (which is 2 ticks).
2550 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2551 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2554 * We received an ack for a packet that wasn't retransmitted;
2555 * it is probably safe to discard any error indications we've
2556 * received recently. This isn't quite right, but close enough
2557 * for now (a route might have failed after we sent a segment,
2558 * and the return path might not be symmetrical).
2560 tp->t_softerror = 0;
2564 * Determine a reasonable value for maxseg size.
2565 * If the route is known, check route for mtu.
2566 * If none, use an mss that can be handled on the outgoing
2567 * interface without forcing IP to fragment; if bigger than
2568 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2569 * to utilize large mbufs. If no route is found, route has no mtu,
2570 * or the destination isn't local, use a default, hopefully conservative
2571 * size (usually 512 or the default IP max size, but no more than the mtu
2572 * of the interface), as we can't discover anything about intervening
2573 * gateways or networks. We also initialize the congestion/slow start
2574 * window to be a single segment if the destination isn't local.
2575 * While looking at the routing entry, we also initialize other path-dependent
2576 * parameters from pre-set or cached values in the routing entry.
2578 * Also take into account the space needed for options that we
2579 * send regularly. Make maxseg shorter by that amount to assure
2580 * that we can send maxseg amount of data even when the options
2581 * are present. Store the upper limit of the length of options plus
2584 * NOTE that this routine is only called when we process an incoming
2585 * segment, for outgoing segments only tcp_mssopt is called.
2587 * In case of T/TCP, we call this routine during implicit connection
2588 * setup as well (offer = -1), to initialize maxseg from the cached
2600 struct inpcb *inp = tp->t_inpcb;
2602 struct rmxp_tao *taop;
2603 int origoffer = offer;
2605 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2606 size_t min_protoh = isipv6 ?
2607 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
2608 sizeof(struct tcpiphdr);
2610 const int isipv6 = 0;
2611 const size_t min_protoh = sizeof(struct tcpiphdr);
2615 rt = tcp_rtlookup6(&inp->inp_inc);
2617 rt = tcp_rtlookup(&inp->inp_inc);
2619 tp->t_maxopd = tp->t_maxseg =
2620 isipv6 ? tcp_v6mssdflt : tcp_mssdflt;
2624 so = inp->inp_socket;
2626 taop = rmx_taop(rt->rt_rmx);
2628 * Offer == -1 means that we didn't receive SYN yet,
2629 * use cached value in that case;
2632 offer = taop->tao_mssopt;
2634 * Offer == 0 means that there was no MSS on the SYN segment,
2635 * in this case we use tcp_mssdflt.
2638 offer = isipv6 ? tcp_v6mssdflt : tcp_mssdflt;
2641 * Sanity check: make sure that maxopd will be large
2642 * enough to allow some data on segments even is the
2643 * all the option space is used (40bytes). Otherwise
2644 * funny things may happen in tcp_output.
2646 offer = max(offer, 64);
2647 taop->tao_mssopt = offer;
2650 * While we're here, check if there's an initial rtt
2651 * or rttvar. Convert from the route-table units
2652 * to scaled multiples of the slow timeout timer.
2654 if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2656 * XXX the lock bit for RTT indicates that the value
2657 * is also a minimum value; this is subject to time.
2659 if (rt->rt_rmx.rmx_locks & RTV_RTT)
2660 tp->t_rttmin = rtt / (RTM_RTTUNIT / hz);
2661 tp->t_srtt = rtt / (RTM_RTTUNIT / (hz * TCP_RTT_SCALE));
2662 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
2663 tcpstat.tcps_usedrtt++;
2664 if (rt->rt_rmx.rmx_rttvar) {
2665 tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2666 (RTM_RTTUNIT / (hz * TCP_RTTVAR_SCALE));
2667 tcpstat.tcps_usedrttvar++;
2669 /* default variation is +- 1 rtt */
2671 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2673 TCPT_RANGESET(tp->t_rxtcur,
2674 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2675 tp->t_rttmin, TCPTV_REXMTMAX);
2678 * if there's an mtu associated with the route, use it
2679 * else, use the link mtu.
2681 if (rt->rt_rmx.rmx_mtu)
2682 mss = rt->rt_rmx.rmx_mtu - min_protoh;
2685 mss = nd_ifinfo[rt->rt_ifp->if_index].linkmtu -
2687 if (!in6_localaddr(&inp->in6p_faddr))
2688 mss = min(mss, tcp_v6mssdflt);
2690 mss = ifp->if_mtu - min_protoh;
2691 if (!in_localaddr(inp->inp_faddr))
2692 mss = min(mss, tcp_mssdflt);
2695 mss = min(mss, offer);
2697 * maxopd stores the maximum length of data AND options
2698 * in a segment; maxseg is the amount of data in a normal
2699 * segment. We need to store this value (maxopd) apart
2700 * from maxseg, because now every segment carries options
2701 * and thus we normally have somewhat less data in segments.
2706 * In case of T/TCP, origoffer==-1 indicates, that no segments
2707 * were received yet. In this case we just guess, otherwise
2708 * we do the same as before T/TCP.
2710 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2712 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2713 mss -= TCPOLEN_TSTAMP_APPA;
2714 if ((tp->t_flags & (TF_REQ_CC|TF_NOOPT)) == TF_REQ_CC &&
2716 (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC))
2717 mss -= TCPOLEN_CC_APPA;
2719 #if (MCLBYTES & (MCLBYTES - 1)) == 0
2721 mss &= ~(MCLBYTES-1);
2724 mss = mss / MCLBYTES * MCLBYTES;
2727 * If there's a pipesize, change the socket buffer
2728 * to that size. Make the socket buffers an integral
2729 * number of mss units; if the mss is larger than
2730 * the socket buffer, decrease the mss.
2733 if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
2735 bufsize = so->so_snd.sb_hiwat;
2739 bufsize = roundup(bufsize, mss);
2740 if (bufsize > sb_max)
2742 if (bufsize > so->so_snd.sb_hiwat)
2743 (void)sbreserve(&so->so_snd, bufsize, so, NULL);
2748 if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
2750 bufsize = so->so_rcv.sb_hiwat;
2751 if (bufsize > mss) {
2752 bufsize = roundup(bufsize, mss);
2753 if (bufsize > sb_max)
2755 if (bufsize > so->so_rcv.sb_hiwat)
2756 (void)sbreserve(&so->so_rcv, bufsize, so, NULL);
2760 * Set the slow-start flight size depending on whether this
2761 * is a local network or not.
2764 tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
2765 else if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
2766 (!isipv6 && in_localaddr(inp->inp_faddr)))
2767 tp->snd_cwnd = mss * ss_fltsz_local;
2769 tp->snd_cwnd = mss * ss_fltsz;
2771 if (rt->rt_rmx.rmx_ssthresh) {
2773 * There's some sort of gateway or interface
2774 * buffer limit on the path. Use this to set
2775 * the slow start threshhold, but set the
2776 * threshold to no less than 2*mss.
2778 tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
2779 tcpstat.tcps_usedssthresh++;
2784 * Determine the MSS option to send on an outgoing SYN.
2792 int isipv6 = ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2793 int min_protoh = isipv6 ?
2794 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
2795 sizeof(struct tcpiphdr);
2797 const int isipv6 = 0;
2798 const size_t min_protoh = sizeof(struct tcpiphdr);
2802 rt = tcp_rtlookup6(&tp->t_inpcb->inp_inc);
2804 rt = tcp_rtlookup(&tp->t_inpcb->inp_inc);
2806 return (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
2808 return (rt->rt_ifp->if_mtu - min_protoh);
2813 * When a partial ack arrives, force the retransmission of the
2814 * next unacknowledged segment. Do not clear tp->t_dupacks.
2815 * By setting snd_nxt to ti_ack, this forces retransmission timer to
2819 tcp_newreno_partial_ack(tp, th)
2823 tcp_seq onxt = tp->snd_nxt;
2824 u_long ocwnd = tp->snd_cwnd;
2826 callout_stop(tp->tt_rexmt);
2828 tp->snd_nxt = th->th_ack;
2830 * Set snd_cwnd to one segment beyond acknowledged offset
2831 * (tp->snd_una has not yet been updated when this function is called.)
2833 tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
2834 tp->t_flags |= TF_ACKNOW;
2835 (void) tcp_output(tp);
2836 tp->snd_cwnd = ocwnd;
2837 if (SEQ_GT(onxt, tp->snd_nxt))
2840 * Partial window deflation. Relies on fact that tp->snd_una
2843 tp->snd_cwnd -= (th->th_ack - tp->snd_una - tp->t_maxseg);