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.12 2003/10/19 05:19:21 hsu 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>
57 #include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
60 #include <net/route.h>
62 #include <netinet/in.h>
63 #include <netinet/in_systm.h>
64 #include <netinet/ip.h>
65 #include <netinet/ip_icmp.h> /* for ICMP_BANDLIM */
66 #include <netinet/in_var.h>
67 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
68 #include <netinet/in_pcb.h>
69 #include <netinet/ip_var.h>
70 #include <netinet/ip6.h>
71 #include <netinet/icmp6.h>
72 #include <netinet6/nd6.h>
73 #include <netinet6/ip6_var.h>
74 #include <netinet6/in6_pcb.h>
75 #include <netinet/tcp.h>
76 #include <netinet/tcp_fsm.h>
77 #include <netinet/tcp_seq.h>
78 #include <netinet/tcp_timer.h>
79 #include <netinet/tcp_var.h>
80 #include <netinet6/tcp6_var.h>
81 #include <netinet/tcpip.h>
83 #include <netinet/tcp_debug.h>
85 u_char tcp_saveipgen[40]; /* the size must be of max ip header, now IPv6 */
86 struct tcphdr tcp_savetcp;
90 #include <netipsec/ipsec.h>
91 #include <netipsec/ipsec6.h>
95 #include <netinet6/ipsec.h>
96 #include <netinet6/ipsec6.h>
97 #include <netproto/key/key.h>
100 #include <machine/in_cksum.h>
102 MALLOC_DEFINE(M_TSEGQ, "tseg_qent", "TCP segment queue entry");
104 static const int tcprexmtthresh = 3;
107 struct tcpstat tcpstat;
108 SYSCTL_STRUCT(_net_inet_tcp, TCPCTL_STATS, stats, CTLFLAG_RW,
109 &tcpstat , tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
111 static int log_in_vain = 0;
112 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
113 &log_in_vain, 0, "Log all incoming TCP connections");
115 static int blackhole = 0;
116 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
117 &blackhole, 0, "Do not send RST when dropping refused connections");
119 int tcp_delack_enabled = 1;
120 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
121 &tcp_delack_enabled, 0,
122 "Delay ACK to try and piggyback it onto a data packet");
124 #ifdef TCP_DROP_SYNFIN
125 static int drop_synfin = 0;
126 SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
127 &drop_synfin, 0, "Drop TCP packets with SYN+FIN set");
130 static int tcp_do_limitedtransmit = 1;
131 SYSCTL_INT(_net_inet_tcp, OID_AUTO, limitedtransmit, CTLFLAG_RW,
132 &tcp_do_limitedtransmit, 0, "Enable RFC 3042 (Limited Transmit)");
134 static int tcp_do_rfc3390 = 1;
135 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_RW,
137 "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
139 static int tcp_do_eifel_detect = 1;
140 SYSCTL_INT(_net_inet_tcp, OID_AUTO, eifel, CTLFLAG_RW,
141 &tcp_do_eifel_detect, 0, "Eifel detection algorithm (RFC 3522)");
143 struct inpcbhead tcb;
144 #define tcb6 tcb /* for KAME src sync over BSD*'s */
145 struct inpcbinfo tcbinfo;
147 static void tcp_dooptions(struct tcpopt *, u_char *, int, int);
148 static void tcp_pulloutofband(struct socket *,
149 struct tcphdr *, struct mbuf *, int);
150 static int tcp_reass(struct tcpcb *, struct tcphdr *, int *,
152 static void tcp_xmit_timer(struct tcpcb *, int);
153 static void tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
155 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
157 #define ND6_HINT(tp) \
159 if ((tp) && (tp)->t_inpcb && \
160 ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0 && \
161 (tp)->t_inpcb->in6p_route.ro_rt) \
162 nd6_nud_hint((tp)->t_inpcb->in6p_route.ro_rt, NULL, 0); \
169 * Indicate whether this ack should be delayed. We can delay the ack if
170 * - delayed acks are enabled and
171 * - there is no delayed ack timer in progress and
172 * - our last ack wasn't a 0-sized window. We never want to delay
173 * the ack that opens up a 0-sized window.
175 #define DELAY_ACK(tp) \
176 (tcp_delack_enabled && !callout_pending(tp->tt_delack) && \
177 (tp->t_flags & TF_RXWIN0SENT) == 0)
180 tcp_reass(tp, th, tlenp, m)
187 struct tseg_qent *p = NULL;
188 struct tseg_qent *nq;
189 struct tseg_qent *te;
190 struct socket *so = tp->t_inpcb->inp_socket;
194 * Call with th==0 after become established to
195 * force pre-ESTABLISHED data up to user socket.
200 /* Allocate a new queue entry. If we can't, just drop the pkt. XXX */
201 MALLOC(te, struct tseg_qent *, sizeof(struct tseg_qent), M_TSEGQ,
204 tcpstat.tcps_rcvmemdrop++;
210 * Find a segment which begins after this one does.
212 LIST_FOREACH(q, &tp->t_segq, tqe_q) {
213 if (SEQ_GT(q->tqe_th->th_seq, th->th_seq))
219 * If there is a preceding segment, it may provide some of
220 * our data already. If so, drop the data from the incoming
221 * segment. If it provides all of our data, drop us.
225 /* conversion to int (in i) handles seq wraparound */
226 i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
229 tcpstat.tcps_rcvduppack++;
230 tcpstat.tcps_rcvdupbyte += *tlenp;
234 * Try to present any queued data
235 * at the left window edge to the user.
236 * This is needed after the 3-WHS
239 goto present; /* ??? */
246 tcpstat.tcps_rcvoopack++;
247 tcpstat.tcps_rcvoobyte += *tlenp;
250 * While we overlap succeeding segments trim them or,
251 * if they are completely covered, dequeue them.
254 int i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
257 if (i < q->tqe_len) {
258 q->tqe_th->th_seq += i;
264 nq = LIST_NEXT(q, tqe_q);
265 LIST_REMOVE(q, tqe_q);
271 /* Insert the new segment queue entry into place. */
274 te->tqe_len = *tlenp;
277 LIST_INSERT_HEAD(&tp->t_segq, te, tqe_q);
279 LIST_INSERT_AFTER(p, te, tqe_q);
284 * Present data to user, advancing rcv_nxt through
285 * completed sequence space.
287 if (!TCPS_HAVEESTABLISHED(tp->t_state))
289 q = LIST_FIRST(&tp->t_segq);
290 if (!q || q->tqe_th->th_seq != tp->rcv_nxt)
293 tp->rcv_nxt += q->tqe_len;
294 flags = q->tqe_th->th_flags & TH_FIN;
295 nq = LIST_NEXT(q, tqe_q);
296 LIST_REMOVE(q, tqe_q);
297 if (so->so_state & SS_CANTRCVMORE)
300 sbappend(&so->so_rcv, q->tqe_m);
303 } while (q && q->tqe_th->th_seq == tp->rcv_nxt);
310 * TCP input routine, follows pages 65-76 of the
311 * protocol specification dated September, 1981 very closely.
315 tcp6_input(mp, offp, proto)
319 struct mbuf *m = *mp;
320 struct in6_ifaddr *ia6;
322 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
325 * draft-itojun-ipv6-tcp-to-anycast
326 * better place to put this in?
328 ia6 = ip6_getdstifaddr(m);
329 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
332 ip6 = mtod(m, struct ip6_hdr *);
333 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
334 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
338 tcp_input(m, *offp, proto);
344 tcp_input(m, off0, proto)
349 struct ip *ip = NULL;
351 struct inpcb *inp = NULL;
356 struct tcpcb *tp = NULL;
358 struct socket *so = 0;
359 int todrop, acked, ourfinisacked, needoutput = 0;
361 struct tcpopt to; /* options in this segment */
362 struct rmxp_tao *taop; /* pointer to our TAO cache entry */
363 struct rmxp_tao tao_noncached; /* in case there's no cached entry */
364 struct sockaddr_in *next_hop = NULL;
365 int rstreason; /* For badport_bandlim accounting purposes */
366 struct ip6_hdr *ip6 = NULL;
370 const int isipv6 = 0;
376 /* Grab info from MT_TAG mbufs prepended to the chain. */
377 for (;m && m->m_type == MT_TAG; m = m->m_next) {
378 if (m->_m_tag_id == PACKET_TAG_IPFORWARD)
379 next_hop = (struct sockaddr_in *)m->m_hdr.mh_data;
382 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
384 bzero((char *)&to, sizeof(to));
386 tcpstat.tcps_rcvtotal++;
389 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
390 ip6 = mtod(m, struct ip6_hdr *);
391 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
392 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
393 tcpstat.tcps_rcvbadsum++;
396 th = (struct tcphdr *)((caddr_t)ip6 + off0);
399 * Be proactive about unspecified IPv6 address in source.
400 * As we use all-zero to indicate unbounded/unconnected pcb,
401 * unspecified IPv6 address can be used to confuse us.
403 * Note that packets with unspecified IPv6 destination is
404 * already dropped in ip6_input.
406 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
412 * Get IP and TCP header together in first mbuf.
413 * Note: IP leaves IP header in first mbuf.
415 if (off0 > sizeof(struct ip)) {
416 ip_stripoptions(m, (struct mbuf *)0);
417 off0 = sizeof(struct ip);
419 if (m->m_len < sizeof(struct tcpiphdr)) {
420 if ((m = m_pullup(m, sizeof(struct tcpiphdr))) == 0) {
421 tcpstat.tcps_rcvshort++;
425 ip = mtod(m, struct ip *);
426 ipov = (struct ipovly *)ip;
427 th = (struct tcphdr *)((caddr_t)ip + off0);
430 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
431 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
432 th->th_sum = m->m_pkthdr.csum_data;
434 th->th_sum = in_pseudo(ip->ip_src.s_addr,
436 htonl(m->m_pkthdr.csum_data +
439 th->th_sum ^= 0xffff;
442 * Checksum extended TCP header and data.
444 len = sizeof(struct ip) + tlen;
445 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
446 ipov->ih_len = (u_short)tlen;
447 ipov->ih_len = htons(ipov->ih_len);
448 th->th_sum = in_cksum(m, len);
451 tcpstat.tcps_rcvbadsum++;
455 /* Re-initialization for later version check */
456 ip->ip_v = IPVERSION;
461 * Check that TCP offset makes sense,
462 * pull out TCP options and adjust length. XXX
464 off = th->th_off << 2;
465 if (off < sizeof(struct tcphdr) || off > tlen) {
466 tcpstat.tcps_rcvbadoff++;
469 tlen -= off; /* tlen is used instead of ti->ti_len */
470 if (off > sizeof(struct tcphdr)) {
472 IP6_EXTHDR_CHECK(m, off0, off, );
473 ip6 = mtod(m, struct ip6_hdr *);
474 th = (struct tcphdr *)((caddr_t)ip6 + off0);
476 if (m->m_len < sizeof(struct ip) + off) {
477 if ((m = m_pullup(m, sizeof(struct ip) + off))
479 tcpstat.tcps_rcvshort++;
482 ip = mtod(m, struct ip *);
483 ipov = (struct ipovly *)ip;
484 th = (struct tcphdr *)((caddr_t)ip + off0);
487 optlen = off - sizeof(struct tcphdr);
488 optp = (u_char *)(th + 1);
490 thflags = th->th_flags;
492 #ifdef TCP_DROP_SYNFIN
494 * If the drop_synfin option is enabled, drop all packets with
495 * both the SYN and FIN bits set. This prevents e.g. nmap from
496 * identifying the TCP/IP stack.
498 * This is a violation of the TCP specification.
500 if (drop_synfin && (thflags & (TH_SYN|TH_FIN)) == (TH_SYN|TH_FIN))
505 * Convert TCP protocol specific fields to host format.
507 th->th_seq = ntohl(th->th_seq);
508 th->th_ack = ntohl(th->th_ack);
509 th->th_win = ntohs(th->th_win);
510 th->th_urp = ntohs(th->th_urp);
513 * Delay droping TCP, IP headers, IPv6 ext headers, and TCP options,
514 * until after ip6_savecontrol() is called and before other functions
515 * which don't want those proto headers.
516 * Because ip6_savecontrol() is going to parse the mbuf to
517 * search for data to be passed up to user-land, it wants mbuf
518 * parameters to be unchanged.
519 * XXX: the call of ip6_savecontrol() has been obsoleted based on
520 * latest version of the advanced API (20020110).
522 drop_hdrlen = off0 + off;
525 * Locate pcb for segment.
528 /* IPFIREWALL_FORWARD section */
529 if (next_hop != NULL && isipv6 == 0) { /* IPv6 support is not yet */
531 * Transparently forwarded. Pretend to be the destination.
532 * already got one like this?
534 inp = in_pcblookup_hash(&tcbinfo, ip->ip_src, th->th_sport,
535 ip->ip_dst, th->th_dport,
536 0, m->m_pkthdr.rcvif);
538 /* It's new. Try find the ambushing socket. */
539 inp = in_pcblookup_hash(&tcbinfo,
540 ip->ip_src, th->th_sport,
543 ntohs(next_hop->sin_port) :
545 1, m->m_pkthdr.rcvif);
549 inp = in6_pcblookup_hash(&tcbinfo,
550 &ip6->ip6_src, th->th_sport,
551 &ip6->ip6_dst, th->th_dport,
552 1, m->m_pkthdr.rcvif);
554 inp = in_pcblookup_hash(&tcbinfo,
555 ip->ip_src, th->th_sport,
556 ip->ip_dst, th->th_dport,
557 1, m->m_pkthdr.rcvif);
562 if (inp != NULL && ipsec6_in_reject_so(m, inp->inp_socket)) {
563 ipsec6stat.in_polvio++;
567 if (inp != NULL && ipsec4_in_reject_so(m, inp->inp_socket)) {
568 ipsecstat.in_polvio++;
575 if (inp != NULL && ipsec6_in_reject(m, inp)) {
579 if (inp != NULL && ipsec4_in_reject(m, inp)) {
586 * If the state is CLOSED (i.e., TCB does not exist) then
587 * all data in the incoming segment is discarded.
588 * If the TCB exists but is in CLOSED state, it is embryonic,
589 * but should either do a listen or a connect soon.
594 char dbuf[INET6_ADDRSTRLEN+2], sbuf[INET6_ADDRSTRLEN+2];
596 char dbuf[4*sizeof "123"], sbuf[4*sizeof "123"];
601 strcat(dbuf, ip6_sprintf(&ip6->ip6_dst));
602 strcat(sbuf, ip6_sprintf(&ip6->ip6_src));
606 strcpy(dbuf, inet_ntoa(ip->ip_dst));
607 strcpy(sbuf, inet_ntoa(ip->ip_src));
609 switch (log_in_vain) {
611 if ((thflags & TH_SYN) == 0)
615 "Connection attempt to TCP %s:%d "
616 "from %s:%d flags:0x%02x\n",
617 dbuf, ntohs(th->th_dport), sbuf,
618 ntohs(th->th_sport), thflags);
627 if (thflags & TH_SYN)
636 rstreason = BANDLIM_RST_CLOSEDPORT;
641 rstreason = BANDLIM_RST_CLOSEDPORT;
644 if (tp->t_state == TCPS_CLOSED)
647 /* Unscale the window into a 32-bit value. */
648 if ((thflags & TH_SYN) == 0)
649 tiwin = th->th_win << tp->snd_scale;
653 so = inp->inp_socket;
656 if (so->so_options & SO_DEBUG) {
657 ostate = tp->t_state;
659 bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
661 bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
666 if (so->so_options & SO_ACCEPTCONN) {
667 struct in_conninfo inc;
670 inc.inc_isipv6 = isipv6;
673 inc.inc6_faddr = ip6->ip6_src;
674 inc.inc6_laddr = ip6->ip6_dst;
675 inc.inc6_route.ro_rt = NULL; /* XXX */
677 inc.inc_faddr = ip->ip_src;
678 inc.inc_laddr = ip->ip_dst;
679 inc.inc_route.ro_rt = NULL; /* XXX */
681 inc.inc_fport = th->th_sport;
682 inc.inc_lport = th->th_dport;
685 * If the state is LISTEN then ignore segment if it contains
686 * a RST. If the segment contains an ACK then it is bad and
687 * send a RST. If it does not contain a SYN then it is not
688 * interesting; drop it.
690 * If the state is SYN_RECEIVED (syncache) and seg contains
691 * an ACK, but not for our SYN/ACK, send a RST. If the seg
692 * contains a RST, check the sequence number to see if it
693 * is a valid reset segment.
695 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
696 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
697 if (!syncache_expand(&inc, th, &so, m)) {
699 * No syncache entry, or ACK was not
700 * for our SYN/ACK. Send a RST.
702 tcpstat.tcps_badsyn++;
703 rstreason = BANDLIM_RST_OPENPORT;
708 * Could not complete 3-way handshake,
709 * connection is being closed down, and
710 * syncache will free mbuf.
714 * Socket is created in state SYN_RECEIVED.
715 * Continue processing segment.
720 * This is what would have happened in
721 * tcp_output() when the SYN,ACK was sent.
723 tp->snd_up = tp->snd_una;
724 tp->snd_max = tp->snd_nxt = tp->iss + 1;
725 tp->last_ack_sent = tp->rcv_nxt;
727 * XXX possible bug - it doesn't appear that tp->snd_wnd is unscaled
728 * until the _second_ ACK is received:
729 * rcv SYN (set wscale opts) --> send SYN/ACK, set snd_wnd = window.
730 * rcv ACK, calculate tiwin --> process SYN_RECEIVED, determine wscale,
731 * move to ESTAB, set snd_wnd to tiwin.
733 tp->snd_wnd = tiwin; /* unscaled */
736 if (thflags & TH_RST) {
737 syncache_chkrst(&inc, th);
740 if (thflags & TH_ACK) {
741 syncache_badack(&inc);
742 tcpstat.tcps_badsyn++;
743 rstreason = BANDLIM_RST_OPENPORT;
750 * Segment's flags are (SYN) or (SYN|FIN).
754 * If deprecated address is forbidden,
755 * we do not accept SYN to deprecated interface
756 * address to prevent any new inbound connection from
757 * getting established.
758 * When we do not accept SYN, we send a TCP RST,
759 * with deprecated source address (instead of dropping
760 * it). We compromise it as it is much better for peer
761 * to send a RST, and RST will be the final packet
764 * If we do not forbid deprecated addresses, we accept
765 * the SYN packet. RFC2462 does not suggest dropping
767 * If we decipher RFC2462 5.5.4, it says like this:
768 * 1. use of deprecated addr with existing
769 * communication is okay - "SHOULD continue to be
771 * 2. use of it with new communication:
772 * (2a) "SHOULD NOT be used if alternate address
773 * with sufficient scope is available"
774 * (2b) nothing mentioned otherwise.
775 * Here we fall into (2b) case as we have no choice in
776 * our source address selection - we must obey the peer.
778 * The wording in RFC2462 is confusing, and there are
779 * multiple description text for deprecated address
780 * handling - worse, they are not exactly the same.
781 * I believe 5.5.4 is the best one, so we follow 5.5.4.
783 if (isipv6 && !ip6_use_deprecated) {
784 struct in6_ifaddr *ia6;
786 if ((ia6 = ip6_getdstifaddr(m)) &&
787 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
789 rstreason = BANDLIM_RST_OPENPORT;
795 * If it is from this socket, drop it, it must be forged.
796 * Don't bother responding if the destination was a broadcast.
798 if (th->th_dport == th->th_sport) {
800 if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
804 if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
809 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
811 * Note that it is quite possible to receive unicast
812 * link-layer packets with a broadcast IP address. Use
813 * in_broadcast() to find them.
815 if (m->m_flags & (M_BCAST|M_MCAST))
818 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
819 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
822 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
823 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
824 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
825 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
829 * SYN appears to be valid; create compressed TCP state
830 * for syncache, or perform t/tcp connection.
832 if (so->so_qlen <= so->so_qlimit) {
833 tcp_dooptions(&to, optp, optlen, 1);
834 if (!syncache_add(&inc, &to, th, &so, m))
838 * Entry added to syncache, mbuf used to
839 * send SYN,ACK packet.
843 * Segment passed TAO tests.
848 tp->t_starttime = ticks;
849 tp->t_state = TCPS_ESTABLISHED;
852 * If there is a FIN, or if there is data and the
853 * connection is local, then delay SYN,ACK(SYN) in
854 * the hope of piggy-backing it on a response
855 * segment. Otherwise must send ACK now in case
856 * the other side is slow starting.
859 ((thflags & TH_FIN) ||
861 ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
862 (!isipv6 && in_localaddr(inp->inp_faddr)))))) {
863 callout_reset(tp->tt_delack, tcp_delacktime,
864 tcp_timer_delack, tp);
865 tp->t_flags |= TF_NEEDSYN;
867 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
869 tcpstat.tcps_connects++;
877 /* XXX temp debugging */
878 /* should not happen - syncache should pick up these connections */
879 if (tp->t_state == TCPS_LISTEN)
880 panic("tcp_input: TCPS_LISTEN");
883 * Segment received on connection.
884 * Reset idle time and keep-alive timer.
886 tp->t_rcvtime = ticks;
887 if (TCPS_HAVEESTABLISHED(tp->t_state))
888 callout_reset(tp->tt_keep, tcp_keepidle, tcp_timer_keep, tp);
892 * XXX this is tradtitional behavior, may need to be cleaned up.
894 tcp_dooptions(&to, optp, optlen, thflags & TH_SYN);
895 if (thflags & TH_SYN) {
896 if (to.to_flags & TOF_SCALE) {
897 tp->t_flags |= TF_RCVD_SCALE;
898 tp->requested_s_scale = to.to_requested_s_scale;
900 if (to.to_flags & TOF_TS) {
901 tp->t_flags |= TF_RCVD_TSTMP;
902 tp->ts_recent = to.to_tsval;
903 tp->ts_recent_age = ticks;
905 if (to.to_flags & (TOF_CC|TOF_CCNEW))
906 tp->t_flags |= TF_RCVD_CC;
907 if (to.to_flags & TOF_MSS)
908 tcp_mss(tp, to.to_mss);
912 * Header prediction: check for the two common cases
913 * of a uni-directional data xfer. If the packet has
914 * no control flags, is in-sequence, the window didn't
915 * change and we're not retransmitting, it's a
916 * candidate. If the length is zero and the ack moved
917 * forward, we're the sender side of the xfer. Just
918 * free the data acked & wake any higher level process
919 * that was blocked waiting for space. If the length
920 * is non-zero and the ack didn't move, we're the
921 * receiver side. If we're getting packets in-order
922 * (the reassembly queue is empty), add the data to
923 * the socket buffer and note that we need a delayed ack.
924 * Make sure that the hidden state-flags are also off.
925 * Since we check for TCPS_ESTABLISHED above, it can only
928 if (tp->t_state == TCPS_ESTABLISHED &&
929 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
930 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
931 ((to.to_flags & TOF_TS) == 0 ||
932 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
934 * Using the CC option is compulsory if once started:
935 * the segment is OK if no T/TCP was negotiated or
936 * if the segment has a CC option equal to CCrecv
938 ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) != (TF_REQ_CC|TF_RCVD_CC) ||
939 ((to.to_flags & TOF_CC) != 0 && to.to_cc == tp->cc_recv)) &&
940 th->th_seq == tp->rcv_nxt &&
941 tiwin && tiwin == tp->snd_wnd &&
942 tp->snd_nxt == tp->snd_max) {
945 * If last ACK falls within this segment's sequence numbers,
946 * record the timestamp.
947 * NOTE that the test is modified according to the latest
948 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
950 if ((to.to_flags & TOF_TS) != 0 &&
951 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
952 tp->ts_recent_age = ticks;
953 tp->ts_recent = to.to_tsval;
957 if (SEQ_GT(th->th_ack, tp->snd_una) &&
958 SEQ_LEQ(th->th_ack, tp->snd_max) &&
959 tp->snd_cwnd >= tp->snd_wnd &&
961 tp->t_dupacks < tcprexmtthresh) ||
962 (tcp_do_newreno && !IN_FASTRECOVERY(tp)))) {
964 * this is a pure ack for outstanding data.
966 ++tcpstat.tcps_predack;
968 * "bad retransmit" recovery
970 * If Eifel detection applies, then
971 * it is deterministic, so use it
972 * unconditionally over the old heuristic.
973 * Otherwise, fall back to the old heuristic.
975 if (tcp_do_eifel_detect &&
976 (to.to_flags & TOF_TS) && to.to_tsecr &&
977 (tp->t_flags & TF_FIRSTACCACK)) {
978 /* Eifel detection applicable. */
979 if (to.to_tsecr < tp->t_rexmtTS) {
980 tcp_revert_congestion_state(tp);
981 ++tcpstat.tcps_eifeldetected;
983 } else if (tp->t_rxtshift == 1 &&
984 ticks < tp->t_badrxtwin) {
985 tcp_revert_congestion_state(tp);
986 ++tcpstat.tcps_rttdetected;
988 tp->t_flags &= ~(TF_FIRSTACCACK | TF_FASTREXMT);
990 * Recalculate the retransmit timer / rtt.
992 * Some machines (certain windows boxes)
993 * send broken timestamp replies during the
994 * SYN+ACK phase, ignore timestamps of 0.
996 if ((to.to_flags & TOF_TS) != 0 &&
999 ticks - to.to_tsecr + 1);
1000 } else if (tp->t_rtttime &&
1001 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1003 ticks - tp->t_rtttime);
1005 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1006 acked = th->th_ack - tp->snd_una;
1007 tcpstat.tcps_rcvackpack++;
1008 tcpstat.tcps_rcvackbyte += acked;
1009 sbdrop(&so->so_snd, acked);
1010 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1011 SEQ_LEQ(th->th_ack, tp->snd_recover))
1012 tp->snd_recover = th->th_ack - 1;
1013 tp->snd_una = th->th_ack;
1016 ND6_HINT(tp); /* some progress has been done */
1019 * If all outstanding data are acked, stop
1020 * retransmit timer, otherwise restart timer
1021 * using current (possibly backed-off) value.
1022 * If process is waiting for space,
1023 * wakeup/selwakeup/signal. If data
1024 * are ready to send, let tcp_output
1025 * decide between more output or persist.
1027 if (tp->snd_una == tp->snd_max)
1028 callout_stop(tp->tt_rexmt);
1029 else if (!callout_active(tp->tt_persist))
1030 callout_reset(tp->tt_rexmt,
1032 tcp_timer_rexmt, tp);
1035 if (so->so_snd.sb_cc)
1036 (void) tcp_output(tp);
1039 } else if (th->th_ack == tp->snd_una &&
1040 LIST_EMPTY(&tp->t_segq) &&
1041 tlen <= sbspace(&so->so_rcv)) {
1043 * this is a pure, in-sequence data packet
1044 * with nothing on the reassembly queue and
1045 * we have enough buffer space to take it.
1047 ++tcpstat.tcps_preddat;
1048 tp->rcv_nxt += tlen;
1049 tcpstat.tcps_rcvpack++;
1050 tcpstat.tcps_rcvbyte += tlen;
1051 ND6_HINT(tp); /* some progress has been done */
1053 * Add data to socket buffer.
1055 if (so->so_state & SS_CANTRCVMORE) {
1058 m_adj(m, drop_hdrlen); /* delayed header drop */
1059 sbappend(&so->so_rcv, m);
1062 if (DELAY_ACK(tp)) {
1063 callout_reset(tp->tt_delack, tcp_delacktime,
1064 tcp_timer_delack, tp);
1066 tp->t_flags |= TF_ACKNOW;
1074 * Calculate amount of space in receive window,
1075 * and then do TCP input processing.
1076 * Receive window is amount of space in rcv queue,
1077 * but not less than advertised window.
1081 win = sbspace(&so->so_rcv);
1084 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1087 switch (tp->t_state) {
1090 * If the state is SYN_RECEIVED:
1091 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1093 case TCPS_SYN_RECEIVED:
1094 if ((thflags & TH_ACK) &&
1095 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1096 SEQ_GT(th->th_ack, tp->snd_max))) {
1097 rstreason = BANDLIM_RST_OPENPORT;
1103 * If the state is SYN_SENT:
1104 * if seg contains an ACK, but not for our SYN, drop the input.
1105 * if seg contains a RST, then drop the connection.
1106 * if seg does not contain SYN, then drop it.
1107 * Otherwise this is an acceptable SYN segment
1108 * initialize tp->rcv_nxt and tp->irs
1109 * if seg contains ack then advance tp->snd_una
1110 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1111 * arrange for segment to be acked (eventually)
1112 * continue processing rest of data/controls, beginning with URG
1115 if ((taop = tcp_gettaocache(&inp->inp_inc)) == NULL) {
1116 taop = &tao_noncached;
1117 bzero(taop, sizeof(*taop));
1120 if ((thflags & TH_ACK) &&
1121 (SEQ_LEQ(th->th_ack, tp->iss) ||
1122 SEQ_GT(th->th_ack, tp->snd_max))) {
1124 * If we have a cached CCsent for the remote host,
1125 * hence we haven't just crashed and restarted,
1126 * do not send a RST. This may be a retransmission
1127 * from the other side after our earlier ACK was lost.
1128 * Our new SYN, when it arrives, will serve as the
1131 if (taop->tao_ccsent != 0)
1134 rstreason = BANDLIM_UNLIMITED;
1138 if (thflags & TH_RST) {
1139 if (thflags & TH_ACK)
1140 tp = tcp_drop(tp, ECONNREFUSED);
1143 if ((thflags & TH_SYN) == 0)
1145 tp->snd_wnd = th->th_win; /* initial send window */
1146 tp->cc_recv = to.to_cc; /* foreign CC */
1148 tp->irs = th->th_seq;
1150 if (thflags & TH_ACK) {
1152 * Our SYN was acked. If segment contains CC.ECHO
1153 * option, check it to make sure this segment really
1154 * matches our SYN. If not, just drop it as old
1155 * duplicate, but send an RST if we're still playing
1156 * by the old rules. If no CC.ECHO option, make sure
1157 * we don't get fooled into using T/TCP.
1159 if (to.to_flags & TOF_CCECHO) {
1160 if (tp->cc_send != to.to_ccecho) {
1161 if (taop->tao_ccsent != 0)
1164 rstreason = BANDLIM_UNLIMITED;
1169 tp->t_flags &= ~TF_RCVD_CC;
1170 tcpstat.tcps_connects++;
1172 /* Do window scaling on this connection? */
1173 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1174 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1175 tp->snd_scale = tp->requested_s_scale;
1176 tp->rcv_scale = tp->request_r_scale;
1178 /* Segment is acceptable, update cache if undefined. */
1179 if (taop->tao_ccsent == 0)
1180 taop->tao_ccsent = to.to_ccecho;
1182 tp->rcv_adv += tp->rcv_wnd;
1183 tp->snd_una++; /* SYN is acked */
1185 * If there's data, delay ACK; if there's also a FIN
1186 * ACKNOW will be turned on later.
1188 if (DELAY_ACK(tp) && tlen != 0)
1189 callout_reset(tp->tt_delack, tcp_delacktime,
1190 tcp_timer_delack, tp);
1192 tp->t_flags |= TF_ACKNOW;
1194 * Received <SYN,ACK> in SYN_SENT[*] state.
1196 * SYN_SENT --> ESTABLISHED
1197 * SYN_SENT* --> FIN_WAIT_1
1199 tp->t_starttime = ticks;
1200 if (tp->t_flags & TF_NEEDFIN) {
1201 tp->t_state = TCPS_FIN_WAIT_1;
1202 tp->t_flags &= ~TF_NEEDFIN;
1205 tp->t_state = TCPS_ESTABLISHED;
1206 callout_reset(tp->tt_keep, tcp_keepidle,
1207 tcp_timer_keep, tp);
1211 * Received initial SYN in SYN-SENT[*] state =>
1212 * simultaneous open. If segment contains CC option
1213 * and there is a cached CC, apply TAO test.
1214 * If it succeeds, connection is * half-synchronized.
1215 * Otherwise, do 3-way handshake:
1216 * SYN-SENT -> SYN-RECEIVED
1217 * SYN-SENT* -> SYN-RECEIVED*
1218 * If there was no CC option, clear cached CC value.
1220 tp->t_flags |= TF_ACKNOW;
1221 callout_stop(tp->tt_rexmt);
1222 if (to.to_flags & TOF_CC) {
1223 if (taop->tao_cc != 0 &&
1224 CC_GT(to.to_cc, taop->tao_cc)) {
1226 * update cache and make transition:
1227 * SYN-SENT -> ESTABLISHED*
1228 * SYN-SENT* -> FIN-WAIT-1*
1230 taop->tao_cc = to.to_cc;
1231 tp->t_starttime = ticks;
1232 if (tp->t_flags & TF_NEEDFIN) {
1233 tp->t_state = TCPS_FIN_WAIT_1;
1234 tp->t_flags &= ~TF_NEEDFIN;
1236 tp->t_state = TCPS_ESTABLISHED;
1237 callout_reset(tp->tt_keep,
1242 tp->t_flags |= TF_NEEDSYN;
1244 tp->t_state = TCPS_SYN_RECEIVED;
1246 /* CC.NEW or no option => invalidate cache */
1248 tp->t_state = TCPS_SYN_RECEIVED;
1254 * Advance th->th_seq to correspond to first data byte.
1255 * If data, trim to stay within window,
1256 * dropping FIN if necessary.
1259 if (tlen > tp->rcv_wnd) {
1260 todrop = tlen - tp->rcv_wnd;
1264 tcpstat.tcps_rcvpackafterwin++;
1265 tcpstat.tcps_rcvbyteafterwin += todrop;
1267 tp->snd_wl1 = th->th_seq - 1;
1268 tp->rcv_up = th->th_seq;
1270 * Client side of transaction: already sent SYN and data.
1271 * If the remote host used T/TCP to validate the SYN,
1272 * our data will be ACK'd; if so, enter normal data segment
1273 * processing in the middle of step 5, ack processing.
1274 * Otherwise, goto step 6.
1276 if (thflags & TH_ACK)
1282 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1283 * if segment contains a SYN and CC [not CC.NEW] option:
1284 * if state == TIME_WAIT and connection duration > MSL,
1285 * drop packet and send RST;
1287 * if SEG.CC > CCrecv then is new SYN, and can implicitly
1288 * ack the FIN (and data) in retransmission queue.
1289 * Complete close and delete TCPCB. Then reprocess
1290 * segment, hoping to find new TCPCB in LISTEN state;
1292 * else must be old SYN; drop it.
1293 * else do normal processing.
1297 case TCPS_TIME_WAIT:
1298 if ((thflags & TH_SYN) &&
1299 (to.to_flags & TOF_CC) && tp->cc_recv != 0) {
1300 if (tp->t_state == TCPS_TIME_WAIT &&
1301 (ticks - tp->t_starttime) > tcp_msl) {
1302 rstreason = BANDLIM_UNLIMITED;
1305 if (CC_GT(to.to_cc, tp->cc_recv)) {
1312 break; /* continue normal processing */
1316 * States other than LISTEN or SYN_SENT.
1317 * First check the RST flag and sequence number since reset segments
1318 * are exempt from the timestamp and connection count tests. This
1319 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1320 * below which allowed reset segments in half the sequence space
1321 * to fall though and be processed (which gives forged reset
1322 * segments with a random sequence number a 50 percent chance of
1323 * killing a connection).
1324 * Then check timestamp, if present.
1325 * Then check the connection count, if present.
1326 * Then check that at least some bytes of segment are within
1327 * receive window. If segment begins before rcv_nxt,
1328 * drop leading data (and SYN); if nothing left, just ack.
1331 * If the RST bit is set, check the sequence number to see
1332 * if this is a valid reset segment.
1334 * In all states except SYN-SENT, all reset (RST) segments
1335 * are validated by checking their SEQ-fields. A reset is
1336 * valid if its sequence number is in the window.
1337 * Note: this does not take into account delayed ACKs, so
1338 * we should test against last_ack_sent instead of rcv_nxt.
1339 * The sequence number in the reset segment is normally an
1340 * echo of our outgoing acknowlegement numbers, but some hosts
1341 * send a reset with the sequence number at the rightmost edge
1342 * of our receive window, and we have to handle this case.
1343 * If we have multiple segments in flight, the intial reset
1344 * segment sequence numbers will be to the left of last_ack_sent,
1345 * but they will eventually catch up.
1346 * In any case, it never made sense to trim reset segments to
1347 * fit the receive window since RFC 1122 says:
1348 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1350 * A TCP SHOULD allow a received RST segment to include data.
1353 * It has been suggested that a RST segment could contain
1354 * ASCII text that encoded and explained the cause of the
1355 * RST. No standard has yet been established for such
1358 * If the reset segment passes the sequence number test examine
1360 * SYN_RECEIVED STATE:
1361 * If passive open, return to LISTEN state.
1362 * If active open, inform user that connection was refused.
1363 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1364 * Inform user that connection was reset, and close tcb.
1365 * CLOSING, LAST_ACK STATES:
1368 * Drop the segment - see Stevens, vol. 2, p. 964 and
1371 if (thflags & TH_RST) {
1372 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
1373 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1374 switch (tp->t_state) {
1376 case TCPS_SYN_RECEIVED:
1377 so->so_error = ECONNREFUSED;
1380 case TCPS_ESTABLISHED:
1381 case TCPS_FIN_WAIT_1:
1382 case TCPS_FIN_WAIT_2:
1383 case TCPS_CLOSE_WAIT:
1384 so->so_error = ECONNRESET;
1386 tp->t_state = TCPS_CLOSED;
1387 tcpstat.tcps_drops++;
1396 case TCPS_TIME_WAIT:
1404 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1405 * and it's less than ts_recent, drop it.
1407 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
1408 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1410 /* Check to see if ts_recent is over 24 days old. */
1411 if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1413 * Invalidate ts_recent. If this segment updates
1414 * ts_recent, the age will be reset later and ts_recent
1415 * will get a valid value. If it does not, setting
1416 * ts_recent to zero will at least satisfy the
1417 * requirement that zero be placed in the timestamp
1418 * echo reply when ts_recent isn't valid. The
1419 * age isn't reset until we get a valid ts_recent
1420 * because we don't want out-of-order segments to be
1421 * dropped when ts_recent is old.
1425 tcpstat.tcps_rcvduppack++;
1426 tcpstat.tcps_rcvdupbyte += tlen;
1427 tcpstat.tcps_pawsdrop++;
1436 * If T/TCP was negotiated and the segment doesn't have CC,
1437 * or if its CC is wrong then drop the segment.
1438 * RST segments do not have to comply with this.
1440 if ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) == (TF_REQ_CC|TF_RCVD_CC) &&
1441 ((to.to_flags & TOF_CC) == 0 || tp->cc_recv != to.to_cc))
1445 * In the SYN-RECEIVED state, validate that the packet belongs to
1446 * this connection before trimming the data to fit the receive
1447 * window. Check the sequence number versus IRS since we know
1448 * the sequence numbers haven't wrapped. This is a partial fix
1449 * for the "LAND" DoS attack.
1451 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1452 rstreason = BANDLIM_RST_OPENPORT;
1456 todrop = tp->rcv_nxt - th->th_seq;
1458 if (thflags & TH_SYN) {
1468 * Following if statement from Stevens, vol. 2, p. 960.
1471 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1473 * Any valid FIN must be to the left of the window.
1474 * At this point the FIN must be a duplicate or out
1475 * of sequence; drop it.
1480 * Send an ACK to resynchronize and drop any data.
1481 * But keep on processing for RST or ACK.
1483 tp->t_flags |= TF_ACKNOW;
1485 tcpstat.tcps_rcvduppack++;
1486 tcpstat.tcps_rcvdupbyte += todrop;
1488 tcpstat.tcps_rcvpartduppack++;
1489 tcpstat.tcps_rcvpartdupbyte += todrop;
1491 drop_hdrlen += todrop; /* drop from the top afterwards */
1492 th->th_seq += todrop;
1494 if (th->th_urp > todrop)
1495 th->th_urp -= todrop;
1503 * If new data are received on a connection after the
1504 * user processes are gone, then RST the other end.
1506 if ((so->so_state & SS_NOFDREF) &&
1507 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1509 tcpstat.tcps_rcvafterclose++;
1510 rstreason = BANDLIM_UNLIMITED;
1515 * If segment ends after window, drop trailing data
1516 * (and PUSH and FIN); if nothing left, just ACK.
1518 todrop = (th->th_seq+tlen) - (tp->rcv_nxt+tp->rcv_wnd);
1520 tcpstat.tcps_rcvpackafterwin++;
1521 if (todrop >= tlen) {
1522 tcpstat.tcps_rcvbyteafterwin += tlen;
1524 * If a new connection request is received
1525 * while in TIME_WAIT, drop the old connection
1526 * and start over if the sequence numbers
1527 * are above the previous ones.
1529 if (thflags & TH_SYN &&
1530 tp->t_state == TCPS_TIME_WAIT &&
1531 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1536 * If window is closed can only take segments at
1537 * window edge, and have to drop data and PUSH from
1538 * incoming segments. Continue processing, but
1539 * remember to ack. Otherwise, drop segment
1542 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1543 tp->t_flags |= TF_ACKNOW;
1544 tcpstat.tcps_rcvwinprobe++;
1548 tcpstat.tcps_rcvbyteafterwin += todrop;
1551 thflags &= ~(TH_PUSH|TH_FIN);
1555 * If last ACK falls within this segment's sequence numbers,
1556 * record its timestamp.
1557 * NOTE that the test is modified according to the latest
1558 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1560 if ((to.to_flags & TOF_TS) != 0 &&
1561 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1562 tp->ts_recent_age = ticks;
1563 tp->ts_recent = to.to_tsval;
1567 * If a SYN is in the window, then this is an
1568 * error and we send an RST and drop the connection.
1570 if (thflags & TH_SYN) {
1571 tp = tcp_drop(tp, ECONNRESET);
1572 rstreason = BANDLIM_UNLIMITED;
1577 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1578 * flag is on (half-synchronized state), then queue data for
1579 * later processing; else drop segment and return.
1581 if ((thflags & TH_ACK) == 0) {
1582 if (tp->t_state == TCPS_SYN_RECEIVED ||
1583 (tp->t_flags & TF_NEEDSYN))
1592 switch (tp->t_state) {
1595 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1596 * ESTABLISHED state and continue processing.
1597 * The ACK was checked above.
1599 case TCPS_SYN_RECEIVED:
1601 tcpstat.tcps_connects++;
1603 /* Do window scaling? */
1604 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1605 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1606 tp->snd_scale = tp->requested_s_scale;
1607 tp->rcv_scale = tp->request_r_scale;
1610 * Upon successful completion of 3-way handshake,
1611 * update cache.CC if it was undefined, pass any queued
1612 * data to the user, and advance state appropriately.
1614 if ((taop = tcp_gettaocache(&inp->inp_inc)) != NULL &&
1616 taop->tao_cc = tp->cc_recv;
1620 * SYN-RECEIVED -> ESTABLISHED
1621 * SYN-RECEIVED* -> FIN-WAIT-1
1623 tp->t_starttime = ticks;
1624 if (tp->t_flags & TF_NEEDFIN) {
1625 tp->t_state = TCPS_FIN_WAIT_1;
1626 tp->t_flags &= ~TF_NEEDFIN;
1628 tp->t_state = TCPS_ESTABLISHED;
1629 callout_reset(tp->tt_keep, tcp_keepidle,
1630 tcp_timer_keep, tp);
1633 * If segment contains data or ACK, will call tcp_reass()
1634 * later; if not, do so now to pass queued data to user.
1636 if (tlen == 0 && (thflags & TH_FIN) == 0)
1637 (void) tcp_reass(tp, (struct tcphdr *)0, 0,
1639 tp->snd_wl1 = th->th_seq - 1;
1643 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1644 * ACKs. If the ack is in the range
1645 * tp->snd_una < th->th_ack <= tp->snd_max
1646 * then advance tp->snd_una to th->th_ack and drop
1647 * data from the retransmission queue. If this ACK reflects
1648 * more up to date window information we update our window information.
1650 case TCPS_ESTABLISHED:
1651 case TCPS_FIN_WAIT_1:
1652 case TCPS_FIN_WAIT_2:
1653 case TCPS_CLOSE_WAIT:
1656 case TCPS_TIME_WAIT:
1658 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1659 if (tlen == 0 && tiwin == tp->snd_wnd) {
1660 tcpstat.tcps_rcvdupack++;
1662 * If we have outstanding data (other than
1663 * a window probe), this is a completely
1664 * duplicate ack (ie, window info didn't
1665 * change), the ack is the biggest we've
1666 * seen and we've seen exactly our rexmt
1667 * threshhold of them, assume a packet
1668 * has been dropped and retransmit it.
1669 * Kludge snd_nxt & the congestion
1670 * window so we send only this one
1673 * We know we're losing at the current
1674 * window size so do congestion avoidance
1675 * (set ssthresh to half the current window
1676 * and pull our congestion window back to
1677 * the new ssthresh).
1679 * Dup acks mean that packets have left the
1680 * network (they're now cached at the receiver)
1681 * so bump cwnd by the amount in the receiver
1682 * to keep a constant cwnd packets in the
1685 if (!callout_active(tp->tt_rexmt) ||
1686 th->th_ack != tp->snd_una)
1688 else if (++tp->t_dupacks > tcprexmtthresh ||
1690 IN_FASTRECOVERY(tp))) {
1691 tp->snd_cwnd += tp->t_maxseg;
1692 (void) tcp_output(tp);
1694 } else if (tp->t_dupacks == tcprexmtthresh) {
1695 tcp_seq onxt = tp->snd_nxt;
1697 if (tcp_do_newreno &&
1703 if (tcp_do_eifel_detect &&
1704 (tp->t_flags & TF_RCVD_TSTMP)) {
1705 tcp_save_congestion_state(tp);
1706 tp->t_flags |= TF_FASTREXMT;
1708 win = min(tp->snd_wnd, tp->snd_cwnd) /
1712 tp->snd_ssthresh = win * tp->t_maxseg;
1713 ENTER_FASTRECOVERY(tp);
1714 tp->snd_recover = tp->snd_max;
1715 callout_stop(tp->tt_rexmt);
1717 tp->snd_nxt = th->th_ack;
1718 tp->snd_cwnd = tp->t_maxseg;
1719 (void) tcp_output(tp);
1720 KASSERT(tp->snd_limited <= 2,
1721 ("tp->snd_limited too big"));
1722 tp->snd_cwnd = tp->snd_ssthresh +
1724 (tp->t_dupacks - tp->snd_limited));
1725 if (SEQ_GT(onxt, tp->snd_nxt))
1728 } else if (tcp_do_limitedtransmit) {
1729 u_long oldcwnd = tp->snd_cwnd;
1730 tcp_seq oldsndmax = tp->snd_max;
1732 KASSERT(tp->t_dupacks == 1 ||
1734 ("dupacks not 1 or 2"));
1735 if (tp->t_dupacks == 1)
1736 tp->snd_limited = 0;
1738 (tp->snd_nxt - tp->snd_una) +
1739 (tp->t_dupacks - tp->snd_limited) *
1741 (void) tcp_output(tp);
1742 sent = tp->snd_max - oldsndmax;
1743 if (sent > tp->t_maxseg) {
1744 KASSERT(tp->snd_limited == 0 &&
1747 tp->snd_limited = 2;
1748 } else if (sent > 0)
1750 tp->snd_cwnd = oldcwnd;
1758 KASSERT(SEQ_GT(th->th_ack, tp->snd_una), ("th_ack <= snd_una"));
1761 * If the congestion window was inflated to account
1762 * for the other side's cached packets, retract it.
1764 if (tcp_do_newreno) {
1765 if (IN_FASTRECOVERY(tp)) {
1766 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
1767 tcp_newreno_partial_ack(tp, th);
1770 * Window inflation should have left us
1771 * with approximately snd_ssthresh
1773 * But in case we would be inclined to
1774 * send a burst, better to do it via
1775 * the slow start mechanism.
1777 if (SEQ_GT(th->th_ack +
1780 tp->snd_cwnd = tp->snd_max -
1784 tp->snd_cwnd = tp->snd_ssthresh;
1788 if (tp->t_dupacks >= tcprexmtthresh &&
1789 tp->snd_cwnd > tp->snd_ssthresh)
1790 tp->snd_cwnd = tp->snd_ssthresh;
1793 if (SEQ_GT(th->th_ack, tp->snd_max)) {
1794 tcpstat.tcps_rcvacktoomuch++;
1798 * If we reach this point, ACK is not a duplicate,
1799 * i.e., it ACKs something we sent.
1801 if (tp->t_flags & TF_NEEDSYN) {
1803 * T/TCP: Connection was half-synchronized, and our
1804 * SYN has been ACK'd (so connection is now fully
1805 * synchronized). Go to non-starred state,
1806 * increment snd_una for ACK of SYN, and check if
1807 * we can do window scaling.
1809 tp->t_flags &= ~TF_NEEDSYN;
1811 /* Do window scaling? */
1812 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1813 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1814 tp->snd_scale = tp->requested_s_scale;
1815 tp->rcv_scale = tp->request_r_scale;
1820 acked = th->th_ack - tp->snd_una;
1821 tcpstat.tcps_rcvackpack++;
1822 tcpstat.tcps_rcvackbyte += acked;
1825 * If we just performed our first retransmit, and the ACK
1826 * arrives within our recovery window, then it was a mistake
1827 * to do the retransmit in the first place. Recover our
1828 * original cwnd and ssthresh, and proceed to transmit where
1831 if (tcp_do_eifel_detect && acked &&
1832 (to.to_flags & TOF_TS) && to.to_tsecr &&
1833 (tp->t_flags & TF_FIRSTACCACK)) {
1834 /* Eifel detection applicable. */
1835 if (to.to_tsecr < tp->t_rexmtTS) {
1836 tcp_revert_congestion_state(tp);
1837 ++tcpstat.tcps_eifeldetected;
1839 } else if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
1840 tcp_revert_congestion_state(tp);
1841 ++tcpstat.tcps_rttdetected;
1845 * If we have a timestamp reply, update smoothed
1846 * round trip time. If no timestamp is present but
1847 * transmit timer is running and timed sequence
1848 * number was acked, update smoothed round trip time.
1849 * Since we now have an rtt measurement, cancel the
1850 * timer backoff (cf., Phil Karn's retransmit alg.).
1851 * Recompute the initial retransmit timer.
1853 * Some machines (certain windows boxes) send broken
1854 * timestamp replies during the SYN+ACK phase, ignore
1857 if ((to.to_flags & TOF_TS) != 0 &&
1859 tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
1860 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
1861 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
1863 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1866 * If all outstanding data is acked, stop retransmit
1867 * timer and remember to restart (more output or persist).
1868 * If there is more data to be acked, restart retransmit
1869 * timer, using current (possibly backed-off) value.
1871 if (th->th_ack == tp->snd_max) {
1872 callout_stop(tp->tt_rexmt);
1874 } else if (!callout_active(tp->tt_persist))
1875 callout_reset(tp->tt_rexmt, tp->t_rxtcur,
1876 tcp_timer_rexmt, tp);
1879 * If no data (only SYN) was ACK'd,
1880 * skip rest of ACK processing.
1885 /* Stop looking for an acceptable ACK since one was received. */
1886 tp->t_flags &= ~(TF_FIRSTACCACK | TF_FASTREXMT);
1889 * When new data is acked, open the congestion window.
1890 * If the window gives us less than ssthresh packets
1891 * in flight, open exponentially (maxseg per packet).
1892 * Otherwise open linearly: maxseg per window
1893 * (maxseg^2 / cwnd per packet).
1895 if (!tcp_do_newreno || !IN_FASTRECOVERY(tp)) {
1896 u_int cw = tp->snd_cwnd;
1897 u_int incr = tp->t_maxseg;
1898 if (cw > tp->snd_ssthresh)
1899 incr = incr * incr / cw;
1900 tp->snd_cwnd = min(cw+incr, TCP_MAXWIN<<tp->snd_scale);
1902 if (acked > so->so_snd.sb_cc) {
1903 tp->snd_wnd -= so->so_snd.sb_cc;
1904 sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
1907 sbdrop(&so->so_snd, acked);
1908 tp->snd_wnd -= acked;
1912 /* detect una wraparound */
1913 if (tcp_do_newreno && !IN_FASTRECOVERY(tp) &&
1914 SEQ_GT(tp->snd_una, tp->snd_recover) &&
1915 SEQ_LEQ(th->th_ack, tp->snd_recover))
1916 tp->snd_recover = th->th_ack - 1;
1917 if (tcp_do_newreno && IN_FASTRECOVERY(tp) &&
1918 SEQ_GEQ(th->th_ack, tp->snd_recover))
1919 EXIT_FASTRECOVERY(tp);
1920 tp->snd_una = th->th_ack;
1921 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1922 tp->snd_nxt = tp->snd_una;
1924 switch (tp->t_state) {
1927 * In FIN_WAIT_1 STATE in addition to the processing
1928 * for the ESTABLISHED state if our FIN is now acknowledged
1929 * then enter FIN_WAIT_2.
1931 case TCPS_FIN_WAIT_1:
1932 if (ourfinisacked) {
1934 * If we can't receive any more
1935 * data, then closing user can proceed.
1936 * Starting the timer is contrary to the
1937 * specification, but if we don't get a FIN
1938 * we'll hang forever.
1940 if (so->so_state & SS_CANTRCVMORE) {
1941 soisdisconnected(so);
1942 callout_reset(tp->tt_2msl, tcp_maxidle,
1943 tcp_timer_2msl, tp);
1945 tp->t_state = TCPS_FIN_WAIT_2;
1950 * In CLOSING STATE in addition to the processing for
1951 * the ESTABLISHED state if the ACK acknowledges our FIN
1952 * then enter the TIME-WAIT state, otherwise ignore
1956 if (ourfinisacked) {
1957 tp->t_state = TCPS_TIME_WAIT;
1958 tcp_canceltimers(tp);
1959 /* Shorten TIME_WAIT [RFC-1644, p.28] */
1960 if (tp->cc_recv != 0 &&
1961 (ticks - tp->t_starttime) < tcp_msl)
1962 callout_reset(tp->tt_2msl,
1965 tcp_timer_2msl, tp);
1967 callout_reset(tp->tt_2msl, 2 * tcp_msl,
1968 tcp_timer_2msl, tp);
1969 soisdisconnected(so);
1974 * In LAST_ACK, we may still be waiting for data to drain
1975 * and/or to be acked, as well as for the ack of our FIN.
1976 * If our FIN is now acknowledged, delete the TCB,
1977 * enter the closed state and return.
1980 if (ourfinisacked) {
1987 * In TIME_WAIT state the only thing that should arrive
1988 * is a retransmission of the remote FIN. Acknowledge
1989 * it and restart the finack timer.
1991 case TCPS_TIME_WAIT:
1992 callout_reset(tp->tt_2msl, 2 * tcp_msl,
1993 tcp_timer_2msl, tp);
2000 * Update window information.
2001 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2003 if ((thflags & TH_ACK) &&
2004 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2005 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2006 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2007 /* keep track of pure window updates */
2009 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2010 tcpstat.tcps_rcvwinupd++;
2011 tp->snd_wnd = tiwin;
2012 tp->snd_wl1 = th->th_seq;
2013 tp->snd_wl2 = th->th_ack;
2014 if (tp->snd_wnd > tp->max_sndwnd)
2015 tp->max_sndwnd = tp->snd_wnd;
2020 * Process segments with URG.
2022 if ((thflags & TH_URG) && th->th_urp &&
2023 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2025 * This is a kludge, but if we receive and accept
2026 * random urgent pointers, we'll crash in
2027 * soreceive. It's hard to imagine someone
2028 * actually wanting to send this much urgent data.
2030 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2031 th->th_urp = 0; /* XXX */
2032 thflags &= ~TH_URG; /* XXX */
2033 goto dodata; /* XXX */
2036 * If this segment advances the known urgent pointer,
2037 * then mark the data stream. This should not happen
2038 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2039 * a FIN has been received from the remote side.
2040 * In these states we ignore the URG.
2042 * According to RFC961 (Assigned Protocols),
2043 * the urgent pointer points to the last octet
2044 * of urgent data. We continue, however,
2045 * to consider it to indicate the first octet
2046 * of data past the urgent section as the original
2047 * spec states (in one of two places).
2049 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2050 tp->rcv_up = th->th_seq + th->th_urp;
2051 so->so_oobmark = so->so_rcv.sb_cc +
2052 (tp->rcv_up - tp->rcv_nxt) - 1;
2053 if (so->so_oobmark == 0)
2054 so->so_state |= SS_RCVATMARK;
2056 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2059 * Remove out of band data so doesn't get presented to user.
2060 * This can happen independent of advancing the URG pointer,
2061 * but if two URG's are pending at once, some out-of-band
2062 * data may creep in... ick.
2064 if (th->th_urp <= (u_long)tlen
2066 && (so->so_options & SO_OOBINLINE) == 0
2069 tcp_pulloutofband(so, th, m,
2070 drop_hdrlen); /* hdr drop is delayed */
2073 * If no out of band data is expected,
2074 * pull receive urgent pointer along
2075 * with the receive window.
2077 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2078 tp->rcv_up = tp->rcv_nxt;
2083 * Process the segment text, merging it into the TCP sequencing queue,
2084 * and arranging for acknowledgment of receipt if necessary.
2085 * This process logically involves adjusting tp->rcv_wnd as data
2086 * is presented to the user (this happens in tcp_usrreq.c,
2087 * case PRU_RCVD). If a FIN has already been received on this
2088 * connection then we just ignore the text.
2090 if ((tlen || (thflags & TH_FIN)) &&
2091 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2092 m_adj(m, drop_hdrlen); /* delayed header drop */
2094 * Insert segment which includes th into TCP reassembly queue
2095 * with control block tp. Set thflags to whether reassembly now
2096 * includes a segment with FIN. This handles the common case
2097 * inline (segment is the next to be received on an established
2098 * connection, and the queue is empty), avoiding linkage into
2099 * and removal from the queue and repetition of various
2101 * Set DELACK for segments received in order, but ack
2102 * immediately when segments are out of order (so
2103 * fast retransmit can work).
2105 if (th->th_seq == tp->rcv_nxt &&
2106 LIST_EMPTY(&tp->t_segq) &&
2107 TCPS_HAVEESTABLISHED(tp->t_state)) {
2109 callout_reset(tp->tt_delack, tcp_delacktime,
2110 tcp_timer_delack, tp);
2112 tp->t_flags |= TF_ACKNOW;
2113 tp->rcv_nxt += tlen;
2114 thflags = th->th_flags & TH_FIN;
2115 tcpstat.tcps_rcvpack++;
2116 tcpstat.tcps_rcvbyte += tlen;
2118 if (so->so_state & SS_CANTRCVMORE)
2121 sbappend(&so->so_rcv, m);
2124 thflags = tcp_reass(tp, th, &tlen, m);
2125 tp->t_flags |= TF_ACKNOW;
2129 * Note the amount of data that peer has sent into
2130 * our window, in order to estimate the sender's
2133 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2140 * If FIN is received ACK the FIN and let the user know
2141 * that the connection is closing.
2143 if (thflags & TH_FIN) {
2144 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2147 * If connection is half-synchronized
2148 * (ie NEEDSYN flag on) then delay ACK,
2149 * so it may be piggybacked when SYN is sent.
2150 * Otherwise, since we received a FIN then no
2151 * more input can be expected, send ACK now.
2153 if (DELAY_ACK(tp) && (tp->t_flags & TF_NEEDSYN))
2154 callout_reset(tp->tt_delack, tcp_delacktime,
2155 tcp_timer_delack, tp);
2157 tp->t_flags |= TF_ACKNOW;
2160 switch (tp->t_state) {
2163 * In SYN_RECEIVED and ESTABLISHED STATES
2164 * enter the CLOSE_WAIT state.
2166 case TCPS_SYN_RECEIVED:
2167 tp->t_starttime = ticks;
2169 case TCPS_ESTABLISHED:
2170 tp->t_state = TCPS_CLOSE_WAIT;
2174 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2175 * enter the CLOSING state.
2177 case TCPS_FIN_WAIT_1:
2178 tp->t_state = TCPS_CLOSING;
2182 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2183 * starting the time-wait timer, turning off the other
2186 case TCPS_FIN_WAIT_2:
2187 tp->t_state = TCPS_TIME_WAIT;
2188 tcp_canceltimers(tp);
2189 /* Shorten TIME_WAIT [RFC-1644, p.28] */
2190 if (tp->cc_recv != 0 &&
2191 (ticks - tp->t_starttime) < tcp_msl) {
2192 callout_reset(tp->tt_2msl,
2193 tp->t_rxtcur * TCPTV_TWTRUNC,
2194 tcp_timer_2msl, tp);
2195 /* For transaction client, force ACK now. */
2196 tp->t_flags |= TF_ACKNOW;
2199 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2200 tcp_timer_2msl, tp);
2201 soisdisconnected(so);
2205 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2207 case TCPS_TIME_WAIT:
2208 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2209 tcp_timer_2msl, tp);
2214 if (so->so_options & SO_DEBUG)
2215 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2220 * Return any desired output.
2222 if (needoutput || (tp->t_flags & TF_ACKNOW))
2223 (void) tcp_output(tp);
2228 * Generate an ACK dropping incoming segment if it occupies
2229 * sequence space, where the ACK reflects our state.
2231 * We can now skip the test for the RST flag since all
2232 * paths to this code happen after packets containing
2233 * RST have been dropped.
2235 * In the SYN-RECEIVED state, don't send an ACK unless the
2236 * segment we received passes the SYN-RECEIVED ACK test.
2237 * If it fails send a RST. This breaks the loop in the
2238 * "LAND" DoS attack, and also prevents an ACK storm
2239 * between two listening ports that have been sent forged
2240 * SYN segments, each with the source address of the other.
2242 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2243 (SEQ_GT(tp->snd_una, th->th_ack) ||
2244 SEQ_GT(th->th_ack, tp->snd_max)) ) {
2245 rstreason = BANDLIM_RST_OPENPORT;
2249 if (so->so_options & SO_DEBUG)
2250 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2254 tp->t_flags |= TF_ACKNOW;
2255 (void) tcp_output(tp);
2260 * Generate a RST, dropping incoming segment.
2261 * Make ACK acceptable to originator of segment.
2262 * Don't bother to respond if destination was broadcast/multicast.
2264 if ((thflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
2267 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2268 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2271 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2272 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2273 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2274 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2277 /* IPv6 anycast check is done at tcp6_input() */
2280 * Perform bandwidth limiting.
2283 if (badport_bandlim(rstreason) < 0)
2288 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2289 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2292 if (thflags & TH_ACK)
2293 /* mtod() below is safe as long as hdr dropping is delayed */
2294 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
2297 if (thflags & TH_SYN)
2299 /* mtod() below is safe as long as hdr dropping is delayed */
2300 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
2301 (tcp_seq)0, TH_RST|TH_ACK);
2307 * Drop space held by incoming segment and return.
2310 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2311 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2319 * Parse TCP options and place in tcpopt.
2322 tcp_dooptions(to, cp, cnt, is_syn)
2330 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2332 if (opt == TCPOPT_EOL)
2334 if (opt == TCPOPT_NOP)
2340 if (optlen < 2 || optlen > cnt)
2345 if (optlen != TCPOLEN_MAXSEG)
2349 to->to_flags |= TOF_MSS;
2350 bcopy((char *)cp + 2,
2351 (char *)&to->to_mss, sizeof(to->to_mss));
2352 to->to_mss = ntohs(to->to_mss);
2355 if (optlen != TCPOLEN_WINDOW)
2359 to->to_flags |= TOF_SCALE;
2360 to->to_requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
2362 case TCPOPT_TIMESTAMP:
2363 if (optlen != TCPOLEN_TIMESTAMP)
2365 to->to_flags |= TOF_TS;
2366 bcopy((char *)cp + 2,
2367 (char *)&to->to_tsval, sizeof(to->to_tsval));
2368 to->to_tsval = ntohl(to->to_tsval);
2369 bcopy((char *)cp + 6,
2370 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
2371 to->to_tsecr = ntohl(to->to_tsecr);
2374 if (optlen != TCPOLEN_CC)
2376 to->to_flags |= TOF_CC;
2377 bcopy((char *)cp + 2,
2378 (char *)&to->to_cc, sizeof(to->to_cc));
2379 to->to_cc = ntohl(to->to_cc);
2382 if (optlen != TCPOLEN_CC)
2386 to->to_flags |= TOF_CCNEW;
2387 bcopy((char *)cp + 2,
2388 (char *)&to->to_cc, sizeof(to->to_cc));
2389 to->to_cc = ntohl(to->to_cc);
2392 if (optlen != TCPOLEN_CC)
2396 to->to_flags |= TOF_CCECHO;
2397 bcopy((char *)cp + 2,
2398 (char *)&to->to_ccecho, sizeof(to->to_ccecho));
2399 to->to_ccecho = ntohl(to->to_ccecho);
2408 * Pull out of band byte out of a segment so
2409 * it doesn't appear in the user's data queue.
2410 * It is still reflected in the segment length for
2411 * sequencing purposes.
2414 tcp_pulloutofband(so, th, m, off)
2418 int off; /* delayed to be droped hdrlen */
2420 int cnt = off + th->th_urp - 1;
2423 if (m->m_len > cnt) {
2424 char *cp = mtod(m, caddr_t) + cnt;
2425 struct tcpcb *tp = sototcpcb(so);
2428 tp->t_oobflags |= TCPOOB_HAVEDATA;
2429 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2431 if (m->m_flags & M_PKTHDR)
2440 panic("tcp_pulloutofband");
2444 * Collect new round-trip time estimate
2445 * and update averages and current timeout.
2448 tcp_xmit_timer(tp, rtt)
2454 tcpstat.tcps_rttupdated++;
2456 if (tp->t_srtt != 0) {
2458 * srtt is stored as fixed point with 5 bits after the
2459 * binary point (i.e., scaled by 8). The following magic
2460 * is equivalent to the smoothing algorithm in rfc793 with
2461 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2462 * point). Adjust rtt to origin 0.
2464 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2465 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2467 if ((tp->t_srtt += delta) <= 0)
2471 * We accumulate a smoothed rtt variance (actually, a
2472 * smoothed mean difference), then set the retransmit
2473 * timer to smoothed rtt + 4 times the smoothed variance.
2474 * rttvar is stored as fixed point with 4 bits after the
2475 * binary point (scaled by 16). The following is
2476 * equivalent to rfc793 smoothing with an alpha of .75
2477 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2478 * rfc793's wired-in beta.
2482 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2483 if ((tp->t_rttvar += delta) <= 0)
2485 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2486 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2489 * No rtt measurement yet - use the unsmoothed rtt.
2490 * Set the variance to half the rtt (so our first
2491 * retransmit happens at 3*rtt).
2493 tp->t_srtt = rtt << TCP_RTT_SHIFT;
2494 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2495 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2501 * the retransmit should happen at rtt + 4 * rttvar.
2502 * Because of the way we do the smoothing, srtt and rttvar
2503 * will each average +1/2 tick of bias. When we compute
2504 * the retransmit timer, we want 1/2 tick of rounding and
2505 * 1 extra tick because of +-1/2 tick uncertainty in the
2506 * firing of the timer. The bias will give us exactly the
2507 * 1.5 tick we need. But, because the bias is
2508 * statistical, we have to test that we don't drop below
2509 * the minimum feasible timer (which is 2 ticks).
2511 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2512 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2515 * We received an ack for a packet that wasn't retransmitted;
2516 * it is probably safe to discard any error indications we've
2517 * received recently. This isn't quite right, but close enough
2518 * for now (a route might have failed after we sent a segment,
2519 * and the return path might not be symmetrical).
2521 tp->t_softerror = 0;
2525 * Determine a reasonable value for maxseg size.
2526 * If the route is known, check route for mtu.
2527 * If none, use an mss that can be handled on the outgoing
2528 * interface without forcing IP to fragment; if bigger than
2529 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2530 * to utilize large mbufs. If no route is found, route has no mtu,
2531 * or the destination isn't local, use a default, hopefully conservative
2532 * size (usually 512 or the default IP max size, but no more than the mtu
2533 * of the interface), as we can't discover anything about intervening
2534 * gateways or networks. We also initialize the congestion/slow start
2535 * window to be a single segment if the destination isn't local.
2536 * While looking at the routing entry, we also initialize other path-dependent
2537 * parameters from pre-set or cached values in the routing entry.
2539 * Also take into account the space needed for options that we
2540 * send regularly. Make maxseg shorter by that amount to assure
2541 * that we can send maxseg amount of data even when the options
2542 * are present. Store the upper limit of the length of options plus
2545 * NOTE that this routine is only called when we process an incoming
2546 * segment, for outgoing segments only tcp_mssopt is called.
2548 * In case of T/TCP, we call this routine during implicit connection
2549 * setup as well (offer = -1), to initialize maxseg from the cached
2561 struct inpcb *inp = tp->t_inpcb;
2563 struct rmxp_tao *taop;
2564 int origoffer = offer;
2566 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2567 size_t min_protoh = isipv6 ?
2568 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
2569 sizeof(struct tcpiphdr);
2571 const int isipv6 = 0;
2572 const size_t min_protoh = sizeof(struct tcpiphdr);
2576 rt = tcp_rtlookup6(&inp->inp_inc);
2578 rt = tcp_rtlookup(&inp->inp_inc);
2580 tp->t_maxopd = tp->t_maxseg =
2581 isipv6 ? tcp_v6mssdflt : tcp_mssdflt;
2585 so = inp->inp_socket;
2587 taop = rmx_taop(rt->rt_rmx);
2589 * Offer == -1 means that we didn't receive SYN yet,
2590 * use cached value in that case;
2593 offer = taop->tao_mssopt;
2595 * Offer == 0 means that there was no MSS on the SYN segment,
2596 * in this case we use tcp_mssdflt.
2599 offer = isipv6 ? tcp_v6mssdflt : tcp_mssdflt;
2602 * Sanity check: make sure that maxopd will be large
2603 * enough to allow some data on segments even is the
2604 * all the option space is used (40bytes). Otherwise
2605 * funny things may happen in tcp_output.
2607 offer = max(offer, 64);
2608 taop->tao_mssopt = offer;
2611 * While we're here, check if there's an initial rtt
2612 * or rttvar. Convert from the route-table units
2613 * to scaled multiples of the slow timeout timer.
2615 if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2617 * XXX the lock bit for RTT indicates that the value
2618 * is also a minimum value; this is subject to time.
2620 if (rt->rt_rmx.rmx_locks & RTV_RTT)
2621 tp->t_rttmin = rtt / (RTM_RTTUNIT / hz);
2622 tp->t_srtt = rtt / (RTM_RTTUNIT / (hz * TCP_RTT_SCALE));
2623 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
2624 tcpstat.tcps_usedrtt++;
2625 if (rt->rt_rmx.rmx_rttvar) {
2626 tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2627 (RTM_RTTUNIT / (hz * TCP_RTTVAR_SCALE));
2628 tcpstat.tcps_usedrttvar++;
2630 /* default variation is +- 1 rtt */
2632 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2634 TCPT_RANGESET(tp->t_rxtcur,
2635 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2636 tp->t_rttmin, TCPTV_REXMTMAX);
2639 * if there's an mtu associated with the route, use it
2640 * else, use the link mtu.
2642 if (rt->rt_rmx.rmx_mtu)
2643 mss = rt->rt_rmx.rmx_mtu - min_protoh;
2646 mss = nd_ifinfo[rt->rt_ifp->if_index].linkmtu -
2648 if (!in6_localaddr(&inp->in6p_faddr))
2649 mss = min(mss, tcp_v6mssdflt);
2651 mss = ifp->if_mtu - min_protoh;
2652 if (!in_localaddr(inp->inp_faddr))
2653 mss = min(mss, tcp_mssdflt);
2656 mss = min(mss, offer);
2658 * maxopd stores the maximum length of data AND options
2659 * in a segment; maxseg is the amount of data in a normal
2660 * segment. We need to store this value (maxopd) apart
2661 * from maxseg, because now every segment carries options
2662 * and thus we normally have somewhat less data in segments.
2667 * In case of T/TCP, origoffer==-1 indicates, that no segments
2668 * were received yet. In this case we just guess, otherwise
2669 * we do the same as before T/TCP.
2671 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2673 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2674 mss -= TCPOLEN_TSTAMP_APPA;
2675 if ((tp->t_flags & (TF_REQ_CC|TF_NOOPT)) == TF_REQ_CC &&
2677 (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC))
2678 mss -= TCPOLEN_CC_APPA;
2680 #if (MCLBYTES & (MCLBYTES - 1)) == 0
2682 mss &= ~(MCLBYTES-1);
2685 mss = mss / MCLBYTES * MCLBYTES;
2688 * If there's a pipesize, change the socket buffer
2689 * to that size. Make the socket buffers an integral
2690 * number of mss units; if the mss is larger than
2691 * the socket buffer, decrease the mss.
2694 if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
2696 bufsize = so->so_snd.sb_hiwat;
2700 bufsize = roundup(bufsize, mss);
2701 if (bufsize > sb_max)
2703 if (bufsize > so->so_snd.sb_hiwat)
2704 (void)sbreserve(&so->so_snd, bufsize, so, NULL);
2709 if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
2711 bufsize = so->so_rcv.sb_hiwat;
2712 if (bufsize > mss) {
2713 bufsize = roundup(bufsize, mss);
2714 if (bufsize > sb_max)
2716 if (bufsize > so->so_rcv.sb_hiwat)
2717 (void)sbreserve(&so->so_rcv, bufsize, so, NULL);
2721 * Set the slow-start flight size depending on whether this
2722 * is a local network or not.
2725 tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
2726 else if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
2727 (!isipv6 && in_localaddr(inp->inp_faddr)))
2728 tp->snd_cwnd = mss * ss_fltsz_local;
2730 tp->snd_cwnd = mss * ss_fltsz;
2732 if (rt->rt_rmx.rmx_ssthresh) {
2734 * There's some sort of gateway or interface
2735 * buffer limit on the path. Use this to set
2736 * the slow start threshhold, but set the
2737 * threshold to no less than 2*mss.
2739 tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
2740 tcpstat.tcps_usedssthresh++;
2745 * Determine the MSS option to send on an outgoing SYN.
2753 int isipv6 = ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2754 int min_protoh = isipv6 ?
2755 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
2756 sizeof(struct tcpiphdr);
2758 const int isipv6 = 0;
2759 const size_t min_protoh = sizeof(struct tcpiphdr);
2763 rt = tcp_rtlookup6(&tp->t_inpcb->inp_inc);
2765 rt = tcp_rtlookup(&tp->t_inpcb->inp_inc);
2767 return (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
2769 return (rt->rt_ifp->if_mtu - min_protoh);
2774 * When a partial ack arrives, force the retransmission of the
2775 * next unacknowledged segment. Do not clear tp->t_dupacks.
2776 * By setting snd_nxt to ti_ack, this forces retransmission timer to
2780 tcp_newreno_partial_ack(tp, th)
2784 tcp_seq onxt = tp->snd_nxt;
2785 u_long ocwnd = tp->snd_cwnd;
2787 callout_stop(tp->tt_rexmt);
2789 tp->snd_nxt = th->th_ack;
2791 * Set snd_cwnd to one segment beyond acknowledged offset
2792 * (tp->snd_una has not yet been updated when this function is called.)
2794 tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
2795 tp->t_flags |= TF_ACKNOW;
2796 (void) tcp_output(tp);
2797 tp->snd_cwnd = ocwnd;
2798 if (SEQ_GT(onxt, tp->snd_nxt))
2801 * Partial window deflation. Relies on fact that tp->snd_una
2804 tp->snd_cwnd -= (th->th_ack - tp->snd_una - tp->t_maxseg);